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