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