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