@carbonteq/fp 0.10.0 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -3
- package/dist/errors.cjs +1 -3
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +2 -5
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts +2 -5
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs +1 -2
- package/dist/errors.mjs.map +1 -1
- package/dist/flow-experimental.cjs +197 -151
- package/dist/flow-experimental.cjs.map +1 -1
- package/dist/flow-experimental.d.cts +11 -11
- package/dist/flow-experimental.d.cts.map +1 -1
- package/dist/flow-experimental.d.mts +11 -11
- package/dist/flow-experimental.d.mts.map +1 -1
- package/dist/flow-experimental.mjs +196 -150
- package/dist/flow-experimental.mjs.map +1 -1
- package/dist/flow.cjs +194 -150
- package/dist/flow.cjs.map +1 -1
- package/dist/flow.d.cts +8 -10
- package/dist/flow.d.cts.map +1 -1
- package/dist/flow.d.mts +8 -10
- package/dist/flow.d.mts.map +1 -1
- package/dist/flow.mjs +193 -149
- package/dist/flow.mjs.map +1 -1
- package/dist/index.cjs +10 -10
- package/dist/index.d.cts +7 -7
- package/dist/index.d.mts +7 -7
- package/dist/index.mjs +7 -7
- package/dist/match.cjs +100 -9
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +14 -21
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +14 -21
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +100 -8
- package/dist/match.mjs.map +1 -1
- package/dist/option-experimental.cjs +101 -57
- package/dist/option-experimental.cjs.map +1 -1
- package/dist/option-experimental.d.cts +7 -10
- package/dist/option-experimental.d.cts.map +1 -1
- package/dist/option-experimental.d.mts +7 -10
- package/dist/option-experimental.d.mts.map +1 -1
- package/dist/option-experimental.mjs +100 -56
- package/dist/option-experimental.mjs.map +1 -1
- package/dist/option.cjs +170 -118
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +27 -19
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +27 -19
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +169 -117
- package/dist/option.mjs.map +1 -1
- package/dist/result-experimental.cjs +197 -117
- package/dist/result-experimental.cjs.map +1 -1
- package/dist/result-experimental.d.cts +26 -26
- package/dist/result-experimental.d.cts.map +1 -1
- package/dist/result-experimental.d.mts +26 -26
- package/dist/result-experimental.d.mts.map +1 -1
- package/dist/result-experimental.mjs +195 -115
- package/dist/result-experimental.mjs.map +1 -1
- package/dist/result.cjs +245 -173
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +26 -22
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +26 -22
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +243 -171
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +3 -5
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +6 -8
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +6 -8
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +3 -4
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +1 -3
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +2 -5
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +2 -5
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +1 -2
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +35 -3
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +7 -6
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +7 -6
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +34 -3
- package/dist/utils.mjs.map +1 -1
- package/examples/README.md +14 -0
- package/examples/flow/04-complex-backend.ts +7 -4
- package/examples/flow-experimental/04-complex-backend.ts +7 -4
- package/examples/match/01-stable-match.ts +7 -0
- package/examples/match-experimental/01-experimental-match.ts +7 -0
- package/package.json +22 -31
package/dist/option.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"option.cjs","names":["isPromiseLike","#ctx","#val","UNIT","Result","CapturedTrace","isCapturedTrace"],"sources":["../src/option.ts"],"sourcesContent":["import { Result } from \"./result.js\"\nimport { UNIT } from \"./unit.js\"\nimport { CapturedTrace, isCapturedTrace, isPromiseLike } from \"./utils.js\"\n\ntype Mapper<T, U> = (val: T) => U\ntype AsyncMapper<T, U> = (val: T) => Promise<U>\ntype FlatMapper<T, U> = (val: T) => Option<U>\ntype AsyncFlatMapper<T, U> = (val: T) => Promise<Option<U>>\ntype Predicate<T> = (val: T) => boolean\ntype FilterPredicate<T> = (val: Awaited<T>) => boolean\ntype AsyncPredicate<T> = (val: Awaited<T>) => Promise<boolean>\ntype Falsy = false | 0 | \"\" | null | undefined\n\nexport class UnwrappedNone extends Error {\n readonly name = \"UnwrapError\"\n\n constructor() {\n super(\"Attempted to unwrap Option::None\")\n }\n}\n\nconst UNWRAPPED_NONE_ERR = new UnwrappedNone()\n\nconst NONE_VAL = Symbol(\"Option::None\")\n\n/** Option alias for presence-without-payload values. */\nexport type UnitOption = Option<UNIT>\n/** Extracts the contained value type from an Option type. */\nexport type UnwrapOption<T> = T extends Option<infer R> ? R : never\n\ntype CombinedOptions<T extends Option<unknown>[]> = {\n [K in keyof T]: UnwrapOption<T[K]>\n}\n\ntype OptionCtx = { promiseNoneSlot: boolean }\n\ninterface MatchCases<T, U> {\n Some: (val: T) => U\n None: () => U\n}\n\n/**\n * Wrapper that makes Option yieldable with proper type tracking.\n *\n * @internal\n */\nclass OptionYieldWrap<T> {\n constructor(readonly option: Option<T>) {}\n\n *[Symbol.iterator](): Generator<OptionYieldWrap<T>, T, unknown> {\n return (yield this) as T\n }\n}\n\n/**\n * Wrapper that makes Option yieldable in async generators with proper type tracking.\n *\n * @internal\n */\nclass AsyncOptionYieldWrap<T> {\n readonly option: Promise<Option<T>>\n\n constructor(option: Option<T> | Promise<Option<T>>) {\n this.option = (\n isPromiseLike(option) ? option : Promise.resolve(option)\n ) as Promise<Option<T>>\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<\n AsyncOptionYieldWrap<T>,\n Awaited<T>,\n unknown\n > {\n return (yield this) as Awaited<T>\n }\n}\n\n/**\n * Represents an optional value: `Some<T>` or `None`.\n * Provides composable, null-safe transformation and chaining methods.\n */\nexport class Option<T> {\n /** Discriminant tag for type-level identification */\n readonly _tag: \"Some\" | \"None\"\n\n readonly #ctx: OptionCtx\n readonly #val: T\n\n /**\n * Creates a new Option instance with internal context.\n *\n * @param val - Stored value or sentinel\n * @param ctx - Internal async tracking context\n * @param tag - Discriminant tag for Some/None\n *\n * @internal\n */\n private constructor(val: T, ctx: OptionCtx, tag: \"Some\" | \"None\") {\n this.#val = val\n this.#ctx = ctx\n this._tag = tag\n }\n\n /** Singleton None instance */\n static readonly None: Option<never> = new Option(\n NONE_VAL as never,\n { promiseNoneSlot: true },\n \"None\",\n )\n\n /**\n * Creates a Some variant containing the provided value.\n *\n * @template Inner - Type of the wrapped value\n * @param val - Value to wrap in Some\n * @returns Option in the Some state\n */\n static Some<Inner>(this: void, val: Inner): Option<Inner> {\n return new Option(val, { promiseNoneSlot: false }, \"Some\")\n }\n\n /**\n * Creates an Option from a nullable value, returning None for null/undefined.\n *\n * @template T - Input type that may include null/undefined\n * @param val - Value to convert\n * @returns Some for non-nullish values, otherwise None\n */\n static fromNullable<T>(val: T): Option<NonNullable<T>> {\n return val === null || val === undefined\n ? Option.None\n : Option.Some(val as NonNullable<T>)\n }\n\n /**\n * Creates an Option from a potentially falsy value, returning None for falsy.\n *\n * Treats false, 0, \"\", null, and undefined as absence.\n *\n * @template T - Input type\n * @param val - Value to convert\n * @returns Some for truthy values, otherwise None\n */\n static fromFalsy<T>(val: T | Falsy): Option<T> {\n return val ? Option.Some(val as T) : Option.None\n }\n\n /**\n * Creates an Option based on a predicate.\n *\n * @template T - Input type\n * @param val - Value to test\n * @param pred - Predicate to decide Some vs None\n * @returns Some when predicate passes, otherwise None\n */\n static fromPredicate<T>(val: T, pred: Predicate<T>): Option<T> {\n return pred(val) ? Option.Some(val) : Option.None\n }\n\n /**\n * Wraps a Promise<Option<T>> as Option<Promise<T>>.\n *\n * NOTE: the returned value starts as `Some(Promise<T>)`; final `None` is known\n * only after settlement. Use `toPromise()` (or await `unwrap`/`safeUnwrap`) to\n * observe settled absence.\n *\n * @template U - Inner value type\n * @param o - Promise resolving to an Option\n * @returns Option containing a Promise of the inner value\n */\n static fromPromise<U>(o: Promise<Option<U>>): Option<Promise<U>> {\n const ctx: OptionCtx = { promiseNoneSlot: false }\n const p = new Promise<U>((resolve, reject) =>\n o.then((innerOpt) => {\n if (innerOpt.isNone()) {\n ctx.promiseNoneSlot = true\n }\n resolve(innerOpt.#val)\n }, reject),\n )\n\n return new Option(p, ctx, \"Some\")\n }\n\n /**\n * Combines multiple Options into a single Option of an array.\n *\n * Returns Some of all values if all inputs are Some; otherwise None.\n *\n * @template T - Variadic tuple of Option types\n * @param options - Options to combine\n * @returns Some of tuple values, or None if any input is None\n */\n static all<T extends Option<unknown>[]>(\n ...options: T\n ): Option<CombinedOptions<T>> {\n const vals = [] as CombinedOptions<T>\n\n for (const opt of options) {\n if (opt.isNone()) return Option.None\n vals.push(opt.#val)\n }\n\n return Option.Some(vals)\n }\n\n /**\n * Returns the first Some in the list, or None if all are None.\n *\n * For async Some values, settlement is awaited and selection follows input order.\n *\n * @template T - Value type\n * @param options - Options to search\n * @returns The first Some found, otherwise None\n */\n static any<T>(...options: Option<T>[]): Option<T> {\n const pending: Option<T>[] = []\n\n for (const opt of options) {\n if (opt.isSome()) {\n if (isPromiseLike(opt.#val)) {\n pending.push(opt)\n continue\n }\n return opt\n }\n }\n\n if (pending.length === 0) {\n return Option.None\n }\n\n const ctx: OptionCtx = { promiseNoneSlot: false }\n const p = Promise.all(\n pending.map(async (opt) => {\n const val = await (opt.#val as Promise<unknown>)\n const isNone = opt.#ctx.promiseNoneSlot || val === NONE_VAL\n return { isNone, val }\n }),\n ).then((settled) => {\n for (const item of settled) {\n if (!item.isNone) {\n return item.val\n }\n }\n ctx.promiseNoneSlot = true\n return NONE_VAL\n })\n\n return new Option(p as T, ctx, \"Some\")\n }\n\n /**\n * Type guard that narrows to Some.\n *\n * @returns true if this Option is Some\n */\n isSome(): this is Option<T> & { readonly _tag: \"Some\" } {\n return this._tag === \"Some\" && !this.isNone()\n }\n\n /**\n * Type guard that narrows to None.\n *\n * Includes async None tracking for Option<Promise<T>>.\n *\n * @returns true if this Option is None\n */\n isNone(): this is Option<never> & { readonly _tag: \"None\" } {\n return (\n this._tag === \"None\" ||\n this.#val === NONE_VAL ||\n (isPromiseLike(this.#val) && this.#ctx.promiseNoneSlot)\n )\n }\n\n /**\n * Type guard for the UNIT sentinel value.\n *\n * @returns true if the contained value is UNIT\n */\n isUnit(): this is Option<UNIT> {\n return this.#val === UNIT\n }\n\n /**\n * Returns the contained value or throws if None.\n *\n * @throws UnwrappedNone when called on None\n * @returns The contained value\n */\n unwrap(this: Option<never>): never\n unwrap(this: Option<Promise<T>>): Promise<T>\n unwrap(this: Option<T>): T\n unwrap() {\n if (this.isNone()) {\n throw UNWRAPPED_NONE_ERR\n }\n\n const curr = this.#val\n if (isPromiseLike(curr)) {\n const ctx = this.#ctx\n return curr.then((value) => {\n if (value === NONE_VAL || ctx.promiseNoneSlot) {\n throw UNWRAPPED_NONE_ERR\n }\n return value\n })\n }\n\n return curr\n }\n\n /**\n * Returns the contained value or the provided default.\n *\n * @param defaultValue - Value to use when None\n * @returns The contained value or default\n */\n unwrapOr(defaultValue: T): T {\n if (this.isNone()) return defaultValue\n return this.#val\n }\n\n /**\n * Returns the contained value or computes a default lazily.\n *\n * @param fn - Default factory invoked only when None\n * @returns The contained value or computed default\n */\n unwrapOrElse(fn: () => T): T {\n if (this.isNone()) return fn()\n return this.#val\n }\n\n /**\n * Returns the contained value or null for None.\n *\n * @returns The contained value, or null when None\n */\n safeUnwrap(this: Option<never>): null\n safeUnwrap(this: Option<Promise<T>>): Promise<T | null>\n safeUnwrap(this: Option<T>): T | null\n safeUnwrap() {\n if (this.isNone()) return null\n\n const curr = this.#val\n if (isPromiseLike(curr)) {\n const ctx = this.#ctx\n return curr.then((value) =>\n value === NONE_VAL || ctx.promiseNoneSlot ? null : value,\n )\n }\n\n return curr\n }\n\n /**\n * Exhaustive pattern match on Option state.\n *\n * @template U - Result type\n * @param cases - Handlers for Some and None\n * @returns Result of the matching handler\n */\n match<U>(cases: MatchCases<T, U>): U {\n if (this.isNone()) {\n return cases.None()\n }\n return cases.Some(this.#val)\n }\n\n // -------------------------------------------------------------------------\n // map() - with async overloads per spec\n // -------------------------------------------------------------------------\n\n /**\n * Transforms the contained value and wraps it in a new Option.\n *\n * If None, returns None without calling the mapper. Supports async values\n * and async mappers; returns Option<Promise<U>> when async is involved.\n *\n * @template U - Result value type\n * @param mapper - Function to transform the contained value\n * @returns Option of the mapped value (sync or async)\n *\n * @see flatMap\n */\n map<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n mapper: AsyncMapper<Curr, U>,\n ): Option<Promise<U>>\n map<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n mapper: Mapper<Curr, U>,\n ): Option<Promise<U>>\n map<U>(this: Option<T>, mapper: AsyncMapper<T, U>): Option<Promise<U>>\n map<U>(this: Option<T>, mapper: Mapper<T, U>): Option<U>\n map<U, Curr = Awaited<T>>(\n mapper: Mapper<NoInfer<Curr>, U> | AsyncMapper<NoInfer<Curr>, U>,\n ) {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const p = curr as Promise<Curr>\n // Create a NEW context for this branch to avoid cross-branch mutation\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const safetlyMapped = Option.safeMap(p, mapper, newCtx)\n return new Option(safetlyMapped, newCtx, \"Some\")\n }\n\n const transformed = mapper(curr as unknown as Curr)\n if (isPromiseLike(transformed)) {\n return new Option(transformed, { promiseNoneSlot: false }, \"Some\")\n }\n // Sync operations can share context since there's no async mutation\n return new Option(transformed, { promiseNoneSlot: false }, \"Some\")\n }\n\n /**\n * Safely maps a promised value while tracking None in async context.\n *\n * @template Curr - Input value type\n * @template U - Output value type\n * @param p - Promise to map over\n * @param mapper - Transform function\n * @param ctx - Async context for None tracking\n * @returns Promise of the transformed value or sentinel\n */\n private static safeMap<Curr, U>(\n p: Promise<Curr>,\n mapper: (val: Curr) => U | Promise<U>,\n ctx: OptionCtx,\n ) {\n return p.then((v) => {\n if (v === NONE_VAL) {\n ctx.promiseNoneSlot = true\n return NONE_VAL\n }\n return mapper(v)\n }) as Promise<U>\n }\n\n // -------------------------------------------------------------------------\n // mapOr() - maps value or returns default (returns U, not Option<U>)\n // -------------------------------------------------------------------------\n\n /**\n * Maps the value or returns a default (unwrapped).\n *\n * If None, returns the default without calling fn. Supports async values\n * and async mappers; returns Promise<U> when async is involved.\n *\n * @template U - Result type\n * @param defaultVal - Value to return if None\n * @param fn - Mapper applied when Some\n * @returns Mapped value or default (sync or async)\n */\n mapOr<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n defaultVal: U,\n fn: Mapper<Curr, U>,\n ): Promise<U>\n mapOr<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n defaultVal: U,\n fn: AsyncMapper<Curr, U>,\n ): Promise<U>\n mapOr<U>(this: Option<T>, defaultVal: U, fn: AsyncMapper<T, U>): Promise<U>\n mapOr<U>(this: Option<T>, defaultVal: U, fn: Mapper<T, U>): U\n mapOr<U, Curr = Awaited<T>>(\n defaultVal: U,\n fn: Mapper<NoInfer<Curr>, U> | AsyncMapper<NoInfer<Curr>, U>,\n ): U | Promise<U> {\n if (this.isNone()) {\n return isPromiseLike(this.#val) ? Promise.resolve(defaultVal) : defaultVal\n }\n\n const curr = this.#val\n if (isPromiseLike(curr)) {\n const p = curr as Promise<Curr>\n const ctx = this.#ctx\n return p.then(async (v) => {\n if (v === NONE_VAL || ctx.promiseNoneSlot) return defaultVal\n return fn(v)\n })\n }\n\n return fn(curr as unknown as Curr)\n }\n\n // -------------------------------------------------------------------------\n // flatMap() - with async overloads per spec\n // -------------------------------------------------------------------------\n\n /**\n * Chains operations that return Option, flattening nested Options.\n *\n * If None, returns None without calling the mapper. Supports async values\n * and async mappers; returns Option<Promise<U>> when async is involved.\n *\n * @template U - Result value type\n * @param mapper - Function returning an Option\n * @returns Flattened Option result (sync or async)\n *\n * @see map\n */\n flatMap<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n mapper: AsyncFlatMapper<Curr, U>,\n ): Option<Promise<U>>\n flatMap<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n mapper: FlatMapper<Curr, U>,\n ): Option<Promise<U>>\n flatMap<U>(this: Option<T>, mapper: AsyncFlatMapper<T, U>): Option<Promise<U>>\n flatMap<U>(this: Option<T>, mapper: FlatMapper<T, U>): Option<U>\n flatMap<U, Curr = Awaited<T>>(\n mapper: FlatMapper<NoInfer<Curr>, U> | AsyncFlatMapper<NoInfer<Curr>, U>,\n ): Option<U> | Option<Promise<U>> {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const p = curr as Promise<Curr>\n // Create a NEW context for this branch to avoid cross-branch mutation\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const castedNone = NONE_VAL as unknown as Promise<U>\n const newP = new Promise<U>((resolve, reject) => {\n p.then((innerVal) => {\n if (innerVal === NONE_VAL) {\n newCtx.promiseNoneSlot = true\n resolve(castedNone)\n } else {\n const r = mapper(innerVal)\n if (isPromiseLike(r)) {\n r.then((innerOpt) => {\n if (innerOpt.isNone()) {\n newCtx.promiseNoneSlot = true\n }\n resolve(innerOpt.#val)\n }, reject)\n } else {\n if (r.isNone()) {\n newCtx.promiseNoneSlot = true\n resolve(NONE_VAL as U)\n } else {\n resolve(r.#val)\n }\n }\n }\n }, reject)\n })\n return new Option(newP, newCtx, \"Some\")\n }\n\n const mapped = mapper(curr as unknown as Curr)\n if (isPromiseLike(mapped)) {\n return Option.fromPromise(mapped)\n }\n return mapped\n }\n\n // -------------------------------------------------------------------------\n // filter() - with async predicate support\n // -------------------------------------------------------------------------\n\n /**\n * Filters the contained value by a predicate.\n *\n * If Some, returns Some when predicate passes, otherwise None. Supports\n * async values and async predicates; returns Option<Promise<T>> when async.\n *\n * @param pred - Predicate function\n * @returns Option filtered by the predicate (sync or async)\n */\n filter(pred: FilterPredicate<T>): Option<T>\n filter(pred: AsyncPredicate<T>): Option<Promise<T>>\n filter(\n pred: FilterPredicate<T> | AsyncPredicate<T>,\n ): Option<T> | Option<Promise<T>> {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const p = curr as Promise<Awaited<T>>\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const next = p.then(async (v) => {\n if (v === NONE_VAL) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n const passed = await pred(v as Awaited<T>)\n if (!passed) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n return v\n }) as Promise<T>\n return new Option(next, newCtx, \"Some\")\n }\n\n const result = pred(curr as Awaited<T>)\n\n if (isPromiseLike(result)) {\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const p = result.then((passed) => {\n if (passed) return curr as T\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }) as Promise<T>\n return new Option(p, newCtx, \"Some\")\n }\n\n return result ? this : Option.None\n }\n\n // -------------------------------------------------------------------------\n // zip() - with async overloads per spec\n // -------------------------------------------------------------------------\n\n /**\n * Pairs the original value with a derived value in a tuple.\n *\n * If None, returns None. Supports async values and async derivation; returns\n * Option<Promise<[Curr, Awaited<U>]>> when async is involved.\n *\n * @template U - Derived value type\n * @param fn - Function to derive a value from the contained value\n * @returns Option of tuple with original and derived values\n */\n zip<U, Curr>(\n this: Option<Promise<Curr>>,\n fn: (val: Curr) => U,\n ): Option<Promise<[Curr, Awaited<U>]>>\n zip<U, Curr>(\n this: Option<Curr>,\n fn: (val: Curr) => Promise<U>,\n ): Option<Promise<[Curr, Awaited<U>]>>\n zip<U, Curr>(this: Option<Curr>, fn: (val: Curr) => U): Option<[Curr, U]>\n zip<U, Curr = Awaited<T>>(fn: Mapper<Curr, U> | AsyncMapper<Curr, U>) {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const val = curr as Promise<Curr>\n // Create a NEW context for this branch to avoid cross-branch mutation\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n\n const p = val.then(async (v) => {\n if (v === NONE_VAL) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n\n const next = await fn(v)\n return [v, next]\n }) as Promise<[Curr, Awaited<U>]>\n\n return new Option(p, newCtx, \"Some\")\n }\n\n const value = curr as unknown as Curr\n const u = fn(value)\n if (isPromiseLike(u)) {\n const p = u.then((uu) => [value, uu] as [Curr, Awaited<U>])\n return new Option(p, { promiseNoneSlot: false }, \"Some\")\n }\n\n return new Option([value, u], { promiseNoneSlot: false }, \"Some\")\n }\n\n // -------------------------------------------------------------------------\n // flatZip() - with async overloads per spec\n // -------------------------------------------------------------------------\n\n /**\n * Pairs the original value with a derived Option value, flattening the result.\n *\n * If None, returns None. Supports async values and async Option derivation;\n * returns Option<Promise<[Curr, U]>> when async is involved.\n *\n * @template U - Derived Option value type\n * @param fn - Function returning an Option\n * @returns Option of tuple with original and derived values\n */\n flatZip<U, Curr>(\n this: Option<Promise<Curr>>,\n fn: (val: Curr) => Promise<Option<U>>,\n ): Option<Promise<[Curr, U]>>\n flatZip<U, Curr>(\n this: Option<Promise<Curr>>,\n fn: (val: Curr) => Option<U>,\n ): Option<Promise<[Curr, U]>>\n flatZip<U, Curr>(\n this: Option<Curr>,\n fn: (val: Curr) => Promise<Option<U>>,\n ): Option<Promise<[Curr, U]>>\n flatZip<U, Curr>(\n this: Option<Curr>,\n fn: (val: Curr) => Option<U>,\n ): Option<[Curr, U]>\n flatZip<U, Curr = Awaited<T>>(\n fn: Mapper<Curr, Option<U>> | AsyncMapper<Curr, Option<U>>,\n ) {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const val = curr as Promise<Curr>\n // Create a NEW context for this branch to avoid cross-branch mutation\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n\n const p = val.then(async (v) => {\n if (v === NONE_VAL) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n\n const next = await fn(v)\n if (next.isNone()) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n return [v, next.#val] as [Curr, U]\n }) as Promise<[Curr, U]>\n\n return new Option(p, newCtx, \"Some\")\n }\n\n const c = curr as unknown as Curr\n const u = fn(c)\n if (isPromiseLike(u)) {\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const p = u.then((uu) => {\n if (uu.isNone()) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n return [c, uu.#val] as [Curr, U]\n })\n return new Option(p, newCtx, \"Some\")\n }\n\n return u.map((inner) => [c, inner])\n }\n\n /**\n * Executes a side effect for Some values and returns self.\n *\n * For `Option<Promise<T>>`, `tap` receives the wrapped promise object,\n * not the settled inner value.\n *\n * @param fn - Side effect function\n * @returns The same Option (chainable)\n */\n tap(fn: (val: T) => void): Option<T> {\n if (this.isSome()) {\n fn(this.#val)\n }\n return this\n }\n\n /**\n * Converts this Option to a Result, using the provided error for None.\n *\n * @template E - Error type\n * @param error - Error value for None\n * @returns Ok with value when Some, otherwise Err with error\n */\n toResult<E>(error: E): Result<T, E> {\n if (this.isNone()) {\n return Result.Err(error)\n }\n return Result.Ok(this.#val)\n }\n\n /**\n * Resolves the inner promise (if any) while preserving Option structure.\n *\n * @template Curr - Awaited value type\n * @returns Promise of Option with awaited value, or None\n */\n async toPromise<Curr = Awaited<T>>(): Promise<Option<Curr>> {\n if (this.isNone()) {\n return Option.None\n }\n\n const curr = this.#val\n\n let inner: Curr\n if (isPromiseLike(curr)) {\n const awaited = await curr\n if (awaited === NONE_VAL || this.#ctx.promiseNoneSlot) {\n return Option.None\n }\n inner = awaited as Curr\n } else {\n inner = curr as unknown as Curr\n }\n\n return new Option(inner, this.#ctx, \"Some\")\n }\n\n /**\n * Maps over array elements inside an Option<Array<T>>.\n *\n * @template Inner - Array element type\n * @template Out - Mapped element type\n * @param mapper - Function to map each element\n * @returns Option containing the mapped array\n * @throws TypeError if called on a non-array value\n */\n innerMap<Inner, Out>(\n this: Option<Array<Inner>>,\n mapper: (val: Inner) => Out,\n ): Option<NoInfer<Out>[]> {\n if (this.isNone()) return Option.None\n\n if (!Array.isArray(this.#val)) {\n throw new TypeError(\"innerMap can only be called on Option<Array<T>>\")\n }\n\n return new Option((this.#val as Inner[]).map(mapper), this.#ctx, \"Some\")\n }\n\n /**\n * Returns a string representation of the Option.\n *\n * @returns \"Option::None\" or \"Option::Some(value)\"\n */\n toString(): string {\n if (this.isNone()) return \"Option::None\"\n return `Option::Some(${String(this.#val)})`\n }\n\n /**\n * Makes Option iterable for use with generator-based syntax.\n *\n * Yields self and returns the unwrapped value when resumed.\n * Used internally by {@link Option.gen} for `yield*` syntax.\n *\n * @example\n * ```ts\n * const result = Option.gen(function* () {\n * const value = yield* Option.Some(42);\n * return value * 2;\n * });\n * // Some(84)\n * ```\n *\n * @internal\n */\n *[Symbol.iterator](): Generator<Option<T>, T, unknown> {\n const trace = new Error().stack\n return (yield new CapturedTrace(this, trace) as unknown as Option<T>) as T\n }\n\n /**\n * Makes Option iterable for use with async generator-based syntax.\n *\n * Yields self and returns the unwrapped value when resumed.\n * Used internally by {@link Option.asyncGen} for `yield*` syntax.\n *\n * @example\n * ```ts\n * const result = await Option.asyncGen(async function* () {\n * const value = yield* await Promise.resolve(Option.Some(42));\n * return value * 2;\n * });\n * // Some(84)\n * ```\n *\n * @internal\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<\n Option<T>,\n Awaited<T>,\n unknown\n > {\n const trace = new Error().stack\n return (yield new CapturedTrace(\n this,\n trace,\n ) as unknown as Option<T>) as Awaited<T>\n }\n\n /**\n * Generator-based syntax for chaining Option operations (simplified, no adapter).\n *\n * Provides imperative-style code while maintaining functional Option handling.\n * Use `yield*` to unwrap Options or short-circuit on `None`.\n *\n * Short-circuits on first `None`, returning singleton `None`. Uses iteration\n * instead of recursion to avoid stack overflow on deep chains.\n *\n * @template T - The return type of the generator\n * @param genFn - A generator function that yields Options\n * @returns `Some<T>` with the generator's return value, or `None`\n *\n * @example\n * ```ts\n * // Simple sync chain\n * const result = Option.gen(function* () {\n * const a = yield* Option.Some(1);\n * const b = yield* Option.Some(2);\n * return a + b;\n * });\n * // Some(3)\n *\n * // None short-circuit\n * const shortCircuit = Option.gen(function* () {\n * const a = yield* Option.Some(1);\n * const b = yield* Option.None; // Short-circuits here\n * const c = yield* Option.Some(3); // Never executes\n * return a + b + c;\n * });\n * // None\n *\n * // Chaining optional operations\n * const email = Option.gen(function* () {\n * const user = yield* findUser(userId);\n * const profile = yield* Option.fromNullable(user.profile);\n * const settings = yield* Option.fromNullable(profile.settings);\n * return settings.email;\n * });\n *\n * // Nested optional access\n * const city = Option.gen(function* () {\n * const user = yield* Option.fromNullable(getUser());\n * const address = yield* Option.fromNullable(user?.address);\n * const city = yield* Option.fromNullable(address?.city);\n * return city;\n * });\n * ```\n *\n * @see {@link genAdapter} for better type inference in complex chains\n * @see {@link asyncGen} for async operations\n */\n static gen<T>(\n this: void,\n genFn: () => Generator<Option<unknown>, T, unknown>,\n ): Option<T> {\n const iterator = genFn()\n\n // Use iteration instead of recursion to avoid stack overflow\n let nextArg: unknown\n let currentResult: Option<T>\n\n while (true) {\n const next = iterator.next(nextArg)\n\n if (next.done) {\n // Generator completed successfully - wrap return value in Some\n currentResult = Option.Some(next.value)\n break\n }\n\n // next.value is the Option that was yielded\n let yielded = next.value as Option<unknown>\n\n if (isCapturedTrace(yielded)) {\n yielded = yielded.value as Option<unknown>\n }\n\n if (yielded.isNone()) {\n // Early termination on None - return singleton None\n currentResult = Option.None\n break\n }\n\n // Unwrap the Some value and pass it back to the generator\n nextArg = yielded.unwrap()\n }\n\n return currentResult\n }\n\n /**\n * Generator-based syntax for chaining Option operations with an adapter function.\n *\n * Provides better type inference and IDE support compared to {@link gen}.\n * The `$` adapter wraps Options and enables clearer type tracking.\n *\n * Short-circuits on first `None`, returning singleton `None`. Uses iteration\n * instead of recursion to avoid stack overflow on deep chains.\n *\n * @template Eff - The effect type (inferred from usage)\n * @template T - The return type of the generator\n * @param genFn - A generator function receiving an adapter `$`\n * @returns `Some<T>` with the generator's return value, or `None`\n *\n * @example\n * ```ts\n * // Better type inference\n * const result = Option.genAdapter(function* ($) {\n * const a = yield* $(Option.Some(1));\n * const b = yield* $(Option.Some(2));\n * return a + b;\n * });\n * // Some(3)\n *\n * // Deep nested access with better type safety\n * const email = Option.genAdapter(function* ($) {\n * const user = yield* $(Option.fromNullable(apiResponse?.user));\n * const profile = yield* $(Option.fromNullable(user?.profile));\n * const contact = yield* $(Option.fromNullable(profile?.contact));\n * return contact?.email;\n * });\n *\n * // Complex validation chain\n * const validConfig = Option.genAdapter(function* ($) {\n * const raw = yield* $(loadConfig());\n * const parsed = yield* $(parseConfig(raw));\n * const validated = yield* $(validateConfig(parsed));\n * return validated;\n * });\n * ```\n *\n * @see {@link gen} for simpler chains without adapter\n * @see {@link asyncGenAdapter} for async operations\n */\n // biome-ignore lint/suspicious/noExplicitAny: inference\n static genAdapter<Eff extends OptionYieldWrap<any>, T>(\n this: void,\n genFn: (\n adapter: <A>(option: Option<A>) => OptionYieldWrap<A>,\n // biome-ignore lint/suspicious/noExplicitAny: inference\n ) => Generator<Eff, T, any>,\n ): Option<T> {\n const adapter = <A>(option: Option<A>): OptionYieldWrap<A> =>\n new OptionYieldWrap(option)\n\n const iterator = genFn(adapter)\n\n // Use iteration instead of recursion to avoid stack overflow\n let nextArg: unknown\n let currentResult: Option<T>\n\n while (true) {\n const next = iterator.next(nextArg)\n\n if (next.done) {\n // Generator completed successfully - wrap return value in Some\n currentResult = Option.Some(next.value)\n break\n }\n\n // next.value is the OptionYieldWrap that was yielded\n const wrapped = next.value as OptionYieldWrap<unknown>\n let option = wrapped.option\n\n if (isCapturedTrace(option)) {\n option = (option as CapturedTrace<Option<unknown>>)\n .value as Option<unknown>\n }\n\n if (option.isNone()) {\n // Early termination on None - return singleton None\n currentResult = Option.None\n break\n }\n\n // Unwrap the Some value and pass it back to the generator\n nextArg = option.unwrap()\n }\n\n return currentResult\n }\n\n /**\n * Async generator-based syntax for chaining Option operations (simplified, no adapter).\n *\n * Use `yield*` with `Option<T>` values directly. For `Promise<Option<T>>`,\n * await first then `yield*`.\n *\n * Short-circuits on first `None`, returning singleton `None`. Uses async iteration\n * instead of recursion to avoid stack overflow on deep chains.\n *\n * @template T - The return type of the generator\n * @param genFn - An async generator function that yields Options\n * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`\n *\n * @example\n * ```ts\n * // Simple async chain\n * const result = await Option.asyncGen(async function* () {\n * const a = yield* Option.Some(1);\n * const b = yield* await asyncOperation(a); // await Promise<Option> first\n * const c = yield* Option.Some(3);\n * return a + b + c;\n * });\n * // Some(result)\n *\n * // None short-circuit in async\n * const shortCircuit = await Option.asyncGen(async function* () {\n * const data = yield* await fetchOptionalData();\n * const parsed = yield* parse(data); // Short-circuits on None\n * const validated = yield* validate(parsed); // Never executes\n * return validated;\n * });\n * // None\n *\n * // Mixed sync/async workflow\n * const result = await Option.asyncGen(async function* () {\n * const id = yield* Option.Some(parseInt(input)); // sync\n * const user = yield* await fetchUser(id); // async\n * const profile = yield* Option.fromNullable(user?.profile); // sync\n * const enriched = yield* await enrichProfile(profile); // async\n * return enriched;\n * });\n *\n * // Complex pipeline with multiple optional steps\n * async function processLead(email: string): Promise<Option<Lead>> {\n * return await Option.asyncGen(async function* () {\n * const normalized = yield* Option.Some(normalizeEmail(email));\n * const existing = yield* await findExistingLead(normalized);\n * const enriched = yield* await enrichLeadData(existing);\n * const validated = yield* validateLead(enriched);\n * return validated;\n * });\n * }\n * ```\n *\n * @see {@link asyncGenAdapter} for better type inference and cleaner syntax\n * @see {@link gen} for synchronous operations\n */\n static async asyncGen<T>(\n this: void,\n genFn: () => AsyncGenerator<Option<unknown>, T, unknown>,\n ): Promise<Option<T>> {\n const iterator = genFn()\n\n // Use iteration instead of recursion to avoid stack overflow\n let nextArg: unknown\n let currentResult: Option<T>\n\n while (true) {\n const next = await iterator.next(nextArg)\n\n if (next.done) {\n // Generator completed successfully - wrap return value in Some\n currentResult = Option.Some(next.value)\n break\n }\n\n // next.value is an Option (user awaits promises before yielding)\n let option = next.value as Option<unknown>\n\n if (isCapturedTrace(option)) {\n option = option.value as Option<unknown>\n }\n\n if (option.isNone()) {\n // Early termination on None - return singleton None\n currentResult = Option.None\n break\n }\n\n // Unwrap the Some value\n nextArg = await option.unwrap()\n }\n\n return currentResult\n }\n\n /**\n * Async generator-based syntax for chaining Option operations with an adapter function.\n *\n * The `$` adapter handles both sync `Option<T>` and async `Promise<Option<T>>`,\n * automatically awaiting promises. This provides cleaner syntax for mixed sync/async workflows.\n *\n * Short-circuits on first `None`, returning singleton `None`. Uses async iteration\n * instead of recursion to avoid stack overflow on deep chains.\n *\n * @template Eff - The effect type (inferred from usage)\n * @template T - The return type of the generator\n * @param genFn - An async generator function receiving an adapter `$`\n * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`\n *\n * @example\n * ```ts\n * // No need to manually await - adapter handles it\n * const result = await Option.asyncGenAdapter(async function* ($) {\n * const a = yield* $(Option.Some(1)); // sync Option\n * const b = yield* $(asyncOperation(a)); // Promise<Option> - auto-awaited\n * const c = yield* $(Option.Some(3));\n * return a + b + c;\n * });\n *\n * // Complex workflow with database and API calls\n * const userData = await Option.asyncGenAdapter(async function* ($) {\n * const session = yield* $(getSession()); // Promise<Option<Session>>\n * const userId = yield* $(Option.fromNullable(session?.userId));\n * const profile = yield* $(await fetchProfile(userId)); // Promise<Option<Profile>>\n * const preferences = yield* $(Option.fromNullable(profile?.preferences));\n * const enriched = yield* $(await enrichPreferences(preferences));\n * return enriched;\n * });\n *\n * // Real-world: Optional data enrichment\n * async function getProductDetails(productId: string): Promise<Option<ProductDetails>> {\n * return await Option.asyncGenAdapter(async function* ($) {\n * const product = yield* $(await fetchProduct(productId));\n * const pricing = yield* $(await fetchPricing(product.sku));\n * const inventory = yield* $(await checkInventory(product.id));\n * const reviews = yield* $(await fetchReviews(product.id));\n * const related = yield* $(await fetchRelatedProducts(product.category));\n *\n * return { product, pricing, inventory, reviews, related };\n * });\n * }\n * ```\n *\n * @see {@link asyncGen} when you want explicit `await` for async operations\n * @see {@link genAdapter} for synchronous operations\n */\n // biome-ignore lint/suspicious/noExplicitAny: inference\n static async asyncGenAdapter<Eff extends AsyncOptionYieldWrap<any>, T>(\n this: void,\n genFn: (\n adapter: <A>(\n option: Option<A> | Promise<Option<A>>,\n ) => AsyncOptionYieldWrap<A>,\n // biome-ignore lint/suspicious/noExplicitAny: inference\n ) => AsyncGenerator<Eff, T, any>,\n ): Promise<Option<T>> {\n const adapter = <A>(\n option: Option<A> | Promise<Option<A>>,\n ): AsyncOptionYieldWrap<A> => new AsyncOptionYieldWrap(option)\n\n const iterator = genFn(adapter)\n\n // Use iteration instead of recursion to avoid stack overflow\n let nextArg: unknown\n let currentResult: Option<T>\n\n while (true) {\n const next = await iterator.next(nextArg)\n\n if (next.done) {\n // Generator completed successfully - wrap return value in Some\n currentResult = Option.Some(next.value)\n break\n }\n\n // next.value is the AsyncOptionYieldWrap that was yielded\n const wrapped = next.value as AsyncOptionYieldWrap<unknown>\n let option = await wrapped.option\n\n if (isCapturedTrace(option)) {\n option = (option as CapturedTrace<Option<unknown>>)\n .value as Option<unknown>\n }\n\n if (option.isNone()) {\n // Early termination on None - return singleton None\n currentResult = Option.None\n break\n }\n\n // Unwrap the Some value\n nextArg = await option.unwrap()\n }\n\n return currentResult\n }\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L,OAAI,OAAO,QAAQ,EAAE;AAEnB,oBAAgB,OAAO;AACvB;;AAIF,aAAU,MAAM,OAAO,QAAQ;;AAGjC,SAAO"}
|
|
1
|
+
{"version":3,"file":"option.cjs","names":["isPromiseLike","UNIT","Result","CapturedTrace","isCapturedTrace","closeGenerator","closeAsyncGenerator"],"sources":["../src/option.ts"],"sourcesContent":["import { Result } from \"./result.js\"\nimport { UNIT } from \"./unit.js\"\nimport {\n CapturedTrace,\n closeAsyncGenerator,\n closeGenerator,\n isCapturedTrace,\n isPromiseLike,\n} from \"./utils.js\"\n\ntype Mapper<T, U> = (val: T) => U\ntype AsyncMapper<T, U> = (val: T) => Promise<U>\ntype FlatMapper<T, U> = (val: T) => Option<U>\ntype AsyncFlatMapper<T, U> = (val: T) => Promise<Option<U>>\ntype Predicate<T> = (val: T) => boolean\ntype FilterPredicate<T> = (val: Awaited<T>) => boolean\ntype AsyncPredicate<T> = (val: Awaited<T>) => Promise<boolean>\ntype Falsy = false | 0 | \"\" | null | undefined\n\nexport class UnwrappedNone extends Error {\n readonly name = \"UnwrapError\"\n\n constructor() {\n super(\"Attempted to unwrap Option::None\")\n }\n}\n\nconst UNWRAPPED_NONE_ERR = new UnwrappedNone()\n\nconst NONE_VAL = Symbol(\"Option::None\")\n\n/** Option alias for presence-without-payload values. */\nexport type UnitOption = Option<UNIT>\n/** Extracts the contained value type from an Option type. */\nexport type UnwrapOption<T> = T extends Option<infer R> ? R : never\n\ntype CombinedOptions<T extends Option<unknown>[]> = {\n [K in keyof T]: UnwrapOption<T[K]>\n}\n\ntype OptionCtx = { promiseNoneSlot: boolean }\n\ninterface MatchCases<T, U> {\n Some: (val: T) => U\n None: () => U\n}\n\n/**\n * Wrapper that makes Option yieldable with proper type tracking.\n *\n * @internal\n */\nclass OptionYieldWrap<T> {\n constructor(readonly option: Option<T>) {}\n\n *[Symbol.iterator](): Generator<OptionYieldWrap<T>, T, unknown> {\n return (yield this) as T\n }\n}\n\n/**\n * Wrapper that makes Option yieldable in async generators with proper type tracking.\n *\n * @internal\n */\nclass AsyncOptionYieldWrap<T> {\n readonly option: Promise<Option<T>>\n\n constructor(option: Option<T> | Promise<Option<T>>) {\n this.option = (\n isPromiseLike(option) ? option : Promise.resolve(option)\n ) as Promise<Option<T>>\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<\n AsyncOptionYieldWrap<T>,\n Awaited<T>,\n unknown\n > {\n return (yield this) as Awaited<T>\n }\n}\n\n/**\n * Represents an optional value: `Some<T>` or `None`.\n * Provides composable, null-safe transformation and chaining methods.\n */\nexport class Option<T> {\n /** Discriminant tag for type-level identification */\n readonly _tag: \"Some\" | \"None\"\n\n readonly #ctx: OptionCtx\n readonly #val: T\n\n /**\n * Creates a new Option instance with internal context.\n *\n * @param val - Stored value or sentinel\n * @param ctx - Internal async tracking context\n * @param tag - Discriminant tag for Some/None\n *\n * @internal\n */\n private constructor(val: T, ctx: OptionCtx, tag: \"Some\" | \"None\") {\n this.#val = val\n this.#ctx = ctx\n this._tag = tag\n }\n\n /** Singleton None instance */\n static readonly None: Option<never> = new Option(\n NONE_VAL as never,\n { promiseNoneSlot: true },\n \"None\",\n )\n\n /**\n * Creates a Some variant containing the provided value.\n *\n * @template Inner - Type of the wrapped value\n * @param val - Value to wrap in Some\n * @returns Option in the Some state\n */\n static Some<Inner>(this: void, val: Inner): Option<Inner> {\n return new Option(val, { promiseNoneSlot: false }, \"Some\")\n }\n\n /**\n * Creates an Option from a nullable value, returning None for null/undefined.\n *\n * @template T - Input type that may include null/undefined\n * @param val - Value to convert\n * @returns Some for non-nullish values, otherwise None\n */\n static fromNullable<T>(val: T): Option<NonNullable<T>> {\n return val === null || val === undefined\n ? Option.None\n : Option.Some(val as NonNullable<T>)\n }\n\n /**\n * Creates an Option from a potentially falsy value, returning None for falsy.\n *\n * Treats false, 0, \"\", null, and undefined as absence.\n *\n * @template T - Input type\n * @param val - Value to convert\n * @returns Some for truthy values, otherwise None\n */\n static fromFalsy<T>(val: T | Falsy): Option<T> {\n return val ? Option.Some(val as T) : Option.None\n }\n\n /**\n * Creates an Option based on a predicate.\n *\n * @template T - Input type\n * @param val - Value to test\n * @param pred - Predicate to decide Some vs None\n * @returns Some when predicate passes, otherwise None\n */\n static fromPredicate<T>(val: T, pred: Predicate<T>): Option<T> {\n return pred(val) ? Option.Some(val) : Option.None\n }\n\n /**\n * Wraps a Promise<Option<T>> as Option<Promise<T>>.\n *\n * NOTE: the returned value starts as `Some(Promise<T>)`; final `None` is known\n * only after settlement. Use `toPromise()` (or await `unwrap`/`safeUnwrap`) to\n * observe settled absence.\n *\n * @template U - Inner value type\n * @param o - Promise resolving to an Option\n * @returns Option containing a Promise of the inner value\n */\n static fromPromise<U>(o: Promise<Option<U>>): Option<Promise<U>> {\n const ctx: OptionCtx = { promiseNoneSlot: false }\n const p = new Promise<U>((resolve, reject) =>\n o.then((innerOpt) => {\n if (innerOpt.isNone()) {\n ctx.promiseNoneSlot = true\n }\n resolve(innerOpt.#val)\n }, reject),\n )\n\n return new Option(p, ctx, \"Some\")\n }\n\n /**\n * Combines multiple Options into a single Option of an array.\n *\n * Returns Some of all values if all inputs are Some; otherwise None.\n *\n * @template T - Variadic tuple of Option types\n * @param options - Options to combine\n * @returns Some of tuple values, or None if any input is None\n */\n static all<T extends Option<unknown>[]>(\n ...options: T\n ): Option<CombinedOptions<T>> {\n const vals = [] as CombinedOptions<T>\n\n for (const opt of options) {\n if (opt.isNone()) return Option.None\n vals.push(opt.#val)\n }\n\n return Option.Some(vals)\n }\n\n /**\n * Returns the first Some in the list, or None if all are None.\n *\n * Awaits candidates in input order, without waiting for the suffix after success.\n *\n * @template T - Value type\n * @param options - Options to search\n * @returns The first Some found, otherwise None\n */\n static any<T>(...options: Option<T>[]): Option<T> {\n let hasPending = false\n for (const opt of options) {\n if (!opt.isSome()) continue\n if (isPromiseLike(opt.#val)) {\n hasPending = true\n break\n }\n return opt\n }\n if (!hasPending) return Option.None\n\n // Observe already-created payloads without changing ordered selection.\n for (const opt of options) {\n if (isPromiseLike(opt.#val)) {\n Promise.resolve(opt.#val).then(undefined, () => {})\n }\n }\n\n const ctx: OptionCtx = { promiseNoneSlot: false }\n const p = (async () => {\n for (const opt of options) {\n if (!opt.isSome()) continue\n const val = await opt.#val\n if (!opt.#ctx.promiseNoneSlot && val !== NONE_VAL) return val\n }\n ctx.promiseNoneSlot = true\n return NONE_VAL\n })()\n\n return new Option(p as T, ctx, \"Some\")\n }\n\n /**\n * Type guard that narrows to Some.\n *\n * @returns true if this Option is Some\n */\n isSome(): this is Option<T> & { readonly _tag: \"Some\" } {\n return this._tag === \"Some\" && !this.isNone()\n }\n\n /**\n * Type guard that narrows to None.\n *\n * Includes async None tracking while preserving the stored payload type.\n *\n * @returns true if this Option is None\n */\n isNone(): this is Option<T> & { readonly _tag: \"None\" } {\n return (\n this._tag === \"None\" ||\n this.#val === NONE_VAL ||\n (isPromiseLike(this.#val) && this.#ctx.promiseNoneSlot)\n )\n }\n\n /**\n * Type guard for the UNIT sentinel value.\n *\n * @returns true if the contained value is UNIT\n */\n isUnit(): this is Option<UNIT> {\n return this.#val === UNIT\n }\n\n /**\n * Returns the contained value or throws if None.\n *\n * @throws UnwrappedNone when called on None\n * @returns The contained value\n */\n unwrap(this: Option<never>): never\n unwrap(this: Option<Promise<T>>): Promise<T>\n unwrap(this: Option<T>): T\n unwrap() {\n if (this.isNone()) {\n throw UNWRAPPED_NONE_ERR\n }\n\n const curr = this.#val\n if (isPromiseLike(curr)) {\n const ctx = this.#ctx\n return curr.then((value) => {\n if (value === NONE_VAL || ctx.promiseNoneSlot) {\n throw UNWRAPPED_NONE_ERR\n }\n return value\n })\n }\n\n return curr\n }\n\n /**\n * Returns the contained value or the provided default.\n * Promise-backed options wait for settlement before choosing the default.\n * @param defaultValue - Value to use when None\n * @returns The contained value or default\n */\n unwrapOr<U>(this: Option<never>, defaultValue: U): U\n unwrapOr<Curr>(\n this: Option<Promise<Curr>>,\n defaultValue: Promise<NoInfer<Awaited<Curr>>>,\n ): Promise<Awaited<Curr>>\n unwrapOr<Curr>(\n this: Option<Promise<Curr>>,\n defaultValue: NoInfer<Awaited<Curr>> | Promise<NoInfer<Awaited<Curr>>>,\n ): Awaited<Curr> | Promise<Awaited<Curr>>\n unwrapOr(this: Option<T>, defaultValue: T): T\n unwrapOr(defaultValue: unknown): unknown {\n const curr = this.#val\n if (isPromiseLike(curr)) {\n const ctx = this.#ctx\n return curr.then((value) =>\n value === NONE_VAL || ctx.promiseNoneSlot ? defaultValue : value,\n )\n }\n return this.isNone() ? defaultValue : curr\n }\n\n /**\n * Returns the contained value or computes a default lazily.\n * Promise-backed options invoke the factory only after settled absence.\n * @param fn - Default factory invoked only when None\n * @returns The contained value or computed default\n */\n unwrapOrElse<U>(this: Option<never>, fn: () => U): U\n unwrapOrElse<Curr>(\n this: Option<Promise<Curr>>,\n fn: () => Promise<NoInfer<Awaited<Curr>>>,\n ): Promise<Awaited<Curr>>\n unwrapOrElse<Curr>(\n this: Option<Promise<Curr>>,\n fn: () => NoInfer<Awaited<Curr>> | Promise<NoInfer<Awaited<Curr>>>,\n ): Awaited<Curr> | Promise<Awaited<Curr>>\n unwrapOrElse(this: Option<T>, fn: () => T): T\n unwrapOrElse(fn: () => unknown): unknown {\n const curr = this.#val\n if (isPromiseLike(curr)) {\n const ctx = this.#ctx\n return curr.then((value) =>\n value === NONE_VAL || ctx.promiseNoneSlot ? fn() : value,\n )\n }\n return this.isNone() ? fn() : curr\n }\n\n /**\n * Returns the contained value or null for None.\n *\n * @returns The contained value, or null when None\n */\n safeUnwrap(this: Option<never>): null\n safeUnwrap(this: Option<Promise<T>>): Promise<T | null>\n safeUnwrap(this: Option<T>): T | null\n safeUnwrap() {\n if (this.isNone()) return null\n\n const curr = this.#val\n if (isPromiseLike(curr)) {\n const ctx = this.#ctx\n return curr.then((value) =>\n value === NONE_VAL || ctx.promiseNoneSlot ? null : value,\n )\n }\n\n return curr\n }\n\n /**\n * Exhaustive pattern match on Option state.\n *\n * @template U - Result type\n * @param cases - Handlers for Some and None\n * @returns Result of the matching handler\n */\n match<U>(cases: MatchCases<T, U>): U {\n if (this.isNone()) {\n return cases.None()\n }\n return cases.Some(this.#val)\n }\n\n // -------------------------------------------------------------------------\n // map() - with async overloads per spec\n // -------------------------------------------------------------------------\n\n /**\n * Transforms the contained value and wraps it in a new Option.\n *\n * If None, returns None without calling the mapper. Supports async values\n * and async mappers; returns Option<Promise<U>> when async is involved.\n *\n * @template U - Result value type\n * @param mapper - Function to transform the contained value\n * @returns Option of the mapped value (sync or async)\n *\n * @see flatMap\n */\n map<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n mapper: AsyncMapper<Curr, U>,\n ): Option<Promise<U>>\n map<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n mapper: Mapper<Curr, U>,\n ): Option<Promise<U>>\n map<U>(this: Option<T>, mapper: AsyncMapper<T, U>): Option<Promise<U>>\n map<U>(this: Option<T>, mapper: Mapper<T, U>): Option<U>\n map<U, Curr = Awaited<T>>(\n mapper: Mapper<NoInfer<Curr>, U> | AsyncMapper<NoInfer<Curr>, U>,\n ) {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const p = curr as Promise<Curr>\n // Create a NEW context for this branch to avoid cross-branch mutation\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const safetlyMapped = Option.safeMap(p, mapper, newCtx)\n return new Option(safetlyMapped, newCtx, \"Some\")\n }\n\n const transformed = mapper(curr as unknown as Curr)\n if (isPromiseLike(transformed)) {\n return new Option(transformed, { promiseNoneSlot: false }, \"Some\")\n }\n // Sync operations can share context since there's no async mutation\n return new Option(transformed, { promiseNoneSlot: false }, \"Some\")\n }\n\n /**\n * Safely maps a promised value while tracking None in async context.\n *\n * @template Curr - Input value type\n * @template U - Output value type\n * @param p - Promise to map over\n * @param mapper - Transform function\n * @param ctx - Async context for None tracking\n * @returns Promise of the transformed value or sentinel\n */\n private static safeMap<Curr, U>(\n p: Promise<Curr>,\n mapper: (val: Curr) => U | Promise<U>,\n ctx: OptionCtx,\n ) {\n return p.then((v) => {\n if (v === NONE_VAL) {\n ctx.promiseNoneSlot = true\n return NONE_VAL\n }\n return mapper(v)\n }) as Promise<U>\n }\n\n // -------------------------------------------------------------------------\n // mapOr() - maps value or returns default (returns U, not Option<U>)\n // -------------------------------------------------------------------------\n\n /**\n * Maps the value or returns a default (unwrapped).\n *\n * If None, returns the default without calling fn. Supports async values\n * and async mappers; returns Promise<U> when async is involved.\n *\n * @template U - Result type\n * @param defaultVal - Value to return if None\n * @param fn - Mapper applied when Some\n * @returns Mapped value or default (sync or async)\n */\n mapOr<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n defaultVal: U,\n fn: Mapper<Curr, U>,\n ): Promise<U>\n mapOr<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n defaultVal: U,\n fn: AsyncMapper<Curr, U>,\n ): Promise<U>\n mapOr<U>(this: Option<T>, defaultVal: U, fn: AsyncMapper<T, U>): Promise<U>\n mapOr<U>(this: Option<T>, defaultVal: U, fn: Mapper<T, U>): U\n mapOr<U, Curr = Awaited<T>>(\n defaultVal: U,\n fn: Mapper<NoInfer<Curr>, U> | AsyncMapper<NoInfer<Curr>, U>,\n ): U | Promise<U> {\n if (this.isNone()) {\n return isPromiseLike(this.#val) ? Promise.resolve(defaultVal) : defaultVal\n }\n\n const curr = this.#val\n if (isPromiseLike(curr)) {\n const p = curr as Promise<Curr>\n const ctx = this.#ctx\n return p.then(async (v) => {\n if (v === NONE_VAL || ctx.promiseNoneSlot) return defaultVal\n return fn(v)\n })\n }\n\n return fn(curr as unknown as Curr)\n }\n\n // -------------------------------------------------------------------------\n // flatMap() - with async overloads per spec\n // -------------------------------------------------------------------------\n\n /**\n * Chains operations that return Option, flattening nested Options.\n *\n * If None, returns None without calling the mapper. Supports async values\n * and async mappers; returns Option<Promise<U>> when async is involved.\n * Mapper throws propagate synchronously for sync inputs and reject the\n * returned promise chain for promise inputs; they do not become None.\n *\n * @template U - Result value type\n * @param mapper - Function returning an Option\n * @returns Flattened Option result (sync or async)\n *\n * @see map\n */\n flatMap<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n mapper: AsyncFlatMapper<Curr, U>,\n ): Option<Promise<Awaited<U>>>\n flatMap<U, Curr = Awaited<T>>(\n this: Option<Promise<Curr>>,\n mapper: FlatMapper<Curr, U>,\n ): Option<Promise<Awaited<U>>>\n flatMap<U>(this: Option<T>, mapper: AsyncFlatMapper<T, U>): Option<Promise<U>>\n flatMap<U>(this: Option<T>, mapper: FlatMapper<T, U>): Option<U>\n flatMap<U, Curr = Awaited<T>>(\n mapper: FlatMapper<NoInfer<Curr>, U> | AsyncFlatMapper<NoInfer<Curr>, U>,\n ): Option<U> | Option<Promise<U>> {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const p = curr as Promise<Curr>\n // Create a NEW context for this branch to avoid cross-branch mutation\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const newP = p.then(async (innerVal) => {\n if (innerVal === NONE_VAL) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL as U\n }\n const mapped = await mapper(innerVal)\n const value = await mapped.#val\n if (mapped.isNone() || value === NONE_VAL) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL as U\n }\n return value\n }) as Promise<U>\n return new Option(newP, newCtx, \"Some\")\n }\n\n const mapped = mapper(curr as unknown as Curr)\n if (isPromiseLike(mapped)) {\n return Option.fromPromise(mapped)\n }\n return mapped\n }\n\n // -------------------------------------------------------------------------\n // filter() - with async predicate support\n // -------------------------------------------------------------------------\n\n /**\n * Filters the contained value by a predicate.\n *\n * If Some, returns Some when predicate passes, otherwise None. Supports\n * async values and async predicates; returns Option<Promise<T>> when async.\n *\n * @param pred - Predicate function\n * @returns Option filtered by the predicate (sync or async)\n */\n filter(pred: FilterPredicate<T>): Option<T>\n filter(pred: AsyncPredicate<T>): Option<Promise<T>>\n filter(\n pred: FilterPredicate<T> | AsyncPredicate<T>,\n ): Option<T> | Option<Promise<T>> {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const p = curr as Promise<Awaited<T>>\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const next = p.then(async (v) => {\n if (v === NONE_VAL) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n const passed = await pred(v as Awaited<T>)\n if (!passed) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n return v\n }) as Promise<T>\n return new Option(next, newCtx, \"Some\")\n }\n\n const result = pred(curr as Awaited<T>)\n\n if (isPromiseLike(result)) {\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const p = result.then((passed) => {\n if (passed) return curr as T\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }) as Promise<T>\n return new Option(p, newCtx, \"Some\")\n }\n\n return result ? this : Option.None\n }\n\n // -------------------------------------------------------------------------\n // zip() - with async overloads per spec\n // -------------------------------------------------------------------------\n\n /**\n * Pairs the original value with a derived value in a tuple.\n *\n * If None, returns None. Supports async values and async derivation; returns\n * Option<Promise<[Curr, Awaited<U>]>> when async is involved.\n *\n * @template U - Derived value type\n * @param fn - Function to derive a value from the contained value\n * @returns Option of tuple with original and derived values\n */\n zip<U, Curr>(\n this: Option<Promise<Curr>>,\n fn: (val: Curr) => U,\n ): Option<Promise<[Curr, Awaited<U>]>>\n zip<U, Curr>(\n this: Option<Curr>,\n fn: (val: Curr) => Promise<U>,\n ): Option<Promise<[Curr, Awaited<U>]>>\n zip<U, Curr>(this: Option<Curr>, fn: (val: Curr) => U): Option<[Curr, U]>\n zip<U, Curr = Awaited<T>>(fn: Mapper<Curr, U> | AsyncMapper<Curr, U>) {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const val = curr as Promise<Curr>\n // Create a NEW context for this branch to avoid cross-branch mutation\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n\n const p = val.then(async (v) => {\n if (v === NONE_VAL) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n\n const next = await fn(v)\n return [v, next]\n }) as Promise<[Curr, Awaited<U>]>\n\n return new Option(p, newCtx, \"Some\")\n }\n\n const value = curr as unknown as Curr\n const u = fn(value)\n if (isPromiseLike(u)) {\n const p = u.then((uu) => [value, uu] as [Curr, Awaited<U>])\n return new Option(p, { promiseNoneSlot: false }, \"Some\")\n }\n\n return new Option([value, u], { promiseNoneSlot: false }, \"Some\")\n }\n\n // -------------------------------------------------------------------------\n // flatZip() - with async overloads per spec\n // -------------------------------------------------------------------------\n\n /**\n * Pairs the original value with a derived Option value, flattening the result.\n *\n * If None, returns None. Supports async values and async Option derivation;\n * returns Option<Promise<[Curr, U]>> when async is involved.\n *\n * @template U - Derived Option value type\n * @param fn - Function returning an Option\n * @returns Option of tuple with original and derived values\n */\n flatZip<U, Curr>(\n this: Option<Promise<Curr>>,\n fn: (val: Curr) => Promise<Option<U>>,\n ): Option<Promise<[Curr, U]>>\n flatZip<U, Curr>(\n this: Option<Promise<Curr>>,\n fn: (val: Curr) => Option<U>,\n ): Option<Promise<[Curr, U]>>\n flatZip<U, Curr>(\n this: Option<Curr>,\n fn: (val: Curr) => Promise<Option<U>>,\n ): Option<Promise<[Curr, U]>>\n flatZip<U, Curr>(\n this: Option<Curr>,\n fn: (val: Curr) => Option<U>,\n ): Option<[Curr, U]>\n flatZip<U, Curr = Awaited<T>>(\n fn: Mapper<Curr, Option<U>> | AsyncMapper<Curr, Option<U>>,\n ) {\n if (this.isNone()) return Option.None\n\n const curr = this.#val\n\n if (isPromiseLike(curr)) {\n const val = curr as Promise<Curr>\n // Create a NEW context for this branch to avoid cross-branch mutation\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n\n const p = val.then(async (v) => {\n if (v === NONE_VAL) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n\n const next = await fn(v)\n if (next.isNone()) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n return [v, next.#val] as [Curr, U]\n }) as Promise<[Curr, U]>\n\n return new Option(p, newCtx, \"Some\")\n }\n\n const c = curr as unknown as Curr\n const u = fn(c)\n if (isPromiseLike(u)) {\n const newCtx: OptionCtx = { promiseNoneSlot: false }\n const p = u.then((uu) => {\n if (uu.isNone()) {\n newCtx.promiseNoneSlot = true\n return NONE_VAL\n }\n return [c, uu.#val] as [Curr, U]\n })\n return new Option(p, newCtx, \"Some\")\n }\n\n return u.map((inner) => [c, inner])\n }\n\n /**\n * Executes a side effect for Some values and returns self.\n *\n * For `Option<Promise<T>>`, `tap` receives the wrapped promise object,\n * not the settled inner value.\n *\n * @param fn - Side effect function\n * @returns The same Option (chainable)\n */\n tap(fn: (val: T) => void): Option<T> {\n if (this.isSome()) {\n fn(this.#val)\n }\n return this\n }\n\n /**\n * Converts this Option to a Result, using the provided error for None.\n * Promise-backed Options preserve settled absence and propagate rejections.\n *\n * @template E - Error type\n * @param error - Error value for None\n * @returns Ok with value when Some, otherwise Err with error\n */\n toResult<E>(error: E): Result<T, E> {\n if (isPromiseLike(this.#val)) {\n return Result.fromPromise(\n this.toPromise<Awaited<T>>().then((option) =>\n option.isNone()\n ? Result.Err<E, Awaited<T>>(error)\n : Result.Ok<Awaited<T>, E>(option.unwrap()),\n ),\n ) as unknown as Result<T, E>\n }\n if (this.isNone()) {\n return Result.Err(error)\n }\n return Result.Ok(this.#val)\n }\n\n /**\n * Resolves the inner promise (if any) while preserving Option structure.\n *\n * @template Curr - Awaited value type\n * @returns Promise of Option with awaited value, or None\n */\n async toPromise<Curr = Awaited<T>>(): Promise<Option<Curr>> {\n if (this.isNone()) {\n return Option.None\n }\n\n const curr = this.#val\n\n let inner: Curr\n if (isPromiseLike(curr)) {\n const awaited = await curr\n if (awaited === NONE_VAL || this.#ctx.promiseNoneSlot) {\n return Option.None\n }\n inner = awaited as Curr\n } else {\n inner = curr as unknown as Curr\n }\n\n return new Option(inner, this.#ctx, \"Some\")\n }\n\n /**\n * Maps over array elements inside an Option<Array<T>>.\n *\n * @template Inner - Array element type\n * @template Out - Mapped element type\n * @param mapper - Function to map each element\n * @returns Option containing the mapped array\n * @throws TypeError if called on a non-array value\n */\n innerMap<Inner, Out>(\n this: Option<Array<Inner>>,\n mapper: (val: Inner) => Out,\n ): Option<NoInfer<Out>[]> {\n if (this.isNone()) return Option.None\n\n if (!Array.isArray(this.#val)) {\n throw new TypeError(\"innerMap can only be called on Option<Array<T>>\")\n }\n\n return new Option((this.#val as Inner[]).map(mapper), this.#ctx, \"Some\")\n }\n\n /**\n * Returns a string representation of the Option.\n *\n * @returns \"Option::None\" or \"Option::Some(value)\"\n */\n toString(): string {\n if (this.isNone()) return \"Option::None\"\n return `Option::Some(${String(this.#val)})`\n }\n\n /**\n * Makes Option iterable for use with generator-based syntax.\n *\n * Yields self and returns the unwrapped value when resumed.\n * Used internally by {@link Option.gen} for `yield*` syntax.\n *\n * @example\n * ```ts\n * const result = Option.gen(function* () {\n * const value = yield* Option.Some(42);\n * return value * 2;\n * });\n * // Some(84)\n * ```\n *\n * @internal\n */\n *[Symbol.iterator](): Generator<Option<T>, T, unknown> {\n const trace = new Error().stack\n return (yield new CapturedTrace(this, trace) as unknown as Option<T>) as T\n }\n\n /**\n * Makes Option iterable for use with async generator-based syntax.\n *\n * Yields self and returns the unwrapped value when resumed.\n * Used internally by {@link Option.asyncGen} for `yield*` syntax.\n *\n * @example\n * ```ts\n * const result = await Option.asyncGen(async function* () {\n * const value = yield* await Promise.resolve(Option.Some(42));\n * return value * 2;\n * });\n * // Some(84)\n * ```\n *\n * @internal\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<\n Option<T>,\n Awaited<T>,\n unknown\n > {\n const trace = new Error().stack\n return (yield new CapturedTrace(\n this,\n trace,\n ) as unknown as Option<T>) as Awaited<T>\n }\n\n /**\n * Generator-based syntax for chaining Option operations (simplified, no adapter).\n *\n * Provides imperative-style code while maintaining functional Option handling.\n * Use `yield*` to unwrap Options or short-circuit on `None`.\n *\n * Short-circuits on first `None`, returning singleton `None`. Uses iteration\n * instead of recursion to avoid stack overflow on deep chains.\n *\n * @template T - The return type of the generator\n * @param genFn - A generator function that yields Options\n * @returns `Some<T>` with the generator's return value, or `None`\n *\n * @example\n * ```ts\n * // Simple sync chain\n * const result = Option.gen(function* () {\n * const a = yield* Option.Some(1);\n * const b = yield* Option.Some(2);\n * return a + b;\n * });\n * // Some(3)\n *\n * // None short-circuit\n * const shortCircuit = Option.gen(function* () {\n * const a = yield* Option.Some(1);\n * const b = yield* Option.None; // Short-circuits here\n * const c = yield* Option.Some(3); // Never executes\n * return a + b + c;\n * });\n * // None\n *\n * // Chaining optional operations\n * const email = Option.gen(function* () {\n * const user = yield* findUser(userId);\n * const profile = yield* Option.fromNullable(user.profile);\n * const settings = yield* Option.fromNullable(profile.settings);\n * return settings.email;\n * });\n *\n * // Nested optional access\n * const city = Option.gen(function* () {\n * const user = yield* Option.fromNullable(getUser());\n * const address = yield* Option.fromNullable(user?.address);\n * const city = yield* Option.fromNullable(address?.city);\n * return city;\n * });\n * ```\n *\n * @see {@link genAdapter} for better type inference in complex chains\n * @see {@link asyncGen} for async operations\n */\n static gen<T>(\n this: void,\n genFn: () => Generator<Option<unknown>, T, unknown>,\n ): Option<T> {\n const iterator = genFn()\n\n // Use iteration instead of recursion to avoid stack overflow\n let nextArg: unknown\n let currentResult: Option<T>\n\n let naturalCompleted = false\n try {\n while (true) {\n const next = iterator.next(nextArg)\n\n if (next.done) {\n naturalCompleted = true\n // Generator completed successfully - wrap return value in Some\n currentResult = Option.Some(next.value)\n break\n }\n\n // next.value is the Option that was yielded\n let yielded = next.value as Option<unknown>\n\n if (isCapturedTrace(yielded)) {\n yielded = yielded.value as Option<unknown>\n }\n\n if (yielded.isNone()) {\n // Early termination on None - return singleton None\n currentResult = Option.None\n break\n }\n\n // Unwrap the Some value and pass it back to the generator\n nextArg = yielded.unwrap()\n }\n } finally {\n if (!naturalCompleted) {\n closeGenerator(iterator, (yielded) => {\n if (isCapturedTrace(yielded)) yielded = yielded.value\n const effect = yielded as Option<unknown>\n return effect.isNone() ? undefined : effect.unwrap()\n })\n }\n }\n\n return currentResult\n }\n\n /**\n * Generator-based syntax for chaining Option operations with an adapter function.\n *\n * Provides better type inference and IDE support compared to {@link gen}.\n * The `$` adapter wraps Options and enables clearer type tracking.\n *\n * Short-circuits on first `None`, returning singleton `None`. Uses iteration\n * instead of recursion to avoid stack overflow on deep chains.\n *\n * @template Eff - The effect type (inferred from usage)\n * @template T - The return type of the generator\n * @param genFn - A generator function receiving an adapter `$`\n * @returns `Some<T>` with the generator's return value, or `None`\n *\n * @example\n * ```ts\n * // Better type inference\n * const result = Option.genAdapter(function* ($) {\n * const a = yield* $(Option.Some(1));\n * const b = yield* $(Option.Some(2));\n * return a + b;\n * });\n * // Some(3)\n *\n * // Deep nested access with better type safety\n * const email = Option.genAdapter(function* ($) {\n * const user = yield* $(Option.fromNullable(apiResponse?.user));\n * const profile = yield* $(Option.fromNullable(user?.profile));\n * const contact = yield* $(Option.fromNullable(profile?.contact));\n * return contact?.email;\n * });\n *\n * // Complex validation chain\n * const validConfig = Option.genAdapter(function* ($) {\n * const raw = yield* $(loadConfig());\n * const parsed = yield* $(parseConfig(raw));\n * const validated = yield* $(validateConfig(parsed));\n * return validated;\n * });\n * ```\n *\n * @see {@link gen} for simpler chains without adapter\n * @see {@link asyncGenAdapter} for async operations\n */\n // biome-ignore lint/suspicious/noExplicitAny: inference\n static genAdapter<Eff extends OptionYieldWrap<any>, T>(\n this: void,\n genFn: (\n adapter: <A>(option: Option<A>) => OptionYieldWrap<A>,\n // biome-ignore lint/suspicious/noExplicitAny: inference\n ) => Generator<Eff, T, any>,\n ): Option<T> {\n const adapter = <A>(option: Option<A>): OptionYieldWrap<A> =>\n new OptionYieldWrap(option)\n\n const iterator = genFn(adapter)\n\n // Use iteration instead of recursion to avoid stack overflow\n let nextArg: unknown\n let currentResult: Option<T>\n\n let naturalCompleted = false\n try {\n while (true) {\n const next = iterator.next(nextArg)\n\n if (next.done) {\n naturalCompleted = true\n // Generator completed successfully - wrap return value in Some\n currentResult = Option.Some(next.value)\n break\n }\n\n // next.value is the OptionYieldWrap that was yielded\n const wrapped = next.value as OptionYieldWrap<unknown>\n let option = wrapped.option\n\n if (isCapturedTrace(option)) {\n option = (option as CapturedTrace<Option<unknown>>)\n .value as Option<unknown>\n }\n\n if (option.isNone()) {\n // Early termination on None - return singleton None\n currentResult = Option.None\n break\n }\n\n // Unwrap the Some value and pass it back to the generator\n nextArg = option.unwrap()\n }\n } finally {\n if (!naturalCompleted) {\n closeGenerator(iterator, (yielded) => {\n if (isCapturedTrace(yielded)) yielded = yielded.value\n let effect = (yielded as OptionYieldWrap<unknown>).option\n if (isCapturedTrace(effect)) {\n effect = effect.value as Option<unknown>\n }\n return effect.isNone() ? undefined : effect.unwrap()\n })\n }\n }\n\n return currentResult\n }\n\n /**\n * Async generator-based syntax for chaining Option operations (simplified, no adapter).\n *\n * Use `yield*` with `Option<T>` values directly. For `Promise<Option<T>>`,\n * await first then `yield*`.\n *\n * Short-circuits on first `None`, returning singleton `None`. Uses async iteration\n * instead of recursion to avoid stack overflow on deep chains.\n *\n * @template T - The return type of the generator\n * @param genFn - An async generator function that yields Options\n * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`\n *\n * @example\n * ```ts\n * // Simple async chain\n * const result = await Option.asyncGen(async function* () {\n * const a = yield* Option.Some(1);\n * const b = yield* await asyncOperation(a); // await Promise<Option> first\n * const c = yield* Option.Some(3);\n * return a + b + c;\n * });\n * // Some(result)\n *\n * // None short-circuit in async\n * const shortCircuit = await Option.asyncGen(async function* () {\n * const data = yield* await fetchOptionalData();\n * const parsed = yield* parse(data); // Short-circuits on None\n * const validated = yield* validate(parsed); // Never executes\n * return validated;\n * });\n * // None\n *\n * // Mixed sync/async workflow\n * const result = await Option.asyncGen(async function* () {\n * const id = yield* Option.Some(parseInt(input)); // sync\n * const user = yield* await fetchUser(id); // async\n * const profile = yield* Option.fromNullable(user?.profile); // sync\n * const enriched = yield* await enrichProfile(profile); // async\n * return enriched;\n * });\n *\n * // Complex pipeline with multiple optional steps\n * async function processLead(email: string): Promise<Option<Lead>> {\n * return await Option.asyncGen(async function* () {\n * const normalized = yield* Option.Some(normalizeEmail(email));\n * const existing = yield* await findExistingLead(normalized);\n * const enriched = yield* await enrichLeadData(existing);\n * const validated = yield* validateLead(enriched);\n * return validated;\n * });\n * }\n * ```\n *\n * Settles promise-backed Options before checking for None; raw rejections propagate.\n * @see {@link asyncGenAdapter} for better type inference and cleaner syntax\n * @see {@link gen} for synchronous operations\n */\n static async asyncGen<T>(\n this: void,\n genFn: () => AsyncGenerator<Option<unknown>, T, unknown>,\n ): Promise<Option<T>> {\n const iterator = genFn()\n\n // Use iteration instead of recursion to avoid stack overflow\n let nextArg: unknown\n let currentResult: Option<T>\n\n let naturalCompleted = false\n try {\n while (true) {\n const next = await iterator.next(nextArg)\n\n if (next.done) {\n naturalCompleted = true\n // Generator completed successfully - wrap return value in Some\n currentResult = Option.Some(next.value)\n break\n }\n\n // next.value is an Option (user awaits promises before yielding)\n let option = next.value as Option<unknown>\n\n if (isCapturedTrace(option)) {\n option = option.value as Option<unknown>\n }\n\n option = await option.toPromise()\n\n if (option.isNone()) {\n // Early termination on None - return singleton None\n currentResult = Option.None\n break\n }\n\n // Unwrap the Some value\n nextArg = await option.unwrap()\n }\n } finally {\n if (!naturalCompleted) {\n await closeAsyncGenerator(iterator, async (yielded) => {\n if (isCapturedTrace(yielded)) yielded = yielded.value\n let effect = yielded as Option<unknown>\n effect = await effect.toPromise()\n return effect.isNone() ? undefined : effect.unwrap()\n })\n }\n }\n\n return currentResult\n }\n\n /**\n * Async generator-based syntax for chaining Option operations with an adapter function.\n *\n * The `$` adapter handles both sync `Option<T>` and async `Promise<Option<T>>`,\n * automatically awaiting promises. This provides cleaner syntax for mixed sync/async workflows.\n * Settles promise-backed Options before checking for None; raw rejections propagate.\n *\n * Short-circuits on first `None`, returning singleton `None`. Uses async iteration\n * instead of recursion to avoid stack overflow on deep chains.\n *\n * @template Eff - The effect type (inferred from usage)\n * @template T - The return type of the generator\n * @param genFn - An async generator function receiving an adapter `$`\n * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`\n *\n * @example\n * ```ts\n * // No need to manually await - adapter handles it\n * const result = await Option.asyncGenAdapter(async function* ($) {\n * const a = yield* $(Option.Some(1)); // sync Option\n * const b = yield* $(asyncOperation(a)); // Promise<Option> - auto-awaited\n * const c = yield* $(Option.Some(3));\n * return a + b + c;\n * });\n *\n * // Complex workflow with database and API calls\n * const userData = await Option.asyncGenAdapter(async function* ($) {\n * const session = yield* $(getSession()); // Promise<Option<Session>>\n * const userId = yield* $(Option.fromNullable(session?.userId));\n * const profile = yield* $(await fetchProfile(userId)); // Promise<Option<Profile>>\n * const preferences = yield* $(Option.fromNullable(profile?.preferences));\n * const enriched = yield* $(await enrichPreferences(preferences));\n * return enriched;\n * });\n *\n * // Real-world: Optional data enrichment\n * async function getProductDetails(productId: string): Promise<Option<ProductDetails>> {\n * return await Option.asyncGenAdapter(async function* ($) {\n * const product = yield* $(await fetchProduct(productId));\n * const pricing = yield* $(await fetchPricing(product.sku));\n * const inventory = yield* $(await checkInventory(product.id));\n * const reviews = yield* $(await fetchReviews(product.id));\n * const related = yield* $(await fetchRelatedProducts(product.category));\n *\n * return { product, pricing, inventory, reviews, related };\n * });\n * }\n * ```\n *\n * @see {@link asyncGen} when you want explicit `await` for async operations\n * @see {@link genAdapter} for synchronous operations\n */\n // biome-ignore lint/suspicious/noExplicitAny: inference\n static async asyncGenAdapter<Eff extends AsyncOptionYieldWrap<any>, T>(\n this: void,\n genFn: (\n adapter: <A>(\n option: Option<A> | Promise<Option<A>>,\n ) => AsyncOptionYieldWrap<A>,\n // biome-ignore lint/suspicious/noExplicitAny: inference\n ) => AsyncGenerator<Eff, T, any>,\n ): Promise<Option<T>> {\n const adapter = <A>(\n option: Option<A> | Promise<Option<A>>,\n ): AsyncOptionYieldWrap<A> => new AsyncOptionYieldWrap(option)\n\n const iterator = genFn(adapter)\n\n // Use iteration instead of recursion to avoid stack overflow\n let nextArg: unknown\n let currentResult: Option<T>\n\n let naturalCompleted = false\n try {\n while (true) {\n const next = await iterator.next(nextArg)\n\n if (next.done) {\n naturalCompleted = true\n // Generator completed successfully - wrap return value in Some\n currentResult = Option.Some(next.value)\n break\n }\n\n // next.value is the AsyncOptionYieldWrap that was yielded\n const wrapped = next.value as AsyncOptionYieldWrap<unknown>\n let option = await wrapped.option\n\n if (isCapturedTrace(option)) {\n option = (option as CapturedTrace<Option<unknown>>)\n .value as Option<unknown>\n }\n\n option = await option.toPromise()\n\n if (option.isNone()) {\n // Early termination on None - return singleton None\n currentResult = Option.None\n break\n }\n\n // Unwrap the Some value\n nextArg = await option.unwrap()\n }\n } finally {\n if (!naturalCompleted) {\n await closeAsyncGenerator(iterator, async (yielded) => {\n if (isCapturedTrace(yielded)) yielded = yielded.value\n let effect = await (yielded as AsyncOptionYieldWrap<unknown>).option\n if (isCapturedTrace(effect)) {\n effect = effect.value as Option<unknown>\n }\n effect = await effect.toPromise()\n return effect.isNone() ? undefined : effect.unwrap()\n })\n }\n }\n\n return currentResult\n }\n}\n"],"mappings":";;;;;;AAmBA,IAAa,gBAAb,cAAmC,MAAM;CAC9B,OAAO;CAEhB,cAAc;EACZ,MAAM,kCAAkC;CAC1C;AACF;AAEA,MAAM,qBAAqB,IAAI,cAAc;AAE7C,MAAM,WAAW,OAAO,cAAc;;;;;;AAuBtC,IAAM,kBAAN,MAAyB;CACF;CAArB,YAAqB,QAAmB;EAAnB;CAAoB;CAEzC,EAAE,OAAO,YAAuD;EAC9D,OAAQ,MAAM;CAChB;AACF;;;;;;AAOA,IAAM,uBAAN,MAA8B;CACnB;CAET,YAAY,QAAwC;EAClD,KAAK,SACHA,4BAAc,MAAM,IAAI,SAAS,QAAQ,QAAQ,MAAM;CAE3D;CAEA,QAAQ,OAAO,iBAIb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ACF;IAGA,UAAU,MAAM,OAAO,OAAO;GAChC;EACF,UAAU;GACR,IAAI,CAAC,kBACH,MAAME,kCAAoB,UAAU,OAAO,YAAY;IACrD,IAAIF,8BAAgB,OAAO,GAAG,UAAU,QAAQ;IAChD,IAAI,SAAS,MAAO,QAA0C;IAC9D,IAAIA,8BAAgB,MAAM,GACxB,SAAS,OAAO;IAElB,SAAS,MAAM,OAAO,UAAU;IAChC,OAAO,OAAO,OAAO,IAAI,SAAY,OAAO,OAAO;GACrD,CAAC;EAEL;EAEA,OAAO;CACT;AACF"}
|
package/dist/option.d.cts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { UNIT } from "./unit.cjs";
|
|
2
1
|
import { Result } from "./result.cjs";
|
|
3
|
-
|
|
4
|
-
//#region src/option.d.ts
|
|
2
|
+
import { UNIT } from "./unit.cjs";
|
|
5
3
|
type Mapper<T, U> = (val: T) => U;
|
|
6
4
|
type AsyncMapper<T, U> = (val: T) => Promise<U>;
|
|
7
5
|
type FlatMapper<T, U> = (val: T) => Option<U>;
|
|
@@ -10,15 +8,15 @@ type Predicate<T> = (val: T) => boolean;
|
|
|
10
8
|
type FilterPredicate<T> = (val: Awaited<T>) => boolean;
|
|
11
9
|
type AsyncPredicate<T> = (val: Awaited<T>) => Promise<boolean>;
|
|
12
10
|
type Falsy = false | 0 | "" | null | undefined;
|
|
13
|
-
declare class UnwrappedNone extends Error {
|
|
11
|
+
export declare class UnwrappedNone extends Error {
|
|
14
12
|
readonly name = "UnwrapError";
|
|
15
13
|
constructor();
|
|
16
14
|
}
|
|
17
15
|
/** Option alias for presence-without-payload values. */
|
|
18
|
-
type UnitOption = Option<UNIT>;
|
|
16
|
+
export type UnitOption = Option<UNIT>;
|
|
19
17
|
/** Extracts the contained value type from an Option type. */
|
|
20
|
-
type UnwrapOption<T> = T extends Option<infer R> ? R : never;
|
|
21
|
-
type CombinedOptions<T extends Option<unknown>[]> = { [K in keyof T]: UnwrapOption<T[K]
|
|
18
|
+
export type UnwrapOption<T> = T extends Option<infer R> ? R : never;
|
|
19
|
+
type CombinedOptions<T extends Option<unknown>[]> = { [K in keyof T]: UnwrapOption<T[K]>; };
|
|
22
20
|
interface MatchCases<T, U> {
|
|
23
21
|
Some: (val: T) => U;
|
|
24
22
|
None: () => U;
|
|
@@ -47,7 +45,7 @@ declare class AsyncOptionYieldWrap<T> {
|
|
|
47
45
|
* Represents an optional value: `Some<T>` or `None`.
|
|
48
46
|
* Provides composable, null-safe transformation and chaining methods.
|
|
49
47
|
*/
|
|
50
|
-
declare class Option<T> {
|
|
48
|
+
export declare class Option<T> {
|
|
51
49
|
#private;
|
|
52
50
|
/** Discriminant tag for type-level identification */
|
|
53
51
|
readonly _tag: "Some" | "None";
|
|
@@ -123,7 +121,7 @@ declare class Option<T> {
|
|
|
123
121
|
/**
|
|
124
122
|
* Returns the first Some in the list, or None if all are None.
|
|
125
123
|
*
|
|
126
|
-
*
|
|
124
|
+
* Awaits candidates in input order, without waiting for the suffix after success.
|
|
127
125
|
*
|
|
128
126
|
* @template T - Value type
|
|
129
127
|
* @param options - Options to search
|
|
@@ -141,11 +139,11 @@ declare class Option<T> {
|
|
|
141
139
|
/**
|
|
142
140
|
* Type guard that narrows to None.
|
|
143
141
|
*
|
|
144
|
-
* Includes async None tracking
|
|
142
|
+
* Includes async None tracking while preserving the stored payload type.
|
|
145
143
|
*
|
|
146
144
|
* @returns true if this Option is None
|
|
147
145
|
*/
|
|
148
|
-
isNone(): this is Option<
|
|
146
|
+
isNone(): this is Option<T> & {
|
|
149
147
|
readonly _tag: "None";
|
|
150
148
|
};
|
|
151
149
|
/**
|
|
@@ -165,18 +163,24 @@ declare class Option<T> {
|
|
|
165
163
|
unwrap(this: Option<T>): T;
|
|
166
164
|
/**
|
|
167
165
|
* Returns the contained value or the provided default.
|
|
168
|
-
*
|
|
166
|
+
* Promise-backed options wait for settlement before choosing the default.
|
|
169
167
|
* @param defaultValue - Value to use when None
|
|
170
168
|
* @returns The contained value or default
|
|
171
169
|
*/
|
|
172
|
-
unwrapOr(defaultValue:
|
|
170
|
+
unwrapOr<U>(this: Option<never>, defaultValue: U): U;
|
|
171
|
+
unwrapOr<Curr>(this: Option<Promise<Curr>>, defaultValue: Promise<NoInfer<Awaited<Curr>>>): Promise<Awaited<Curr>>;
|
|
172
|
+
unwrapOr<Curr>(this: Option<Promise<Curr>>, defaultValue: NoInfer<Awaited<Curr>> | Promise<NoInfer<Awaited<Curr>>>): Awaited<Curr> | Promise<Awaited<Curr>>;
|
|
173
|
+
unwrapOr(this: Option<T>, defaultValue: T): T;
|
|
173
174
|
/**
|
|
174
175
|
* Returns the contained value or computes a default lazily.
|
|
175
|
-
*
|
|
176
|
+
* Promise-backed options invoke the factory only after settled absence.
|
|
176
177
|
* @param fn - Default factory invoked only when None
|
|
177
178
|
* @returns The contained value or computed default
|
|
178
179
|
*/
|
|
179
|
-
unwrapOrElse(fn: () =>
|
|
180
|
+
unwrapOrElse<U>(this: Option<never>, fn: () => U): U;
|
|
181
|
+
unwrapOrElse<Curr>(this: Option<Promise<Curr>>, fn: () => Promise<NoInfer<Awaited<Curr>>>): Promise<Awaited<Curr>>;
|
|
182
|
+
unwrapOrElse<Curr>(this: Option<Promise<Curr>>, fn: () => NoInfer<Awaited<Curr>> | Promise<NoInfer<Awaited<Curr>>>): Awaited<Curr> | Promise<Awaited<Curr>>;
|
|
183
|
+
unwrapOrElse(this: Option<T>, fn: () => T): T;
|
|
180
184
|
/**
|
|
181
185
|
* Returns the contained value or null for None.
|
|
182
186
|
*
|
|
@@ -240,6 +244,8 @@ declare class Option<T> {
|
|
|
240
244
|
*
|
|
241
245
|
* If None, returns None without calling the mapper. Supports async values
|
|
242
246
|
* and async mappers; returns Option<Promise<U>> when async is involved.
|
|
247
|
+
* Mapper throws propagate synchronously for sync inputs and reject the
|
|
248
|
+
* returned promise chain for promise inputs; they do not become None.
|
|
243
249
|
*
|
|
244
250
|
* @template U - Result value type
|
|
245
251
|
* @param mapper - Function returning an Option
|
|
@@ -247,8 +253,8 @@ declare class Option<T> {
|
|
|
247
253
|
*
|
|
248
254
|
* @see map
|
|
249
255
|
*/
|
|
250
|
-
flatMap<U, Curr = Awaited<T>>(this: Option<Promise<Curr>>, mapper: AsyncFlatMapper<Curr, U>): Option<Promise<U
|
|
251
|
-
flatMap<U, Curr = Awaited<T>>(this: Option<Promise<Curr>>, mapper: FlatMapper<Curr, U>): Option<Promise<U
|
|
256
|
+
flatMap<U, Curr = Awaited<T>>(this: Option<Promise<Curr>>, mapper: AsyncFlatMapper<Curr, U>): Option<Promise<Awaited<U>>>;
|
|
257
|
+
flatMap<U, Curr = Awaited<T>>(this: Option<Promise<Curr>>, mapper: FlatMapper<Curr, U>): Option<Promise<Awaited<U>>>;
|
|
252
258
|
flatMap<U>(this: Option<T>, mapper: AsyncFlatMapper<T, U>): Option<Promise<U>>;
|
|
253
259
|
flatMap<U>(this: Option<T>, mapper: FlatMapper<T, U>): Option<U>;
|
|
254
260
|
/**
|
|
@@ -301,6 +307,7 @@ declare class Option<T> {
|
|
|
301
307
|
tap(fn: (val: T) => void): Option<T>;
|
|
302
308
|
/**
|
|
303
309
|
* Converts this Option to a Result, using the provided error for None.
|
|
310
|
+
* Promise-backed Options preserve settled absence and propagate rejections.
|
|
304
311
|
*
|
|
305
312
|
* @template E - Error type
|
|
306
313
|
* @param error - Error value for None
|
|
@@ -518,6 +525,7 @@ declare class Option<T> {
|
|
|
518
525
|
* }
|
|
519
526
|
* ```
|
|
520
527
|
*
|
|
528
|
+
* Settles promise-backed Options before checking for None; raw rejections propagate.
|
|
521
529
|
* @see {@link asyncGenAdapter} for better type inference and cleaner syntax
|
|
522
530
|
* @see {@link gen} for synchronous operations
|
|
523
531
|
*/
|
|
@@ -527,6 +535,7 @@ declare class Option<T> {
|
|
|
527
535
|
*
|
|
528
536
|
* The `$` adapter handles both sync `Option<T>` and async `Promise<Option<T>>`,
|
|
529
537
|
* automatically awaiting promises. This provides cleaner syntax for mixed sync/async workflows.
|
|
538
|
+
* Settles promise-backed Options before checking for None; raw rejections propagate.
|
|
530
539
|
*
|
|
531
540
|
* Short-circuits on first `None`, returning singleton `None`. Uses async iteration
|
|
532
541
|
* instead of recursion to avoid stack overflow on deep chains.
|
|
@@ -575,6 +584,5 @@ declare class Option<T> {
|
|
|
575
584
|
*/
|
|
576
585
|
static asyncGenAdapter<Eff extends AsyncOptionYieldWrap<any>, T>(this: void, genFn: (adapter: <A>(option: Option<A> | Promise<Option<A>>) => AsyncOptionYieldWrap<A>) => AsyncGenerator<Eff, T, any>): Promise<Option<T>>;
|
|
577
586
|
}
|
|
578
|
-
|
|
579
|
-
export { Option, UnitOption, UnwrapOption, UnwrappedNone };
|
|
587
|
+
export {};
|
|
580
588
|
//# sourceMappingURL=option.d.cts.map
|
package/dist/option.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"option.d.cts","names":[],"sources":["../src/option.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"option.d.cts","names":[],"sources":["../src/option.ts"],"mappings":";;KAUK,OAAO,GAAG,MAAM,KAAK,MAAM;KAC3B,YAAY,GAAG,MAAM,KAAK,MAAM,QAAQ;KACxC,WAAW,GAAG,MAAM,KAAK,MAAM,OAAO;KACtC,gBAAgB,GAAG,MAAM,KAAK,MAAM,QAAQ,OAAO;KACnD,UAAU,MAAM,KAAK;KACrB,gBAAgB,MAAM,KAAK,QAAQ;KACnC,eAAe,MAAM,KAAK,QAAQ,OAAO;KACzC;qBAEQ,sBAAsB;WACxB;EAET;;;YAUU,aAAa,OAAO;;YAEpB,aAAa,KAAK,UAAU,aAAa,KAAK;KAErD,gBAAgB,UAAU,wBAC5B,WAAW,IAAI,aAAa,EAAE;UAKvB,WAAW,GAAG;EACtB,OAAO,KAAK,MAAM;EAClB,YAAY;;;;;;;cAQR,gBAAgB;WACC,QAAQ,OAAO;EAApC,YAAqB,QAAQ,OAAO;GAElC,OAAO,aAAa,UAAU,gBAAgB,IA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;EA8BrD,SAAS,OAAO,KACd,MAAM,OAAO,MAAM,SACnB,SAAS,KAAK,UAAU,MACvB,OAAO,QAAQ;;;;;;EAelB;;;;;;;;;;;;;;;;;;GAsBE,OAAO,aAAa,UAAU,OAAO,IAAI;;;;;;;;;;;;;;;;;;GAsBnC,OAAO,kBAAkB,eAC/B,OAAO,IACP,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SA8DH,IAAI,GACT,YACA,aAAa,UAAU,iBAAiB,cACvC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SA6FH,WAAW,YAAY,sBAAsB,GAClD,YACA,QACE,UAAU,GAAG,QAAQ,OAAO,OAAO,gBAAgB,OAEhD,UAAU,KAAK,UACnB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAkHG,SAAS,GACpB,YACA,aAAa,eAAe,iBAAiB,cAC5C,QAAQ,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAwGL,gBAAgB,YAAY,2BAA2B,GAClE,YACA,QACE,UAAU,GACR,QAAQ,OAAO,KAAK,QAAQ,OAAO,QAChC,qBAAqB,OAEvB,eAAe,KAAK,UACxB,QAAQ,OAAO"}
|
package/dist/option.d.mts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { UNIT } from "./unit.mjs";
|
|
2
1
|
import { Result } from "./result.mjs";
|
|
3
|
-
|
|
4
|
-
//#region src/option.d.ts
|
|
2
|
+
import { UNIT } from "./unit.mjs";
|
|
5
3
|
type Mapper<T, U> = (val: T) => U;
|
|
6
4
|
type AsyncMapper<T, U> = (val: T) => Promise<U>;
|
|
7
5
|
type FlatMapper<T, U> = (val: T) => Option<U>;
|
|
@@ -10,15 +8,15 @@ type Predicate<T> = (val: T) => boolean;
|
|
|
10
8
|
type FilterPredicate<T> = (val: Awaited<T>) => boolean;
|
|
11
9
|
type AsyncPredicate<T> = (val: Awaited<T>) => Promise<boolean>;
|
|
12
10
|
type Falsy = false | 0 | "" | null | undefined;
|
|
13
|
-
declare class UnwrappedNone extends Error {
|
|
11
|
+
export declare class UnwrappedNone extends Error {
|
|
14
12
|
readonly name = "UnwrapError";
|
|
15
13
|
constructor();
|
|
16
14
|
}
|
|
17
15
|
/** Option alias for presence-without-payload values. */
|
|
18
|
-
type UnitOption = Option<UNIT>;
|
|
16
|
+
export type UnitOption = Option<UNIT>;
|
|
19
17
|
/** Extracts the contained value type from an Option type. */
|
|
20
|
-
type UnwrapOption<T> = T extends Option<infer R> ? R : never;
|
|
21
|
-
type CombinedOptions<T extends Option<unknown>[]> = { [K in keyof T]: UnwrapOption<T[K]
|
|
18
|
+
export type UnwrapOption<T> = T extends Option<infer R> ? R : never;
|
|
19
|
+
type CombinedOptions<T extends Option<unknown>[]> = { [K in keyof T]: UnwrapOption<T[K]>; };
|
|
22
20
|
interface MatchCases<T, U> {
|
|
23
21
|
Some: (val: T) => U;
|
|
24
22
|
None: () => U;
|
|
@@ -47,7 +45,7 @@ declare class AsyncOptionYieldWrap<T> {
|
|
|
47
45
|
* Represents an optional value: `Some<T>` or `None`.
|
|
48
46
|
* Provides composable, null-safe transformation and chaining methods.
|
|
49
47
|
*/
|
|
50
|
-
declare class Option<T> {
|
|
48
|
+
export declare class Option<T> {
|
|
51
49
|
#private;
|
|
52
50
|
/** Discriminant tag for type-level identification */
|
|
53
51
|
readonly _tag: "Some" | "None";
|
|
@@ -123,7 +121,7 @@ declare class Option<T> {
|
|
|
123
121
|
/**
|
|
124
122
|
* Returns the first Some in the list, or None if all are None.
|
|
125
123
|
*
|
|
126
|
-
*
|
|
124
|
+
* Awaits candidates in input order, without waiting for the suffix after success.
|
|
127
125
|
*
|
|
128
126
|
* @template T - Value type
|
|
129
127
|
* @param options - Options to search
|
|
@@ -141,11 +139,11 @@ declare class Option<T> {
|
|
|
141
139
|
/**
|
|
142
140
|
* Type guard that narrows to None.
|
|
143
141
|
*
|
|
144
|
-
* Includes async None tracking
|
|
142
|
+
* Includes async None tracking while preserving the stored payload type.
|
|
145
143
|
*
|
|
146
144
|
* @returns true if this Option is None
|
|
147
145
|
*/
|
|
148
|
-
isNone(): this is Option<
|
|
146
|
+
isNone(): this is Option<T> & {
|
|
149
147
|
readonly _tag: "None";
|
|
150
148
|
};
|
|
151
149
|
/**
|
|
@@ -165,18 +163,24 @@ declare class Option<T> {
|
|
|
165
163
|
unwrap(this: Option<T>): T;
|
|
166
164
|
/**
|
|
167
165
|
* Returns the contained value or the provided default.
|
|
168
|
-
*
|
|
166
|
+
* Promise-backed options wait for settlement before choosing the default.
|
|
169
167
|
* @param defaultValue - Value to use when None
|
|
170
168
|
* @returns The contained value or default
|
|
171
169
|
*/
|
|
172
|
-
unwrapOr(defaultValue:
|
|
170
|
+
unwrapOr<U>(this: Option<never>, defaultValue: U): U;
|
|
171
|
+
unwrapOr<Curr>(this: Option<Promise<Curr>>, defaultValue: Promise<NoInfer<Awaited<Curr>>>): Promise<Awaited<Curr>>;
|
|
172
|
+
unwrapOr<Curr>(this: Option<Promise<Curr>>, defaultValue: NoInfer<Awaited<Curr>> | Promise<NoInfer<Awaited<Curr>>>): Awaited<Curr> | Promise<Awaited<Curr>>;
|
|
173
|
+
unwrapOr(this: Option<T>, defaultValue: T): T;
|
|
173
174
|
/**
|
|
174
175
|
* Returns the contained value or computes a default lazily.
|
|
175
|
-
*
|
|
176
|
+
* Promise-backed options invoke the factory only after settled absence.
|
|
176
177
|
* @param fn - Default factory invoked only when None
|
|
177
178
|
* @returns The contained value or computed default
|
|
178
179
|
*/
|
|
179
|
-
unwrapOrElse(fn: () =>
|
|
180
|
+
unwrapOrElse<U>(this: Option<never>, fn: () => U): U;
|
|
181
|
+
unwrapOrElse<Curr>(this: Option<Promise<Curr>>, fn: () => Promise<NoInfer<Awaited<Curr>>>): Promise<Awaited<Curr>>;
|
|
182
|
+
unwrapOrElse<Curr>(this: Option<Promise<Curr>>, fn: () => NoInfer<Awaited<Curr>> | Promise<NoInfer<Awaited<Curr>>>): Awaited<Curr> | Promise<Awaited<Curr>>;
|
|
183
|
+
unwrapOrElse(this: Option<T>, fn: () => T): T;
|
|
180
184
|
/**
|
|
181
185
|
* Returns the contained value or null for None.
|
|
182
186
|
*
|
|
@@ -240,6 +244,8 @@ declare class Option<T> {
|
|
|
240
244
|
*
|
|
241
245
|
* If None, returns None without calling the mapper. Supports async values
|
|
242
246
|
* and async mappers; returns Option<Promise<U>> when async is involved.
|
|
247
|
+
* Mapper throws propagate synchronously for sync inputs and reject the
|
|
248
|
+
* returned promise chain for promise inputs; they do not become None.
|
|
243
249
|
*
|
|
244
250
|
* @template U - Result value type
|
|
245
251
|
* @param mapper - Function returning an Option
|
|
@@ -247,8 +253,8 @@ declare class Option<T> {
|
|
|
247
253
|
*
|
|
248
254
|
* @see map
|
|
249
255
|
*/
|
|
250
|
-
flatMap<U, Curr = Awaited<T>>(this: Option<Promise<Curr>>, mapper: AsyncFlatMapper<Curr, U>): Option<Promise<U
|
|
251
|
-
flatMap<U, Curr = Awaited<T>>(this: Option<Promise<Curr>>, mapper: FlatMapper<Curr, U>): Option<Promise<U
|
|
256
|
+
flatMap<U, Curr = Awaited<T>>(this: Option<Promise<Curr>>, mapper: AsyncFlatMapper<Curr, U>): Option<Promise<Awaited<U>>>;
|
|
257
|
+
flatMap<U, Curr = Awaited<T>>(this: Option<Promise<Curr>>, mapper: FlatMapper<Curr, U>): Option<Promise<Awaited<U>>>;
|
|
252
258
|
flatMap<U>(this: Option<T>, mapper: AsyncFlatMapper<T, U>): Option<Promise<U>>;
|
|
253
259
|
flatMap<U>(this: Option<T>, mapper: FlatMapper<T, U>): Option<U>;
|
|
254
260
|
/**
|
|
@@ -301,6 +307,7 @@ declare class Option<T> {
|
|
|
301
307
|
tap(fn: (val: T) => void): Option<T>;
|
|
302
308
|
/**
|
|
303
309
|
* Converts this Option to a Result, using the provided error for None.
|
|
310
|
+
* Promise-backed Options preserve settled absence and propagate rejections.
|
|
304
311
|
*
|
|
305
312
|
* @template E - Error type
|
|
306
313
|
* @param error - Error value for None
|
|
@@ -518,6 +525,7 @@ declare class Option<T> {
|
|
|
518
525
|
* }
|
|
519
526
|
* ```
|
|
520
527
|
*
|
|
528
|
+
* Settles promise-backed Options before checking for None; raw rejections propagate.
|
|
521
529
|
* @see {@link asyncGenAdapter} for better type inference and cleaner syntax
|
|
522
530
|
* @see {@link gen} for synchronous operations
|
|
523
531
|
*/
|
|
@@ -527,6 +535,7 @@ declare class Option<T> {
|
|
|
527
535
|
*
|
|
528
536
|
* The `$` adapter handles both sync `Option<T>` and async `Promise<Option<T>>`,
|
|
529
537
|
* automatically awaiting promises. This provides cleaner syntax for mixed sync/async workflows.
|
|
538
|
+
* Settles promise-backed Options before checking for None; raw rejections propagate.
|
|
530
539
|
*
|
|
531
540
|
* Short-circuits on first `None`, returning singleton `None`. Uses async iteration
|
|
532
541
|
* instead of recursion to avoid stack overflow on deep chains.
|
|
@@ -575,6 +584,5 @@ declare class Option<T> {
|
|
|
575
584
|
*/
|
|
576
585
|
static asyncGenAdapter<Eff extends AsyncOptionYieldWrap<any>, T>(this: void, genFn: (adapter: <A>(option: Option<A> | Promise<Option<A>>) => AsyncOptionYieldWrap<A>) => AsyncGenerator<Eff, T, any>): Promise<Option<T>>;
|
|
577
586
|
}
|
|
578
|
-
|
|
579
|
-
export { Option, UnitOption, UnwrapOption, UnwrappedNone };
|
|
587
|
+
export {};
|
|
580
588
|
//# sourceMappingURL=option.d.mts.map
|