@carbonteq/fp 0.9.1 → 0.10.0

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