@carbonteq/fp 0.8.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/README.md +718 -95
  2. package/dist/errors.cjs +20 -0
  3. package/dist/errors.cjs.map +1 -0
  4. package/dist/errors.d.cts +10 -0
  5. package/dist/errors.d.cts.map +1 -0
  6. package/dist/errors.d.mts +10 -0
  7. package/dist/errors.d.mts.map +1 -0
  8. package/dist/errors.mjs +17 -0
  9. package/dist/errors.mjs.map +1 -0
  10. package/dist/flow-experimental.cjs +286 -0
  11. package/dist/flow-experimental.cjs.map +1 -0
  12. package/dist/flow-experimental.d.cts +69 -0
  13. package/dist/flow-experimental.d.cts.map +1 -0
  14. package/dist/flow-experimental.d.mts +69 -0
  15. package/dist/flow-experimental.d.mts.map +1 -0
  16. package/dist/flow-experimental.mjs +284 -0
  17. package/dist/flow-experimental.mjs.map +1 -0
  18. package/dist/flow.cjs +296 -0
  19. package/dist/flow.cjs.map +1 -0
  20. package/dist/flow.d.cts +79 -0
  21. package/dist/flow.d.cts.map +1 -0
  22. package/dist/flow.d.mts +79 -0
  23. package/dist/flow.d.mts.map +1 -0
  24. package/dist/flow.mjs +294 -0
  25. package/dist/flow.mjs.map +1 -0
  26. package/dist/index.cjs +28 -7
  27. package/dist/index.d.cts +11 -5
  28. package/dist/index.d.mts +11 -0
  29. package/dist/index.mjs +12 -0
  30. package/dist/match.cjs +294 -3
  31. package/dist/match.cjs.map +1 -0
  32. package/dist/match.d.cts +481 -5
  33. package/dist/match.d.cts.map +1 -0
  34. package/dist/match.d.mts +481 -0
  35. package/dist/match.d.mts.map +1 -0
  36. package/dist/match.mjs +287 -0
  37. package/dist/match.mjs.map +1 -0
  38. package/dist/option-experimental.cjs +1503 -0
  39. package/dist/option-experimental.cjs.map +1 -0
  40. package/dist/option-experimental.d.cts +1383 -0
  41. package/dist/option-experimental.d.cts.map +1 -0
  42. package/dist/option-experimental.d.mts +1383 -0
  43. package/dist/option-experimental.d.mts.map +1 -0
  44. package/dist/option-experimental.mjs +1501 -0
  45. package/dist/option-experimental.mjs.map +1 -0
  46. package/dist/option.cjs +806 -4
  47. package/dist/option.cjs.map +1 -0
  48. package/dist/option.d.cts +580 -3
  49. package/dist/option.d.cts.map +1 -0
  50. package/dist/option.d.mts +580 -0
  51. package/dist/option.d.mts.map +1 -0
  52. package/dist/option.mjs +805 -0
  53. package/dist/option.mjs.map +1 -0
  54. package/dist/result-experimental.cjs +1266 -0
  55. package/dist/result-experimental.cjs.map +1 -0
  56. package/dist/result-experimental.d.cts +1127 -0
  57. package/dist/result-experimental.d.cts.map +1 -0
  58. package/dist/result-experimental.d.mts +1127 -0
  59. package/dist/result-experimental.d.mts.map +1 -0
  60. package/dist/result-experimental.mjs +1265 -0
  61. package/dist/result-experimental.mjs.map +1 -0
  62. package/dist/result.cjs +1077 -5
  63. package/dist/result.cjs.map +1 -0
  64. package/dist/result.d.cts +833 -3
  65. package/dist/result.d.cts.map +1 -0
  66. package/dist/result.d.mts +833 -0
  67. package/dist/result.d.mts.map +1 -0
  68. package/dist/result.mjs +1077 -0
  69. package/dist/result.mjs.map +1 -0
  70. package/dist/tuple.cjs +3 -0
  71. package/dist/tuple.cjs.map +1 -1
  72. package/dist/tuple.d.cts +5 -2
  73. package/dist/tuple.d.cts.map +1 -1
  74. package/dist/tuple.d.mts +15 -0
  75. package/dist/tuple.d.mts.map +1 -0
  76. package/dist/{tuple.js → tuple.mjs} +3 -1
  77. package/dist/tuple.mjs.map +1 -0
  78. package/dist/unit.cjs +8 -2
  79. package/dist/unit.cjs.map +1 -0
  80. package/dist/unit.d.cts +8 -2
  81. package/dist/unit.d.cts.map +1 -0
  82. package/dist/unit.d.mts +8 -0
  83. package/dist/unit.d.mts.map +1 -0
  84. package/dist/unit.mjs +7 -0
  85. package/dist/unit.mjs.map +1 -0
  86. package/dist/utils.cjs +24 -0
  87. package/dist/utils.cjs.map +1 -0
  88. package/dist/utils.d.cts +14 -0
  89. package/dist/utils.d.cts.map +1 -0
  90. package/dist/utils.d.mts +14 -0
  91. package/dist/utils.d.mts.map +1 -0
  92. package/dist/utils.mjs +20 -0
  93. package/dist/utils.mjs.map +1 -0
  94. package/examples/README.md +46 -0
  95. package/examples/flow/01-basics.ts +74 -0
  96. package/examples/flow/02-async.ts +73 -0
  97. package/examples/flow/03-recovery.ts +60 -0
  98. package/examples/flow/04-complex-backend.ts +237 -0
  99. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  100. package/examples/flow/index.ts +13 -0
  101. package/examples/flow-experimental/01-basics.ts +78 -0
  102. package/examples/flow-experimental/02-async.ts +77 -0
  103. package/examples/flow-experimental/03-recovery.ts +93 -0
  104. package/examples/flow-experimental/04-complex-backend.ts +241 -0
  105. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  106. package/examples/flow-experimental/index.ts +14 -0
  107. package/examples/match/01-stable-match.ts +147 -0
  108. package/examples/match/index.ts +19 -0
  109. package/examples/match-experimental/01-experimental-match.ts +150 -0
  110. package/examples/match-experimental/index.ts +18 -0
  111. package/examples/option/01-basics.ts +16 -0
  112. package/examples/option/02-map-flatMap.ts +36 -0
  113. package/examples/option/03-zip-flatZip.ts +23 -0
  114. package/examples/option/04-constructors.ts +21 -0
  115. package/examples/option/05-transform.ts +15 -0
  116. package/examples/option/06-aggregation.ts +14 -0
  117. package/examples/option/index.ts +49 -0
  118. package/examples/option-experimental/01-map.ts +109 -0
  119. package/examples/option-experimental/02-flatMap.ts +234 -0
  120. package/examples/option-experimental/03-zip.ts +197 -0
  121. package/examples/option-experimental/04-flatZip.ts +251 -0
  122. package/examples/option-experimental/05-gen.ts +360 -0
  123. package/examples/option-experimental/06-genAdapter.ts +463 -0
  124. package/examples/option-experimental/07-asyncGen.ts +353 -0
  125. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  126. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  127. package/examples/option-experimental/10-workflow-async.ts +378 -0
  128. package/examples/option-experimental/index.ts +341 -0
  129. package/examples/option-experimental/shared-domain.ts +325 -0
  130. package/examples/result/01-basics.ts +16 -0
  131. package/examples/result/02-map-flatMap.ts +34 -0
  132. package/examples/result/03-zip-flatZip.ts +23 -0
  133. package/examples/result/04-validation.ts +44 -0
  134. package/examples/result/05-constructors.ts +30 -0
  135. package/examples/result/06-utilities.ts +36 -0
  136. package/examples/result/index.ts +53 -0
  137. package/examples/result-experimental/01-map.ts +60 -0
  138. package/examples/result-experimental/02-flatMap.ts +169 -0
  139. package/examples/result-experimental/03-zip.ts +145 -0
  140. package/examples/result-experimental/04-flatZip.ts +252 -0
  141. package/examples/result-experimental/05-gen.ts +293 -0
  142. package/examples/result-experimental/06-genAdapter.ts +396 -0
  143. package/examples/result-experimental/07-asyncGen.ts +379 -0
  144. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  145. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  146. package/examples/result-experimental/10-workflow-async.ts +356 -0
  147. package/examples/result-experimental/index.ts +312 -0
  148. package/examples/result-experimental/shared-domain.ts +263 -0
  149. package/package.json +120 -48
  150. package/dist/chunk-CUT6urMc.cjs +0 -30
  151. package/dist/index.d.ts +0 -5
  152. package/dist/index.js +0 -6
  153. package/dist/match-BQP0RNSk.js +0 -13
  154. package/dist/match-BQP0RNSk.js.map +0 -1
  155. package/dist/match-COIWq-e8.d.cts +0 -18
  156. package/dist/match-COIWq-e8.d.cts.map +0 -1
  157. package/dist/match-DXKW7ym5.d.ts +0 -18
  158. package/dist/match-DXKW7ym5.d.ts.map +0 -1
  159. package/dist/match-DyAuOeqx.cjs +0 -25
  160. package/dist/match-DyAuOeqx.cjs.map +0 -1
  161. package/dist/match.d.ts +0 -5
  162. package/dist/match.js +0 -3
  163. package/dist/option-8_eiz02z.d.cts +0 -45
  164. package/dist/option-8_eiz02z.d.cts.map +0 -1
  165. package/dist/option-Be_DXVE6.js +0 -181
  166. package/dist/option-Be_DXVE6.js.map +0 -1
  167. package/dist/option-CoelyMEg.d.ts +0 -45
  168. package/dist/option-CoelyMEg.d.ts.map +0 -1
  169. package/dist/option-DHCdfOco.cjs +0 -193
  170. package/dist/option-DHCdfOco.cjs.map +0 -1
  171. package/dist/option.d.ts +0 -3
  172. package/dist/option.js +0 -4
  173. package/dist/result-CdGWA5IL.js +0 -318
  174. package/dist/result-CdGWA5IL.js.map +0 -1
  175. package/dist/result-DsVjSFnO.d.ts +0 -132
  176. package/dist/result-DsVjSFnO.d.ts.map +0 -1
  177. package/dist/result-Dy_C5dC6.d.cts +0 -132
  178. package/dist/result-Dy_C5dC6.d.cts.map +0 -1
  179. package/dist/result-nuhyCRyu.cjs +0 -336
  180. package/dist/result-nuhyCRyu.cjs.map +0 -1
  181. package/dist/result.d.ts +0 -3
  182. package/dist/result.js +0 -4
  183. package/dist/tuple.d.ts +0 -12
  184. package/dist/tuple.d.ts.map +0 -1
  185. package/dist/tuple.js.map +0 -1
  186. package/dist/unit-CnjFzJN1.cjs +0 -12
  187. package/dist/unit-CnjFzJN1.cjs.map +0 -1
  188. package/dist/unit-CoBLIJFc.d.ts +0 -9
  189. package/dist/unit-CoBLIJFc.d.ts.map +0 -1
  190. package/dist/unit-D0y_qAUW.d.cts +0 -9
  191. package/dist/unit-D0y_qAUW.d.cts.map +0 -1
  192. package/dist/unit-udy5j53P.js +0 -6
  193. package/dist/unit-udy5j53P.js.map +0 -1
  194. package/dist/unit.d.ts +0 -2
  195. package/dist/unit.js +0 -3
@@ -0,0 +1,1501 @@
1
+ import { UNIT } from "./unit.mjs";
2
+ import { CapturedTrace, isCapturedTrace, isPromiseLike } from "./utils.mjs";
3
+ import { ExperimentalResult } from "./result-experimental.mjs";
4
+
5
+ //#region src/option-experimental.ts
6
+ /**
7
+ * Error thrown when attempting to unwrap a `None` value.
8
+ *
9
+ * This exception is thrown by {@link ExperimentalOption.unwrap} when called on a `None`.
10
+ * It represents a programmer error - you should only call `unwrap()` when
11
+ * you are certain the ExperimentalOption contains a value, or use safe alternatives
12
+ * like {@link ExperimentalOption.unwrapOr} or {@link ExperimentalOption.safeUnwrap}.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * try {
17
+ * ExperimentalOption.None.unwrap();
18
+ * } catch (e) {
19
+ * e instanceof UnwrappedNone // true
20
+ * e.name // "UnwrapError"
21
+ * }
22
+ * ```
23
+ */
24
+ var UnwrappedNone = class extends Error {
25
+ name = "UnwrapError";
26
+ constructor() {
27
+ super("Attempted to unwrap ExperimentalOption::None");
28
+ }
29
+ };
30
+ const UNWRAPPED_NONE_ERR = new UnwrappedNone();
31
+ const NONE_VAL = Symbol("ExperimentalOption::None");
32
+ /**
33
+ * Wrapper that makes ExperimentalOption yieldable with proper type tracking.
34
+ *
35
+ * @internal
36
+ */
37
+ var OptionYieldWrap = class {
38
+ constructor(option) {
39
+ this.option = option;
40
+ }
41
+ *[Symbol.iterator]() {
42
+ return yield this;
43
+ }
44
+ };
45
+ /**
46
+ * Wrapper that makes ExperimentalOption yieldable in async generators with proper type tracking.
47
+ *
48
+ * @internal
49
+ */
50
+ var AsyncOptionYieldWrap = class {
51
+ option;
52
+ constructor(option) {
53
+ this.option = isPromiseLike(option) ? option : Promise.resolve(option);
54
+ }
55
+ async *[Symbol.asyncIterator]() {
56
+ return yield this;
57
+ }
58
+ };
59
+ /**
60
+ * A type-safe container for optional values.
61
+ *
62
+ * `ExperimentalOption<T>` represents a value that may or may not be present. It eliminates the
63
+ * need for `null` and `undefined` checks by making absence explicit through the
64
+ * type system.
65
+ *
66
+ * ## States
67
+ *
68
+ * - **Some\<T\>**: Contains a value of type `T`
69
+ * - **None**: Represents absence of a value (singleton)
70
+ *
71
+ * ## Basic Usage
72
+ *
73
+ * ```ts
74
+ * import { ExperimentalOption } from "@carbonteq/fp";
75
+ *
76
+ * // Creating ExperimentalOptions
77
+ * const some: ExperimentalOption<number> = ExperimentalOption.Some(42);
78
+ * const none: ExperimentalOption<number> = ExperimentalOption.None;
79
+ *
80
+ * // From nullable values
81
+ * const fromNull = ExperimentalOption.fromNullable(null); // None
82
+ * const fromValue = ExperimentalOption.fromNullable("hello"); // Some("hello")
83
+ *
84
+ * // Checking and extracting
85
+ * if (some.isSome()) {
86
+ * console.log(some.unwrap()); // 42
87
+ * }
88
+ *
89
+ * // Chaining operations
90
+ * const result = ExperimentalOption.Some(5)
91
+ * .map(x => x * 2)
92
+ * .flatMap(x => ExperimentalOption.Some(x + 1));
93
+ * // Some(11)
94
+ * ```
95
+ *
96
+ * ## Async Variants
97
+ *
98
+ * For operations that return Promises, use `*Async` methods:
99
+ *
100
+ * ```ts
101
+ * // Sync
102
+ * ExperimentalOption.Some(5).map(x => x * 2); // ExperimentalOption<number>
103
+ *
104
+ * // Async
105
+ * ExperimentalOption.Some(5).mapAsync(async x => x * 2); // Promise<ExperimentalOption<number>>
106
+ * ```
107
+ *
108
+ * @template T - The type of the contained value
109
+ *
110
+ * @see {@link https://carbonteq.github.io/ct-fp/option | ExperimentalOption Documentation}
111
+ */
112
+ var ExperimentalOption = class ExperimentalOption {
113
+ /** Discriminant tag for type-level identification */
114
+ _tag;
115
+ #val;
116
+ constructor(val, tag) {
117
+ this.#val = val;
118
+ this._tag = tag;
119
+ }
120
+ /**
121
+ * Singleton `None` instance representing absence of a value.
122
+ *
123
+ * This is a shared instance - all `None` values reference the same object.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * const none1 = ExperimentalOption.None;
128
+ * const none2 = ExperimentalOption.None;
129
+ * none1 === none2 // true
130
+ * ```
131
+ */
132
+ static None = new ExperimentalOption(NONE_VAL, "None");
133
+ /**
134
+ * Creates a `Some` variant containing the provided value.
135
+ *
136
+ * @template Inner - The type of value to wrap
137
+ * @param val - The value to wrap in a Some
138
+ * @returns An `ExperimentalOption<Inner>` in the Some state
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const opt = ExperimentalOption.Some(42); // ExperimentalOption<number>
143
+ * const str = ExperimentalOption.Some("hello"); // ExperimentalOption<string>
144
+ * const obj = ExperimentalOption.Some({ id: 1 }); // ExperimentalOption<{ id: number }>
145
+ * ```
146
+ */
147
+ static Some(val) {
148
+ return new ExperimentalOption(val, "Some");
149
+ }
150
+ /**
151
+ * Creates an `ExperimentalOption` from a nullable value, returning `None` for `null` or `undefined`.
152
+ *
153
+ * Unlike {@link fromFalsy}, this only treats `null` and `undefined` as absence.
154
+ * Values like `0`, `""`, and `false` are considered valid and wrapped in `Some`.
155
+ *
156
+ * @template T - The input type which may include null/undefined
157
+ * @param val - The value to convert to an ExperimentalOption
158
+ * @returns `Some<NonNullable<T>>` if value is non-nullish, else `None`
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * ExperimentalOption.fromNullable("hello") // Some("hello")
163
+ * ExperimentalOption.fromNullable(null) // None
164
+ * ExperimentalOption.fromNullable(undefined) // None
165
+ * ExperimentalOption.fromNullable(0) // Some(0) - 0 is not nullish
166
+ * ExperimentalOption.fromNullable("") // Some("") - empty string is not nullish
167
+ * ExperimentalOption.fromNullable(false) // Some(false) - false is not nullish
168
+ *
169
+ * // With user input
170
+ * function findUser(id: string): User | null {
171
+ * return database.getUser(id) ?? null;
172
+ * }
173
+ * const user = ExperimentalOption.fromNullable(findUser("123"));
174
+ * // ExperimentalOption<User>
175
+ * ```
176
+ */
177
+ static fromNullable(val) {
178
+ return val === null || val === void 0 ? ExperimentalOption.None : ExperimentalOption.Some(val);
179
+ }
180
+ /**
181
+ * Creates an `ExperimentalOption` from a value that may be falsy, returning `None` for falsy values.
182
+ *
183
+ * Treats `false`, `0`, `""`, `null`, and `undefined` as absence.
184
+ * Use {@link fromNullable} if you only want to exclude `null`/`undefined`.
185
+ *
186
+ * @template T - The type of value to wrap
187
+ * @param val - The value to convert to an ExperimentalOption
188
+ * @returns `Some<T>` if value is truthy, else `None`
189
+ *
190
+ * @example
191
+ * ```ts
192
+ * ExperimentalOption.fromFalsy("hello") // Some("hello")
193
+ * ExperimentalOption.fromFalsy("") // None
194
+ * ExperimentalOption.fromFalsy(0) // None
195
+ * ExperimentalOption.fromFalsy(false) // None
196
+ * ExperimentalOption.fromFalsy(null) // None
197
+ * ExperimentalOption.fromFalsy(undefined) // None
198
+ *
199
+ * // Useful for validation
200
+ * const isValid = ExperimentalOption.fromFalsy(getConfigValue("API_KEY"));
201
+ * ```
202
+ */
203
+ static fromFalsy(val) {
204
+ return val ? ExperimentalOption.Some(val) : ExperimentalOption.None;
205
+ }
206
+ /**
207
+ * Creates an `ExperimentalOption` based on a predicate function result.
208
+ *
209
+ * Returns `Some` if the predicate returns `true`, otherwise `None`.
210
+ *
211
+ * @template T - The type of value to test
212
+ * @param val - The value to test
213
+ * @param pred - A predicate function that returns true if value should be wrapped
214
+ * @returns `Some<T>` if predicate returns true, else `None`
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * const age = 25;
219
+ * ExperimentalOption.fromPredicate(age, a => a >= 18) // Some(25)
220
+ * ExperimentalOption.fromPredicate(15, a => a >= 18) // None
221
+ *
222
+ * // Can be used for validation
223
+ * const isValidEmail = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
224
+ * ExperimentalOption.fromPredicate(user.email, isValidEmail)
225
+ *
226
+ * // With complex predicates
227
+ * const isValidPassword = (pw: string) =>
228
+ * pw.length >= 8 && /[A-Z]/.test(pw) && /[0-9]/.test(pw);
229
+ * ExperimentalOption.fromPredicate(password, isValidPassword)
230
+ * ```
231
+ */
232
+ static fromPredicate(val, pred) {
233
+ return pred(val) ? ExperimentalOption.Some(val) : ExperimentalOption.None;
234
+ }
235
+ /**
236
+ * Combines multiple ExperimentalOptions into a single ExperimentalOption of an array.
237
+ *
238
+ * Returns `Some` containing an array of all unwrapped values if ALL inputs are `Some`.
239
+ * Returns `None` if ANY input is `None`.
240
+ *
241
+ * @template T - Variadic tuple of ExperimentalOption types
242
+ * @param options - Variable number of ExperimentalOptions to combine
243
+ * @returns `ExperimentalOption<[T1, T2, ...]>` with array of values, or `None`
244
+ *
245
+ * @example
246
+ * ```ts
247
+ * // All Some -> array of values
248
+ * const all = ExperimentalOption.all(
249
+ * ExperimentalOption.Some(1),
250
+ * ExperimentalOption.Some(2),
251
+ * ExperimentalOption.Some(3)
252
+ * );
253
+ * // Some([1, 2, 3])
254
+ *
255
+ * // Any None -> None
256
+ * const withNone = ExperimentalOption.all(
257
+ * ExperimentalOption.Some(1),
258
+ * ExperimentalOption.None,
259
+ * ExperimentalOption.Some(3)
260
+ * );
261
+ * // None
262
+ *
263
+ * // Empty -> Some([])
264
+ * const empty = ExperimentalOption.all();
265
+ * // Some([])
266
+ *
267
+ * // Practical example: combine multiple validations
268
+ * const name = ExperimentalOption.fromNullable(user.name);
269
+ * const email = ExperimentalOption.fromNullable(user.email);
270
+ * const age = ExperimentalOption.fromNullable(user.age);
271
+ *
272
+ * const complete = ExperimentalOption.all(name, email, age);
273
+ * // ExperimentalOption<[string, string, number]>
274
+ * ```
275
+ */
276
+ static all(...options) {
277
+ const vals = [];
278
+ for (const opt of options) {
279
+ if (opt.isNone()) return ExperimentalOption.None;
280
+ vals.push(opt.#val);
281
+ }
282
+ return ExperimentalOption.Some(vals);
283
+ }
284
+ /**
285
+ * Returns the first `Some` from a list of ExperimentalOptions, or `None` if all are `None`.
286
+ *
287
+ * Short-circuits on the first `Some` found, evaluating subsequent options lazily.
288
+ *
289
+ * @template T - The type of values in the ExperimentalOptions
290
+ * @param options - Variable number of ExperimentalOptions to check
291
+ * @returns The first `Some<T>` found, or `None`
292
+ *
293
+ * @example
294
+ * ```ts
295
+ * // Returns first Some
296
+ * const first = ExperimentalOption.any(
297
+ * ExperimentalOption.None,
298
+ * ExperimentalOption.Some("First value"),
299
+ * ExperimentalOption.Some("Second value")
300
+ * );
301
+ * // Some("First value")
302
+ *
303
+ * // All None -> None
304
+ * const allNone = ExperimentalOption.any(
305
+ * ExperimentalOption.None,
306
+ * ExperimentalOption.None,
307
+ * ExperimentalOption.None
308
+ * );
309
+ * // None
310
+ *
311
+ * // Practical: Try multiple fallback sources
312
+ * const config = ExperimentalOption.any(
313
+ * ExperimentalOption.fromNullable(process.env.API_KEY),
314
+ * ExperimentalOption.fromNullable(getEnvVar("API_KEY")),
315
+ * ExperimentalOption.fromNullable(readConfigFile("API_KEY"))
316
+ * );
317
+ *
318
+ * // Empty -> None
319
+ * const empty = ExperimentalOption.any();
320
+ * // None
321
+ * ```
322
+ */
323
+ static any(...options) {
324
+ for (const opt of options) if (opt.isSome()) return opt;
325
+ return ExperimentalOption.None;
326
+ }
327
+ /**
328
+ * Type guard that narrows the type to `Some`.
329
+ *
330
+ * Returns `true` if this ExperimentalOption is in the `Some` state, containing a value.
331
+ *
332
+ * @returns `true` if this is a `Some`, `false` if `None`
333
+ *
334
+ * @example
335
+ * ```ts
336
+ * const opt: ExperimentalOption<number> = ExperimentalOption.Some(42);
337
+ *
338
+ * if (opt.isSome()) {
339
+ * // TypeScript knows opt is ExperimentalOption<number> & { _tag: "Some" }
340
+ * console.log(opt.unwrap()); // 42
341
+ * }
342
+ * ```
343
+ */
344
+ isSome() {
345
+ return this._tag === "Some" && this.#val !== NONE_VAL;
346
+ }
347
+ /**
348
+ * Type guard that narrows the type to `None`.
349
+ *
350
+ * Returns `true` if this ExperimentalOption is in the `None` state (absence of value).
351
+ *
352
+ * @returns `true` if this is `None`, `false` if `Some`
353
+ *
354
+ * @example
355
+ * ```ts
356
+ * const opt: ExperimentalOption<number> = ExperimentalOption.None;
357
+ *
358
+ * if (opt.isNone()) {
359
+ * // TypeScript knows opt is ExperimentalOption<never> & { _tag: "None" }
360
+ * console.log("No value present");
361
+ * }
362
+ * ```
363
+ */
364
+ isNone() {
365
+ return this._tag === "None" || this.#val === NONE_VAL;
366
+ }
367
+ /**
368
+ * Type guard that checks if the contained value is the `Unit` type.
369
+ *
370
+ * Returns `true` if this ExperimentalOption contains the special `UNIT` value,
371
+ * used to represent operations that produce no meaningful output.
372
+ *
373
+ * @returns `true` if this contains `UNIT`, `false` otherwise
374
+ *
375
+ * @example
376
+ * ```ts
377
+ * const unitOpt: ExperimentalOption<UNIT> = ExperimentalOption.Some(UNIT);
378
+ * unitOpt.isUnit(); // true
379
+ *
380
+ * const normalOpt: ExperimentalOption<number> = ExperimentalOption.Some(42);
381
+ * normalOpt.isUnit(); // false
382
+ * ```
383
+ */
384
+ isUnit() {
385
+ return this.#val === UNIT;
386
+ }
387
+ /**
388
+ * Returns the contained value or throws {@link UnwrappedNone} if `None`.
389
+ *
390
+ * This is an unsafe operation that throws on `None`. Use only when you are
391
+ * certain the ExperimentalOption contains a value, or use safe alternatives like
392
+ * {@link unwrapOr} or {@link safeUnwrap}.
393
+ *
394
+ * @throws {@link UnwrappedNone} if this is `None`
395
+ * @returns The contained value
396
+ *
397
+ * @example
398
+ * ```ts
399
+ * ExperimentalOption.Some(42).unwrap(); // 42
400
+ * ExperimentalOption.None.unwrap(); // throws UnwrappedNone
401
+ *
402
+ * // Safe usage pattern
403
+ * const opt = ExperimentalOption.Some(42);
404
+ * if (opt.isSome()) {
405
+ * const value = opt.unwrap(); // Safe: we checked isSome()
406
+ * }
407
+ * ```
408
+ *
409
+ * @see {@link unwrapOr} for safe unwrapping with a default value
410
+ * @see {@link unwrapOrElse} for lazy default computation
411
+ * @see {@link safeUnwrap} for null-returning safe unwrap
412
+ */
413
+ unwrap() {
414
+ if (this.isNone()) throw UNWRAPPED_NONE_ERR;
415
+ return this.#val;
416
+ }
417
+ /**
418
+ * Returns the contained value, or the provided default value if `None`.
419
+ *
420
+ * A safe alternative to {@link unwrap} that doesn't throw.
421
+ *
422
+ * @param defaultValue - The value to return if this is `None`
423
+ * @returns The contained value, or the default
424
+ *
425
+ * @example
426
+ * ```ts
427
+ * ExperimentalOption.Some(42).unwrapOr(0); // 42
428
+ * ExperimentalOption.None.unwrapOr(0); // 0
429
+ *
430
+ * // With user input
431
+ * const age = ExperimentalOption.fromNullable(user.age).unwrapOr(18);
432
+ *
433
+ * // With complex defaults
434
+ * const config = ExperimentalOption.fromNullable(getConfig())
435
+ * .unwrapOr({ port: 3000, host: "localhost" });
436
+ * ```
437
+ *
438
+ * @see {@link unwrapOrElse} for lazy default computation
439
+ * @see {@link safeUnwrap} for null-returning safe unwrap
440
+ */
441
+ unwrapOr(defaultValue) {
442
+ if (this.isNone()) return defaultValue;
443
+ return this.#val;
444
+ }
445
+ /**
446
+ * Returns the contained value, or computes a default via a function if `None`.
447
+ *
448
+ * Unlike {@link unwrapOr}, the default is computed lazily - only if this is `None`.
449
+ * Use this when the default value is expensive to compute.
450
+ *
451
+ * @param fn - A factory function that produces the default value
452
+ * @returns The contained value, or the computed default
453
+ *
454
+ * @example
455
+ * ```ts
456
+ * // Lazy default - only computed if needed
457
+ * const value = ExperimentalOption.None.unwrapOrElse(() => {
458
+ * console.log("Computing expensive default...");
459
+ * return expensivelyComputeDefault();
460
+ * });
461
+ * // Prints "Computing expensive default..."
462
+ *
463
+ * // Not computed when Some
464
+ * const some = ExperimentalOption.Some(42).unwrapOrElse(() => {
465
+ * console.log("This won't print");
466
+ * return expensivelyComputeDefault();
467
+ * });
468
+ * // Returns 42 without printing
469
+ *
470
+ * // Practical: cache lookup with fallback
471
+ * const cached = ExperimentalOption.fromNullable(cache.get(key))
472
+ * .unwrapOrElse(() => {
473
+ * const value = fetchFromDatabase(key);
474
+ * cache.set(key, value);
475
+ * return value;
476
+ * });
477
+ * ```
478
+ *
479
+ * @see {@link unwrapOr} for simple default values
480
+ * @see {@link unwrap} for unsafe unwrapping
481
+ */
482
+ unwrapOrElse(fn) {
483
+ if (this.isNone()) return fn();
484
+ return this.#val;
485
+ }
486
+ /**
487
+ * Returns the contained value, or `null` if `None`.
488
+ *
489
+ * Provides a safe way to extract values that integrates with TypeScript's
490
+ * null checking while maintaining the ExperimentalOption semantics.
491
+ *
492
+ * @returns The contained value, or `null`
493
+ *
494
+ * @example
495
+ * ```ts
496
+ * ExperimentalOption.Some(42).safeUnwrap(); // 42
497
+ * ExperimentalOption.None.safeUnwrap(); // null
498
+ *
499
+ * // Integration with existing null-handling code
500
+ * const value = ExperimentalOption.fromNullable(user.name).safeUnwrap();
501
+ * if (value !== null) {
502
+ * console.log(value.toUpperCase());
503
+ * }
504
+ *
505
+ * // With nullish coalescing
506
+ * const displayName = ExperimentalOption.fromNullable(user.displayName)
507
+ * .safeUnwrap() ?? user.email;
508
+ * ```
509
+ *
510
+ * @see {@link unwrapOr} for typed defaults
511
+ * @see {@link unwrapOrElse} for lazy defaults
512
+ */
513
+ safeUnwrap() {
514
+ if (this.isNone()) return null;
515
+ return this.#val;
516
+ }
517
+ /**
518
+ * Pattern matches on both states of the ExperimentalOption, providing exhaustive handling.
519
+ *
520
+ * This is the most explicit way to handle ExperimentalOptions, ensuring both `Some` and `None`
521
+ * cases are handled at compile time.
522
+ *
523
+ * @template U - The result type of both branches
524
+ * @param cases - Object containing handlers for both states
525
+ * @returns The result of calling the appropriate handler
526
+ *
527
+ * @example
528
+ * ```ts
529
+ * const result = ExperimentalOption.Some(42).match({
530
+ * Some: (value) => `Got: ${value}`,
531
+ * None: () => "Got nothing"
532
+ * });
533
+ * // "Got: 42"
534
+ *
535
+ * const noneResult = ExperimentalOption.None.match({
536
+ * Some: (value) => `Got: ${value}`,
537
+ * None: () => "Got nothing"
538
+ * });
539
+ * // "Got nothing"
540
+ *
541
+ * // Practical: user lookup
542
+ * const message = findUser(userId).match({
543
+ * Some: (user) => `Welcome, ${user.name}!`,
544
+ * None: () => "User not found"
545
+ * });
546
+ * ```
547
+ *
548
+ * @see {@link isSome} and {@link isNone} for conditional handling
549
+ */
550
+ match(cases) {
551
+ if (this.isNone()) return cases.None();
552
+ return cases.Some(this.#val);
553
+ }
554
+ /**
555
+ * Pattern matches using positional arguments (FP convention alias for `match`).
556
+ *
557
+ * This is a more concise alternative to `match` using positional arguments
558
+ * instead of an object. Familiar to developers from Scala, Haskell, and other FP languages.
559
+ *
560
+ * @template U - The result type of both branches
561
+ * @param onSome - Handler called with the value if `Some`
562
+ * @param onNone - Handler called if `None`
563
+ * @returns The result of calling the appropriate handler
564
+ *
565
+ * @example
566
+ * ```ts
567
+ * const result = ExperimentalOption.Some(42).fold(
568
+ * (value) => `Got: ${value}`,
569
+ * () => "Got nothing"
570
+ * );
571
+ * // "Got: 42"
572
+ *
573
+ * const noneResult = ExperimentalOption.None.fold(
574
+ * (value) => `Got: ${value}`,
575
+ * () => "Got nothing"
576
+ * );
577
+ * // "Got nothing"
578
+ *
579
+ * // Equivalent to match:
580
+ * experimentalOption.fold(onSome, onNone);
581
+ * experimentalOption.match({ Some: onSome, None: onNone });
582
+ * ```
583
+ *
584
+ * @see {@link match} for object-based pattern matching
585
+ * @see {@link foldAsync} for async handlers
586
+ */
587
+ fold(onSome, onNone) {
588
+ if (this.isNone()) return onNone();
589
+ return onSome(this.#val);
590
+ }
591
+ /**
592
+ * Async pattern matching using positional arguments.
593
+ *
594
+ * Async variant of `fold` for when handlers return Promises.
595
+ * Rejections from `onSome` are propagated (not converted to `None`).
596
+ *
597
+ * @template U - The result type of both branches
598
+ * @param onSome - Async handler called with the value if `Some`
599
+ * @param onNone - Async handler called if `None`
600
+ * @returns Promise resolving to the result of the appropriate handler
601
+ *
602
+ * @example
603
+ * ```ts
604
+ * const result = await ExperimentalOption.Some(userId).foldAsync(
605
+ * async (id) => await fetchUser(id),
606
+ * async () => await getDefaultUser()
607
+ * );
608
+ *
609
+ * // With database lookup
610
+ * const user = await ExperimentalOption.fromNullable(sessionUserId).foldAsync(
611
+ * async (id) => await db.users.findById(id),
612
+ * async () => ({ id: 0, name: "Guest" })
613
+ * );
614
+ * ```
615
+ *
616
+ * @see {@link fold} for synchronous handlers
617
+ * @see {@link matchAsync} for object-based async pattern matching
618
+ */
619
+ async foldAsync(onSome, onNone) {
620
+ if (this.isNone()) return onNone();
621
+ return onSome(this.#val);
622
+ }
623
+ /**
624
+ * Async pattern matching on both states of the ExperimentalOption.
625
+ *
626
+ * Async variant of `match` for when handlers return Promises.
627
+ * Rejections from `Some` handler are propagated (not converted to `None`).
628
+ *
629
+ * @template U - The result type of both branches
630
+ * @param cases - Object containing async handlers for both states
631
+ * @returns Promise resolving to the result of the appropriate handler
632
+ *
633
+ * @example
634
+ * ```ts
635
+ * const result = await ExperimentalOption.Some(userId).matchAsync({
636
+ * Some: async (id) => await fetchUser(id),
637
+ * None: async () => await getDefaultUser()
638
+ * });
639
+ *
640
+ * // With API calls
641
+ * const data = await maybeConfig.matchAsync({
642
+ * Some: async (config) => await loadWithConfig(config),
643
+ * None: async () => await loadDefaults()
644
+ * });
645
+ * ```
646
+ *
647
+ * @see {@link match} for synchronous pattern matching
648
+ * @see {@link foldAsync} for positional-argument async matching
649
+ */
650
+ async matchAsync(cases) {
651
+ if (this.isNone()) return cases.None();
652
+ return cases.Some(this.#val);
653
+ }
654
+ /**
655
+ * Pattern matches with a subset of cases, using a default for unhandled cases.
656
+ *
657
+ * Unlike `match` which requires all cases, `matchPartial` allows handling
658
+ * only specific cases with a fallback default function.
659
+ *
660
+ * @template U - The result type
661
+ * @param cases - Partial object with optional `Some` and `None` handlers
662
+ * @param getDefault - Lazy default function for unhandled cases
663
+ * @returns The result of the matching handler or the default
664
+ *
665
+ * @example
666
+ * ```ts
667
+ * // Only handle Some, default for None
668
+ * ExperimentalOption.Some(42).matchPartial({ Some: (v) => v * 2 }, () => 0); // 84
669
+ * ExperimentalOption.None.matchPartial({ Some: (v) => v * 2 }, () => 0); // 0
670
+ *
671
+ * // Only handle None
672
+ * ExperimentalOption.Some(42).matchPartial({ None: () => -1 }, () => 100); // 100
673
+ * ExperimentalOption.None.matchPartial({ None: () => -1 }, () => 100); // -1
674
+ *
675
+ * // Lazy default with function
676
+ * experimentalOption.matchPartial(
677
+ * { Some: (v) => process(v) },
678
+ * () => computeExpensiveDefault()
679
+ * );
680
+ * ```
681
+ *
682
+ * @see {@link match} for exhaustive pattern matching
683
+ */
684
+ matchPartial(cases, getDefault) {
685
+ if (this.isNone()) return cases.None ? cases.None() : getDefault();
686
+ return cases.Some ? cases.Some(this.#val) : getDefault();
687
+ }
688
+ map(fn) {
689
+ if (this.isNone()) return ExperimentalOption.None;
690
+ return ExperimentalOption.Some(fn(this.#val));
691
+ }
692
+ /**
693
+ * Transforms the contained value using an async function.
694
+ *
695
+ * If `Some`, awaits the async function and wraps the result in a new `Some`.
696
+ * If `None`, returns a resolved `None` Promise without calling the function.
697
+ *
698
+ * @template U - The type of the transformed value
699
+ * @param fn - An async function that transforms the contained value
700
+ * @returns `Promise<Some<U>>` with the transformed value, or `Promise<None>`
701
+ *
702
+ * @example
703
+ * ```ts
704
+ * // Simple async transform
705
+ * const result = await ExperimentalOption.Some(5).mapAsync(async x => {
706
+ * return x * 2;
707
+ * });
708
+ * // Some(10)
709
+ *
710
+ * // Chaining with .then()
711
+ * ExperimentalOption.Some(5)
712
+ * .map(x => x * 2) // Some(10)
713
+ * .mapAsync(async x => {
714
+ * return await fetchData(x); // Some<Data>
715
+ * })
716
+ * .then(o => o.map(d => d.name)); // Promise<Some<string>>
717
+ *
718
+ * // Practical: API call after validation
719
+ * const userData = await ExperimentalOption.Some(userId)
720
+ * .mapAsync(async id => await fetchUser(id))
721
+ * .then(o => o.mapAsync(async user => await fetchProfile(user.id)));
722
+ * // Promise<ExperimentalOption<Profile>>
723
+ * ```
724
+ *
725
+ * @see {@link map} for synchronous transformations
726
+ */
727
+ async mapAsync(fn) {
728
+ if (this.isNone()) return Promise.resolve(ExperimentalOption.None);
729
+ return fn(this.#val).then((u) => ExperimentalOption.Some(u));
730
+ }
731
+ /**
732
+ * Maps the value or returns a default value (unwrapped).
733
+ *
734
+ * Unlike {@link map}, this returns the value directly (not wrapped in ExperimentalOption).
735
+ * If `Some`, applies the function and returns the result.
736
+ * If `None`, returns the default value without calling the function.
737
+ *
738
+ * @template U - The type of the result
739
+ * @param defaultValue - The value to return if `None`
740
+ * @param fn - A function to apply if `Some`
741
+ * @returns The mapped value or the default
742
+ *
743
+ * @example
744
+ * ```ts
745
+ * ExperimentalOption.Some(5).mapOr(0, x => x * 2); // 10
746
+ * ExperimentalOption.None.mapOr(0, x => x * 2); // 0
747
+ *
748
+ * // Practical: formatting with fallback
749
+ * const displayName = ExperimentalOption.fromNullable(user.name)
750
+ * .mapOr("Anonymous", name => name.toUpperCase());
751
+ * // "JOHN" or "Anonymous"
752
+ *
753
+ * // With complex defaults
754
+ * const balance = ExperimentalOption.fromNullable(account?.balance)
755
+ * .mapOr(0, b => b.toFixed(2));
756
+ * ```
757
+ *
758
+ * @see {@link map} for wrapped results
759
+ * @see {@link mapOrAsync} for async transformations
760
+ */
761
+ mapOr(defaultValue, fn) {
762
+ if (this.isNone()) return defaultValue;
763
+ return fn(this.#val);
764
+ }
765
+ /**
766
+ * Maps the value using an async function or returns a default value.
767
+ *
768
+ * @template U - The type of the result
769
+ * @param defaultValue - The value to return if `None`
770
+ * @param fn - An async function to apply if `Some`
771
+ * @returns `Promise<U>` with the mapped value or the default
772
+ *
773
+ * @example
774
+ * ```ts
775
+ * const result = await ExperimentalOption.Some(5).mapOrAsync(0, async x => {
776
+ * return x * 2;
777
+ * });
778
+ * // 10
779
+ *
780
+ * const noneResult = await ExperimentalOption.None.mapOrAsync(0, async x => {
781
+ * return x * 2;
782
+ * });
783
+ * // 0
784
+ *
785
+ * // Practical: async fetch with fallback
786
+ * const balance = await ExperimentalOption.fromNullable(userId)
787
+ * .mapOrAsync(0, async id => await getAccountBalance(id));
788
+ * ```
789
+ *
790
+ * @see {@link mapOr} for synchronous transformations
791
+ */
792
+ async mapOrAsync(defaultValue, fn) {
793
+ if (this.isNone()) return defaultValue;
794
+ return fn(this.#val);
795
+ }
796
+ /**
797
+ * Chains operations that return ExperimentalOptions, flattening nested ExperimentalOptions.
798
+ *
799
+ * Also known as `bind` or `chain`. Use this to sequence operations where
800
+ * each step depends on the previous value and may fail.
801
+ *
802
+ * If `Some`, applies the function and returns its result directly.
803
+ * If `None`, returns `None` without calling the function.
804
+ *
805
+ * @template U - The type of the value in the returned ExperimentalOption
806
+ * @param fn - A function that returns an ExperimentalOption
807
+ * @returns The result of the function, or `None`
808
+ *
809
+ * @example
810
+ * ```ts
811
+ * // Basic chaining
812
+ * ExperimentalOption.Some(5).flatMap(x => ExperimentalOption.Some(x + 1)); // Some(6)
813
+ * ExperimentalOption.Some(5).flatMap(x => ExperimentalOption.None); // None
814
+ * ExperimentalOption.None.flatMap(x => ExperimentalOption.Some(x + 1)); // None
815
+ *
816
+ * // Chaining optional operations
817
+ * const email = findUser(userId)
818
+ * .flatMap(user => ExperimentalOption.fromNullable(user.profile))
819
+ * .flatMap(profile => ExperimentalOption.fromNullable(profile.avatar))
820
+ * .flatMap(avatar => ExperimentalOption.fromNullable(avatar.url));
821
+ *
822
+ * // Practical: multi-step validation
823
+ * const valid = ExperimentalOption.Some(input)
824
+ * .flatMap(s => parseEmail(s))
825
+ * .flatMap(email => checkDomain(email))
826
+ * .flatMap(domain => resolveDomain(domain));
827
+ * ```
828
+ *
829
+ * @see {@link flatMapAsync} for async operations
830
+ * @see {@link map} for simple transformations
831
+ * @see {@link gen} for imperative-style chaining
832
+ */
833
+ flatMap(fn) {
834
+ if (this.isNone()) return ExperimentalOption.None;
835
+ return fn(this.#val);
836
+ }
837
+ /**
838
+ * Chains async operations that return ExperimentalOptions.
839
+ *
840
+ * @template U - The type of the value in the returned ExperimentalOption
841
+ * @param fn - An async function that returns an ExperimentalOption
842
+ * @returns `Promise<ExperimentalOption<U>>` with the result, or `Promise<None>`
843
+ *
844
+ * @example
845
+ * ```ts
846
+ * // Async database lookup chain
847
+ * const profile = await ExperimentalOption.Some(userId)
848
+ * .flatMapAsync(async id => await findUser(id))
849
+ * .flatMapAsync(async user => await getProfile(user.id))
850
+ * .flatMapAsync(async p => await getAvatar(p.avatarId));
851
+ * // Promise<ExperimentalOption<Avatar>>
852
+ *
853
+ * // Practical: multi-step async pipeline
854
+ * const result = await ExperimentalOption.Some(email)
855
+ * .flatMapAsync(validateEmail)
856
+ * .flatMapAsync(e => fetchUserByEmail(e))
857
+ * .flatMapAsync(u => getUserPermissions(u.id));
858
+ * ```
859
+ *
860
+ * @see {@link flatMap} for synchronous operations
861
+ * @see {@link asyncGen} for imperative-style async chaining
862
+ */
863
+ async flatMapAsync(fn) {
864
+ if (this.isNone()) return ExperimentalOption.None;
865
+ return fn(this.#val);
866
+ }
867
+ /**
868
+ * Converts `Some` to `None` if the predicate returns `false`.
869
+ *
870
+ * If `Some`, tests the predicate and returns `Some` if true, `None` if false.
871
+ * If `None`, returns `None` without calling the predicate.
872
+ *
873
+ * @param pred - A predicate function to test the contained value
874
+ * @returns `Some<T>` if predicate passes, else `None`
875
+ *
876
+ * @example
877
+ * ```ts
878
+ * ExperimentalOption.Some(5).filter(x => x > 3); // Some(5)
879
+ * ExperimentalOption.Some(5).filter(x => x > 10); // None
880
+ * ExperimentalOption.None.filter(x => x > 3); // None
881
+ *
882
+ * // Age validation
883
+ * const adult = ExperimentalOption.Some(age)
884
+ * .filter(a => a >= 18);
885
+ *
886
+ * // Multiple filters
887
+ * const valid = ExperimentalOption.Some(password)
888
+ * .filter(pw => pw.length >= 8)
889
+ * .filter(pw => /[A-Z]/.test(pw))
890
+ * .filter(pw => /[0-9]/.test(pw));
891
+ * ```
892
+ *
893
+ * @see {@link filterAsync} for async predicates
894
+ * @see {@link fromPredicate} for creating ExperimentalOptions from predicates
895
+ */
896
+ filter(pred) {
897
+ if (this.isNone()) return ExperimentalOption.None;
898
+ return pred(this.#val) ? this : ExperimentalOption.None;
899
+ }
900
+ /**
901
+ * Converts `Some` to `None` if the async predicate returns `false`.
902
+ *
903
+ * @param pred - An async predicate function to test the contained value
904
+ * @returns `Promise<Some<T>>` if predicate passes, else `Promise<None>`
905
+ *
906
+ * @example
907
+ * ```ts
908
+ * // Async validation
909
+ * const valid = await ExperimentalOption.Some(email)
910
+ * .filterAsync(async e => await checkEmailDomain(e));
911
+ *
912
+ * // Practical: database validation
913
+ * const unique = await ExperimentalOption.Some(username)
914
+ * .filterAsync(async u => await isUsernameAvailable(u));
915
+ * ```
916
+ *
917
+ * @see {@link filter} for synchronous predicates
918
+ */
919
+ async filterAsync(pred) {
920
+ if (this.isNone()) return Promise.resolve(ExperimentalOption.None);
921
+ return pred(this.#val).then((passed) => passed ? this : ExperimentalOption.None);
922
+ }
923
+ zip(fn) {
924
+ if (this.isNone()) return ExperimentalOption.None;
925
+ return ExperimentalOption.Some([this.#val, fn(this.#val)]);
926
+ }
927
+ /**
928
+ * Pairs the original value with an async derived value.
929
+ *
930
+ * @template U - The type of the derived value
931
+ * @param fn - An async function that derives a value from the contained value
932
+ * @returns `Promise<Some<[T, U]>>` with the tuple, or `Promise<None>`
933
+ *
934
+ * @example
935
+ * ```ts
936
+ * const result = await ExperimentalOption.Some(user)
937
+ * .zipAsync(async u => await fetchCount(u));
938
+ * // Some([user, number])
939
+ *
940
+ * // Practical: user with additional data
941
+ * const enriched = await ExperimentalOption.Some(userId)
942
+ * .zipAsync(async id => await fetchUser(id))
943
+ * .then(o => o.zipAsync(async ([id, user]) => await getStats(user.id)));
944
+ * // Promise<ExperimentalOption<[userId, User, Stats]>>
945
+ * ```
946
+ *
947
+ * @see {@link zip} for synchronous derivation
948
+ */
949
+ async zipAsync(fn) {
950
+ if (this.isNone()) return Promise.resolve(ExperimentalOption.None);
951
+ return fn(this.#val).then((u) => ExperimentalOption.Some([this.#val, u]));
952
+ }
953
+ /**
954
+ * Pairs the original value with a value from another ExperimentalOption.
955
+ *
956
+ * Combines two independent ExperimentalOptions into a tuple. Both must be `Some` to succeed.
957
+ *
958
+ * @template U - The type of the value in the other ExperimentalOption
959
+ * @param fn - A function that returns an ExperimentalOption to combine with
960
+ * @returns `Some<[T, U]>` with both values, or `None`
961
+ *
962
+ * @example
963
+ * ```ts
964
+ * // Basic usage
965
+ * ExperimentalOption.Some(5).flatZip(x => ExperimentalOption.Some(10)); // Some([5, 10])
966
+ * ExperimentalOption.Some(5).flatZip(x => ExperimentalOption.None); // None
967
+ * ExperimentalOption.None.flatZip(x => ExperimentalOption.Some(10)); // None
968
+ *
969
+ * // Practical: combine independent lookups
970
+ * const productData = ExperimentalOption.Some(productId)
971
+ * .flatZip(id => fetchProductPrice(id));
972
+ * // ExperimentalOption<[productId, price]>
973
+ *
974
+ * // Multiple dependencies
975
+ * const complete = ExperimentalOption.Some(userId)
976
+ * .flatZip(id => fetchUser(id))
977
+ * .flatMap(([id, user]) => ExperimentalOption.Some([id, user.profileId]))
978
+ * .flatZip(([id, profileId]) => fetchProfile(profileId));
979
+ * // ExperimentalOption<[userId, profileId, profile]>
980
+ * ```
981
+ *
982
+ * @see {@link flatZipAsync} for async ExperimentalOptions
983
+ * @see {@link zip} for derived values
984
+ * @see {@link all} for combining multiple ExperimentalOptions at once
985
+ */
986
+ flatZip(fn) {
987
+ if (this.isNone()) return ExperimentalOption.None;
988
+ const other = fn(this.#val);
989
+ if (other.isNone()) return ExperimentalOption.None;
990
+ return ExperimentalOption.Some([this.#val, other.unwrap()]);
991
+ }
992
+ /**
993
+ * Pairs the original value with a value from an async ExperimentalOption.
994
+ *
995
+ * @template U - The type of the value in the other ExperimentalOption
996
+ * @param fn - An async function that returns an ExperimentalOption
997
+ * @returns `Promise<Some<[T, U]>>` with both values, or `Promise<None>`
998
+ *
999
+ * @example
1000
+ * ```ts
1001
+ * const result = await ExperimentalOption.Some(userId)
1002
+ * .flatZipAsync(async id => await fetchUser(id));
1003
+ * // ExperimentalOption<[userId, User]>
1004
+ *
1005
+ * // Practical: async pipeline
1006
+ * const enriched = await ExperimentalOption.Some(userId)
1007
+ * .flatZipAsync(async id => await fetchUser(id))
1008
+ * .then(o => o.flatMapAsync(async ([id, user]) =>
1009
+ * ExperimentalOption.Some([id, user, await fetchProfile(user.profileId)])
1010
+ * ));
1011
+ * ```
1012
+ *
1013
+ * @see {@link flatZip} for synchronous ExperimentalOptions
1014
+ */
1015
+ async flatZipAsync(fn) {
1016
+ if (this.isNone()) return Promise.resolve(ExperimentalOption.None);
1017
+ return fn(this.#val).then((other) => {
1018
+ if (other.isNone()) return ExperimentalOption.None;
1019
+ return ExperimentalOption.Some([this.#val, other.unwrap()]);
1020
+ });
1021
+ }
1022
+ /**
1023
+ * Executes a side effect function if `Some`, returning `this` unchanged.
1024
+ *
1025
+ * Useful for logging, debugging, or executing effects without breaking the chain.
1026
+ *
1027
+ * @param fn - A side effect function to execute with the contained value
1028
+ * @returns `this` (unchanged, for chaining)
1029
+ *
1030
+ * @example
1031
+ * ```ts
1032
+ * // Logging without breaking chain
1033
+ * ExperimentalOption.Some(user)
1034
+ * .tap(u => console.log(`Processing ${u.name}`))
1035
+ * .map(u => u.email);
1036
+ *
1037
+ * // Debugging
1038
+ * ExperimentalOption.Some(input)
1039
+ * .tap(val => console.log("Before:", val))
1040
+ * .map(transform)
1041
+ * .tap(val => console.log("After:", val));
1042
+ *
1043
+ * // Practical: audit trail
1044
+ * const result = ExperimentalOption.Some(transaction)
1045
+ * .tap((t) => auditLog("start", t.id))
1046
+ * .flatMap((t) => process(t))
1047
+ * .tap((r) => auditLog("success", r.id));
1048
+ * ```
1049
+ *
1050
+ * @see {@link tapAsync} for async side effects
1051
+ */
1052
+ tap(fn) {
1053
+ if (this.isSome()) fn(this.#val);
1054
+ return this;
1055
+ }
1056
+ /**
1057
+ * Executes an async side effect function if `Some`, returning `this` unchanged.
1058
+ *
1059
+ * @param fn - An async side effect function to execute
1060
+ * @returns `Promise<ExperimentalOption<T>>` that resolves to `this`
1061
+ *
1062
+ * @example
1063
+ * ```ts
1064
+ * // Async logging
1065
+ * await ExperimentalOption.Some(user)
1066
+ * .tapAsync(async u => await logAnalytics(u.id))
1067
+ * .map(u => u.email);
1068
+ *
1069
+ * // Practical: metrics collection
1070
+ * const result = await ExperimentalOption.Some(request)
1071
+ * .tapAsync(async req => await trackMetric("request_start", req.id))
1072
+ * .flatMapAsync(async req => await processRequest(req))
1073
+ * .tapAsync(async res => await trackMetric("request_success", res.id));
1074
+ * ```
1075
+ *
1076
+ * @see {@link tap} for synchronous side effects
1077
+ */
1078
+ async tapAsync(fn) {
1079
+ if (this.isSome()) return fn(this.#val).then(() => this);
1080
+ return Promise.resolve(this);
1081
+ }
1082
+ /**
1083
+ * Converts this ExperimentalOption to a Result.
1084
+ *
1085
+ * `Some` becomes `Ok`, `None` becomes `Err` with the provided error.
1086
+ *
1087
+ * @template E - The type of the error for the `Err` variant
1088
+ * @param error - The error value to use if this is `None`
1089
+ * @returns `Result<T, E>` with the value or error
1090
+ *
1091
+ * @example
1092
+ * ```ts
1093
+ * ExperimentalOption.Some(42).toResult("was none"); // Ok(42)
1094
+ * ExperimentalOption.None.toResult("was none"); // Err("was none")
1095
+ *
1096
+ * // Practical: convert to Result for error handling
1097
+ * const user = ExperimentalOption.fromNullable(getUser())
1098
+ * .toResult(new Error("User not found"));
1099
+ *
1100
+ * // With custom error types
1101
+ * const config = ExperimentalOption.fromNullable(loadConfig())
1102
+ * .toResult({ code: "CONFIG_MISSING", message: "Config file not found" });
1103
+ * ```
1104
+ *
1105
+ * @see {@link ExperimentalResult} for the Result type
1106
+ */
1107
+ toResult(error) {
1108
+ if (this.isNone()) return ExperimentalResult.Err(error);
1109
+ return ExperimentalResult.Ok(this.#val);
1110
+ }
1111
+ /**
1112
+ * Maps over array elements inside an `ExperimentalOption<Array<T>>`.
1113
+ *
1114
+ * Only callable when `T` is an array type. Applies the mapper to each
1115
+ * element if `Some`, or returns `None`.
1116
+ *
1117
+ * @template Inner - The element type of the array
1118
+ * @template Out - The output element type
1119
+ * @param mapper - A function to transform each array element
1120
+ * @returns `Some<Out[]>` with mapped array, or `None`
1121
+ * @throws {TypeError} if called on a non-array ExperimentalOption
1122
+ *
1123
+ * @example
1124
+ * ```ts
1125
+ * ExperimentalOption.Some([1, 2, 3]).innerMap(n => n * 2);
1126
+ * // Some([2, 4, 6])
1127
+ *
1128
+ * ExperimentalOption.None.innerMap(n => n * 2);
1129
+ * // None
1130
+ *
1131
+ * // Practical: transform list results
1132
+ * const users = await fetchUsers() // ExperimentalOption<User[]>
1133
+ * .innerMap(u => u.name)
1134
+ * .innerMap(names => names.sort());
1135
+ * // Some<string[]>
1136
+ *
1137
+ * // Error case
1138
+ * ExperimentalOption.Some(42).innerMap(x => x * 2);
1139
+ * // throws TypeError: innerMap can only be called on ExperimentalOption<Array<T>>
1140
+ * ```
1141
+ *
1142
+ * @see {@link map} for transforming the contained value directly
1143
+ */
1144
+ innerMap(mapper) {
1145
+ if (this.isNone()) return ExperimentalOption.None;
1146
+ if (!Array.isArray(this.#val)) throw new TypeError("innerMap can only be called on ExperimentalOption<Array<T>>");
1147
+ return ExperimentalOption.Some(this.#val.map(mapper));
1148
+ }
1149
+ /**
1150
+ * Returns a string representation of the ExperimentalOption.
1151
+ *
1152
+ * @returns A string describing the ExperimentalOption state and value
1153
+ *
1154
+ * @example
1155
+ * ```ts
1156
+ * ExperimentalOption.Some(42).toString(); // "ExperimentalOption::Some(42)"
1157
+ * ExperimentalOption.None.toString(); // "ExperimentalOption::None"
1158
+ * ExperimentalOption.Some("hello").toString(); // "ExperimentalOption::Some(hello)"
1159
+ * ```
1160
+ */
1161
+ toString() {
1162
+ if (this.isNone()) return "ExperimentalOption::None";
1163
+ return `ExperimentalOption::Some(${String(this.#val)})`;
1164
+ }
1165
+ /**
1166
+ * Makes ExperimentalOption iterable for use with generator-based syntax.
1167
+ *
1168
+ * Yields self and returns the unwrapped value when resumed.
1169
+ * Used internally by {@link ExperimentalOption.gen} for `yield*` syntax.
1170
+ *
1171
+ * @example
1172
+ * ```ts
1173
+ * const result = ExperimentalOption.gen(function* () {
1174
+ * const value = yield* ExperimentalOption.Some(42);
1175
+ * return value * 2;
1176
+ * });
1177
+ * // Some(84)
1178
+ * ```
1179
+ *
1180
+ * @internal
1181
+ */
1182
+ *[Symbol.iterator]() {
1183
+ const trace = (/* @__PURE__ */ new Error()).stack;
1184
+ return yield new CapturedTrace(this, trace);
1185
+ }
1186
+ /**
1187
+ * Makes ExperimentalOption iterable for use with async generator-based syntax.
1188
+ *
1189
+ * Yields self and returns the unwrapped value when resumed.
1190
+ * Used internally by {@link ExperimentalOption.asyncGen} for `yield*` syntax.
1191
+ *
1192
+ * @example
1193
+ * ```ts
1194
+ * const result = await ExperimentalOption.asyncGen(async function* () {
1195
+ * const value = yield* await Promise.resolve(ExperimentalOption.Some(42));
1196
+ * return value * 2;
1197
+ * });
1198
+ * // Some(84)
1199
+ * ```
1200
+ *
1201
+ * @internal
1202
+ */
1203
+ async *[Symbol.asyncIterator]() {
1204
+ const trace = (/* @__PURE__ */ new Error()).stack;
1205
+ return yield new CapturedTrace(this, trace);
1206
+ }
1207
+ /**
1208
+ * Generator-based syntax for chaining ExperimentalOption operations (simplified, no adapter).
1209
+ *
1210
+ * Provides imperative-style code while maintaining functional ExperimentalOption handling.
1211
+ * Use `yield*` to unwrap ExperimentalOptions or short-circuit on `None`.
1212
+ *
1213
+ * Short-circuits on first `None`, returning singleton `None`. Uses iteration
1214
+ * instead of recursion to avoid stack overflow on deep chains.
1215
+ *
1216
+ * @template T - The return type of the generator
1217
+ * @param genFn - A generator function that yields ExperimentalOptions
1218
+ * @returns `Some<T>` with the generator's return value, or `None`
1219
+ *
1220
+ * @example
1221
+ * ```ts
1222
+ * // Simple sync chain
1223
+ * const result = ExperimentalOption.gen(function* () {
1224
+ * const a = yield* ExperimentalOption.Some(1);
1225
+ * const b = yield* ExperimentalOption.Some(2);
1226
+ * return a + b;
1227
+ * });
1228
+ * // Some(3)
1229
+ *
1230
+ * // None short-circuit
1231
+ * const shortCircuit = ExperimentalOption.gen(function* () {
1232
+ * const a = yield* ExperimentalOption.Some(1);
1233
+ * const b = yield* ExperimentalOption.None; // Short-circuits here
1234
+ * const c = yield* ExperimentalOption.Some(3); // Never executes
1235
+ * return a + b + c;
1236
+ * });
1237
+ * // None
1238
+ *
1239
+ * // Chaining optional operations
1240
+ * const email = ExperimentalOption.gen(function* () {
1241
+ * const user = yield* findUser(userId);
1242
+ * const profile = yield* ExperimentalOption.fromNullable(user.profile);
1243
+ * const settings = yield* ExperimentalOption.fromNullable(profile.settings);
1244
+ * return settings.email;
1245
+ * });
1246
+ *
1247
+ * // Nested optional access
1248
+ * const city = ExperimentalOption.gen(function* () {
1249
+ * const user = yield* ExperimentalOption.fromNullable(getUser());
1250
+ * const address = yield* ExperimentalOption.fromNullable(user?.address);
1251
+ * const city = yield* ExperimentalOption.fromNullable(address?.city);
1252
+ * return city;
1253
+ * });
1254
+ * ```
1255
+ *
1256
+ * @see {@link genAdapter} for better type inference in complex chains
1257
+ * @see {@link asyncGen} for async operations
1258
+ */
1259
+ static gen(genFn) {
1260
+ const iterator = genFn();
1261
+ let nextArg;
1262
+ let currentResult;
1263
+ while (true) {
1264
+ const next = iterator.next(nextArg);
1265
+ if (next.done) {
1266
+ currentResult = ExperimentalOption.Some(next.value);
1267
+ break;
1268
+ }
1269
+ let yielded = next.value;
1270
+ if (isCapturedTrace(yielded)) yielded = yielded.value;
1271
+ if (yielded.isNone()) {
1272
+ iterator.return?.(void 0);
1273
+ currentResult = ExperimentalOption.None;
1274
+ break;
1275
+ }
1276
+ nextArg = yielded.unwrap();
1277
+ }
1278
+ return currentResult;
1279
+ }
1280
+ /**
1281
+ * Generator-based syntax for chaining ExperimentalOption operations with an adapter function.
1282
+ *
1283
+ * Provides better type inference and IDE support compared to {@link gen}.
1284
+ * The `$` adapter wraps ExperimentalOptions and enables clearer type tracking.
1285
+ *
1286
+ * Short-circuits on first `None`, returning singleton `None`. Uses iteration
1287
+ * instead of recursion to avoid stack overflow on deep chains.
1288
+ *
1289
+ * @template Eff - The effect type (inferred from usage)
1290
+ * @template T - The return type of the generator
1291
+ * @param genFn - A generator function receiving an adapter `$`
1292
+ * @returns `Some<T>` with the generator's return value, or `None`
1293
+ *
1294
+ * @example
1295
+ * ```ts
1296
+ * // Better type inference
1297
+ * const result = ExperimentalOption.genAdapter(function* ($) {
1298
+ * const a = yield* $(ExperimentalOption.Some(1));
1299
+ * const b = yield* $(ExperimentalOption.Some(2));
1300
+ * return a + b;
1301
+ * });
1302
+ * // Some(3)
1303
+ *
1304
+ * // Deep nested access with better type safety
1305
+ * const email = ExperimentalOption.genAdapter(function* ($) {
1306
+ * const user = yield* $(ExperimentalOption.fromNullable(apiResponse?.user));
1307
+ * const profile = yield* $(ExperimentalOption.fromNullable(user?.profile));
1308
+ * const contact = yield* $(ExperimentalOption.fromNullable(profile?.contact));
1309
+ * return contact?.email;
1310
+ * });
1311
+ *
1312
+ * // Complex validation chain
1313
+ * const validConfig = ExperimentalOption.genAdapter(function* ($) {
1314
+ * const raw = yield* $(loadConfig());
1315
+ * const parsed = yield* $(parseConfig(raw));
1316
+ * const validated = yield* $(validateConfig(parsed));
1317
+ * return validated;
1318
+ * });
1319
+ * ```
1320
+ *
1321
+ * @see {@link gen} for simpler chains without adapter
1322
+ * @see {@link asyncGenAdapter} for async operations
1323
+ */
1324
+ static genAdapter(genFn) {
1325
+ const adapter = (option) => new OptionYieldWrap(option);
1326
+ const iterator = genFn(adapter);
1327
+ let nextArg;
1328
+ let currentResult;
1329
+ while (true) {
1330
+ const next = iterator.next(nextArg);
1331
+ if (next.done) {
1332
+ currentResult = ExperimentalOption.Some(next.value);
1333
+ break;
1334
+ }
1335
+ let option = next.value.option;
1336
+ if (isCapturedTrace(option)) option = option.value;
1337
+ if (option.isNone()) {
1338
+ iterator.return?.(void 0);
1339
+ currentResult = ExperimentalOption.None;
1340
+ break;
1341
+ }
1342
+ nextArg = option.unwrap();
1343
+ }
1344
+ return currentResult;
1345
+ }
1346
+ /**
1347
+ * Async generator-based syntax for chaining ExperimentalOption operations (simplified, no adapter).
1348
+ *
1349
+ * Use `yield*` with `ExperimentalOption<T>` values directly. For `Promise<ExperimentalOption<T>>`,
1350
+ * await first then `yield*`.
1351
+ *
1352
+ * Short-circuits on first `None`, returning singleton `None`. Uses async iteration
1353
+ * instead of recursion to avoid stack overflow on deep chains.
1354
+ *
1355
+ * @template T - The return type of the generator
1356
+ * @param genFn - An async generator function that yields ExperimentalOptions
1357
+ * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
1358
+ *
1359
+ * @example
1360
+ * ```ts
1361
+ * // Simple async chain
1362
+ * const result = await ExperimentalOption.asyncGen(async function* () {
1363
+ * const a = yield* ExperimentalOption.Some(1);
1364
+ * const b = yield* await asyncOperation(a); // await Promise<ExperimentalOption> first
1365
+ * const c = yield* ExperimentalOption.Some(3);
1366
+ * return a + b + c;
1367
+ * });
1368
+ * // Some(result)
1369
+ *
1370
+ * // None short-circuit in async
1371
+ * const shortCircuit = await ExperimentalOption.asyncGen(async function* () {
1372
+ * const data = yield* await fetchOptionalData();
1373
+ * const parsed = yield* parse(data); // Short-circuits on None
1374
+ * const validated = yield* validate(parsed); // Never executes
1375
+ * return validated;
1376
+ * });
1377
+ * // None
1378
+ *
1379
+ * // Mixed sync/async workflow
1380
+ * const result = await ExperimentalOption.asyncGen(async function* () {
1381
+ * const id = yield* ExperimentalOption.Some(parseInt(input)); // sync
1382
+ * const user = yield* await fetchUser(id); // async
1383
+ * const profile = yield* ExperimentalOption.fromNullable(user?.profile); // sync
1384
+ * const enriched = yield* await enrichProfile(profile); // async
1385
+ * return enriched;
1386
+ * });
1387
+ *
1388
+ * // Complex pipeline with multiple optional steps
1389
+ * async function processLead(email: string): Promise<ExperimentalOption<Lead>> {
1390
+ * return await ExperimentalOption.asyncGen(async function* () {
1391
+ * const normalized = yield* ExperimentalOption.Some(normalizeEmail(email));
1392
+ * const existing = yield* await findExistingLead(normalized);
1393
+ * const enriched = yield* await enrichLeadData(existing);
1394
+ * const validated = yield* validateLead(enriched);
1395
+ * return validated;
1396
+ * });
1397
+ * }
1398
+ * ```
1399
+ *
1400
+ * @see {@link asyncGenAdapter} for better type inference and cleaner syntax
1401
+ * @see {@link gen} for synchronous operations
1402
+ */
1403
+ static async asyncGen(genFn) {
1404
+ const iterator = genFn();
1405
+ let nextArg;
1406
+ let currentResult;
1407
+ while (true) {
1408
+ const next = await iterator.next(nextArg);
1409
+ if (next.done) {
1410
+ currentResult = ExperimentalOption.Some(next.value);
1411
+ break;
1412
+ }
1413
+ let option = next.value;
1414
+ if (isCapturedTrace(option)) option = option.value;
1415
+ if (option.isNone()) {
1416
+ await iterator.return?.(void 0);
1417
+ currentResult = ExperimentalOption.None;
1418
+ break;
1419
+ }
1420
+ nextArg = await option.unwrap();
1421
+ }
1422
+ return currentResult;
1423
+ }
1424
+ /**
1425
+ * Async generator-based syntax for chaining ExperimentalOption operations with an adapter function.
1426
+ *
1427
+ * The `$` adapter handles both sync `ExperimentalOption<T>` and async `Promise<ExperimentalOption<T>>`,
1428
+ * automatically awaiting promises. This provides cleaner syntax for mixed sync/async workflows.
1429
+ *
1430
+ * Short-circuits on first `None`, returning singleton `None`. Uses async iteration
1431
+ * instead of recursion to avoid stack overflow on deep chains.
1432
+ *
1433
+ * @template Eff - The effect type (inferred from usage)
1434
+ * @template T - The return type of the generator
1435
+ * @param genFn - An async generator function receiving an adapter `$`
1436
+ * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
1437
+ *
1438
+ * @example
1439
+ * ```ts
1440
+ * // No need to manually await - adapter handles it
1441
+ * const result = await ExperimentalOption.asyncGenAdapter(async function* ($) {
1442
+ * const a = yield* $(ExperimentalOption.Some(1)); // sync ExperimentalOption
1443
+ * const b = yield* $(asyncOperation(a)); // Promise<ExperimentalOption> - auto-awaited
1444
+ * const c = yield* $(ExperimentalOption.Some(3));
1445
+ * return a + b + c;
1446
+ * });
1447
+ *
1448
+ * // Complex workflow with database and API calls
1449
+ * const userData = await ExperimentalOption.asyncGenAdapter(async function* ($) {
1450
+ * const session = yield* $(getSession()); // Promise<ExperimentalOption<Session>>
1451
+ * const userId = yield* $(ExperimentalOption.fromNullable(session?.userId));
1452
+ * const profile = yield* $(await fetchProfile(userId)); // Promise<ExperimentalOption<Profile>>
1453
+ * const preferences = yield* $(ExperimentalOption.fromNullable(profile?.preferences));
1454
+ * const enriched = yield* $(await enrichPreferences(preferences));
1455
+ * return enriched;
1456
+ * });
1457
+ *
1458
+ * // Real-world: Optional data enrichment
1459
+ * async function getProductDetails(productId: string): Promise<ExperimentalOption<ProductDetails>> {
1460
+ * return await ExperimentalOption.asyncGenAdapter(async function* ($) {
1461
+ * const product = yield* $(await fetchProduct(productId));
1462
+ * const pricing = yield* $(await fetchPricing(product.sku));
1463
+ * const inventory = yield* $(await checkInventory(product.id));
1464
+ * const reviews = yield* $(await fetchReviews(product.id));
1465
+ * const related = yield* $(await fetchRelatedProducts(product.category));
1466
+ *
1467
+ * return { product, pricing, inventory, reviews, related };
1468
+ * });
1469
+ * }
1470
+ * ```
1471
+ *
1472
+ * @see {@link asyncGen} when you want explicit `await` for async operations
1473
+ * @see {@link genAdapter} for synchronous operations
1474
+ */
1475
+ static async asyncGenAdapter(genFn) {
1476
+ const adapter = (option) => new AsyncOptionYieldWrap(option);
1477
+ const iterator = genFn(adapter);
1478
+ let nextArg;
1479
+ let currentResult;
1480
+ while (true) {
1481
+ const next = await iterator.next(nextArg);
1482
+ if (next.done) {
1483
+ currentResult = ExperimentalOption.Some(next.value);
1484
+ break;
1485
+ }
1486
+ let option = await next.value.option;
1487
+ if (isCapturedTrace(option)) option = option.value;
1488
+ if (option.isNone()) {
1489
+ await iterator.return?.(void 0);
1490
+ currentResult = ExperimentalOption.None;
1491
+ break;
1492
+ }
1493
+ nextArg = await option.unwrap();
1494
+ }
1495
+ return currentResult;
1496
+ }
1497
+ };
1498
+
1499
+ //#endregion
1500
+ export { ExperimentalOption, UnwrappedNone };
1501
+ //# sourceMappingURL=option-experimental.mjs.map