@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,805 @@
1
+ import { UNIT } from "./unit.mjs";
2
+ import { CapturedTrace, isCapturedTrace, isPromiseLike } from "./utils.mjs";
3
+ import { Result } from "./result.mjs";
4
+
5
+ //#region src/option.ts
6
+ var UnwrappedNone = class extends Error {
7
+ name = "UnwrapError";
8
+ constructor() {
9
+ super("Attempted to unwrap Option::None");
10
+ }
11
+ };
12
+ const UNWRAPPED_NONE_ERR = new UnwrappedNone();
13
+ const NONE_VAL = Symbol("Option::None");
14
+ /**
15
+ * Wrapper that makes Option yieldable with proper type tracking.
16
+ *
17
+ * @internal
18
+ */
19
+ var OptionYieldWrap = class {
20
+ constructor(option) {
21
+ this.option = option;
22
+ }
23
+ *[Symbol.iterator]() {
24
+ return yield this;
25
+ }
26
+ };
27
+ /**
28
+ * Wrapper that makes Option yieldable in async generators with proper type tracking.
29
+ *
30
+ * @internal
31
+ */
32
+ var AsyncOptionYieldWrap = class {
33
+ option;
34
+ constructor(option) {
35
+ this.option = isPromiseLike(option) ? option : Promise.resolve(option);
36
+ }
37
+ async *[Symbol.asyncIterator]() {
38
+ return yield this;
39
+ }
40
+ };
41
+ /**
42
+ * Represents an optional value: `Some<T>` or `None`.
43
+ * Provides composable, null-safe transformation and chaining methods.
44
+ */
45
+ var Option = class Option {
46
+ /** Discriminant tag for type-level identification */
47
+ _tag;
48
+ #ctx;
49
+ #val;
50
+ /**
51
+ * Creates a new Option instance with internal context.
52
+ *
53
+ * @param val - Stored value or sentinel
54
+ * @param ctx - Internal async tracking context
55
+ * @param tag - Discriminant tag for Some/None
56
+ *
57
+ * @internal
58
+ */
59
+ constructor(val, ctx, tag) {
60
+ this.#val = val;
61
+ this.#ctx = ctx;
62
+ this._tag = tag;
63
+ }
64
+ /** Singleton None instance */
65
+ static None = new Option(NONE_VAL, { promiseNoneSlot: true }, "None");
66
+ /**
67
+ * Creates a Some variant containing the provided value.
68
+ *
69
+ * @template Inner - Type of the wrapped value
70
+ * @param val - Value to wrap in Some
71
+ * @returns Option in the Some state
72
+ */
73
+ static Some(val) {
74
+ return new Option(val, { promiseNoneSlot: false }, "Some");
75
+ }
76
+ /**
77
+ * Creates an Option from a nullable value, returning None for null/undefined.
78
+ *
79
+ * @template T - Input type that may include null/undefined
80
+ * @param val - Value to convert
81
+ * @returns Some for non-nullish values, otherwise None
82
+ */
83
+ static fromNullable(val) {
84
+ return val === null || val === void 0 ? Option.None : Option.Some(val);
85
+ }
86
+ /**
87
+ * Creates an Option from a potentially falsy value, returning None for falsy.
88
+ *
89
+ * Treats false, 0, "", null, and undefined as absence.
90
+ *
91
+ * @template T - Input type
92
+ * @param val - Value to convert
93
+ * @returns Some for truthy values, otherwise None
94
+ */
95
+ static fromFalsy(val) {
96
+ return val ? Option.Some(val) : Option.None;
97
+ }
98
+ /**
99
+ * Creates an Option based on a predicate.
100
+ *
101
+ * @template T - Input type
102
+ * @param val - Value to test
103
+ * @param pred - Predicate to decide Some vs None
104
+ * @returns Some when predicate passes, otherwise None
105
+ */
106
+ static fromPredicate(val, pred) {
107
+ return pred(val) ? Option.Some(val) : Option.None;
108
+ }
109
+ /**
110
+ * Wraps a Promise<Option<T>> as Option<Promise<T>>.
111
+ *
112
+ * NOTE: the returned value starts as `Some(Promise<T>)`; final `None` is known
113
+ * only after settlement. Use `toPromise()` (or await `unwrap`/`safeUnwrap`) to
114
+ * observe settled absence.
115
+ *
116
+ * @template U - Inner value type
117
+ * @param o - Promise resolving to an Option
118
+ * @returns Option containing a Promise of the inner value
119
+ */
120
+ static fromPromise(o) {
121
+ const ctx = { promiseNoneSlot: false };
122
+ return new Option(new Promise((resolve, reject) => o.then((innerOpt) => {
123
+ if (innerOpt.isNone()) ctx.promiseNoneSlot = true;
124
+ resolve(innerOpt.#val);
125
+ }, reject)), ctx, "Some");
126
+ }
127
+ /**
128
+ * Combines multiple Options into a single Option of an array.
129
+ *
130
+ * Returns Some of all values if all inputs are Some; otherwise None.
131
+ *
132
+ * @template T - Variadic tuple of Option types
133
+ * @param options - Options to combine
134
+ * @returns Some of tuple values, or None if any input is None
135
+ */
136
+ static all(...options) {
137
+ const vals = [];
138
+ for (const opt of options) {
139
+ if (opt.isNone()) return Option.None;
140
+ vals.push(opt.#val);
141
+ }
142
+ return Option.Some(vals);
143
+ }
144
+ /**
145
+ * Returns the first Some in the list, or None if all are None.
146
+ *
147
+ * For async Some values, settlement is awaited and selection follows input order.
148
+ *
149
+ * @template T - Value type
150
+ * @param options - Options to search
151
+ * @returns The first Some found, otherwise None
152
+ */
153
+ static any(...options) {
154
+ const pending = [];
155
+ for (const opt of options) if (opt.isSome()) {
156
+ if (isPromiseLike(opt.#val)) {
157
+ pending.push(opt);
158
+ continue;
159
+ }
160
+ return opt;
161
+ }
162
+ if (pending.length === 0) return Option.None;
163
+ const ctx = { promiseNoneSlot: false };
164
+ return new Option(Promise.all(pending.map(async (opt) => {
165
+ const val = await opt.#val;
166
+ return {
167
+ isNone: opt.#ctx.promiseNoneSlot || val === NONE_VAL,
168
+ val
169
+ };
170
+ })).then((settled) => {
171
+ for (const item of settled) if (!item.isNone) return item.val;
172
+ ctx.promiseNoneSlot = true;
173
+ return NONE_VAL;
174
+ }), ctx, "Some");
175
+ }
176
+ /**
177
+ * Type guard that narrows to Some.
178
+ *
179
+ * @returns true if this Option is Some
180
+ */
181
+ isSome() {
182
+ return this._tag === "Some" && !this.isNone();
183
+ }
184
+ /**
185
+ * Type guard that narrows to None.
186
+ *
187
+ * Includes async None tracking for Option<Promise<T>>.
188
+ *
189
+ * @returns true if this Option is None
190
+ */
191
+ isNone() {
192
+ return this._tag === "None" || this.#val === NONE_VAL || isPromiseLike(this.#val) && this.#ctx.promiseNoneSlot;
193
+ }
194
+ /**
195
+ * Type guard for the UNIT sentinel value.
196
+ *
197
+ * @returns true if the contained value is UNIT
198
+ */
199
+ isUnit() {
200
+ return this.#val === UNIT;
201
+ }
202
+ unwrap() {
203
+ if (this.isNone()) throw UNWRAPPED_NONE_ERR;
204
+ const curr = this.#val;
205
+ if (isPromiseLike(curr)) {
206
+ const ctx = this.#ctx;
207
+ return curr.then((value) => {
208
+ if (value === NONE_VAL || ctx.promiseNoneSlot) throw UNWRAPPED_NONE_ERR;
209
+ return value;
210
+ });
211
+ }
212
+ return curr;
213
+ }
214
+ /**
215
+ * Returns the contained value or the provided default.
216
+ *
217
+ * @param defaultValue - Value to use when None
218
+ * @returns The contained value or default
219
+ */
220
+ unwrapOr(defaultValue) {
221
+ if (this.isNone()) return defaultValue;
222
+ return this.#val;
223
+ }
224
+ /**
225
+ * Returns the contained value or computes a default lazily.
226
+ *
227
+ * @param fn - Default factory invoked only when None
228
+ * @returns The contained value or computed default
229
+ */
230
+ unwrapOrElse(fn) {
231
+ if (this.isNone()) return fn();
232
+ return this.#val;
233
+ }
234
+ safeUnwrap() {
235
+ if (this.isNone()) return null;
236
+ const curr = this.#val;
237
+ if (isPromiseLike(curr)) {
238
+ const ctx = this.#ctx;
239
+ return curr.then((value) => value === NONE_VAL || ctx.promiseNoneSlot ? null : value);
240
+ }
241
+ return curr;
242
+ }
243
+ /**
244
+ * Exhaustive pattern match on Option state.
245
+ *
246
+ * @template U - Result type
247
+ * @param cases - Handlers for Some and None
248
+ * @returns Result of the matching handler
249
+ */
250
+ match(cases) {
251
+ if (this.isNone()) return cases.None();
252
+ return cases.Some(this.#val);
253
+ }
254
+ map(mapper) {
255
+ if (this.isNone()) return Option.None;
256
+ const curr = this.#val;
257
+ if (isPromiseLike(curr)) {
258
+ const p = curr;
259
+ const newCtx = { promiseNoneSlot: false };
260
+ return new Option(Option.safeMap(p, mapper, newCtx), newCtx, "Some");
261
+ }
262
+ const transformed = mapper(curr);
263
+ if (isPromiseLike(transformed)) return new Option(transformed, { promiseNoneSlot: false }, "Some");
264
+ return new Option(transformed, { promiseNoneSlot: false }, "Some");
265
+ }
266
+ /**
267
+ * Safely maps a promised value while tracking None in async context.
268
+ *
269
+ * @template Curr - Input value type
270
+ * @template U - Output value type
271
+ * @param p - Promise to map over
272
+ * @param mapper - Transform function
273
+ * @param ctx - Async context for None tracking
274
+ * @returns Promise of the transformed value or sentinel
275
+ */
276
+ static safeMap(p, mapper, ctx) {
277
+ return p.then((v) => {
278
+ if (v === NONE_VAL) {
279
+ ctx.promiseNoneSlot = true;
280
+ return NONE_VAL;
281
+ }
282
+ return mapper(v);
283
+ });
284
+ }
285
+ mapOr(defaultVal, fn) {
286
+ if (this.isNone()) return isPromiseLike(this.#val) ? Promise.resolve(defaultVal) : defaultVal;
287
+ const curr = this.#val;
288
+ if (isPromiseLike(curr)) {
289
+ const p = curr;
290
+ const ctx = this.#ctx;
291
+ return p.then(async (v) => {
292
+ if (v === NONE_VAL || ctx.promiseNoneSlot) return defaultVal;
293
+ return fn(v);
294
+ });
295
+ }
296
+ return fn(curr);
297
+ }
298
+ flatMap(mapper) {
299
+ if (this.isNone()) return Option.None;
300
+ const curr = this.#val;
301
+ if (isPromiseLike(curr)) {
302
+ const p = curr;
303
+ const newCtx = { promiseNoneSlot: false };
304
+ const castedNone = NONE_VAL;
305
+ return new Option(new Promise((resolve, reject) => {
306
+ p.then((innerVal) => {
307
+ if (innerVal === NONE_VAL) {
308
+ newCtx.promiseNoneSlot = true;
309
+ resolve(castedNone);
310
+ } else {
311
+ const r = mapper(innerVal);
312
+ if (isPromiseLike(r)) r.then((innerOpt) => {
313
+ if (innerOpt.isNone()) newCtx.promiseNoneSlot = true;
314
+ resolve(innerOpt.#val);
315
+ }, reject);
316
+ else if (r.isNone()) {
317
+ newCtx.promiseNoneSlot = true;
318
+ resolve(NONE_VAL);
319
+ } else resolve(r.#val);
320
+ }
321
+ }, reject);
322
+ }), newCtx, "Some");
323
+ }
324
+ const mapped = mapper(curr);
325
+ if (isPromiseLike(mapped)) return Option.fromPromise(mapped);
326
+ return mapped;
327
+ }
328
+ filter(pred) {
329
+ if (this.isNone()) return Option.None;
330
+ const curr = this.#val;
331
+ if (isPromiseLike(curr)) {
332
+ const p = curr;
333
+ const newCtx = { promiseNoneSlot: false };
334
+ return new Option(p.then(async (v) => {
335
+ if (v === NONE_VAL) {
336
+ newCtx.promiseNoneSlot = true;
337
+ return NONE_VAL;
338
+ }
339
+ if (!await pred(v)) {
340
+ newCtx.promiseNoneSlot = true;
341
+ return NONE_VAL;
342
+ }
343
+ return v;
344
+ }), newCtx, "Some");
345
+ }
346
+ const result = pred(curr);
347
+ if (isPromiseLike(result)) {
348
+ const newCtx = { promiseNoneSlot: false };
349
+ return new Option(result.then((passed) => {
350
+ if (passed) return curr;
351
+ newCtx.promiseNoneSlot = true;
352
+ return NONE_VAL;
353
+ }), newCtx, "Some");
354
+ }
355
+ return result ? this : Option.None;
356
+ }
357
+ zip(fn) {
358
+ if (this.isNone()) return Option.None;
359
+ const curr = this.#val;
360
+ if (isPromiseLike(curr)) {
361
+ const val = curr;
362
+ const newCtx = { promiseNoneSlot: false };
363
+ return new Option(val.then(async (v) => {
364
+ if (v === NONE_VAL) {
365
+ newCtx.promiseNoneSlot = true;
366
+ return NONE_VAL;
367
+ }
368
+ return [v, await fn(v)];
369
+ }), newCtx, "Some");
370
+ }
371
+ const value = curr;
372
+ const u = fn(value);
373
+ if (isPromiseLike(u)) return new Option(u.then((uu) => [value, uu]), { promiseNoneSlot: false }, "Some");
374
+ return new Option([value, u], { promiseNoneSlot: false }, "Some");
375
+ }
376
+ flatZip(fn) {
377
+ if (this.isNone()) return Option.None;
378
+ const curr = this.#val;
379
+ if (isPromiseLike(curr)) {
380
+ const val = curr;
381
+ const newCtx = { promiseNoneSlot: false };
382
+ return new Option(val.then(async (v) => {
383
+ if (v === NONE_VAL) {
384
+ newCtx.promiseNoneSlot = true;
385
+ return NONE_VAL;
386
+ }
387
+ const next = await fn(v);
388
+ if (next.isNone()) {
389
+ newCtx.promiseNoneSlot = true;
390
+ return NONE_VAL;
391
+ }
392
+ return [v, next.#val];
393
+ }), newCtx, "Some");
394
+ }
395
+ const c = curr;
396
+ const u = fn(c);
397
+ if (isPromiseLike(u)) {
398
+ const newCtx = { promiseNoneSlot: false };
399
+ return new Option(u.then((uu) => {
400
+ if (uu.isNone()) {
401
+ newCtx.promiseNoneSlot = true;
402
+ return NONE_VAL;
403
+ }
404
+ return [c, uu.#val];
405
+ }), newCtx, "Some");
406
+ }
407
+ return u.map((inner) => [c, inner]);
408
+ }
409
+ /**
410
+ * Executes a side effect for Some values and returns self.
411
+ *
412
+ * For `Option<Promise<T>>`, `tap` receives the wrapped promise object,
413
+ * not the settled inner value.
414
+ *
415
+ * @param fn - Side effect function
416
+ * @returns The same Option (chainable)
417
+ */
418
+ tap(fn) {
419
+ if (this.isSome()) fn(this.#val);
420
+ return this;
421
+ }
422
+ /**
423
+ * Converts this Option to a Result, using the provided error for None.
424
+ *
425
+ * @template E - Error type
426
+ * @param error - Error value for None
427
+ * @returns Ok with value when Some, otherwise Err with error
428
+ */
429
+ toResult(error) {
430
+ if (this.isNone()) return Result.Err(error);
431
+ return Result.Ok(this.#val);
432
+ }
433
+ /**
434
+ * Resolves the inner promise (if any) while preserving Option structure.
435
+ *
436
+ * @template Curr - Awaited value type
437
+ * @returns Promise of Option with awaited value, or None
438
+ */
439
+ async toPromise() {
440
+ if (this.isNone()) return Option.None;
441
+ const curr = this.#val;
442
+ let inner;
443
+ if (isPromiseLike(curr)) {
444
+ const awaited = await curr;
445
+ if (awaited === NONE_VAL || this.#ctx.promiseNoneSlot) return Option.None;
446
+ inner = awaited;
447
+ } else inner = curr;
448
+ return new Option(inner, this.#ctx, "Some");
449
+ }
450
+ /**
451
+ * Maps over array elements inside an Option<Array<T>>.
452
+ *
453
+ * @template Inner - Array element type
454
+ * @template Out - Mapped element type
455
+ * @param mapper - Function to map each element
456
+ * @returns Option containing the mapped array
457
+ * @throws TypeError if called on a non-array value
458
+ */
459
+ innerMap(mapper) {
460
+ if (this.isNone()) return Option.None;
461
+ if (!Array.isArray(this.#val)) throw new TypeError("innerMap can only be called on Option<Array<T>>");
462
+ return new Option(this.#val.map(mapper), this.#ctx, "Some");
463
+ }
464
+ /**
465
+ * Returns a string representation of the Option.
466
+ *
467
+ * @returns "Option::None" or "Option::Some(value)"
468
+ */
469
+ toString() {
470
+ if (this.isNone()) return "Option::None";
471
+ return `Option::Some(${String(this.#val)})`;
472
+ }
473
+ /**
474
+ * Makes Option iterable for use with generator-based syntax.
475
+ *
476
+ * Yields self and returns the unwrapped value when resumed.
477
+ * Used internally by {@link Option.gen} for `yield*` syntax.
478
+ *
479
+ * @example
480
+ * ```ts
481
+ * const result = Option.gen(function* () {
482
+ * const value = yield* Option.Some(42);
483
+ * return value * 2;
484
+ * });
485
+ * // Some(84)
486
+ * ```
487
+ *
488
+ * @internal
489
+ */
490
+ *[Symbol.iterator]() {
491
+ const trace = (/* @__PURE__ */ new Error()).stack;
492
+ return yield new CapturedTrace(this, trace);
493
+ }
494
+ /**
495
+ * Makes Option iterable for use with async generator-based syntax.
496
+ *
497
+ * Yields self and returns the unwrapped value when resumed.
498
+ * Used internally by {@link Option.asyncGen} for `yield*` syntax.
499
+ *
500
+ * @example
501
+ * ```ts
502
+ * const result = await Option.asyncGen(async function* () {
503
+ * const value = yield* await Promise.resolve(Option.Some(42));
504
+ * return value * 2;
505
+ * });
506
+ * // Some(84)
507
+ * ```
508
+ *
509
+ * @internal
510
+ */
511
+ async *[Symbol.asyncIterator]() {
512
+ const trace = (/* @__PURE__ */ new Error()).stack;
513
+ return yield new CapturedTrace(this, trace);
514
+ }
515
+ /**
516
+ * Generator-based syntax for chaining Option operations (simplified, no adapter).
517
+ *
518
+ * Provides imperative-style code while maintaining functional Option handling.
519
+ * Use `yield*` to unwrap Options or short-circuit on `None`.
520
+ *
521
+ * Short-circuits on first `None`, returning singleton `None`. Uses iteration
522
+ * instead of recursion to avoid stack overflow on deep chains.
523
+ *
524
+ * @template T - The return type of the generator
525
+ * @param genFn - A generator function that yields Options
526
+ * @returns `Some<T>` with the generator's return value, or `None`
527
+ *
528
+ * @example
529
+ * ```ts
530
+ * // Simple sync chain
531
+ * const result = Option.gen(function* () {
532
+ * const a = yield* Option.Some(1);
533
+ * const b = yield* Option.Some(2);
534
+ * return a + b;
535
+ * });
536
+ * // Some(3)
537
+ *
538
+ * // None short-circuit
539
+ * const shortCircuit = Option.gen(function* () {
540
+ * const a = yield* Option.Some(1);
541
+ * const b = yield* Option.None; // Short-circuits here
542
+ * const c = yield* Option.Some(3); // Never executes
543
+ * return a + b + c;
544
+ * });
545
+ * // None
546
+ *
547
+ * // Chaining optional operations
548
+ * const email = Option.gen(function* () {
549
+ * const user = yield* findUser(userId);
550
+ * const profile = yield* Option.fromNullable(user.profile);
551
+ * const settings = yield* Option.fromNullable(profile.settings);
552
+ * return settings.email;
553
+ * });
554
+ *
555
+ * // Nested optional access
556
+ * const city = Option.gen(function* () {
557
+ * const user = yield* Option.fromNullable(getUser());
558
+ * const address = yield* Option.fromNullable(user?.address);
559
+ * const city = yield* Option.fromNullable(address?.city);
560
+ * return city;
561
+ * });
562
+ * ```
563
+ *
564
+ * @see {@link genAdapter} for better type inference in complex chains
565
+ * @see {@link asyncGen} for async operations
566
+ */
567
+ static gen(genFn) {
568
+ const iterator = genFn();
569
+ let nextArg;
570
+ let currentResult;
571
+ while (true) {
572
+ const next = iterator.next(nextArg);
573
+ if (next.done) {
574
+ currentResult = Option.Some(next.value);
575
+ break;
576
+ }
577
+ let yielded = next.value;
578
+ if (isCapturedTrace(yielded)) yielded = yielded.value;
579
+ if (yielded.isNone()) {
580
+ currentResult = Option.None;
581
+ break;
582
+ }
583
+ nextArg = yielded.unwrap();
584
+ }
585
+ return currentResult;
586
+ }
587
+ /**
588
+ * Generator-based syntax for chaining Option operations with an adapter function.
589
+ *
590
+ * Provides better type inference and IDE support compared to {@link gen}.
591
+ * The `$` adapter wraps Options and enables clearer type tracking.
592
+ *
593
+ * Short-circuits on first `None`, returning singleton `None`. Uses iteration
594
+ * instead of recursion to avoid stack overflow on deep chains.
595
+ *
596
+ * @template Eff - The effect type (inferred from usage)
597
+ * @template T - The return type of the generator
598
+ * @param genFn - A generator function receiving an adapter `$`
599
+ * @returns `Some<T>` with the generator's return value, or `None`
600
+ *
601
+ * @example
602
+ * ```ts
603
+ * // Better type inference
604
+ * const result = Option.genAdapter(function* ($) {
605
+ * const a = yield* $(Option.Some(1));
606
+ * const b = yield* $(Option.Some(2));
607
+ * return a + b;
608
+ * });
609
+ * // Some(3)
610
+ *
611
+ * // Deep nested access with better type safety
612
+ * const email = Option.genAdapter(function* ($) {
613
+ * const user = yield* $(Option.fromNullable(apiResponse?.user));
614
+ * const profile = yield* $(Option.fromNullable(user?.profile));
615
+ * const contact = yield* $(Option.fromNullable(profile?.contact));
616
+ * return contact?.email;
617
+ * });
618
+ *
619
+ * // Complex validation chain
620
+ * const validConfig = Option.genAdapter(function* ($) {
621
+ * const raw = yield* $(loadConfig());
622
+ * const parsed = yield* $(parseConfig(raw));
623
+ * const validated = yield* $(validateConfig(parsed));
624
+ * return validated;
625
+ * });
626
+ * ```
627
+ *
628
+ * @see {@link gen} for simpler chains without adapter
629
+ * @see {@link asyncGenAdapter} for async operations
630
+ */
631
+ static genAdapter(genFn) {
632
+ const adapter = (option) => new OptionYieldWrap(option);
633
+ const iterator = genFn(adapter);
634
+ let nextArg;
635
+ let currentResult;
636
+ while (true) {
637
+ const next = iterator.next(nextArg);
638
+ if (next.done) {
639
+ currentResult = Option.Some(next.value);
640
+ break;
641
+ }
642
+ let option = next.value.option;
643
+ if (isCapturedTrace(option)) option = option.value;
644
+ if (option.isNone()) {
645
+ currentResult = Option.None;
646
+ break;
647
+ }
648
+ nextArg = option.unwrap();
649
+ }
650
+ return currentResult;
651
+ }
652
+ /**
653
+ * Async generator-based syntax for chaining Option operations (simplified, no adapter).
654
+ *
655
+ * Use `yield*` with `Option<T>` values directly. For `Promise<Option<T>>`,
656
+ * await first then `yield*`.
657
+ *
658
+ * Short-circuits on first `None`, returning singleton `None`. Uses async iteration
659
+ * instead of recursion to avoid stack overflow on deep chains.
660
+ *
661
+ * @template T - The return type of the generator
662
+ * @param genFn - An async generator function that yields Options
663
+ * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
664
+ *
665
+ * @example
666
+ * ```ts
667
+ * // Simple async chain
668
+ * const result = await Option.asyncGen(async function* () {
669
+ * const a = yield* Option.Some(1);
670
+ * const b = yield* await asyncOperation(a); // await Promise<Option> first
671
+ * const c = yield* Option.Some(3);
672
+ * return a + b + c;
673
+ * });
674
+ * // Some(result)
675
+ *
676
+ * // None short-circuit in async
677
+ * const shortCircuit = await Option.asyncGen(async function* () {
678
+ * const data = yield* await fetchOptionalData();
679
+ * const parsed = yield* parse(data); // Short-circuits on None
680
+ * const validated = yield* validate(parsed); // Never executes
681
+ * return validated;
682
+ * });
683
+ * // None
684
+ *
685
+ * // Mixed sync/async workflow
686
+ * const result = await Option.asyncGen(async function* () {
687
+ * const id = yield* Option.Some(parseInt(input)); // sync
688
+ * const user = yield* await fetchUser(id); // async
689
+ * const profile = yield* Option.fromNullable(user?.profile); // sync
690
+ * const enriched = yield* await enrichProfile(profile); // async
691
+ * return enriched;
692
+ * });
693
+ *
694
+ * // Complex pipeline with multiple optional steps
695
+ * async function processLead(email: string): Promise<Option<Lead>> {
696
+ * return await Option.asyncGen(async function* () {
697
+ * const normalized = yield* Option.Some(normalizeEmail(email));
698
+ * const existing = yield* await findExistingLead(normalized);
699
+ * const enriched = yield* await enrichLeadData(existing);
700
+ * const validated = yield* validateLead(enriched);
701
+ * return validated;
702
+ * });
703
+ * }
704
+ * ```
705
+ *
706
+ * @see {@link asyncGenAdapter} for better type inference and cleaner syntax
707
+ * @see {@link gen} for synchronous operations
708
+ */
709
+ static async asyncGen(genFn) {
710
+ const iterator = genFn();
711
+ let nextArg;
712
+ let currentResult;
713
+ while (true) {
714
+ const next = await iterator.next(nextArg);
715
+ if (next.done) {
716
+ currentResult = Option.Some(next.value);
717
+ break;
718
+ }
719
+ let option = next.value;
720
+ if (isCapturedTrace(option)) option = option.value;
721
+ if (option.isNone()) {
722
+ currentResult = Option.None;
723
+ break;
724
+ }
725
+ nextArg = await option.unwrap();
726
+ }
727
+ return currentResult;
728
+ }
729
+ /**
730
+ * Async generator-based syntax for chaining Option operations with an adapter function.
731
+ *
732
+ * The `$` adapter handles both sync `Option<T>` and async `Promise<Option<T>>`,
733
+ * automatically awaiting promises. This provides cleaner syntax for mixed sync/async workflows.
734
+ *
735
+ * Short-circuits on first `None`, returning singleton `None`. Uses async iteration
736
+ * instead of recursion to avoid stack overflow on deep chains.
737
+ *
738
+ * @template Eff - The effect type (inferred from usage)
739
+ * @template T - The return type of the generator
740
+ * @param genFn - An async generator function receiving an adapter `$`
741
+ * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
742
+ *
743
+ * @example
744
+ * ```ts
745
+ * // No need to manually await - adapter handles it
746
+ * const result = await Option.asyncGenAdapter(async function* ($) {
747
+ * const a = yield* $(Option.Some(1)); // sync Option
748
+ * const b = yield* $(asyncOperation(a)); // Promise<Option> - auto-awaited
749
+ * const c = yield* $(Option.Some(3));
750
+ * return a + b + c;
751
+ * });
752
+ *
753
+ * // Complex workflow with database and API calls
754
+ * const userData = await Option.asyncGenAdapter(async function* ($) {
755
+ * const session = yield* $(getSession()); // Promise<Option<Session>>
756
+ * const userId = yield* $(Option.fromNullable(session?.userId));
757
+ * const profile = yield* $(await fetchProfile(userId)); // Promise<Option<Profile>>
758
+ * const preferences = yield* $(Option.fromNullable(profile?.preferences));
759
+ * const enriched = yield* $(await enrichPreferences(preferences));
760
+ * return enriched;
761
+ * });
762
+ *
763
+ * // Real-world: Optional data enrichment
764
+ * async function getProductDetails(productId: string): Promise<Option<ProductDetails>> {
765
+ * return await Option.asyncGenAdapter(async function* ($) {
766
+ * const product = yield* $(await fetchProduct(productId));
767
+ * const pricing = yield* $(await fetchPricing(product.sku));
768
+ * const inventory = yield* $(await checkInventory(product.id));
769
+ * const reviews = yield* $(await fetchReviews(product.id));
770
+ * const related = yield* $(await fetchRelatedProducts(product.category));
771
+ *
772
+ * return { product, pricing, inventory, reviews, related };
773
+ * });
774
+ * }
775
+ * ```
776
+ *
777
+ * @see {@link asyncGen} when you want explicit `await` for async operations
778
+ * @see {@link genAdapter} for synchronous operations
779
+ */
780
+ static async asyncGenAdapter(genFn) {
781
+ const adapter = (option) => new AsyncOptionYieldWrap(option);
782
+ const iterator = genFn(adapter);
783
+ let nextArg;
784
+ let currentResult;
785
+ while (true) {
786
+ const next = await iterator.next(nextArg);
787
+ if (next.done) {
788
+ currentResult = Option.Some(next.value);
789
+ break;
790
+ }
791
+ let option = await next.value.option;
792
+ if (isCapturedTrace(option)) option = option.value;
793
+ if (option.isNone()) {
794
+ currentResult = Option.None;
795
+ break;
796
+ }
797
+ nextArg = await option.unwrap();
798
+ }
799
+ return currentResult;
800
+ }
801
+ };
802
+
803
+ //#endregion
804
+ export { Option, UnwrappedNone };
805
+ //# sourceMappingURL=option.mjs.map