@carbonteq/fp 0.9.1 → 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 (146) hide show
  1. package/README.md +310 -96
  2. package/dist/errors.cjs +1 -0
  3. package/dist/errors.cjs.map +1 -1
  4. package/dist/errors.d.cts.map +1 -1
  5. package/dist/errors.d.mts.map +1 -1
  6. package/dist/errors.mjs.map +1 -1
  7. package/dist/flow-experimental.cjs +286 -0
  8. package/dist/flow-experimental.cjs.map +1 -0
  9. package/dist/flow-experimental.d.cts +69 -0
  10. package/dist/flow-experimental.d.cts.map +1 -0
  11. package/dist/flow-experimental.d.mts +69 -0
  12. package/dist/flow-experimental.d.mts.map +1 -0
  13. package/dist/flow-experimental.mjs +284 -0
  14. package/dist/flow-experimental.mjs.map +1 -0
  15. package/dist/flow.cjs +296 -0
  16. package/dist/flow.cjs.map +1 -0
  17. package/dist/flow.d.cts +79 -0
  18. package/dist/flow.d.cts.map +1 -0
  19. package/dist/flow.d.mts +79 -0
  20. package/dist/flow.d.mts.map +1 -0
  21. package/dist/flow.mjs +294 -0
  22. package/dist/flow.mjs.map +1 -0
  23. package/dist/index.cjs +26 -11
  24. package/dist/index.d.cts +8 -3
  25. package/dist/index.d.mts +8 -3
  26. package/dist/index.mjs +8 -3
  27. package/dist/match.cjs +282 -0
  28. package/dist/match.cjs.map +1 -1
  29. package/dist/match.d.cts +471 -5
  30. package/dist/match.d.cts.map +1 -1
  31. package/dist/match.d.mts +471 -5
  32. package/dist/match.d.mts.map +1 -1
  33. package/dist/match.mjs +277 -1
  34. package/dist/match.mjs.map +1 -1
  35. package/dist/option-experimental.cjs +1503 -0
  36. package/dist/option-experimental.cjs.map +1 -0
  37. package/dist/option-experimental.d.cts +1383 -0
  38. package/dist/option-experimental.d.cts.map +1 -0
  39. package/dist/option-experimental.d.mts +1383 -0
  40. package/dist/option-experimental.d.mts.map +1 -0
  41. package/dist/option-experimental.mjs +1501 -0
  42. package/dist/option-experimental.mjs.map +1 -0
  43. package/dist/option.cjs +556 -29
  44. package/dist/option.cjs.map +1 -1
  45. package/dist/option.d.cts +505 -24
  46. package/dist/option.d.cts.map +1 -1
  47. package/dist/option.d.mts +505 -24
  48. package/dist/option.d.mts.map +1 -1
  49. package/dist/option.mjs +556 -30
  50. package/dist/option.mjs.map +1 -1
  51. package/dist/result-experimental.cjs +1266 -0
  52. package/dist/result-experimental.cjs.map +1 -0
  53. package/dist/result-experimental.d.cts +1127 -0
  54. package/dist/result-experimental.d.cts.map +1 -0
  55. package/dist/result-experimental.d.mts +1127 -0
  56. package/dist/result-experimental.d.mts.map +1 -0
  57. package/dist/result-experimental.mjs +1265 -0
  58. package/dist/result-experimental.mjs.map +1 -0
  59. package/dist/result.cjs +715 -122
  60. package/dist/result.cjs.map +1 -1
  61. package/dist/result.d.cts +785 -94
  62. package/dist/result.d.cts.map +1 -1
  63. package/dist/result.d.mts +785 -94
  64. package/dist/result.d.mts.map +1 -1
  65. package/dist/result.mjs +714 -117
  66. package/dist/result.mjs.map +1 -1
  67. package/dist/tuple.cjs +3 -0
  68. package/dist/tuple.cjs.map +1 -1
  69. package/dist/tuple.d.cts +5 -1
  70. package/dist/tuple.d.cts.map +1 -1
  71. package/dist/tuple.d.mts +5 -1
  72. package/dist/tuple.d.mts.map +1 -1
  73. package/dist/tuple.mjs +2 -0
  74. package/dist/tuple.mjs.map +1 -1
  75. package/dist/unit.cjs +2 -0
  76. package/dist/unit.cjs.map +1 -1
  77. package/dist/unit.d.cts +2 -0
  78. package/dist/unit.d.cts.map +1 -1
  79. package/dist/unit.d.mts +2 -0
  80. package/dist/unit.d.mts.map +1 -1
  81. package/dist/unit.mjs +1 -0
  82. package/dist/unit.mjs.map +1 -1
  83. package/dist/utils.cjs +15 -0
  84. package/dist/utils.cjs.map +1 -1
  85. package/dist/utils.d.cts +10 -1
  86. package/dist/utils.d.cts.map +1 -1
  87. package/dist/utils.d.mts +10 -1
  88. package/dist/utils.d.mts.map +1 -1
  89. package/dist/utils.mjs +13 -1
  90. package/dist/utils.mjs.map +1 -1
  91. package/examples/README.md +46 -0
  92. package/examples/flow/01-basics.ts +74 -0
  93. package/examples/flow/02-async.ts +73 -0
  94. package/examples/flow/03-recovery.ts +60 -0
  95. package/examples/flow/04-complex-backend.ts +237 -0
  96. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  97. package/examples/flow/index.ts +13 -0
  98. package/examples/flow-experimental/01-basics.ts +78 -0
  99. package/examples/flow-experimental/02-async.ts +77 -0
  100. package/examples/flow-experimental/03-recovery.ts +93 -0
  101. package/examples/flow-experimental/04-complex-backend.ts +241 -0
  102. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  103. package/examples/flow-experimental/index.ts +14 -0
  104. package/examples/match/01-stable-match.ts +147 -0
  105. package/examples/match/index.ts +19 -0
  106. package/examples/match-experimental/01-experimental-match.ts +150 -0
  107. package/examples/match-experimental/index.ts +18 -0
  108. package/examples/option/01-basics.ts +16 -0
  109. package/examples/option/02-map-flatMap.ts +36 -0
  110. package/examples/option/03-zip-flatZip.ts +23 -0
  111. package/examples/option/04-constructors.ts +21 -0
  112. package/examples/option/05-transform.ts +15 -0
  113. package/examples/option/06-aggregation.ts +14 -0
  114. package/examples/option/index.ts +49 -0
  115. package/examples/option-experimental/01-map.ts +109 -0
  116. package/examples/option-experimental/02-flatMap.ts +234 -0
  117. package/examples/option-experimental/03-zip.ts +197 -0
  118. package/examples/option-experimental/04-flatZip.ts +251 -0
  119. package/examples/option-experimental/05-gen.ts +360 -0
  120. package/examples/option-experimental/06-genAdapter.ts +463 -0
  121. package/examples/option-experimental/07-asyncGen.ts +353 -0
  122. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  123. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  124. package/examples/option-experimental/10-workflow-async.ts +378 -0
  125. package/examples/option-experimental/index.ts +341 -0
  126. package/examples/option-experimental/shared-domain.ts +325 -0
  127. package/examples/result/01-basics.ts +16 -0
  128. package/examples/result/02-map-flatMap.ts +34 -0
  129. package/examples/result/03-zip-flatZip.ts +23 -0
  130. package/examples/result/04-validation.ts +44 -0
  131. package/examples/result/05-constructors.ts +30 -0
  132. package/examples/result/06-utilities.ts +36 -0
  133. package/examples/result/index.ts +53 -0
  134. package/examples/result-experimental/01-map.ts +60 -0
  135. package/examples/result-experimental/02-flatMap.ts +169 -0
  136. package/examples/result-experimental/03-zip.ts +145 -0
  137. package/examples/result-experimental/04-flatZip.ts +252 -0
  138. package/examples/result-experimental/05-gen.ts +293 -0
  139. package/examples/result-experimental/06-genAdapter.ts +396 -0
  140. package/examples/result-experimental/07-asyncGen.ts +379 -0
  141. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  142. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  143. package/examples/result-experimental/10-workflow-async.ts +356 -0
  144. package/examples/result-experimental/index.ts +312 -0
  145. package/examples/result-experimental/shared-domain.ts +263 -0
  146. package/package.json +50 -18
@@ -0,0 +1,1265 @@
1
+ import { UnwrappedErrWithOk, UnwrappedOkWithErr } from "./errors.mjs";
2
+ import { UNIT } from "./unit.mjs";
3
+ import { CapturedTrace, isCapturedTrace, isPromiseLike } from "./utils.mjs";
4
+ import { ExperimentalOption } from "./option-experimental.mjs";
5
+
6
+ //#region src/result-experimental.ts
7
+ /** Sentinel value stored in #val when Result is Err */
8
+ const ERR_VAL = Symbol("Result::Err");
9
+ /**
10
+ * Wrapper that makes Result yieldable with proper type tracking.
11
+ * The Generator signature ensures TypeScript tracks the inner type T.
12
+ *
13
+ * @internal
14
+ */
15
+ var ResultYieldWrap = class {
16
+ constructor(result) {
17
+ this.result = result;
18
+ }
19
+ *[Symbol.iterator]() {
20
+ const trace = (/* @__PURE__ */ new Error()).stack;
21
+ return yield new CapturedTrace(this, trace);
22
+ }
23
+ };
24
+ /**
25
+ * Wrapper that makes Result yieldable in async generators with proper type tracking.
26
+ * Supports Promise<Result<T, E>> for async result chaining.
27
+ *
28
+ * @internal
29
+ */
30
+ var AsyncResultYieldWrap = class {
31
+ constructor(result) {
32
+ this.result = result;
33
+ }
34
+ async *[Symbol.asyncIterator]() {
35
+ const trace = (/* @__PURE__ */ new Error()).stack;
36
+ return yield new CapturedTrace(this, trace);
37
+ }
38
+ };
39
+ /**
40
+ * Experimental Result variant with explicit async companion methods.
41
+ */
42
+ var ExperimentalResult = class ExperimentalResult {
43
+ /** Discriminant tag for type-level identification */
44
+ _tag;
45
+ /** Value when Ok; ERR_VAL sentinel when Err */
46
+ #val;
47
+ /** Error when Err (sync); undefined when Ok */
48
+ #err;
49
+ constructor(val, err, tag) {
50
+ this.#val = val;
51
+ this.#err = err;
52
+ this._tag = tag;
53
+ }
54
+ /** Singleton UNIT_RESULT for void-success operations */
55
+ static UNIT_RESULT = new ExperimentalResult(UNIT, void 0, "Ok");
56
+ /** Create an Ok containing the given value */
57
+ static Ok(val) {
58
+ return new ExperimentalResult(val, void 0, "Ok");
59
+ }
60
+ /** Create an Err containing the given error */
61
+ static Err(err) {
62
+ return new ExperimentalResult(ERR_VAL, err, "Err");
63
+ }
64
+ /**
65
+ * Type guard for Ok state.
66
+ *
67
+ * Narrows the type, making `T` accessible and `E` equivalent to `never` in
68
+ * the true branch.
69
+ *
70
+ * @returns `true` if this Result is Ok
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * const result = ExperimentalResult.Ok(42);
75
+ * if (result.isOk()) {
76
+ * // TypeScript knows value is accessible: 42
77
+ * console.log(result.unwrap()); // 42
78
+ * }
79
+ * ```
80
+ *
81
+ * @see isErr
82
+ */
83
+ isOk() {
84
+ return this._tag === "Ok" && this.#val !== ERR_VAL;
85
+ }
86
+ /**
87
+ * Type guard for Err state.
88
+ *
89
+ * Narrows the type, making `E` accessible and `T` equivalent to `never` in
90
+ * the true branch.
91
+ *
92
+ * @returns `true` if this Result is Err
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * const result = ExperimentalResult.Err("failed");
97
+ * if (result.isErr()) {
98
+ * // TypeScript knows error is accessible: "failed"
99
+ * console.log(result.unwrapErr()); // "failed"
100
+ * }
101
+ * ```
102
+ *
103
+ * @see isOk
104
+ */
105
+ isErr() {
106
+ return this._tag === "Err" || this.#val === ERR_VAL;
107
+ }
108
+ /**
109
+ * Type guard for Unit value.
110
+ *
111
+ * Returns `true` when the Ok value is the `UNIT` singleton, used for void-success
112
+ * operations (e.g., side-effecting functions that return nothing on success).
113
+ *
114
+ * @returns `true` if this Result is Ok containing UNIT
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * function saveToDb(): ExperimentalResult<UNIT, DbError> {
119
+ * // ... save logic
120
+ * return ExperimentalResult.UNIT_RESULT;
121
+ * }
122
+ *
123
+ * const result = saveToDb();
124
+ * if (result.isUnit()) {
125
+ * console.log("Saved successfully");
126
+ * }
127
+ * ```
128
+ */
129
+ isUnit() {
130
+ return this.#val === UNIT;
131
+ }
132
+ /**
133
+ * Returns a string representation of the Result.
134
+ *
135
+ * Useful for debugging and logging. Shows "Result::Ok" or "Result::Err" with
136
+ * the contained value or error.
137
+ *
138
+ * @returns String representation in format "Result::Ok<value>" or "Result::Err<error>"
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * ExperimentalResult.Ok(42).toString(); // "Result::Ok<42>"
143
+ * ExperimentalResult.Err("fail").toString(); // "Result::Err<fail>"
144
+ * ```
145
+ */
146
+ toString() {
147
+ if (this.isOk()) return `Result::Ok<${String(this.#val)}>`;
148
+ return `Result::Err<${String(this.#err)}>`;
149
+ }
150
+ /**
151
+ * Returns the contained value or throws.
152
+ *
153
+ * If the Result is Err and the error extends Error, the original error is re-thrown
154
+ * (preserving stack trace). Otherwise, throws `UnwrappedOkWithErr`.
155
+ *
156
+ * **Use with caution**: Prefer `unwrapOr`, `unwrapOrElse`, or `match` for safer
157
+ * error handling.
158
+ *
159
+ * @throws The original error if E extends Error, otherwise `UnwrappedOkWithErr`
160
+ * @returns The contained value if Ok
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * ExperimentalResult.Ok(42).unwrap(); // 42
165
+ * ExperimentalResult.Err(new Error("fail")).unwrap(); // throws Error("fail")
166
+ * ExperimentalResult.Err("fail").unwrap(); // throws UnwrappedOkWithErr
167
+ * ```
168
+ *
169
+ * @see unwrapOr
170
+ * @see unwrapOrElse
171
+ * @see safeUnwrap
172
+ */
173
+ unwrap() {
174
+ if (this.isErr()) {
175
+ const err = this.#err;
176
+ if (err instanceof Error) throw err;
177
+ throw new UnwrappedOkWithErr(this.toString());
178
+ }
179
+ return this.#val;
180
+ }
181
+ /**
182
+ * Returns the contained error or throws.
183
+ *
184
+ * **Use with caution**: Prefer `match` or `isErr` check for safer error access.
185
+ *
186
+ * @throws `UnwrappedErrWithOk` if the Result is Ok
187
+ * @returns The contained error if Err
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * ExperimentalResult.Err("fail").unwrapErr(); // "fail"
192
+ * ExperimentalResult.Ok(42).unwrapErr(); // throws UnwrappedErrWithOk
193
+ * ```
194
+ */
195
+ unwrapErr() {
196
+ if (this._tag === "Err") return this.#err;
197
+ throw new UnwrappedErrWithOk(this.toString());
198
+ }
199
+ /**
200
+ * Returns the contained value or the provided default.
201
+ *
202
+ * A safe alternative to `unwrap` for providing fallback values.
203
+ *
204
+ * @param defaultValue - The value to return if Err
205
+ * @returns The contained value if Ok, otherwise defaultValue
206
+ *
207
+ * @example
208
+ * ```ts
209
+ * ExperimentalResult.Ok(42).unwrapOr(0); // 42
210
+ * ExperimentalResult.Err("fail").unwrapOr(0); // 0
211
+ * ```
212
+ *
213
+ * @see unwrapOrElse
214
+ * @see safeUnwrap
215
+ */
216
+ unwrapOr(defaultValue) {
217
+ if (this.isErr()) return defaultValue;
218
+ return this.#val;
219
+ }
220
+ /**
221
+ * Returns the contained value or computes a default from the error.
222
+ *
223
+ * Use when the fallback value depends on the error content.
224
+ *
225
+ * @param fn - Function that receives the error and returns a fallback value
226
+ * @returns The contained value if Ok, otherwise the result of fn(error)
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * const result = ExperimentalResult.Err("Not found");
231
+ * result.unwrapOrElse((err) => `Default: ${err}`); // "Default: Not found"
232
+ *
233
+ * ExperimentalResult.Ok(42).unwrapOrElse((err) => 0); // 42
234
+ * ```
235
+ *
236
+ * @see unwrapOr
237
+ * @see unwrap
238
+ */
239
+ unwrapOrElse(fn) {
240
+ if (this.isErr()) return fn(this.#err);
241
+ return this.#val;
242
+ }
243
+ /**
244
+ * Safely unwraps the value, returning null for Err.
245
+ *
246
+ * A convenience method for JavaScript-friendly null handling.
247
+ *
248
+ * @returns The contained value if Ok, otherwise null
249
+ *
250
+ * @example
251
+ * ```ts
252
+ * ExperimentalResult.Ok(42).safeUnwrap(); // 42
253
+ * ExperimentalResult.Err("fail").safeUnwrap(); // null
254
+ *
255
+ * // Useful for null coalescing
256
+ * const value = result.safeUnwrap() ?? "default";
257
+ * ```
258
+ *
259
+ * @see unwrapOr
260
+ */
261
+ safeUnwrap() {
262
+ if (this.isErr()) return null;
263
+ return this.#val === ERR_VAL ? null : this.#val;
264
+ }
265
+ /**
266
+ * Exhaustive pattern matching on Result state.
267
+ *
268
+ * Handles both Ok and Err branches with provided functions, ensuring all cases
269
+ * are covered. TypeScript enforces that both branches are specified.
270
+ *
271
+ * @param cases - Object containing Ok and Err handler functions
272
+ * @returns The result of calling the appropriate handler
273
+ *
274
+ * @example
275
+ * ```ts
276
+ * const message = ExperimentalResult.Ok(42).match({
277
+ * Ok: (val) => `Success: ${val}`,
278
+ * Err: (err) => `Failed: ${err}`,
279
+ * });
280
+ * // "Success: 42"
281
+ *
282
+ * // For side effects
283
+ * result.match({
284
+ * Ok: (data) => console.log("Got:", data),
285
+ * Err: (error) => console.error("Error:", error),
286
+ * });
287
+ * ```
288
+ */
289
+ match(cases) {
290
+ if (this.isErr()) return cases.Err(this.#err);
291
+ return cases.Ok(this.#val);
292
+ }
293
+ /**
294
+ * Pattern matches using positional arguments (FP convention alias for `match`).
295
+ *
296
+ * This is a more concise alternative to `match` using positional arguments
297
+ * instead of an object. Familiar to developers from Scala, Haskell, and other FP languages.
298
+ *
299
+ * @template U - The result type of both branches
300
+ * @param onOk - Handler called with the value if `Ok`
301
+ * @param onErr - Handler called with the error if `Err`
302
+ * @returns The result of calling the appropriate handler
303
+ *
304
+ * @example
305
+ * ```ts
306
+ * const result = ExperimentalResult.Ok(42).fold(
307
+ * (value) => `Success: ${value}`,
308
+ * (error) => `Failed: ${error}`
309
+ * );
310
+ * // "Success: 42"
311
+ *
312
+ * const errResult = ExperimentalResult.Err("network error").fold(
313
+ * (value) => `Success: ${value}`,
314
+ * (error) => `Failed: ${error}`
315
+ * );
316
+ * // "Failed: network error"
317
+ *
318
+ * // Equivalent to match:
319
+ * result.fold(onOk, onErr);
320
+ * result.match({ Ok: onOk, Err: onErr });
321
+ * ```
322
+ *
323
+ * @see {@link match} for object-based pattern matching
324
+ * @see {@link foldAsync} for async handlers
325
+ */
326
+ fold(onOk, onErr) {
327
+ if (this.isErr()) return onErr(this.#err);
328
+ return onOk(this.#val);
329
+ }
330
+ /**
331
+ * Async pattern matching using positional arguments.
332
+ *
333
+ * Async variant of `fold` for when handlers return Promises.
334
+ *
335
+ * @template U - The result type of both branches
336
+ * @param onOk - Async handler called with the value if `Ok`
337
+ * @param onErr - Async handler called with the error if `Err`
338
+ * @returns Promise resolving to the result of the appropriate handler
339
+ *
340
+ * @example
341
+ * ```ts
342
+ * const result = await ExperimentalResult.Ok(userId).foldAsync(
343
+ * async (id) => await fetchUserData(id),
344
+ * async (error) => await logAndGetFallback(error)
345
+ * );
346
+ *
347
+ * // Error recovery with logging
348
+ * const data = await apiResult.foldAsync(
349
+ * async (response) => await processResponse(response),
350
+ * async (error) => {
351
+ * await reportError(error);
352
+ * return getDefaultData();
353
+ * }
354
+ * );
355
+ * ```
356
+ *
357
+ * @see {@link fold} for synchronous handlers
358
+ * @see {@link matchAsync} for object-based async pattern matching
359
+ */
360
+ async foldAsync(onOk, onErr) {
361
+ if (this.isErr()) return onErr(this.#err);
362
+ return onOk(this.#val);
363
+ }
364
+ /**
365
+ * Async pattern matching on both states of the Result.
366
+ *
367
+ * Async variant of `match` for when handlers return Promises.
368
+ *
369
+ * @template U - The result type of both branches
370
+ * @param cases - Object containing async handlers for both states
371
+ * @returns Promise resolving to the result of the appropriate handler
372
+ *
373
+ * @example
374
+ * ```ts
375
+ * const result = await apiResult.matchAsync({
376
+ * Ok: async (data) => await processData(data),
377
+ * Err: async (error) => await handleError(error)
378
+ * });
379
+ *
380
+ * // With database operations
381
+ * const user = await findUserResult.matchAsync({
382
+ * Ok: async (user) => await enrichUserData(user),
383
+ * Err: async (error) => {
384
+ * await logError(error);
385
+ * return createGuestUser();
386
+ * }
387
+ * });
388
+ * ```
389
+ *
390
+ * @see {@link match} for synchronous pattern matching
391
+ * @see {@link foldAsync} for positional-argument async matching
392
+ */
393
+ async matchAsync(cases) {
394
+ if (this.isErr()) return cases.Err(this.#err);
395
+ return cases.Ok(this.#val);
396
+ }
397
+ /**
398
+ * Pattern matches with a subset of cases, using a default for unhandled cases.
399
+ *
400
+ * Unlike `match` which requires all cases, `matchPartial` allows handling
401
+ * only specific cases with a fallback default value or function.
402
+ *
403
+ * @template U - The result type
404
+ * @param cases - Partial object with optional `Ok` and `Err` handlers
405
+ * @param getDefault - Lazy default function for unhandled cases
406
+ * @returns The result of the matching handler or the default
407
+ *
408
+ * @example
409
+ * ```ts
410
+ * // Only handle Ok, default for Err
411
+ * ExperimentalResult.Ok(42).matchPartial({ Ok: (v) => v * 2 }, () => 0); // 84
412
+ * ExperimentalResult.Err("fail").matchPartial({ Ok: (v) => v * 2 }, () => 0); // 0
413
+ *
414
+ * // Only handle Err for logging
415
+ * result.matchPartial({ Err: (e) => { logError(e); return null; } }, () => null);
416
+ *
417
+ * // Lazy default with function
418
+ * result.matchPartial(
419
+ * { Ok: (v) => process(v) },
420
+ * () => computeExpensiveDefault()
421
+ * );
422
+ * ```
423
+ *
424
+ * @see {@link match} for exhaustive pattern matching
425
+ */
426
+ matchPartial(cases, getDefault) {
427
+ if (this.isErr()) return cases.Err ? cases.Err(this.#err) : getDefault();
428
+ return cases.Ok ? cases.Ok(this.#val) : getDefault();
429
+ }
430
+ map(fn) {
431
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
432
+ const curr = this.#val;
433
+ return ExperimentalResult.Ok(fn(curr));
434
+ }
435
+ /**
436
+ * Transforms the success value using an async function.
437
+ *
438
+ * Same as `map` but for async mappers. Returns `Promise<Result<U, E>>`.
439
+ *
440
+ * @param fn - Async function to transform the success value
441
+ * @returns Promise resolving to Result<U, E> with transformed value or propagated error
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * await ExperimentalResult.Ok(42).mapAsync(async (x) => x * 2); // Promise<Ok(84)>
446
+ * await ExperimentalResult.Err("fail").mapAsync(async (x) => x * 2); // Promise<Err("fail")>
447
+ * ```
448
+ *
449
+ * @see map
450
+ */
451
+ async mapAsync(fn) {
452
+ if (this.isErr()) return Promise.resolve(ExperimentalResult.Err(this.#err));
453
+ const curr = this.#val;
454
+ return fn(curr).then((u) => ExperimentalResult.Ok(u)).catch((e) => ExperimentalResult.Err(e));
455
+ }
456
+ /**
457
+ * Chains operations that return Results, flattening nested Results.
458
+ *
459
+ * If the Result is Ok, applies the function (which returns a new Result) and
460
+ * returns that Result directly. If Err, propagates the error unchanged.
461
+ *
462
+ * Error types are unified: `Result<U, E | E2>`.
463
+ *
464
+ * For async operations, use `flatMapAsync` instead.
465
+ *
466
+ * @param fn - Function that returns a Result
467
+ * @returns Result<U, E | E2> from the function or propagated error
468
+ *
469
+ * @example
470
+ * ```ts
471
+ * // Success chain
472
+ * ExperimentalResult.Ok(42)
473
+ * .flatMap((x) => ExperimentalResult.Ok(x + 1)) // Ok(43)
474
+ * .flatMap((x) => ExperimentalResult.Err("too big")); // Err("too big")
475
+ *
476
+ * // Error propagation
477
+ * ExperimentalResult.Err("initial").flatMap((x) => ExperimentalResult.Ok(x + 1)); // Err("initial")
478
+ * ```
479
+ *
480
+ * @see flatMapAsync
481
+ * @see map
482
+ * @see flatZip
483
+ */
484
+ flatMap(fn) {
485
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
486
+ return fn(this.#val);
487
+ }
488
+ /**
489
+ * Chains async operations that return Results.
490
+ *
491
+ * Same as `flatMap` but for async Result-returning functions.
492
+ * Returns `Promise<Result<U, E | E2>>`.
493
+ *
494
+ * @param fn - Async function that returns a Promise resolving to Result
495
+ * @returns Promise resolving to Result<U, E | E2>
496
+ *
497
+ * @example
498
+ * ```ts
499
+ * const fetchUser = (id: number): Promise<Result<User, string>> =>
500
+ * Promise.resolve(ExperimentalResult.Ok({ id, name: "Alice" }));
501
+ *
502
+ * await ExperimentalResult.Ok(42)
503
+ * .flatMapAsync(fetchUser)
504
+ * .then((r) => r.map((user) => user.name));
505
+ * // Promise<Ok("Alice")>
506
+ * ```
507
+ *
508
+ * @see flatMap
509
+ */
510
+ async flatMapAsync(fn) {
511
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
512
+ return fn(this.#val).then((r) => r.isErr() ? ExperimentalResult.Err(r.#err) : r).catch((e) => ExperimentalResult.Err(e));
513
+ }
514
+ zip(fn) {
515
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
516
+ const curr = this.#val;
517
+ return ExperimentalResult.Ok([curr, fn(curr)]);
518
+ }
519
+ /**
520
+ * Pairs the original value with a derived async value.
521
+ *
522
+ * Same as `zip` but for async derivation functions.
523
+ * Returns `Promise<Result<[T, U], E>>`.
524
+ *
525
+ * @param fn - Async function to derive a value from the original
526
+ * @returns Promise resolving to Result<[T, U], E>
527
+ *
528
+ * @example
529
+ * ```ts
530
+ * await ExperimentalResult.Ok(42).zipAsync(async (x) => x * 10); // Promise<Ok([42, 420])>
531
+ * ```
532
+ *
533
+ * @see zip
534
+ */
535
+ async zipAsync(fn) {
536
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
537
+ const curr = this.#val;
538
+ return fn(curr).then((u) => ExperimentalResult.Ok([curr, u]));
539
+ }
540
+ /**
541
+ * Combines the current Result with another independent Result in a tuple.
542
+ *
543
+ * Unlike `zip` which derives a value from the original, `flatZip` works with
544
+ * two independent Results. If either is Err, propagates the first error.
545
+ *
546
+ * For async Results, use `flatZipAsync` instead.
547
+ *
548
+ * @param fn - Function that receives the value and returns another Result
549
+ * @returns Result<[T, U], E | E2> containing tuple of both values, or error
550
+ *
551
+ * @example
552
+ * ```ts
553
+ * ExperimentalResult.Ok(42)
554
+ * .flatZip((x) => ExperimentalResult.Ok(x + 5)) // Ok([42, 47])
555
+ * .flatZip(([a, b]) => ExperimentalResult.Err("x")); // Err("x")
556
+ *
557
+ * ExperimentalResult.Ok(42).flatZip((x) => ExperimentalResult.Err("fail")); // Err("fail")
558
+ * ExperimentalResult.Err("init").flatZip((x) => ExperimentalResult.Ok(5)); // Err("init")
559
+ * ```
560
+ *
561
+ * @see flatZipAsync
562
+ * @see zip
563
+ * @see flatMap
564
+ */
565
+ flatZip(fn) {
566
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
567
+ const curr = this.#val;
568
+ const r = fn(curr);
569
+ if (r.isErr()) return ExperimentalResult.Err(r.unwrapErr());
570
+ return ExperimentalResult.Ok([curr, r.unwrap()]);
571
+ }
572
+ /**
573
+ * Combines the current Result with another independent async Result in a tuple.
574
+ *
575
+ * Same as `flatZip` but for async Result-returning functions.
576
+ * Returns `Promise<Result<[T, U], E | E2>>`.
577
+ *
578
+ * @param fn - Async function that receives the value and returns a Promise resolving to Result
579
+ * @returns Promise resolving to Result<[T, U], E | E2>
580
+ *
581
+ * @example
582
+ * ```ts
583
+ * const fetchData = (id: number): Promise<Result<Data, string>> =>
584
+ * Promise.resolve(ExperimentalResult.Ok({ id, value: 100 }));
585
+ *
586
+ * await ExperimentalResult.Ok(42).flatZipAsync(fetchData); // Promise<Ok([42, {id: 42, value: 100}])>
587
+ * ```
588
+ *
589
+ * @see flatZip
590
+ */
591
+ async flatZipAsync(fn) {
592
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
593
+ const curr = this.#val;
594
+ return fn(curr).then((r) => {
595
+ if (r.isErr()) return ExperimentalResult.Err(r.unwrapErr());
596
+ return ExperimentalResult.Ok([curr, r.unwrap()]);
597
+ });
598
+ }
599
+ mapErr(fn) {
600
+ if (this.isErr()) return ExperimentalResult.Err(fn(this.#err));
601
+ return ExperimentalResult.Ok(this.#val);
602
+ }
603
+ /**
604
+ * Transforms the error value using an async function.
605
+ *
606
+ * Same as `mapErr` but for async error transformations.
607
+ * Returns `Promise<Result<T, E2>>`.
608
+ *
609
+ * @param fn - Async function to transform the error
610
+ * @returns Promise resolving to Result<T, E2> with transformed error or original Ok
611
+ *
612
+ * @example
613
+ * ```ts
614
+ * await ExperimentalResult.Err("timeout").mapErrAsync(async (e) => await formatError(e));
615
+ * // Promise<Err("Timeout occurred: timeout")>
616
+ * ```
617
+ *
618
+ * @see mapErr
619
+ */
620
+ async mapErrAsync(fn) {
621
+ if (this.isErr()) return fn(this.#err).then((e) => ExperimentalResult.Err(e));
622
+ return ExperimentalResult.Ok(this.#val);
623
+ }
624
+ mapBoth(fnOk, fnErr) {
625
+ if (this.isErr()) return ExperimentalResult.Err(fnErr(this.#err));
626
+ return ExperimentalResult.Ok(fnOk(this.#val));
627
+ }
628
+ /**
629
+ * Transforms both the success value and error value using async functions.
630
+ *
631
+ * Same as `mapBoth` but for async transformations.
632
+ * Returns `Promise<Result<T2, E2>>`.
633
+ *
634
+ * @param fnOk - Async function to transform the success value
635
+ * @param fnErr - Async function to transform the error
636
+ * @returns Promise resolving to Result<T2, E2> with transformed value or error
637
+ *
638
+ * @example
639
+ * ```ts
640
+ * await ExperimentalResult.Ok(42).mapBothAsync(
641
+ * async (val) => await formatSuccess(val),
642
+ * async (err) => await formatError(err)
643
+ * );
644
+ * // Promise<Ok("Success: 42")>
645
+ * ```
646
+ *
647
+ * @see mapBoth
648
+ */
649
+ async mapBothAsync(fnOk, fnErr) {
650
+ if (this.isErr()) return fnErr(this.#err).then((e) => ExperimentalResult.Err(e));
651
+ return fnOk(this.#val).then((v) => ExperimentalResult.Ok(v));
652
+ }
653
+ /**
654
+ * Recovers from an error by providing a fallback Result.
655
+ *
656
+ * If the Result is Ok, returns it unchanged. If Err, calls the function
657
+ * with the error to produce a new Result.
658
+ *
659
+ * For async recovery, use `orElseAsync` instead.
660
+ *
661
+ * @param fn - Function that receives the error and returns a fallback Result
662
+ * @returns Result<T, E2> - original Ok or fallback Result from fn
663
+ *
664
+ * @example
665
+ * ```ts
666
+ * // Recovery with fallback
667
+ * fetchFromPrimary()
668
+ * .orElse((e) => fetchFromBackup())
669
+ * .orElse((e) => ExperimentalResult.Ok(defaultValue));
670
+ *
671
+ * // Ok passes through unchanged
672
+ * ExperimentalResult.Ok(42).orElse((e) => ExperimentalResult.Ok(0)); // Ok(42)
673
+ *
674
+ * // Err triggers recovery
675
+ * ExperimentalResult.Err("not found").orElse((e) => ExperimentalResult.Ok(0)); // Ok(0)
676
+ * ExperimentalResult.Err("fail").orElse((e) => ExperimentalResult.Err("critical")); // Err("critical")
677
+ * ```
678
+ *
679
+ * @see orElseAsync
680
+ */
681
+ orElse(fn) {
682
+ if (this.isOk()) return this;
683
+ return fn(this.#err);
684
+ }
685
+ /**
686
+ * Recovers from an error by providing a fallback async Result.
687
+ *
688
+ * Same as `orElse` but for async Result-returning functions.
689
+ * Returns `Promise<Result<T, E2>>`.
690
+ *
691
+ * @param fn - Async function that receives the error and returns a Promise resolving to fallback Result
692
+ * @returns Promise resolving to Result<T, E2> - original Ok or fallback Result from fn
693
+ *
694
+ * @example
695
+ * ```ts
696
+ * await fetchData().orElseAsync(async (e) => {
697
+ * return await fetchBackupData();
698
+ * });
699
+ * ```
700
+ *
701
+ * @see orElse
702
+ */
703
+ async orElseAsync(fn) {
704
+ if (this.isOk()) return this;
705
+ return fn(this.#err);
706
+ }
707
+ validate(validators) {
708
+ if (this.isErr()) return this;
709
+ const baseVal = this.#val;
710
+ const results = validators.map((v) => v(baseVal));
711
+ if (results.some((r) => isPromiseLike(r))) return Promise.all(results).then((resolved) => {
712
+ const errs = [];
713
+ for (const r of resolved) if (r.isErr()) errs.push(r.unwrapErr());
714
+ if (errs.length > 0) return ExperimentalResult.Err(errs);
715
+ return this;
716
+ });
717
+ const syncResults = results;
718
+ const errs = [];
719
+ for (const r of syncResults) if (r.isErr()) errs.push(r.#err);
720
+ if (errs.length > 0) return ExperimentalResult.Err(errs);
721
+ return this;
722
+ }
723
+ /**
724
+ * Runs async validators on the Ok value, collecting ALL errors.
725
+ *
726
+ * Explicit async variant of `validate` for when all validators are async.
727
+ * Always returns `Promise<Result<T, E | VE[]>>`.
728
+ *
729
+ * @param validators - Array of async validator functions
730
+ * @returns Promise resolving to Result<T, E | VE[]> with original value or array of all errors
731
+ *
732
+ * @example
733
+ * ```ts
734
+ * // Form validation with async checks
735
+ * const validated = await ExperimentalResult.Ok(formData).validateAsync([
736
+ * async (d) => await checkEmailUnique(d.email),
737
+ * async (d) => await checkUsernameAvailable(d.username),
738
+ * ]);
739
+ *
740
+ * // Password validation against database
741
+ * await ExperimentalResult.Ok("password123!").validateAsync([
742
+ * async (pw) => await checkNotPreviousPassword(pw),
743
+ * async (pw) => await checkNotCommonPassword(pw),
744
+ * ]);
745
+ * ```
746
+ *
747
+ * @see validate
748
+ */
749
+ async validateAsync(validators) {
750
+ if (this.isErr()) return this;
751
+ const baseVal = this.#val;
752
+ return Promise.all(validators.map((v) => v(baseVal))).then((resolved) => {
753
+ const errs = [];
754
+ for (const r of resolved) if (r.isErr()) errs.push(r.#err);
755
+ if (errs.length > 0) return ExperimentalResult.Err(errs);
756
+ return this;
757
+ });
758
+ }
759
+ /**
760
+ * Combines multiple Results, collecting all values or all errors.
761
+ *
762
+ * Unlike typical Result behavior which short-circuits on first error,
763
+ * `all` collects ALL errors from all Results. This is useful when you
764
+ * want to show complete validation feedback.
765
+ *
766
+ * - All Ok → `Ok([...values])` with preserved tuple types
767
+ * - Any Err → `Err([...errors])` collecting ALL errors
768
+ *
769
+ * @param results - Variable number of Results to combine
770
+ * @returns Result with tuple of all values, or array of all errors
771
+ *
772
+ * @example
773
+ * ```ts
774
+ * ExperimentalResult.all(ExperimentalResult.Ok(1), ExperimentalResult.Ok(2), ExperimentalResult.Ok(3)); // Ok([1, 2, 3])
775
+ * ExperimentalResult.all(ExperimentalResult.Ok(1), ExperimentalResult.Err("a"), ExperimentalResult.Err("b")); // Err(["a", "b"])
776
+ * ExperimentalResult.all(); // Ok([])
777
+ *
778
+ * // Real-world: Parallel validation
779
+ * const [user, posts, likes] = await Promise.all([
780
+ * fetchUser(id),
781
+ * fetchPosts(id),
782
+ * fetchLikes(id),
783
+ * ]);
784
+ *
785
+ * const combined = ExperimentalResult.all(user, posts, likes);
786
+ * // Ok([User, Post[], Like[]]) or Err([...errors])
787
+ * ```
788
+ *
789
+ * @see any
790
+ * @see validate
791
+ */
792
+ static all(...results) {
793
+ const vals = [];
794
+ const errs = [];
795
+ for (const r of results) if (r.isErr()) errs.push(r.unwrapErr());
796
+ else vals.push(r.unwrap());
797
+ if (errs.length > 0) return ExperimentalResult.Err(errs);
798
+ return ExperimentalResult.Ok(vals);
799
+ }
800
+ /**
801
+ * Returns the first Ok, or collects all errors if all are Err.
802
+ *
803
+ * Useful for fallback chains where you want the first success, but want
804
+ * to collect all errors if everything fails.
805
+ *
806
+ * - First Ok → Returns that Ok immediately
807
+ * - All Err → `Err([...all errors])`
808
+ *
809
+ * @param results - Variable number of Results to check
810
+ * @returns First Ok found, or Err with array of all errors
811
+ *
812
+ * @example
813
+ * ```ts
814
+ * ExperimentalResult.any(
815
+ * ExperimentalResult.Err("Error 1"),
816
+ * ExperimentalResult.Ok("First success"),
817
+ * ExperimentalResult.Ok("Second success"),
818
+ * ); // Ok("First success")
819
+ *
820
+ * ExperimentalResult.any(
821
+ * ExperimentalResult.Err("Error 1"),
822
+ * ExperimentalResult.Err("Error 2"),
823
+ * ExperimentalResult.Err("Error 3"),
824
+ * ); // Err(["Error 1", "Error 2", "Error 3"])
825
+ *
826
+ * // Fallback chain
827
+ * ExperimentalResult.any(
828
+ * fetchFromCache(key),
829
+ * fetchFromDb(key),
830
+ * fetchFromRemote(key),
831
+ * );
832
+ * ```
833
+ *
834
+ * @see all
835
+ */
836
+ static any(...results) {
837
+ for (const r of results) if (r.isOk()) return r;
838
+ return ExperimentalResult.Err(results.map((r) => r.unwrapErr()));
839
+ }
840
+ tap(fn) {
841
+ if (this.isOk()) fn(this.#val);
842
+ return this;
843
+ }
844
+ /**
845
+ * Executes an async side effect function for Ok values, then returns self.
846
+ *
847
+ * Same as `tap` but for async side effect functions.
848
+ * Returns `Promise<Result<T, E>>`.
849
+ *
850
+ * @param fn - Async function to execute with the Ok value
851
+ * @returns Promise resolving to the same Result (chainable)
852
+ *
853
+ * @example
854
+ * ```ts
855
+ * await ExperimentalResult.Ok(user)
856
+ * .tapAsync(async (u) => await logAuditTrail(u))
857
+ * .map((u) => u.id);
858
+ * ```
859
+ *
860
+ * @see tap
861
+ */
862
+ async tapAsync(fn) {
863
+ if (this.isOk()) await fn(this.#val);
864
+ return this;
865
+ }
866
+ /**
867
+ * Executes a side effect function for Err values, then returns self.
868
+ *
869
+ * Useful for logging errors or executing cleanup without breaking the chain.
870
+ * The function is only called if the Result is Err.
871
+ *
872
+ * For async side effects, use `tapErrAsync` instead.
873
+ *
874
+ * @param fn - Function to execute with the error
875
+ * @returns The same Result (chainable)
876
+ *
877
+ * @example
878
+ * ```ts
879
+ * ExperimentalResult.Err("Connection failed")
880
+ * .tapErr((err) => console.error(`[Error Log] ${new Date().toISOString()}: ${err}`))
881
+ * .orElse((e) => ExperimentalResult.Ok(defaultValue));
882
+ * // Logs error timestamp
883
+ * // Returns: Ok(defaultValue)
884
+ *
885
+ * // Ok - tapErr does nothing
886
+ * ExperimentalResult.Ok(42).tapErr((e) => console.log(e)); // Ok(42)
887
+ * ```
888
+ *
889
+ * @see tapErrAsync
890
+ * @see tap
891
+ */
892
+ tapErr(fn) {
893
+ if (this.isErr()) fn(this.#err);
894
+ return this;
895
+ }
896
+ /**
897
+ * Executes an async side effect function for Err values, then returns self.
898
+ *
899
+ * Same as `tapErr` but for async side effect functions.
900
+ * Returns `Promise<Result<T, E>>`.
901
+ *
902
+ * @param fn - Async function to execute with the error
903
+ * @returns Promise resolving to the same Result (chainable)
904
+ *
905
+ * @example
906
+ * ```ts
907
+ * await ExperimentalResult.Err("API error")
908
+ * .tapErrAsync(async (e) => await reportToSentry(e))
909
+ * .orElse((e) => ExperimentalResult.Ok(backupData));
910
+ * ```
911
+ *
912
+ * @see tapErr
913
+ */
914
+ async tapErrAsync(fn) {
915
+ if (this.isErr()) await fn(this.#err);
916
+ return this;
917
+ }
918
+ /**
919
+ * Swaps the Ok and Err states, turning success into failure and vice versa.
920
+ *
921
+ * Useful for inverting the meaning of a Result, such as converting
922
+ * validation errors to successes and valid values to errors.
923
+ *
924
+ * @returns Result<E, T> with swapped states
925
+ *
926
+ * @example
927
+ * ```ts
928
+ * ExperimentalResult.Ok("Success value").flip(); // Err("Success value")
929
+ * ExperimentalResult.Err("Error value").flip(); // Ok("Error value")
930
+ *
931
+ * // Invert validation (fail if value is in blacklist)
932
+ * const blacklist = ["admin", "root"];
933
+ * const isBlacklisted = (name: string) =>
934
+ * ExperimentalResult.fromPredicate(name, (n) => !blacklist.includes(n), "blacklisted")
935
+ * .flip(); // Ok if blacklisted, Err if not
936
+ * ```
937
+ */
938
+ flip() {
939
+ if (this.isErr()) return ExperimentalResult.Ok(this.#err);
940
+ return ExperimentalResult.Err(this.#val);
941
+ }
942
+ /**
943
+ * Converts Result to Option, discarding error information.
944
+ *
945
+ * - Ok(value) → Some(value)
946
+ * - Err(error) → None
947
+ *
948
+ * Use when you only care about presence/absence of a value, not the error.
949
+ *
950
+ * @returns Option<T> - Some if Ok, None if Err
951
+ *
952
+ * @example
953
+ * ```ts
954
+ * ExperimentalResult.Ok(42).toOption(); // Some(42)
955
+ * ExperimentalResult.Err("fail").toOption(); // None
956
+ *
957
+ * // Safe user lookup
958
+ * const userOpt = fetchUser(id).toOption();
959
+ * // User or None, regardless of why fetch failed
960
+ * ```
961
+ *
962
+ * @see Option.toResult
963
+ */
964
+ toOption() {
965
+ if (this.isErr()) return ExperimentalOption.None;
966
+ return ExperimentalOption.Some(this.#val);
967
+ }
968
+ /**
969
+ * Maps over array elements inside a Result<Array<T>, E>.
970
+ *
971
+ * Applies the mapper function to each element if the Result is Ok and
972
+ * contains an array. Propagates Err unchanged.
973
+ *
974
+ * @param mapper - Function to map over each array element
975
+ * @returns Result<Array<Out>, E> with mapped array or propagated error
976
+ * @throws Error if the Result is Ok but value is not an array
977
+ *
978
+ * @example
979
+ * ```ts
980
+ * ExperimentalResult.Ok([1, 2, 3]).innerMap((x) => x * 2); // Ok([2, 4, 6])
981
+ * ExperimentalResult.Err("fail").innerMap((x) => x * 2); // Err("fail")
982
+ * ```
983
+ */
984
+ innerMap(mapper) {
985
+ if (this.isErr()) return this;
986
+ if (Array.isArray(this.#val)) return new ExperimentalResult(this.#val.map(mapper), this.#err, "Ok");
987
+ throw new Error("Can only be called for Result<Array<T>, E>");
988
+ }
989
+ /**
990
+ * Makes Result iterable for use with generator-based syntax.
991
+ * Yields self and returns the unwrapped value when resumed.
992
+ *
993
+ * @example
994
+ * ```ts
995
+ * const result = ExperimentalResult.gen(function* () {
996
+ * const value = yield* ExperimentalResult.Ok(42);
997
+ * return value * 2;
998
+ * });
999
+ * ```
1000
+ */
1001
+ *[Symbol.iterator]() {
1002
+ const trace = (/* @__PURE__ */ new Error()).stack;
1003
+ return yield new CapturedTrace(this, trace);
1004
+ }
1005
+ /**
1006
+ * Makes Result iterable for use with async generator-based syntax.
1007
+ * Yields self and returns the unwrapped value when resumed.
1008
+ *
1009
+ * @example
1010
+ * ```ts
1011
+ * const result = await ExperimentalResult.asyncGen(async function* () {
1012
+ * const value = yield* ExperimentalResult.Ok(42);
1013
+ * return value * 2;
1014
+ * });
1015
+ * ```
1016
+ */
1017
+ async *[Symbol.asyncIterator]() {
1018
+ const trace = (/* @__PURE__ */ new Error()).stack;
1019
+ return yield new CapturedTrace(this, trace);
1020
+ }
1021
+ /**
1022
+ * Creates an ExperimentalResult from a nullable value.
1023
+ * Returns Err(error) for null/undefined, otherwise Ok(non-null value).
1024
+ */
1025
+ static fromNullable(val, error) {
1026
+ return val === null || val === void 0 ? ExperimentalResult.Err(error) : ExperimentalResult.Ok(val);
1027
+ }
1028
+ /** Create Result based on predicate result */
1029
+ static fromPredicate(val, pred, error) {
1030
+ return pred(val) ? ExperimentalResult.Ok(val) : ExperimentalResult.Err(error);
1031
+ }
1032
+ /** Catches sync exceptions */
1033
+ static tryCatch(fn, errorMapper) {
1034
+ try {
1035
+ return ExperimentalResult.Ok(fn());
1036
+ } catch (e) {
1037
+ return ExperimentalResult.Err(errorMapper ? errorMapper(e) : e);
1038
+ }
1039
+ }
1040
+ /** Catches async exceptions - returns Promise<Result<T, E>> */
1041
+ static async tryAsyncCatch(fn, errorMapper) {
1042
+ try {
1043
+ return ExperimentalResult.Ok(await fn());
1044
+ } catch (e) {
1045
+ return ExperimentalResult.Err(errorMapper ? errorMapper(e) : e);
1046
+ }
1047
+ }
1048
+ /**
1049
+ * Generator-based syntax for chaining Result operations (simplified, no adapter).
1050
+ * Provides imperative-style code while maintaining functional error handling.
1051
+ *
1052
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
1053
+ * recursion to avoid stack overflow on deep chains.
1054
+ *
1055
+ * @example
1056
+ * ```ts
1057
+ * const result = ExperimentalResult.gen(function* () {
1058
+ * const a = yield* ExperimentalResult.Ok(1);
1059
+ * const b = yield* ExperimentalResult.Ok(2);
1060
+ * return a + b;
1061
+ * });
1062
+ * // Result<number, never>
1063
+ * ```
1064
+ */
1065
+ static gen(genFn) {
1066
+ const iterator = genFn();
1067
+ let nextArg;
1068
+ let currentResult;
1069
+ while (true) {
1070
+ const next = iterator.next(nextArg);
1071
+ if (next.done) {
1072
+ currentResult = ExperimentalResult.Ok(next.value);
1073
+ break;
1074
+ }
1075
+ let yielded = next.value;
1076
+ let stack;
1077
+ if (isCapturedTrace(yielded)) {
1078
+ stack = yielded.stack;
1079
+ yielded = yielded.value;
1080
+ }
1081
+ if (yielded.isErr()) {
1082
+ const err = yielded.unwrapErr();
1083
+ if (stack && err instanceof Error) {
1084
+ const stackLines = stack.split("\n");
1085
+ if (stackLines.length > 2) {
1086
+ const userStack = stackLines.slice(2).join("\n");
1087
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1088
+ }
1089
+ }
1090
+ iterator.return?.(void 0);
1091
+ currentResult = yielded;
1092
+ break;
1093
+ }
1094
+ nextArg = yielded.unwrap();
1095
+ }
1096
+ return currentResult;
1097
+ }
1098
+ /**
1099
+ * Generator-based syntax for chaining Result operations (with adapter).
1100
+ * Uses an adapter function ($) for improved type inference.
1101
+ *
1102
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
1103
+ * recursion to avoid stack overflow on deep chains.
1104
+ *
1105
+ * @example
1106
+ * ```ts
1107
+ * const result = ExperimentalResult.genAdapter(function* ($) {
1108
+ * const a = yield* $(ExperimentalResult.Ok(1));
1109
+ * const b = yield* $(ExperimentalResult.Ok(2));
1110
+ * return a + b;
1111
+ * });
1112
+ * // Result<number, never>
1113
+ * ```
1114
+ */
1115
+ static genAdapter(genFn) {
1116
+ const adapter = (result) => new ResultYieldWrap(result);
1117
+ const iterator = genFn(adapter);
1118
+ let nextArg;
1119
+ let currentResult;
1120
+ while (true) {
1121
+ const next = iterator.next(nextArg);
1122
+ if (next.done) {
1123
+ currentResult = ExperimentalResult.Ok(next.value);
1124
+ break;
1125
+ }
1126
+ const wrapped = next.value;
1127
+ let result = wrapped.result;
1128
+ let stack;
1129
+ if (isCapturedTrace(wrapped)) {
1130
+ stack = wrapped.stack;
1131
+ result = wrapped.value.result;
1132
+ }
1133
+ if (result.isErr()) {
1134
+ const err = result.unwrapErr();
1135
+ if (stack && err instanceof Error) {
1136
+ const stackLines = stack.split("\n");
1137
+ if (stackLines.length > 2) {
1138
+ const userStack = stackLines.slice(2).join("\n");
1139
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1140
+ }
1141
+ }
1142
+ iterator.return?.(void 0);
1143
+ currentResult = result;
1144
+ break;
1145
+ }
1146
+ nextArg = result.unwrap();
1147
+ }
1148
+ return currentResult;
1149
+ }
1150
+ /**
1151
+ * Async generator-based syntax for chaining Result operations (simplified, no adapter).
1152
+ * Use yield* with Result values directly. For Promise<Result<T, E>>, await first then yield*.
1153
+ *
1154
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
1155
+ * recursion to avoid stack overflow on deep chains.
1156
+ *
1157
+ * @example
1158
+ * ```ts
1159
+ * const fetchData = async (
1160
+ * id: number,
1161
+ * ): Promise<ExperimentalResult<{ id: number }, string>> =>
1162
+ * ExperimentalResult.Ok({ id });
1163
+ * const result = await ExperimentalResult.asyncGen(async function* () {
1164
+ * const a = yield* ExperimentalResult.Ok(1);
1165
+ * const dataResult = yield* (await fetchData(a));
1166
+ * return a + dataResult.id;
1167
+ * });
1168
+ * // ExperimentalResult<number, string>
1169
+ * ```
1170
+ */
1171
+ static async asyncGen(genFn) {
1172
+ const iterator = genFn();
1173
+ let nextArg;
1174
+ let currentResult;
1175
+ while (true) {
1176
+ const next = await iterator.next(nextArg);
1177
+ if (next.done) {
1178
+ currentResult = ExperimentalResult.Ok(next.value);
1179
+ break;
1180
+ }
1181
+ let result = next.value;
1182
+ let stack;
1183
+ if (isCapturedTrace(result)) {
1184
+ stack = result.stack;
1185
+ result = result.value;
1186
+ }
1187
+ if (result.isErr()) {
1188
+ const err = result.unwrapErr();
1189
+ if (stack && err instanceof Error) {
1190
+ const stackLines = stack.split("\n");
1191
+ if (stackLines.length > 2) {
1192
+ const userStack = stackLines.slice(2).join("\n");
1193
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1194
+ }
1195
+ }
1196
+ await iterator.return?.(void 0);
1197
+ currentResult = result;
1198
+ break;
1199
+ }
1200
+ nextArg = result.unwrap();
1201
+ }
1202
+ return currentResult;
1203
+ }
1204
+ /**
1205
+ * Async generator-based syntax for chaining Result operations (with adapter).
1206
+ * Uses an adapter function ($) for improved type inference.
1207
+ * Supports both Result<T, E> and Promise<Result<T, E>> for flexibility.
1208
+ *
1209
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
1210
+ * recursion to avoid stack overflow on deep chains.
1211
+ *
1212
+ * @example
1213
+ * ```ts
1214
+ * const fetchData = async (
1215
+ * id: number,
1216
+ * ): Promise<ExperimentalResult<{ id: number }, string>> =>
1217
+ * ExperimentalResult.Ok({ id });
1218
+ * const result = await ExperimentalResult.asyncGenAdapter(async function* ($) {
1219
+ * const a = yield* $(ExperimentalResult.Ok(1));
1220
+ * const data = yield* $(fetchData(a));
1221
+ * return a + data.id;
1222
+ * });
1223
+ * // ExperimentalResult<number, string>
1224
+ * ```
1225
+ */
1226
+ static async asyncGenAdapter(genFn) {
1227
+ const adapter = (result) => new AsyncResultYieldWrap(Promise.resolve(result));
1228
+ const iterator = genFn(adapter);
1229
+ let nextArg;
1230
+ let currentResult;
1231
+ while (true) {
1232
+ const next = await iterator.next(nextArg);
1233
+ if (next.done) {
1234
+ currentResult = ExperimentalResult.Ok(next.value);
1235
+ break;
1236
+ }
1237
+ const wrapped = next.value;
1238
+ let result;
1239
+ let stack;
1240
+ if (isCapturedTrace(wrapped)) {
1241
+ stack = wrapped.stack;
1242
+ result = await wrapped.value.result;
1243
+ } else result = await wrapped.result;
1244
+ if (result.isErr()) {
1245
+ const err = result.unwrapErr();
1246
+ if (stack && err instanceof Error) {
1247
+ const stackLines = stack.split("\n");
1248
+ if (stackLines.length > 2) {
1249
+ const userStack = stackLines.slice(2).join("\n");
1250
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1251
+ }
1252
+ }
1253
+ await iterator.return?.(void 0);
1254
+ currentResult = result;
1255
+ break;
1256
+ }
1257
+ nextArg = result.unwrap();
1258
+ }
1259
+ return currentResult;
1260
+ }
1261
+ };
1262
+
1263
+ //#endregion
1264
+ export { ExperimentalResult };
1265
+ //# sourceMappingURL=result-experimental.mjs.map