@carbonteq/fp 0.8.2 → 0.10.0

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 (195) hide show
  1. package/README.md +718 -95
  2. package/dist/errors.cjs +20 -0
  3. package/dist/errors.cjs.map +1 -0
  4. package/dist/errors.d.cts +10 -0
  5. package/dist/errors.d.cts.map +1 -0
  6. package/dist/errors.d.mts +10 -0
  7. package/dist/errors.d.mts.map +1 -0
  8. package/dist/errors.mjs +17 -0
  9. package/dist/errors.mjs.map +1 -0
  10. package/dist/flow-experimental.cjs +286 -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 +284 -0
  17. package/dist/flow-experimental.mjs.map +1 -0
  18. package/dist/flow.cjs +296 -0
  19. package/dist/flow.cjs.map +1 -0
  20. package/dist/flow.d.cts +79 -0
  21. package/dist/flow.d.cts.map +1 -0
  22. package/dist/flow.d.mts +79 -0
  23. package/dist/flow.d.mts.map +1 -0
  24. package/dist/flow.mjs +294 -0
  25. package/dist/flow.mjs.map +1 -0
  26. package/dist/index.cjs +28 -7
  27. package/dist/index.d.cts +11 -5
  28. package/dist/index.d.mts +11 -0
  29. package/dist/index.mjs +12 -0
  30. package/dist/match.cjs +294 -3
  31. package/dist/match.cjs.map +1 -0
  32. package/dist/match.d.cts +481 -5
  33. package/dist/match.d.cts.map +1 -0
  34. package/dist/match.d.mts +481 -0
  35. package/dist/match.d.mts.map +1 -0
  36. package/dist/match.mjs +287 -0
  37. package/dist/match.mjs.map +1 -0
  38. package/dist/option-experimental.cjs +1503 -0
  39. package/dist/option-experimental.cjs.map +1 -0
  40. package/dist/option-experimental.d.cts +1383 -0
  41. package/dist/option-experimental.d.cts.map +1 -0
  42. package/dist/option-experimental.d.mts +1383 -0
  43. package/dist/option-experimental.d.mts.map +1 -0
  44. package/dist/option-experimental.mjs +1501 -0
  45. package/dist/option-experimental.mjs.map +1 -0
  46. package/dist/option.cjs +806 -4
  47. package/dist/option.cjs.map +1 -0
  48. package/dist/option.d.cts +580 -3
  49. package/dist/option.d.cts.map +1 -0
  50. package/dist/option.d.mts +580 -0
  51. package/dist/option.d.mts.map +1 -0
  52. package/dist/option.mjs +805 -0
  53. package/dist/option.mjs.map +1 -0
  54. package/dist/result-experimental.cjs +1266 -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 +1265 -0
  61. package/dist/result-experimental.mjs.map +1 -0
  62. package/dist/result.cjs +1077 -5
  63. package/dist/result.cjs.map +1 -0
  64. package/dist/result.d.cts +833 -3
  65. package/dist/result.d.cts.map +1 -0
  66. package/dist/result.d.mts +833 -0
  67. package/dist/result.d.mts.map +1 -0
  68. package/dist/result.mjs +1077 -0
  69. package/dist/result.mjs.map +1 -0
  70. package/dist/tuple.cjs +3 -0
  71. package/dist/tuple.cjs.map +1 -1
  72. package/dist/tuple.d.cts +5 -2
  73. package/dist/tuple.d.cts.map +1 -1
  74. package/dist/tuple.d.mts +15 -0
  75. package/dist/tuple.d.mts.map +1 -0
  76. package/dist/{tuple.js → tuple.mjs} +3 -1
  77. package/dist/tuple.mjs.map +1 -0
  78. package/dist/unit.cjs +8 -2
  79. package/dist/unit.cjs.map +1 -0
  80. package/dist/unit.d.cts +8 -2
  81. package/dist/unit.d.cts.map +1 -0
  82. package/dist/unit.d.mts +8 -0
  83. package/dist/unit.d.mts.map +1 -0
  84. package/dist/unit.mjs +7 -0
  85. package/dist/unit.mjs.map +1 -0
  86. package/dist/utils.cjs +24 -0
  87. package/dist/utils.cjs.map +1 -0
  88. package/dist/utils.d.cts +14 -0
  89. package/dist/utils.d.cts.map +1 -0
  90. package/dist/utils.d.mts +14 -0
  91. package/dist/utils.d.mts.map +1 -0
  92. package/dist/utils.mjs +20 -0
  93. package/dist/utils.mjs.map +1 -0
  94. package/examples/README.md +46 -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 +237 -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 +241 -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 +147 -0
  108. package/examples/match/index.ts +19 -0
  109. package/examples/match-experimental/01-experimental-match.ts +150 -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 +120 -48
  150. package/dist/chunk-CUT6urMc.cjs +0 -30
  151. package/dist/index.d.ts +0 -5
  152. package/dist/index.js +0 -6
  153. package/dist/match-BQP0RNSk.js +0 -13
  154. package/dist/match-BQP0RNSk.js.map +0 -1
  155. package/dist/match-COIWq-e8.d.cts +0 -18
  156. package/dist/match-COIWq-e8.d.cts.map +0 -1
  157. package/dist/match-DXKW7ym5.d.ts +0 -18
  158. package/dist/match-DXKW7ym5.d.ts.map +0 -1
  159. package/dist/match-DyAuOeqx.cjs +0 -25
  160. package/dist/match-DyAuOeqx.cjs.map +0 -1
  161. package/dist/match.d.ts +0 -5
  162. package/dist/match.js +0 -3
  163. package/dist/option-8_eiz02z.d.cts +0 -45
  164. package/dist/option-8_eiz02z.d.cts.map +0 -1
  165. package/dist/option-Be_DXVE6.js +0 -181
  166. package/dist/option-Be_DXVE6.js.map +0 -1
  167. package/dist/option-CoelyMEg.d.ts +0 -45
  168. package/dist/option-CoelyMEg.d.ts.map +0 -1
  169. package/dist/option-DHCdfOco.cjs +0 -193
  170. package/dist/option-DHCdfOco.cjs.map +0 -1
  171. package/dist/option.d.ts +0 -3
  172. package/dist/option.js +0 -4
  173. package/dist/result-CdGWA5IL.js +0 -318
  174. package/dist/result-CdGWA5IL.js.map +0 -1
  175. package/dist/result-DsVjSFnO.d.ts +0 -132
  176. package/dist/result-DsVjSFnO.d.ts.map +0 -1
  177. package/dist/result-Dy_C5dC6.d.cts +0 -132
  178. package/dist/result-Dy_C5dC6.d.cts.map +0 -1
  179. package/dist/result-nuhyCRyu.cjs +0 -336
  180. package/dist/result-nuhyCRyu.cjs.map +0 -1
  181. package/dist/result.d.ts +0 -3
  182. package/dist/result.js +0 -4
  183. package/dist/tuple.d.ts +0 -12
  184. package/dist/tuple.d.ts.map +0 -1
  185. package/dist/tuple.js.map +0 -1
  186. package/dist/unit-CnjFzJN1.cjs +0 -12
  187. package/dist/unit-CnjFzJN1.cjs.map +0 -1
  188. package/dist/unit-CoBLIJFc.d.ts +0 -9
  189. package/dist/unit-CoBLIJFc.d.ts.map +0 -1
  190. package/dist/unit-D0y_qAUW.d.cts +0 -9
  191. package/dist/unit-D0y_qAUW.d.cts.map +0 -1
  192. package/dist/unit-udy5j53P.js +0 -6
  193. package/dist/unit-udy5j53P.js.map +0 -1
  194. package/dist/unit.d.ts +0 -2
  195. package/dist/unit.js +0 -3
package/dist/result.cjs CHANGED
@@ -1,6 +1,1078 @@
1
- require('./unit-CnjFzJN1.cjs');
2
- const require_result = require('./result-nuhyCRyu.cjs');
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_errors = require('./errors.cjs');
3
+ const require_unit = require('./unit.cjs');
4
+ const require_utils = require('./utils.cjs');
5
+ const require_option = require('./option.cjs');
3
6
 
4
- exports.Result = require_result.Result;
5
- exports.UnwrappedErrWithOk = require_result.UnwrappedErrWithOk;
6
- exports.UnwrappedOkWithErr = require_result.UnwrappedOkWithErr;
7
+ //#region src/result.ts
8
+ /** Sentinel value stored in #val when Result is Err */
9
+ const ERR_VAL = Symbol("Result::Err");
10
+ /** NO_ERR sentinel indicates no async error has occurred */
11
+ const NO_ERR = Symbol("Result::NoErr");
12
+ /** Internal symbol for accessing private factory - not exported */
13
+ const RESULT_INTERNAL = Symbol("Result::Internal");
14
+ /**
15
+ * Wrapper that makes Result yieldable with proper type tracking.
16
+ * The Generator signature ensures TypeScript tracks the inner type T.
17
+ *
18
+ * @internal
19
+ */
20
+ var ResultYieldWrap = class {
21
+ constructor(result) {
22
+ this.result = result;
23
+ }
24
+ *[Symbol.iterator]() {
25
+ const trace = (/* @__PURE__ */ new Error()).stack;
26
+ return yield new require_utils.CapturedTrace(this, trace);
27
+ }
28
+ };
29
+ /**
30
+ * Wrapper that makes Result yieldable in async generators with proper type tracking.
31
+ * Supports Promise<Result<T, E>> for async result chaining.
32
+ *
33
+ * @internal
34
+ */
35
+ var AsyncResultYieldWrap = class {
36
+ constructor(result) {
37
+ this.result = result;
38
+ }
39
+ async *[Symbol.asyncIterator]() {
40
+ const trace = (/* @__PURE__ */ new Error()).stack;
41
+ return yield new require_utils.CapturedTrace(this, trace);
42
+ }
43
+ };
44
+ /**
45
+ * Represents a computation that can succeed (`Ok<T>`) or fail (`Err<E>`).
46
+ * Provides composable transformations with explicit error propagation.
47
+ */
48
+ var Result = class Result {
49
+ /** Discriminant tag for type-level identification */
50
+ _tag;
51
+ /** Value when Ok; ERR_VAL sentinel when Err */
52
+ #val;
53
+ /** Error when Err (sync); undefined when Ok */
54
+ #err;
55
+ /** Context for async error tracking - stores actual error value when async chain fails */
56
+ #ctx;
57
+ constructor(val, err, ctx, tag) {
58
+ this.#val = val;
59
+ this.#err = err;
60
+ this.#ctx = ctx;
61
+ this._tag = tag;
62
+ }
63
+ /** Internal factory for namespace functions - not part of public API */
64
+ static [RESULT_INTERNAL] = { create(val, err, ctx, tag) {
65
+ return new Result(val, err, ctx, tag);
66
+ } };
67
+ /** Get the actual error value (from async context or sync field) */
68
+ getErr() {
69
+ return this.#ctx.asyncErr !== NO_ERR ? this.#ctx.asyncErr : this.#err;
70
+ }
71
+ /** Singleton UNIT_RESULT for void-success operations */
72
+ static UNIT_RESULT = new Result(require_unit.UNIT, void 0, { asyncErr: NO_ERR }, "Ok");
73
+ /**
74
+ * Creates an Ok containing the given value.
75
+ *
76
+ * @template T - Success value type
77
+ * @template E - Error type (defaults to never)
78
+ * @param val - Success value
79
+ * @returns Result in the Ok state
80
+ */
81
+ static Ok(val) {
82
+ return new Result(val, void 0, { asyncErr: NO_ERR }, "Ok");
83
+ }
84
+ /**
85
+ * Creates an Err containing the given error.
86
+ *
87
+ * @template E - Error type
88
+ * @template T - Success value type (defaults to never)
89
+ * @param err - Error value
90
+ * @returns Result in the Err state
91
+ */
92
+ static Err(err) {
93
+ return new Result(ERR_VAL, err, { asyncErr: NO_ERR }, "Err");
94
+ }
95
+ /**
96
+ * Type guard for Ok state.
97
+ *
98
+ * @returns true if this Result is Ok
99
+ */
100
+ isOk() {
101
+ return this._tag === "Ok" && this.#ctx.asyncErr === NO_ERR;
102
+ }
103
+ /**
104
+ * Type guard for Err state.
105
+ *
106
+ * @returns true if this Result is Err
107
+ */
108
+ isErr() {
109
+ return this._tag === "Err" || this.#ctx.asyncErr !== NO_ERR || this._tag === "Ok" && this.#val === ERR_VAL;
110
+ }
111
+ /**
112
+ * Type guard for Ok containing UNIT.
113
+ *
114
+ * @returns true if the Ok value is UNIT
115
+ */
116
+ isUnit() {
117
+ return this.#val === require_unit.UNIT;
118
+ }
119
+ /**
120
+ * Returns a string representation of the Result.
121
+ *
122
+ * @returns "Result::Ok<value>" or "Result::Err<error>"
123
+ */
124
+ toString() {
125
+ if (this.isOk()) return `Result::Ok<${String(this.#val)}>`;
126
+ return `Result::Err<${String(this.getErr())}>`;
127
+ }
128
+ unwrap() {
129
+ if (this.isErr()) {
130
+ const err = this.getErr();
131
+ if (err instanceof Error) throw err;
132
+ throw new require_errors.UnwrappedOkWithErr(this.toString());
133
+ }
134
+ const curr = this.#val;
135
+ if (require_utils.isPromiseLike(curr)) {
136
+ const ctx = this.#ctx;
137
+ return new Promise((resolve, reject) => {
138
+ curr.then((v) => {
139
+ if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) reject(ctx.asyncErr !== NO_ERR && ctx.asyncErr instanceof Error ? ctx.asyncErr : new require_errors.UnwrappedOkWithErr(this.toString()));
140
+ else resolve(v);
141
+ }, reject);
142
+ });
143
+ }
144
+ return curr;
145
+ }
146
+ unwrapErr() {
147
+ if (this._tag === "Err") return this.getErr();
148
+ const curr = this.#val;
149
+ const ctx = this.#ctx;
150
+ if (require_utils.isPromiseLike(curr)) return new Promise((resolve, reject) => {
151
+ curr.then((v) => {
152
+ if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) resolve(ctx.asyncErr !== NO_ERR ? ctx.asyncErr : this.#err);
153
+ else reject(new require_errors.UnwrappedErrWithOk(this.toString()));
154
+ }, reject);
155
+ });
156
+ throw new require_errors.UnwrappedErrWithOk(this.toString());
157
+ }
158
+ unwrapOr(defaultValue) {
159
+ if (this.isErr()) return defaultValue;
160
+ const curr = this.#val;
161
+ const ctx = this.#ctx;
162
+ if (require_utils.isPromiseLike(curr)) return curr.then((v) => {
163
+ if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) return defaultValue;
164
+ return v;
165
+ });
166
+ return curr;
167
+ }
168
+ unwrapOrElse(fn) {
169
+ if (this.isErr()) return fn(this.getErr());
170
+ const curr = this.#val;
171
+ const ctx = this.#ctx;
172
+ if (require_utils.isPromiseLike(curr)) return curr.then((v) => {
173
+ if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) return fn(ctx.asyncErr !== NO_ERR ? ctx.asyncErr : this.#err);
174
+ return v;
175
+ });
176
+ return curr;
177
+ }
178
+ safeUnwrap() {
179
+ if (this.isErr()) return null;
180
+ const curr = this.#val;
181
+ const ctx = this.#ctx;
182
+ if (require_utils.isPromiseLike(curr)) return curr.then((v) => {
183
+ if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) return null;
184
+ return v;
185
+ });
186
+ return curr === ERR_VAL ? null : curr;
187
+ }
188
+ /**
189
+ * Exhaustive pattern match on Result state.
190
+ *
191
+ * @template U - Result type of the handlers
192
+ * @param cases - Handlers for Ok and Err
193
+ * @returns Result of the matching handler
194
+ */
195
+ match(cases) {
196
+ if (this.isErr()) return cases.Err(this.getErr());
197
+ return cases.Ok(this.#val);
198
+ }
199
+ map(fn) {
200
+ if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
201
+ const curr = this.#val;
202
+ const parentErr = this.#err;
203
+ if (require_utils.isPromiseLike(curr)) {
204
+ const p = curr;
205
+ const newCtx = { asyncErr: NO_ERR };
206
+ return new Result(Result.safeMap(p, fn, newCtx, this.#ctx), parentErr, newCtx, "Ok");
207
+ }
208
+ const next = fn(curr);
209
+ if (require_utils.isPromiseLike(next)) return new Result(next, parentErr, { asyncErr: NO_ERR }, "Ok");
210
+ return new Result(next, parentErr, { asyncErr: NO_ERR }, "Ok");
211
+ }
212
+ /**
213
+ * Safely maps a promised Ok value while propagating async errors.
214
+ *
215
+ * @template In - Input value type
216
+ * @template U - Output value type
217
+ * @template E - Error type
218
+ * @param p - Promise of Ok value or ERR sentinel
219
+ * @param mapper - Transform function
220
+ * @param ctx - New async context to populate on error
221
+ * @param parentCtx - Parent async context to read error from
222
+ * @returns Promise of transformed value or ERR sentinel
223
+ */
224
+ static safeMap(p, mapper, ctx, parentCtx) {
225
+ return p.then((v) => {
226
+ if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
227
+ ctx.asyncErr = parentCtx.asyncErr;
228
+ return ERR_VAL;
229
+ }
230
+ return mapper(v);
231
+ });
232
+ }
233
+ /**
234
+ * Transforms the error value while preserving the success value.
235
+ *
236
+ * If the Result is Err, applies the function to the error. If Ok, returns
237
+ * the Ok unchanged without calling the function.
238
+ *
239
+ * @param fn - Function to transform the error
240
+ * @returns Result<T, E2> with transformed error or original Ok
241
+ *
242
+ * @example
243
+ * ```ts
244
+ * Result.Err("network error").mapErr((e) => `Network: ${e}`); // Err("Network: network error")
245
+ * Result.Ok(42).mapErr((e) => `Error: ${e}`); // Ok(42)
246
+ *
247
+ * // Add context to errors
248
+ * fetchData()
249
+ * .mapErr((e) => new ContextualError("Failed to fetch data", e));
250
+ * ```
251
+ *
252
+ * @see mapBoth
253
+ */
254
+ mapErr(fn) {
255
+ if (this._tag === "Err") {
256
+ const mappedErr = fn(this.getErr());
257
+ return Result.Err(mappedErr);
258
+ }
259
+ const curr = this.#val;
260
+ const parentCtx = this.#ctx;
261
+ if (require_utils.isPromiseLike(curr)) {
262
+ const newCtx = { asyncErr: NO_ERR };
263
+ return new Result(curr.then((v) => {
264
+ if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) newCtx.asyncErr = fn(parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : this.#err);
265
+ return v;
266
+ }), void 0, newCtx, "Ok");
267
+ }
268
+ return new Result(this.#val, void 0, { asyncErr: NO_ERR }, "Ok");
269
+ }
270
+ mapBoth(fnOk, fnErr) {
271
+ return this.map(fnOk).mapErr(fnErr);
272
+ }
273
+ flatMap(fn) {
274
+ if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
275
+ const curr = this.#val;
276
+ const parentErr = this.#err;
277
+ const parentCtx = this.#ctx;
278
+ const newCtx = { asyncErr: NO_ERR };
279
+ if (require_utils.isPromiseLike(curr)) return new Result(new Promise((resolve, reject) => {
280
+ curr.then((v) => {
281
+ if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
282
+ newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
283
+ return resolve(ERR_VAL);
284
+ }
285
+ const mapped = fn(v);
286
+ resolve(Result.flatMapHelper(newCtx, mapped));
287
+ }, reject);
288
+ }), parentErr, newCtx, "Ok");
289
+ const mapped = fn(curr);
290
+ if (require_utils.isPromiseLike(mapped)) return new Result(mapped.then((r) => Result.flatMapInnerHelper(newCtx, r)), parentErr, newCtx, "Ok");
291
+ const normalized = Result.flatMapInnerHelper(newCtx, mapped);
292
+ if (require_utils.isPromiseLike(normalized)) return new Result(normalized, parentErr, newCtx, "Ok");
293
+ if (normalized === ERR_VAL) return new Result(ERR_VAL, newCtx.asyncErr !== NO_ERR ? newCtx.asyncErr : parentErr, newCtx, "Err");
294
+ return new Result(normalized, parentErr, newCtx, "Ok");
295
+ }
296
+ /**
297
+ * Normalizes sync/async flatMap outputs to a value or Promise.
298
+ *
299
+ * @template U - Success value type
300
+ * @template E - Original error type
301
+ * @template E2 - Mapped error type
302
+ * @template T - Input value type
303
+ * @param mutableCtx - Mutable context for async error propagation
304
+ * @param mapped - FlatMap output (sync or async Result)
305
+ * @returns Value, Promise, or ERR sentinel
306
+ */
307
+ static flatMapHelper(mutableCtx, mapped) {
308
+ if (require_utils.isPromiseLike(mapped)) return mapped.then((r) => Result.flatMapInnerHelper(mutableCtx, r));
309
+ return Result.flatMapInnerHelper(mutableCtx, mapped);
310
+ }
311
+ /**
312
+ * Extracts the inner value from a Result, updating error context on failure.
313
+ *
314
+ * @template U - Success value type
315
+ * @template E - Original error type
316
+ * @template E2 - Mapped error type
317
+ * @param mutableCtx - Mutable context for async error propagation
318
+ * @param r - Inner Result to unwrap
319
+ * @returns Value, Promise, or ERR sentinel
320
+ */
321
+ static flatMapInnerHelper(mutableCtx, r) {
322
+ if (r._tag === "Err") {
323
+ mutableCtx.asyncErr = r.getErr();
324
+ return ERR_VAL;
325
+ }
326
+ const innerVal = r.#val;
327
+ if (require_utils.isPromiseLike(innerVal)) return innerVal.then((v) => {
328
+ if (v === ERR_VAL || r.#ctx.asyncErr !== NO_ERR) mutableCtx.asyncErr = r.#ctx.asyncErr !== NO_ERR ? r.#ctx.asyncErr : r.#err;
329
+ return v;
330
+ });
331
+ if (innerVal === ERR_VAL) {
332
+ mutableCtx.asyncErr = r.getErr();
333
+ return ERR_VAL;
334
+ }
335
+ return innerVal;
336
+ }
337
+ zip(fn) {
338
+ if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
339
+ const curr = this.#val;
340
+ const parentErr = this.#err;
341
+ const parentCtx = this.#ctx;
342
+ const newCtx = { asyncErr: NO_ERR };
343
+ if (require_utils.isPromiseLike(curr)) return new Result(curr.then((v) => {
344
+ if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
345
+ newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
346
+ return ERR_VAL;
347
+ }
348
+ const u = fn(v);
349
+ if (require_utils.isPromiseLike(u)) return u.then((uu) => [v, uu]);
350
+ return [v, u];
351
+ }), parentErr, newCtx, "Ok");
352
+ const u = fn(curr);
353
+ if (require_utils.isPromiseLike(u)) return new Result(u.then((uu) => [curr, uu]), parentErr, { asyncErr: NO_ERR }, "Ok");
354
+ return new Result([curr, u], parentErr, { asyncErr: NO_ERR }, "Ok");
355
+ }
356
+ flatZip(fn) {
357
+ if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
358
+ const curr = this.#val;
359
+ const parentErr = this.#err;
360
+ const parentCtx = this.#ctx;
361
+ const newCtx = { asyncErr: NO_ERR };
362
+ if (require_utils.isPromiseLike(curr)) return new Result(curr.then((v) => {
363
+ if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
364
+ newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
365
+ return ERR_VAL;
366
+ }
367
+ const mapped = fn(v);
368
+ return Result.flatZipHelper(newCtx, v, mapped);
369
+ }), parentErr, newCtx, "Ok");
370
+ const mapped = fn(curr);
371
+ const p = Result.flatZipHelper(newCtx, curr, mapped);
372
+ if (require_utils.isPromiseLike(p)) return new Result(p, parentErr, newCtx, "Ok");
373
+ if (p === ERR_VAL) return new Result(ERR_VAL, newCtx.asyncErr !== NO_ERR ? newCtx.asyncErr : parentErr, newCtx, "Err");
374
+ return new Result(p, parentErr, newCtx, "Ok");
375
+ }
376
+ /**
377
+ * Normalizes sync/async flatZip outputs to a tuple or ERR sentinel.
378
+ *
379
+ * @template U - Derived value type
380
+ * @template E - Original error type
381
+ * @template E2 - Mapped error type
382
+ * @template In - Original value type
383
+ * @param mutableCtx - Mutable context for async error propagation
384
+ * @param originalVal - Original value to preserve
385
+ * @param mapped - FlatZip output (sync or async Result)
386
+ * @returns Tuple, Promise of tuple, or ERR sentinel
387
+ */
388
+ static flatZipHelper(mutableCtx, originalVal, mapped) {
389
+ if (require_utils.isPromiseLike(mapped)) return mapped.then((r) => Result.flatZipInnerHelper(mutableCtx, originalVal, r));
390
+ return Result.flatZipInnerHelper(mutableCtx, originalVal, mapped);
391
+ }
392
+ /**
393
+ * Extracts the inner value for flatZip, updating error context on failure.
394
+ *
395
+ * @template U - Derived value type
396
+ * @template E - Original error type
397
+ * @template E2 - Mapped error type
398
+ * @template In - Original value type
399
+ * @param mutableCtx - Mutable context for async error propagation
400
+ * @param originalVal - Original value to preserve
401
+ * @param r - Inner Result to unwrap
402
+ * @returns Tuple, Promise of tuple, or ERR sentinel
403
+ */
404
+ static flatZipInnerHelper(mutableCtx, originalVal, r) {
405
+ if (r._tag === "Err") {
406
+ mutableCtx.asyncErr = r.getErr();
407
+ return ERR_VAL;
408
+ }
409
+ const innerVal = r.#val;
410
+ if (require_utils.isPromiseLike(innerVal)) return innerVal.then((v) => {
411
+ if (v === ERR_VAL || r.#ctx.asyncErr !== NO_ERR) {
412
+ mutableCtx.asyncErr = r.#ctx.asyncErr !== NO_ERR ? r.#ctx.asyncErr : r.#err;
413
+ return ERR_VAL;
414
+ }
415
+ return [originalVal, v];
416
+ });
417
+ if (innerVal === ERR_VAL) {
418
+ mutableCtx.asyncErr = r.getErr();
419
+ return ERR_VAL;
420
+ }
421
+ return [originalVal, innerVal];
422
+ }
423
+ zipErr(fn) {
424
+ if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
425
+ const curr = this.#val;
426
+ const parentErr = this.#err;
427
+ const parentCtx = this.#ctx;
428
+ const newCtx = { asyncErr: NO_ERR };
429
+ if (require_utils.isPromiseLike(curr)) return new Result(curr.then((v) => {
430
+ if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
431
+ newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
432
+ return ERR_VAL;
433
+ }
434
+ const r = fn(v);
435
+ return Result.zipErrHelper(v, r, newCtx);
436
+ }), parentErr, newCtx, "Ok");
437
+ const r = fn(curr);
438
+ const newP = Result.zipErrHelper(curr, r, newCtx);
439
+ if (require_utils.isPromiseLike(newP)) return new Result(newP, parentErr, newCtx, "Ok");
440
+ if (newCtx.asyncErr !== NO_ERR) return new Result(ERR_VAL, newCtx.asyncErr, newCtx, "Err");
441
+ return new Result(newP, parentErr, newCtx, "Ok");
442
+ }
443
+ /**
444
+ * Tracks errors from a Result while preserving the original value.
445
+ *
446
+ * @template In - Original value type
447
+ * @template E - Error type
448
+ * @param v - Original value to preserve
449
+ * @param r - Result to inspect for errors
450
+ * @param newCtx - Context to populate on error
451
+ * @returns Original value or Promise of value
452
+ */
453
+ static zipErrHelper(v, r, newCtx) {
454
+ if (require_utils.isPromiseLike(r)) return r.then((newResult) => {
455
+ const maybeAwaited = Result.captureZipErr(newResult, newCtx);
456
+ if (require_utils.isPromiseLike(maybeAwaited)) return maybeAwaited.then(() => v);
457
+ return v;
458
+ });
459
+ const maybeAwaited = Result.captureZipErr(r, newCtx);
460
+ if (require_utils.isPromiseLike(maybeAwaited)) return maybeAwaited.then(() => v);
461
+ return v;
462
+ }
463
+ static captureZipErr(result, newCtx) {
464
+ if (result._tag === "Err") {
465
+ newCtx.asyncErr = result.getErr();
466
+ return;
467
+ }
468
+ const innerVal = result.#val;
469
+ if (require_utils.isPromiseLike(innerVal)) return innerVal.then((resolved) => {
470
+ if (resolved === ERR_VAL || result.#ctx.asyncErr !== NO_ERR) newCtx.asyncErr = result.#ctx.asyncErr !== NO_ERR ? result.#ctx.asyncErr : result.#err;
471
+ });
472
+ if (innerVal === ERR_VAL || result.#ctx.asyncErr !== NO_ERR) newCtx.asyncErr = result.#ctx.asyncErr !== NO_ERR ? result.#ctx.asyncErr : result.#err;
473
+ }
474
+ validate(validators) {
475
+ if (this.isErr()) return this;
476
+ const currVal = this.#val;
477
+ const parentErr = this.#err;
478
+ const parentCtx = this.#ctx;
479
+ const mutableCtx = { asyncErr: NO_ERR };
480
+ if (require_utils.isPromiseLike(currVal)) return new Result(currVal.then(async (c) => {
481
+ if (c === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
482
+ mutableCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
483
+ return ERR_VAL;
484
+ }
485
+ const awaitedVal = c;
486
+ const results = validators.map((v) => v(awaitedVal));
487
+ return Promise.all(results).then((resolved) => Result.validateHelper(resolved, mutableCtx, awaitedVal));
488
+ }), parentErr, mutableCtx, "Ok");
489
+ const baseVal = currVal;
490
+ const results = validators.map((v) => v(baseVal));
491
+ if (results.some(require_utils.isPromiseLike)) return new Result(Promise.all(results).then((resolved) => Result.validateHelper(resolved, mutableCtx, baseVal)), parentErr, mutableCtx, "Ok");
492
+ const syncResults = results;
493
+ if (syncResults.some((r) => require_utils.isPromiseLike(r.#val))) return new Result(Result.validateHelper(syncResults, mutableCtx, baseVal), parentErr, mutableCtx, "Ok");
494
+ const combinedRes = Result.all(...syncResults);
495
+ return combinedRes.isErr() ? combinedRes : this;
496
+ }
497
+ /**
498
+ * Collapses validator Results into a single value or ERR sentinel.
499
+ *
500
+ * @template Val - Success value type
501
+ * @template Err - Error type
502
+ * @param results - Validator Results to combine
503
+ * @param currCtx - Context to populate on error
504
+ * @param currVal - Original value to return on success
505
+ * @returns Original value, Promise of value, or ERR sentinel
506
+ */
507
+ static validateHelper(results, currCtx, currVal) {
508
+ const combinedRes = Result.all(...results);
509
+ if (require_utils.isPromiseLike(combinedRes.#val)) return combinedRes.#val.then((v) => {
510
+ if (v === ERR_VAL || combinedRes.#ctx.asyncErr !== NO_ERR) {
511
+ currCtx.asyncErr = combinedRes.getErr();
512
+ return ERR_VAL;
513
+ }
514
+ return currVal;
515
+ });
516
+ if (combinedRes.isErr()) {
517
+ currCtx.asyncErr = combinedRes.getErr();
518
+ return ERR_VAL;
519
+ }
520
+ return currVal;
521
+ }
522
+ static all(...results) {
523
+ const vals = results.map((r) => r.#val);
524
+ const newCtx = { asyncErr: NO_ERR };
525
+ if (vals.some(require_utils.isPromiseLike)) return new Result(Promise.all(vals).then((resolvedVals) => {
526
+ const errs = [];
527
+ for (let i = 0; i < results.length; i++) if (results[i]._tag === "Err" || results[i].#ctx.asyncErr !== NO_ERR || resolvedVals[i] === ERR_VAL) errs.push(results[i].getErr());
528
+ if (errs.length > 0) {
529
+ newCtx.asyncErr = errs;
530
+ return ERR_VAL;
531
+ }
532
+ return resolvedVals;
533
+ }), [], newCtx, "Ok");
534
+ const errs = [];
535
+ for (const r of results) if (r._tag === "Err") errs.push(r.getErr());
536
+ if (errs.length > 0) return Result.Err(errs);
537
+ return Result.Ok(vals);
538
+ }
539
+ /**
540
+ * Returns the first Ok, or collects all errors if all are Err.
541
+ *
542
+ * Useful for fallback chains where you want the first success, but want
543
+ * to collect all errors if everything fails.
544
+ *
545
+ * - First Ok → Returns that Ok immediately
546
+ * - All Err → `Err([...all errors])`
547
+ *
548
+ * For async Ok values, this waits for settlement and selects the first
549
+ * successful candidate in input order (not fastest-to-resolve order).
550
+ *
551
+ * @param results - Variable number of Results to check
552
+ * @returns First Ok found, or Err with array of all errors
553
+ *
554
+ * @example
555
+ * ```ts
556
+ * Result.any(
557
+ * Result.Err("Error 1"),
558
+ * Result.Ok("First success"),
559
+ * Result.Ok("Second success"),
560
+ * ); // Ok("First success")
561
+ *
562
+ * Result.any(
563
+ * Result.Err("Error 1"),
564
+ * Result.Err("Error 2"),
565
+ * Result.Err("Error 3"),
566
+ * ); // Err(["Error 1", "Error 2", "Error 3"])
567
+ *
568
+ * // Fallback chain
569
+ * Result.any(
570
+ * fetchFromCache(key),
571
+ * fetchFromDb(key),
572
+ * fetchFromRemote(key),
573
+ * );
574
+ * ```
575
+ *
576
+ * @see all
577
+ */
578
+ static any(...results) {
579
+ const errs = [];
580
+ const pending = [];
581
+ for (const r of results) {
582
+ if (r.isOk()) {
583
+ if (require_utils.isPromiseLike(r.#val)) {
584
+ pending.push(r);
585
+ continue;
586
+ }
587
+ return r;
588
+ }
589
+ errs.push(r.getErr());
590
+ }
591
+ if (pending.length === 0) return Result.Err(errs);
592
+ const ctx = { asyncErr: NO_ERR };
593
+ return new Result(Promise.all(pending.map(async (r) => {
594
+ const val = await r.#val;
595
+ return {
596
+ failed: r.#ctx.asyncErr !== NO_ERR || val === ERR_VAL,
597
+ val,
598
+ err: r.getErr()
599
+ };
600
+ })).then((settled) => {
601
+ for (const item of settled) {
602
+ if (!item.failed) return item.val;
603
+ errs.push(item.err);
604
+ }
605
+ ctx.asyncErr = errs;
606
+ return ERR_VAL;
607
+ }), void 0, ctx, "Ok");
608
+ }
609
+ tap(fn) {
610
+ if (this.isErr()) return this;
611
+ const curr = this.#val;
612
+ const parentCtx = this.#ctx;
613
+ if (require_utils.isPromiseLike(curr)) {
614
+ const newCtx = { asyncErr: NO_ERR };
615
+ return new Result(curr.then((v) => {
616
+ if (v !== ERR_VAL && parentCtx.asyncErr === NO_ERR) fn(v);
617
+ else newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : this.#err;
618
+ return v;
619
+ }), this.#err, newCtx, "Ok");
620
+ }
621
+ fn(curr);
622
+ return this;
623
+ }
624
+ /**
625
+ * Executes a side effect function for Err values, then returns self.
626
+ *
627
+ * Useful for logging errors or executing cleanup without breaking the chain.
628
+ * The function is only called if the Result is Err.
629
+ *
630
+ * @param fn - Function to execute with the error (sync or async)
631
+ * @returns The same Result (chainable)
632
+ *
633
+ * @example
634
+ * ```ts
635
+ * Result.Err("Connection failed")
636
+ * .tapErr((err) => console.error(`[Error Log] ${new Date().toISOString()}: ${err}`))
637
+ * .orElse((e) => Result.Ok(defaultValue));
638
+ * // Logs error timestamp
639
+ * // Returns: Ok(defaultValue)
640
+ *
641
+ * // Ok - tapErr does nothing
642
+ * Result.Ok(42).tapErr((e) => console.log(e)); // Ok(42)
643
+ * ```
644
+ *
645
+ * @see tap
646
+ */
647
+ tapErr(fn) {
648
+ if (this.isErr()) fn(this.getErr());
649
+ return this;
650
+ }
651
+ /**
652
+ * Swaps the Ok and Err states, turning success into failure and vice versa.
653
+ *
654
+ * Useful for inverting the meaning of a Result, such as converting
655
+ * validation errors to successes and valid values to errors.
656
+ *
657
+ * @returns Result<E, T> with swapped states
658
+ *
659
+ * @example
660
+ * ```ts
661
+ * Result.Ok("Success value").flip(); // Err("Success value")
662
+ * Result.Err("Error value").flip(); // Ok("Error value")
663
+ *
664
+ * // Invert validation (fail if value is in blacklist)
665
+ * const blacklist = ["admin", "root"];
666
+ * const isBlacklisted = (name: string) =>
667
+ * Result.fromPredicate(name, (n) => !blacklist.includes(n), "blacklisted")
668
+ * .flip(); // Ok if blacklisted, Err if not
669
+ * ```
670
+ */
671
+ flip() {
672
+ if (this.isErr()) return new Result(this.getErr(), void 0, { asyncErr: NO_ERR }, "Ok");
673
+ return new Result(ERR_VAL, this.#val, { asyncErr: NO_ERR }, "Err");
674
+ }
675
+ /**
676
+ * Converts Result to Option, discarding error information.
677
+ *
678
+ * - Ok(value) → Some(value)
679
+ * - Err(error) → None
680
+ *
681
+ * Use when you only care about presence/absence of a value, not the error.
682
+ *
683
+ * @returns Option<T> - Some if Ok, None if Err
684
+ *
685
+ * @example
686
+ * ```ts
687
+ * Result.Ok(42).toOption(); // Some(42)
688
+ * Result.Err("fail").toOption(); // None
689
+ *
690
+ * // Safe user lookup
691
+ * const userOpt = fetchUser(id).toOption();
692
+ * // User or None, regardless of why fetch failed
693
+ * ```
694
+ *
695
+ * @see Option.toResult
696
+ */
697
+ toOption() {
698
+ if (this.isErr()) return require_option.Option.None;
699
+ return require_option.Option.Some(this.#val);
700
+ }
701
+ /**
702
+ * Resolves the inner promise while preserving Result structure.
703
+ *
704
+ * @returns Promise of Result with awaited value or Err
705
+ */
706
+ async toPromise() {
707
+ const v = await this.#val;
708
+ if (v === ERR_VAL || this.#ctx.asyncErr !== NO_ERR) return new Result(ERR_VAL, this.#ctx.asyncErr !== NO_ERR ? this.#ctx.asyncErr : this.#err, { asyncErr: NO_ERR }, "Err");
709
+ return new Result(v, this.#err, { asyncErr: NO_ERR }, "Ok");
710
+ }
711
+ /**
712
+ * Maps over array elements inside a Result<Array<T>, E>.
713
+ *
714
+ * Applies the mapper function to each element if the Result is Ok and
715
+ * contains an array. Propagates Err unchanged.
716
+ *
717
+ * @param mapper - Function to map over each array element
718
+ * @returns Result<Array<Out>, E> with mapped array or propagated error
719
+ * @throws Error if the Result is Ok but value is not an array
720
+ *
721
+ * @example
722
+ * ```ts
723
+ * Result.Ok([1, 2, 3]).innerMap((x) => x * 2); // Ok([2, 4, 6])
724
+ * Result.Err("fail").innerMap((x) => x * 2); // Err("fail")
725
+ * ```
726
+ */
727
+ innerMap(mapper) {
728
+ if (this.isErr()) return this;
729
+ if (Array.isArray(this.#val)) return new Result(this.#val.map(mapper), this.#err, this.#ctx, "Ok");
730
+ throw new Error("Can only be called for Result<Array<T>, E>");
731
+ }
732
+ /**
733
+ * Recovers from Err by providing a fallback Result.
734
+ *
735
+ * If Ok, returns self unchanged.
736
+ *
737
+ * @template T2 - Fallback success type
738
+ * @template E2 - Fallback error type
739
+ * @param fn - Function to produce a fallback Result from the error
740
+ * @returns Original Ok or fallback Result
741
+ */
742
+ orElse(fn) {
743
+ if (this.isOk()) return this;
744
+ return fn(this.getErr());
745
+ }
746
+ /**
747
+ * Creates a Result from a nullable value.
748
+ *
749
+ * Returns Err when the value is null or undefined, otherwise Ok.
750
+ *
751
+ * @template T - Input value type
752
+ * @template E - Error type
753
+ * @param val - Value to wrap
754
+ * @param error - Error value for null/undefined
755
+ * @returns Ok with value or Err with error
756
+ */
757
+ static fromNullable(val, error) {
758
+ return val === null || val === void 0 ? Result.Err(error) : Result.Ok(val);
759
+ }
760
+ /**
761
+ * Creates a Result based on a predicate.
762
+ *
763
+ * Returns Ok when predicate passes, otherwise Err.
764
+ *
765
+ * @template T - Input value type
766
+ * @template E - Error type
767
+ * @param val - Value to test
768
+ * @param pred - Predicate to decide Ok vs Err
769
+ * @param error - Error value for predicate failure
770
+ * @returns Ok with value or Err with error
771
+ */
772
+ static fromPredicate(val, pred, error) {
773
+ return pred(val) ? Result.Ok(val) : Result.Err(error);
774
+ }
775
+ /**
776
+ * Wraps a Promise<Result<T, E>> as Result<Promise<T>, E>.
777
+ *
778
+ * Returns an optimistic `Ok(Promise<T>)`. If the inner promise fails later,
779
+ * the failure is tracked internally and surfaces when you settle/unwrap
780
+ * (`toPromise`, `unwrap`, `unwrapErr`, etc.).
781
+ *
782
+ * @template U - Success value type
783
+ * @template F - Error type
784
+ * @param promise - Promise resolving to a Result
785
+ * @returns Result containing a Promise of the success value
786
+ */
787
+ static fromPromise(promise) {
788
+ const ctx = { asyncErr: NO_ERR };
789
+ const p = promise.then((innerResult) => {
790
+ if (innerResult.isErr()) {
791
+ try {
792
+ ctx.asyncErr = innerResult.unwrapErr();
793
+ } catch {}
794
+ return ERR_VAL;
795
+ }
796
+ return innerResult.unwrap();
797
+ });
798
+ return Result[RESULT_INTERNAL].create(p, void 0, ctx, "Ok");
799
+ }
800
+ /**
801
+ * Catches synchronous exceptions and converts them to Err.
802
+ *
803
+ * @template T - Success value type
804
+ * @template E - Error type
805
+ * @param fn - Function that may throw
806
+ * @param errorMapper - Optional mapper for thrown errors
807
+ * @returns Ok with return value or Err with mapped error
808
+ */
809
+ static tryCatch(fn, errorMapper) {
810
+ try {
811
+ return Result.Ok(fn());
812
+ } catch (e) {
813
+ return Result.Err(errorMapper ? errorMapper(e) : e);
814
+ }
815
+ }
816
+ /**
817
+ * Catches async exceptions and converts them to Err.
818
+ *
819
+ * Returns an optimistic `Ok(Promise<T>)`. If the async work fails later,
820
+ * the failure is tracked internally and surfaces when you settle/unwrap
821
+ * (`toPromise`, `unwrap`, `unwrapErr`, etc.).
822
+ *
823
+ * @template T - Success value type
824
+ * @template E - Error type
825
+ * @param fn - Async function that may throw
826
+ * @param errorMapper - Optional mapper for thrown errors
827
+ * @returns Result containing a Promise of the success value
828
+ */
829
+ static tryAsyncCatch(fn, errorMapper) {
830
+ const ctx = { asyncErr: NO_ERR };
831
+ const pWithErr = fn().then((v) => v).catch((e) => {
832
+ ctx.asyncErr = errorMapper ? errorMapper(e) : e;
833
+ return ERR_VAL;
834
+ });
835
+ return Result[RESULT_INTERNAL].create(pWithErr, void 0, ctx, "Ok");
836
+ }
837
+ /**
838
+ * Makes Result iterable for use with generator-based syntax.
839
+ * Yields self and returns the unwrapped value when resumed.
840
+ *
841
+ * @example
842
+ * ```ts
843
+ * const result = Result.gen(function* () {
844
+ * const value = yield* Result.Ok(42);
845
+ * return value * 2;
846
+ * });
847
+ * ```
848
+ */
849
+ *[Symbol.iterator]() {
850
+ const trace = (/* @__PURE__ */ new Error()).stack;
851
+ return yield new require_utils.CapturedTrace(this, trace);
852
+ }
853
+ /**
854
+ * Makes Result iterable for use with async generator-based syntax.
855
+ * Yields self and returns the unwrapped value when resumed.
856
+ *
857
+ * @example
858
+ * ```ts
859
+ * const result = await Result.asyncGen(async function* () {
860
+ * const value = yield* $(Result.Ok(42));
861
+ * return value * 2;
862
+ * });
863
+ * ```
864
+ */
865
+ async *[Symbol.asyncIterator]() {
866
+ const trace = (/* @__PURE__ */ new Error()).stack;
867
+ return yield new require_utils.CapturedTrace(this, trace);
868
+ }
869
+ /**
870
+ * Generator-based syntax for chaining Result operations (simplified, no adapter).
871
+ * Provides imperative-style code while maintaining functional error handling.
872
+ *
873
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
874
+ * recursion to avoid stack overflow on deep chains.
875
+ *
876
+ * @example
877
+ * ```ts
878
+ * const result = Result.gen(function* () {
879
+ * const a = yield* Result.Ok(1);
880
+ * const b = yield* Result.Ok(2);
881
+ * return a + b;
882
+ * });
883
+ * // Result<number, never>
884
+ * ```
885
+ */
886
+ static gen(genFn) {
887
+ const iterator = genFn();
888
+ let nextArg;
889
+ let currentResult;
890
+ while (true) {
891
+ const next = iterator.next(nextArg);
892
+ if (next.done) {
893
+ currentResult = Result.Ok(next.value);
894
+ break;
895
+ }
896
+ let yielded = next.value;
897
+ let stack;
898
+ if (require_utils.isCapturedTrace(yielded)) {
899
+ stack = yielded.stack;
900
+ yielded = yielded.value;
901
+ }
902
+ if (yielded.isErr()) {
903
+ const err = yielded.unwrapErr();
904
+ if (stack && err instanceof Error) {
905
+ const stackLines = stack.split("\n");
906
+ if (stackLines.length > 2) {
907
+ const userStack = stackLines.slice(2).join("\n");
908
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
909
+ }
910
+ }
911
+ currentResult = yielded;
912
+ break;
913
+ }
914
+ nextArg = yielded.unwrap();
915
+ }
916
+ return currentResult;
917
+ }
918
+ /**
919
+ * Generator-based syntax for chaining Result operations (with adapter).
920
+ * Uses an adapter function ($) for improved type inference.
921
+ *
922
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
923
+ * recursion to avoid stack overflow on deep chains.
924
+ *
925
+ * @example
926
+ * ```ts
927
+ * const result = Result.genAdapter(function* ($) {
928
+ * const a = yield* $(Result.Ok(1));
929
+ * const b = yield* $(Result.Ok(2));
930
+ * return a + b;
931
+ * });
932
+ * // Result<number, never>
933
+ * ```
934
+ */
935
+ static genAdapter(genFn) {
936
+ const adapter = (result) => new ResultYieldWrap(result);
937
+ const iterator = genFn(adapter);
938
+ let nextArg;
939
+ let currentResult;
940
+ while (true) {
941
+ const next = iterator.next(nextArg);
942
+ if (next.done) {
943
+ currentResult = Result.Ok(next.value);
944
+ break;
945
+ }
946
+ const wrapped = next.value;
947
+ let result = wrapped.result;
948
+ let stack;
949
+ if (require_utils.isCapturedTrace(wrapped)) {
950
+ stack = wrapped.stack;
951
+ result = wrapped.value.result;
952
+ }
953
+ if (result.isErr()) {
954
+ const err = result.unwrapErr();
955
+ if (stack && err instanceof Error) {
956
+ const stackLines = stack.split("\n");
957
+ if (stackLines.length > 2) {
958
+ const userStack = stackLines.slice(2).join("\n");
959
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
960
+ }
961
+ }
962
+ currentResult = result;
963
+ break;
964
+ }
965
+ nextArg = result.unwrap();
966
+ }
967
+ return currentResult;
968
+ }
969
+ /**
970
+ * Async generator-based syntax for chaining Result operations (simplified, no adapter).
971
+ * Use yield* with Result values directly. For Promise<Result<T, E>>, await first then yield*.
972
+ *
973
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
974
+ * recursion to avoid stack overflow on deep chains.
975
+ *
976
+ * @example
977
+ * ```ts
978
+ * const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
979
+ * Promise.resolve(Result.Ok({ id }));
980
+ * const result = await Result.asyncGen(async function* () {
981
+ * const a = yield* Result.Ok(1);
982
+ * const dataResult = yield* await fetchData(a);
983
+ * return a + dataResult.id;
984
+ * });
985
+ * // Result<number, never>
986
+ * ```
987
+ */
988
+ static async asyncGen(genFn) {
989
+ const iterator = genFn();
990
+ let nextArg;
991
+ let currentResult;
992
+ while (true) {
993
+ const next = await iterator.next(nextArg);
994
+ if (next.done) {
995
+ currentResult = Result.Ok(next.value);
996
+ break;
997
+ }
998
+ let result = next.value;
999
+ let stack;
1000
+ if (require_utils.isCapturedTrace(result)) {
1001
+ stack = result.stack;
1002
+ result = result.value;
1003
+ }
1004
+ if (result.isErr()) {
1005
+ const err = result.unwrapErr();
1006
+ if (stack && err instanceof Error) {
1007
+ const stackLines = stack.split("\n");
1008
+ if (stackLines.length > 2) {
1009
+ const userStack = stackLines.slice(2).join("\n");
1010
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1011
+ }
1012
+ }
1013
+ currentResult = result;
1014
+ break;
1015
+ }
1016
+ nextArg = result.unwrap();
1017
+ }
1018
+ return currentResult;
1019
+ }
1020
+ /**
1021
+ * Async generator-based syntax for chaining Result operations (with adapter).
1022
+ * Uses an adapter function ($) for improved type inference.
1023
+ * Supports both Result<T, E> and Promise<Result<T, E>> for flexibility.
1024
+ *
1025
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
1026
+ * recursion to avoid stack overflow on deep chains.
1027
+ *
1028
+ * @example
1029
+ * ```ts
1030
+ * const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
1031
+ * Promise.resolve(Result.Ok({ id }));
1032
+ * const result = await Result.asyncGenAdapter(async function* ($) {
1033
+ * const a = yield* $(Result.Ok(1));
1034
+ * const data = yield* $(fetchData(a));
1035
+ * return a + data.id;
1036
+ * });
1037
+ * // Result<number, never>
1038
+ * ```
1039
+ */
1040
+ static async asyncGenAdapter(genFn) {
1041
+ const adapter = (result) => new AsyncResultYieldWrap(Promise.resolve(result));
1042
+ const iterator = genFn(adapter);
1043
+ let nextArg;
1044
+ let currentResult;
1045
+ while (true) {
1046
+ const next = await iterator.next(nextArg);
1047
+ if (next.done) {
1048
+ currentResult = Result.Ok(next.value);
1049
+ break;
1050
+ }
1051
+ const wrapped = next.value;
1052
+ let result;
1053
+ let stack;
1054
+ if (require_utils.isCapturedTrace(wrapped)) {
1055
+ stack = wrapped.stack;
1056
+ result = await wrapped.value.result;
1057
+ } else result = await wrapped.result;
1058
+ if (result.isErr()) {
1059
+ const err = result.unwrapErr();
1060
+ if (stack && err instanceof Error) {
1061
+ const stackLines = stack.split("\n");
1062
+ if (stackLines.length > 2) {
1063
+ const userStack = stackLines.slice(2).join("\n");
1064
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1065
+ }
1066
+ }
1067
+ currentResult = result;
1068
+ break;
1069
+ }
1070
+ nextArg = result.unwrap();
1071
+ }
1072
+ return currentResult;
1073
+ }
1074
+ };
1075
+
1076
+ //#endregion
1077
+ exports.Result = Result;
1078
+ //# sourceMappingURL=result.cjs.map