From 9b23e810c8bfc15a57ee132ff82e52d0bcb76558 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Wed, 27 Aug 2025 17:21:18 +0200 Subject: [PATCH] add OptionFromNullOr (#438) --- packages/effect/dtslint/data/Option.tst.ts | 22 ++++ packages/effect/src/Deferred.ts | 2 +- packages/effect/src/Effect.ts | 4 +- packages/effect/src/FiberHandle.ts | 2 +- packages/effect/src/Utils.ts | 10 +- packages/effect/src/caching/Cache.ts | 2 +- packages/effect/src/caching/ScopedCache.ts | 2 +- packages/effect/src/collections/Array.ts | 27 +++-- packages/effect/src/collections/Iterable.ts | 14 +-- packages/effect/src/data/Option.ts | 102 +++++++----------- packages/effect/src/data/Predicate.ts | 42 +------- packages/effect/src/data/Result.ts | 16 +-- packages/effect/src/internal/effect.ts | 4 +- .../src/internal/tracing/otlpExporter.ts | 2 +- packages/effect/src/internal/trie.ts | 4 +- packages/effect/src/primitives/String.ts | 6 +- packages/effect/src/schema/AST.ts | 2 +- packages/effect/src/schema/Schema.ts | 28 ++++- packages/effect/src/schema/Transformation.ts | 12 ++- packages/effect/src/time/Cron.ts | 2 +- .../effect/src/unstable/httpapi/HttpApi.ts | 2 +- .../src/unstable/httpapi/HttpApiBuilder.ts | 2 +- .../src/unstable/httpapi/HttpApiEndpoint.ts | 13 +-- packages/effect/test/data/Result.test.ts | 6 +- packages/effect/test/schema/Schema.test.ts | 10 ++ packages/platform-bun/src/BunHttpServer.ts | 2 +- .../src/NodeFileSystem.ts | 20 ++-- .../src/NodeHttpIncomingMessage.ts | 2 +- 28 files changed, 180 insertions(+), 182 deletions(-) diff --git a/packages/effect/dtslint/data/Option.tst.ts b/packages/effect/dtslint/data/Option.tst.ts index 40e43c7c3f..cd58f07529 100644 --- a/packages/effect/dtslint/data/Option.tst.ts +++ b/packages/effect/dtslint/data/Option.tst.ts @@ -9,6 +9,10 @@ declare const numberOrString: Option.Option declare const predicateNumberOrString: Predicate.Predicate declare const refinementNumberOrString: Predicate.Refinement +declare const nullish: number | null | undefined +declare const nullOr: number | null +declare const undefinedOr: number | undefined + describe("Option", () => { it("filter", () => { expect(Option.filter(number, predicateNumberOrString)).type.toBe>() @@ -33,4 +37,22 @@ describe("Option", () => { ) ).type.toBe>() }) + + it("fromNullishOr", () => { + expect(Option.fromNullishOr(nullish)).type.toBe>() + expect(Option.fromNullishOr(nullOr)).type.toBe>() + expect(Option.fromNullishOr(undefinedOr)).type.toBe>() + }) + + it("fromUndefinedOr", () => { + expect(Option.fromUndefinedOr(nullish)).type.toBe>() + expect(Option.fromUndefinedOr(nullOr)).type.toBe>() + expect(Option.fromUndefinedOr(undefinedOr)).type.toBe>() + }) + + it("fromNullOr", () => { + expect(Option.fromNullOr(nullish)).type.toBe>() + expect(Option.fromNullOr(nullOr)).type.toBe>() + expect(Option.fromNullOr(undefinedOr)).type.toBe>() + }) }) diff --git a/packages/effect/src/Deferred.ts b/packages/effect/src/Deferred.ts index 5039de7429..80596c6d8f 100644 --- a/packages/effect/src/Deferred.ts +++ b/packages/effect/src/Deferred.ts @@ -609,7 +609,7 @@ export const unsafeIsDone = (self: Deferred): boolean => self.effect */ export const poll = ( self: Deferred -): Effect>> => internalEffect.sync(() => Option.fromNullable(self.effect)) +): Effect>> => internalEffect.sync(() => Option.fromUndefinedOr(self.effect)) /** * Completes the `Deferred` with the specified value. diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 00226f225b..a92831ec5f 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1702,13 +1702,13 @@ export const fromOption: ( ) => Effect = internal.fromOption /** - * Converts a nullable value to an `Effect`, failing with a `NoSuchElementError` + * Converts a nullish value to an `Effect`, failing with a `NoSuchElementError` * if the value is `null` or `undefined`. * * @since 4.0.0 * @category Conversions */ -export const fromNullable: (value: A) => Effect, Cause.NoSuchElementError> = internal.fromNullable +export const fromNullishOr: (value: A) => Effect, Cause.NoSuchElementError> = internal.fromNullishOr /** * Converts a yieldable value to an Effect. diff --git a/packages/effect/src/FiberHandle.ts b/packages/effect/src/FiberHandle.ts index e6dbc5ce10..e3af5eba35 100644 --- a/packages/effect/src/FiberHandle.ts +++ b/packages/effect/src/FiberHandle.ts @@ -406,7 +406,7 @@ export const set: { * ``` */ export const unsafeGet = (self: FiberHandle): Option.Option> => - self.state._tag === "Closed" ? Option.none() : Option.fromNullable(self.state.fiber) + self.state._tag === "Closed" ? Option.none() : Option.fromUndefinedOr(self.state.fiber) /** * Retrieve the fiber from the FiberHandle. diff --git a/packages/effect/src/Utils.ts b/packages/effect/src/Utils.ts index e0e0b2d37e..9793472b72 100644 --- a/packages/effect/src/Utils.ts +++ b/packages/effect/src/Utils.ts @@ -1,7 +1,7 @@ /** * @since 2.0.0 */ -import { isNullable, isObject } from "./data/Predicate.ts" +import { isNullish, isObject } from "./data/Predicate.ts" import { identity } from "./Function.ts" import type { Kind, TypeLambda } from "./types/HKT.ts" import type * as Types from "./types/Types.ts" @@ -367,17 +367,17 @@ export class PCGRandom { incHi?: OptionalNumber, incLo?: OptionalNumber ) { - if (isNullable(seedLo) && isNullable(seedHi)) { + if (isNullish(seedLo) && isNullish(seedHi)) { seedLo = (Math.random() * 0xffffffff) >>> 0 seedHi = 0 - } else if (isNullable(seedLo)) { + } else if (isNullish(seedLo)) { seedLo = seedHi seedHi = 0 } - if (isNullable(incLo) && isNullable(incHi)) { + if (isNullish(incLo) && isNullish(incHi)) { incLo = this._state ? this._state[3] : defaultIncLo incHi = this._state ? this._state[2] : defaultIncHi - } else if (isNullable(incLo)) { + } else if (isNullish(incLo)) { incLo = incHi as number incHi = 0 } diff --git a/packages/effect/src/caching/Cache.ts b/packages/effect/src/caching/Cache.ts index b750423c2b..6514375d1f 100644 --- a/packages/effect/src/caching/Cache.ts +++ b/packages/effect/src/caching/Cache.ts @@ -587,7 +587,7 @@ export const getSuccess: { core.withFiber((fiber) => effect.succeed( getOptionImpl(self, key, fiber).pipe( - Option.flatMapNullable((entry) => entry.deferred.effect as Exit.Exit), + Option.flatMapNullishOr((entry) => entry.deferred.effect as Exit.Exit), Option.flatMap((exit) => effect.exitIsSuccess(exit) ? Option.some(exit.value) : Option.none()) ) ) diff --git a/packages/effect/src/caching/ScopedCache.ts b/packages/effect/src/caching/ScopedCache.ts index c05aff873f..b7a04a6415 100644 --- a/packages/effect/src/caching/ScopedCache.ts +++ b/packages/effect/src/caching/ScopedCache.ts @@ -291,7 +291,7 @@ export const getSuccess: { getOptionImpl(self, key, fiber), (o) => o.pipe( - Option.flatMapNullable((entry) => entry.deferred.effect as Exit.Exit), + Option.flatMapNullishOr((entry) => entry.deferred.effect as Exit.Exit), Option.flatMap((exit) => effect.exitIsSuccess(exit) ? Option.some(exit.value) : Option.none()) ) ) diff --git a/packages/effect/src/collections/Array.ts b/packages/effect/src/collections/Array.ts index 9669abe779..6dfdcc28ad 100644 --- a/packages/effect/src/collections/Array.ts +++ b/packages/effect/src/collections/Array.ts @@ -3128,15 +3128,15 @@ export const liftOption = , B>( * ```ts * import { Array } from "effect/collections" * - * console.log(Array.fromNullable(1)) // [1] - * console.log(Array.fromNullable(null)) // [] - * console.log(Array.fromNullable(undefined)) // [] + * console.log(Array.fromNullishOr(1)) // [1] + * console.log(Array.fromNullishOr(null)) // [] + * console.log(Array.fromNullishOr(undefined)) // [] * ``` * * @category conversions * @since 2.0.0 */ -export const fromNullable = (a: A): Array> => a == null ? empty() : [a as NonNullable] +export const fromNullishOr = (a: A): Array> => a == null ? empty() : [a as NonNullable] /** * Lifts a function that returns a nullable value into the Array context. @@ -3145,7 +3145,7 @@ export const fromNullable = (a: A): Array> => a == null ? empt * ```ts * import { Array } from "effect/collections" * - * const parseNumber = Array.liftNullable((s: string) => { + * const parseNumber = Array.liftNullishOr((s: string) => { * const n = Number(s) * return isNaN(n) ? null : n * }) @@ -3157,10 +3157,10 @@ export const fromNullable = (a: A): Array> => a == null ? empt * @category lifting * @since 2.0.0 */ -export const liftNullable = , B>( - f: (...a: A) => B | null | undefined +export const liftNullishOr = , B>( + f: (...a: A) => B ): (...a: A) => Array> => -(...a) => fromNullable(f(...a)) +(...a) => fromNullishOr(f(...a)) /** * Maps over an array and flattens the result, removing null and undefined values. @@ -3170,7 +3170,7 @@ export const liftNullable = , B>( * ```ts * import { Array } from "effect/collections" * - * const result = Array.flatMapNullable([1, 2, 3], n => (n % 2 === 0 ? null : n)) + * const result = Array.flatMapNullishOr([1, 2, 3], n => (n % 2 === 0 ? null : n)) * console.log(result) // [1, 3] * * // Explanation: @@ -3182,13 +3182,12 @@ export const liftNullable = , B>( * @category sequencing * @since 2.0.0 */ -export const flatMapNullable: { - (f: (a: A) => B | null | undefined): (self: ReadonlyArray) => Array> - (self: ReadonlyArray, f: (a: A) => B | null | undefined): Array> +export const flatMapNullishOr: { + (f: (a: A) => B): (self: ReadonlyArray) => Array> + (self: ReadonlyArray, f: (a: A) => B): Array> } = dual( 2, - (self: ReadonlyArray, f: (a: A) => B | null | undefined): Array> => - flatMap(self, (a) => fromNullable(f(a))) + (self: ReadonlyArray, f: (a: A) => B): Array> => flatMap(self, (a) => fromNullishOr(f(a))) ) /** diff --git a/packages/effect/src/collections/Iterable.ts b/packages/effect/src/collections/Iterable.ts index 9e3e2a2a95..717f10ae21 100644 --- a/packages/effect/src/collections/Iterable.ts +++ b/packages/effect/src/collections/Iterable.ts @@ -1729,7 +1729,7 @@ export const filter: { * * // Extract valid elements from nullable function results * const data = ["1", "2", "invalid", "4"] - * const parsed = Iterable.flatMapNullable(data, s => { + * const parsed = Iterable.flatMapNullishOr(data, s => { * const num = parseInt(s) * return isNaN(num) ? null : num * 2 * }) @@ -1742,7 +1742,7 @@ export const filter: { * { nested: { value: 20 } }, * {} * ] - * const values = Iterable.flatMapNullable(objects, obj => obj.nested?.value) + * const values = Iterable.flatMapNullishOr(objects, obj => obj.nested?.value) * console.log(Array.from(values)) // [10, 20] * * // Working with Map.get (returns undefined for missing keys) @@ -1752,19 +1752,19 @@ export const filter: { * ["c", 3] * ]) * const keys = ["a", "x", "b", "y", "c"] - * const foundValues = Iterable.flatMapNullable(keys, key => map.get(key)) + * const foundValues = Iterable.flatMapNullishOr(keys, key => map.get(key)) * console.log(Array.from(foundValues)) // [1, 2, 3] * ``` * * @category sequencing * @since 2.0.0 */ -export const flatMapNullable: { - (f: (a: A) => B | null | undefined): (self: Iterable) => Iterable> - (self: Iterable, f: (a: A) => B | null | undefined): Iterable> +export const flatMapNullishOr: { + (f: (a: A) => B): (self: Iterable) => Iterable> + (self: Iterable, f: (a: A) => B): Iterable> } = dual( 2, - (self: Iterable, f: (a: A) => B | null | undefined): Iterable> => + (self: Iterable, f: (a: A) => B): Iterable> => filterMap(self, (a) => { const b = f(a) return b == null ? O.none() : O.some(b) diff --git a/packages/effect/src/data/Option.ts b/packages/effect/src/data/Option.ts index 6f40b0fbbb..c8f3ce2e42 100644 --- a/packages/effect/src/data/Option.ts +++ b/packages/effect/src/data/Option.ts @@ -64,50 +64,18 @@ import * as Reducer from "./Reducer.ts" export type Option = None | Some /** - * @example - * ```ts - * import { Option } from "effect/data" - * - * console.log(Option.TypeId) - * // Output: "~effect/Option" - * ``` - * * @category Symbols - * @since 2.0.0 + * @since 4.0.0 */ export const TypeId: TypeId = "~effect/Option" /** - * @example - * ```ts - * import { Option } from "effect/data" - * - * // Using TypeId for type checking - * const checkTypeId = (value: unknown): value is Option.Option => { - * return typeof value === "object" && value !== null && - * Option.TypeId in value - * } - * ``` - * * @category Symbols - * @since 2.0.0 + * @since 4.0.0 */ export type TypeId = "~effect/Option" /** - * @example - * ```ts - * import { Option } from "effect/data" - * - * const noneValue = Option.none() - * - * // Type checking for None - * if (Option.isNone(noneValue)) { - * console.log("This is a None value") - * console.log(noneValue._tag) // "None" - * } - * ``` - * * @category Models * @since 2.0.0 */ @@ -123,20 +91,6 @@ export interface None extends Pipeable, Inspectable, Yieldable, } /** - * @example - * ```ts - * import { Option } from "effect/data" - * - * const someValue = Option.some(42) - * - * // Type checking for Some - * if (Option.isSome(someValue)) { - * console.log("This is a Some value") - * console.log(someValue._tag) // "Some" - * console.log(someValue.value) // 42 - * } - * ``` - * * @category Models * @since 2.0.0 */ @@ -795,22 +749,38 @@ export const firstSomeOf = > = Iterable( - nullableValue: A -): Option> => (nullableValue == null ? none() : some(nullableValue as NonNullable)) +export const fromNullishOr = ( + a: A +): Option> => (a == null ? none() : some(a as NonNullable)) + +/** + * @category Conversions + * @since 4.0.0 + */ +export const fromUndefinedOr = ( + a: A +): Option> => (a === undefined ? none() : some(a as Exclude)) + +/** + * @category Conversions + * @since 4.0.0 + */ +export const fromNullOr = ( + a: A +): Option> => (a === null ? none() : some(a as Exclude)) /** * Lifts a function that returns `null` or `undefined` into the `Option` @@ -833,7 +803,7 @@ export const fromNullable = ( * return isNaN(n) ? undefined : n * } * - * const parseOption = Option.liftNullable(parse) + * const parseOption = Option.liftNullishOr(parse) * * console.log(parseOption("1")) * // Output: { _id: 'Option', _tag: 'Some', value: 1 } @@ -845,10 +815,10 @@ export const fromNullable = ( * @category Conversions * @since 2.0.0 */ -export const liftNullable = , B>( - f: (...a: A) => B | null | undefined +export const liftNullishOr = , B>( + f: (...a: A) => B ): (...a: A) => Option> => -(...a) => fromNullable(f(...a)) +(...a) => fromNullishOr(f(...a)) /** * Returns the value contained in the `Option` if it is `Some`; otherwise, @@ -1273,7 +1243,7 @@ export const andThen: { ) /** - * Combines `flatMap` and `fromNullable`, transforming the value inside a `Some` + * Combines `flatMap` and `fromNullish`, transforming the value inside a `Some` * using a function that may return `null` or `undefined`. * * **Details** @@ -1307,7 +1277,7 @@ export const andThen: { * // Extracting a deeply nested property * console.log( * Option.some(employee1) - * .pipe(Option.flatMapNullable((employee) => employee.company?.address?.street?.name)) + * .pipe(Option.flatMapNullishOr((employee) => employee.company?.address?.street?.name)) * ) * // Output: { _id: 'Option', _tag: 'Some', value: 'high street' } * @@ -1316,7 +1286,7 @@ export const andThen: { * // Property does not exist * console.log( * Option.some(employee2) - * .pipe(Option.flatMapNullable((employee) => employee.company?.address?.street?.name)) + * .pipe(Option.flatMapNullishOr((employee) => employee.company?.address?.street?.name)) * ) * // Output: { _id: 'Option', _tag: 'None' } * ``` @@ -1324,13 +1294,13 @@ export const andThen: { * @category Sequencing * @since 2.0.0 */ -export const flatMapNullable: { - (f: (a: A) => B | null | undefined): (self: Option) => Option> - (self: Option, f: (a: A) => B | null | undefined): Option> +export const flatMapNullishOr: { + (f: (a: A) => B): (self: Option) => Option> + (self: Option, f: (a: A) => B): Option> } = dual( 2, - (self: Option, f: (a: A) => B | null | undefined): Option> => - isNone(self) ? none() : fromNullable(f(self.value)) + (self: Option, f: (a: A) => B): Option> => + isNone(self) ? none() : fromNullishOr(f(self.value)) ) /** diff --git a/packages/effect/src/data/Predicate.ts b/packages/effect/src/data/Predicate.ts index e7aa0e0cf9..f2d25706f0 100644 --- a/packages/effect/src/data/Predicate.ts +++ b/packages/effect/src/data/Predicate.ts @@ -600,7 +600,7 @@ export const isNullish = (input: unknown): input is null | undefined => input == * @category guards * @since 2.0.0 */ -export const isNotNullish = (input: A): input is Exclude => input != null +export const isNotNullish = (input: A): input is NonNullable => input != null /** * A guard that always fails. @@ -739,46 +739,6 @@ export const isTagged: { (self: unknown, tag: K): self is { _tag: K } => hasProperty(self, "_tag") && self["_tag"] === tag ) -/** - * A guard that succeeds when the input is `null` or `undefined`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { isNullable } from "effect/data/Predicate" - * - * assert.deepStrictEqual(isNullable(null), true) - * assert.deepStrictEqual(isNullable(undefined), true) - * - * assert.deepStrictEqual(isNullable({}), false) - * assert.deepStrictEqual(isNullable([]), false) - * ``` - * - * @category guards - * @since 2.0.0 - */ -export const isNullable = (input: A): input is Extract => input === null || input === undefined - -/** - * A guard that succeeds when the input is not `null` or `undefined`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { isNotNullable } from "effect/data/Predicate" - * - * assert.deepStrictEqual(isNotNullable({}), true) - * assert.deepStrictEqual(isNotNullable([]), true) - * - * assert.deepStrictEqual(isNotNullable(null), false) - * assert.deepStrictEqual(isNotNullable(undefined), false) - * ``` - * - * @category guards - * @since 2.0.0 - */ -export const isNotNullable = (input: A): input is NonNullable => input !== null && input !== undefined - /** * A guard that succeeds when the input is an `Error`. * diff --git a/packages/effect/src/data/Result.ts b/packages/effect/src/data/Result.ts index de3331227f..44aa750652 100644 --- a/packages/effect/src/data/Result.ts +++ b/packages/effect/src/data/Result.ts @@ -304,7 +304,7 @@ export { } /** - * Takes a lazy default and a nullable value, if the value is not nully (`null` + * Takes a lazy default and a nullish value, if the value is not nully (`null` * or `undefined`), turn it into a `Success`, if the value is nully use the * provided default as a `Failure`. * @@ -313,20 +313,20 @@ export { * import * as assert from "node:assert" * import { Result } from "effect/data" * - * assert.deepStrictEqual(Result.fromNullable(1, () => 'fallback'), Result.succeed(1)) - * assert.deepStrictEqual(Result.fromNullable(null, () => 'fallback'), Result.fail('fallback')) + * assert.deepStrictEqual(Result.fromNullishOr(1, () => 'fallback'), Result.succeed(1)) + * assert.deepStrictEqual(Result.fromNullishOr(null, () => 'fallback'), Result.fail('fallback')) * ``` * * @category Constructors * @since 4.0.0 */ -export const fromNullable: { - (onNullable: (a: A) => E): (self: A) => Result, E> - (self: A, onNullable: (a: A) => E): Result, E> +export const fromNullishOr: { + (onNullish: (a: A) => E): (self: A) => Result, E> + (self: A, onNullish: (a: A) => E): Result, E> } = dual( 2, - (self: A, onNullable: (a: A) => E): Result, E> => - self == null ? fail(onNullable(self)) : succeed(self) + (self: A, onNullish: (a: A) => E): Result, E> => + self == null ? fail(onNullish(self)) : succeed(self) ) /** diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index 9111a739f6..5d6c8f9c44 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -809,7 +809,7 @@ export const fromOption: (option: Option.Option) => Effect.Effect(result: Result.Result) => Effect.Effect = fromYieldable /** @internal */ -export const fromNullable = (value: A): Effect.Effect, Cause.NoSuchElementError> => +export const fromNullishOr = (value: A): Effect.Effect, Cause.NoSuchElementError> => value == null ? fail(new NoSuchElementError()) : succeed(value) /** @internal */ @@ -4216,7 +4216,7 @@ export const unsafeMakeSpan = ( ? Option.some(options.parent) : options.root ? Option.none() - : filterDisablePropagation(Option.fromNullable(fiber.currentSpan)) + : filterDisablePropagation(Option.fromUndefinedOr(fiber.currentSpan)) let span: Tracer.Span diff --git a/packages/effect/src/internal/tracing/otlpExporter.ts b/packages/effect/src/internal/tracing/otlpExporter.ts index c3f6513ac1..153d6505eb 100644 --- a/packages/effect/src/internal/tracing/otlpExporter.ts +++ b/packages/effect/src/internal/tracing/otlpExporter.ts @@ -19,7 +19,7 @@ const policy = Schedule.forever.pipe( && error._tag === "ResponseError" && error.response.status === 429 ) { - const retryAfter = Option.fromNullable(error.response.headers["retry-after"]).pipe( + const retryAfter = Option.fromUndefinedOr(error.response.headers["retry-after"]).pipe( Option.flatMap(Num.parse), Option.getOrElse(() => 5) ) diff --git a/packages/effect/src/internal/trie.ts b/packages/effect/src/internal/trie.ts index 6219f26838..1253c0e783 100644 --- a/packages/effect/src/internal/trie.ts +++ b/packages/effect/src/internal/trie.ts @@ -398,7 +398,7 @@ export const get = dual< } } else { if (cIndex === key.length - 1) { - return Option.fromNullable(n.value) + return Option.fromUndefinedOr(n.value) } else { if (n.mid === undefined) { return Option.none() @@ -714,7 +714,7 @@ export const longestPrefixOf = dual< } } - return Option.fromNullable(longestPrefixNode) + return Option.fromUndefinedOr(longestPrefixNode) } ) diff --git a/packages/effect/src/primitives/String.ts b/packages/effect/src/primitives/String.ts index 5073da34c3..3731550728 100644 --- a/packages/effect/src/primitives/String.ts +++ b/packages/effect/src/primitives/String.ts @@ -551,7 +551,7 @@ export const substring = (start: number, end?: number) => (self: string): string export const at: { (index: number): (self: string) => Option.Option (self: string, index: number): Option.Option -} = dual(2, (self: string, index: number): Option.Option => Option.fromNullable(self.at(index))) +} = dual(2, (self: string, index: number): Option.Option => Option.fromUndefinedOr(self.at(index))) /** * Returns the character at the specified index, or `None` if the index is out of bounds. @@ -598,7 +598,7 @@ export const charAt: { export const codePointAt: { (index: number): (self: string) => Option.Option (self: string, index: number): Option.Option -} = dual(2, (self: string, index: number): Option.Option => Option.fromNullable(self.codePointAt(index))) +} = dual(2, (self: string, index: number): Option.Option => Option.fromUndefinedOr(self.codePointAt(index))) /** * Returns the index of the first occurrence of a substring, or `None` if not found. @@ -679,7 +679,7 @@ export const localeCompare = * @since 2.0.0 */ export const match = (regexp: RegExp | string) => (self: string): Option.Option => - Option.fromNullable(self.match(regexp)) + Option.fromNullOr(self.match(regexp)) /** * It is the `pipe`-able version of the native `matchAll` method. diff --git a/packages/effect/src/schema/AST.ts b/packages/effect/src/schema/AST.ts index 2bab2ab6c1..9dfda86b8c 100644 --- a/packages/effect/src/schema/AST.ts +++ b/packages/effect/src/schema/AST.ts @@ -1270,7 +1270,7 @@ export class TypeLiteral extends Base { // handle empty struct // --------------------------------------------- if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) { - return fromRefinement(ast, Predicate.isNotNullable) + return fromRefinement(ast, Predicate.isNotNullish) } return Effect.fnUntracedEager(function*(oinput, options) { if (Option.isNone(oinput)) { diff --git a/packages/effect/src/schema/Schema.ts b/packages/effect/src/schema/Schema.ts index 03c8b65c36..ce22769f60 100644 --- a/packages/effect/src/schema/Schema.ts +++ b/packages/effect/src/schema/Schema.ts @@ -3170,7 +3170,7 @@ export interface Option } /** - * @category Constructors + * @category Option * @since 4.0.0 */ export function Option(value: S): Option { @@ -3225,6 +3225,32 @@ export function Option(value: S): Option { ) } +/** + * @since 4.0.0 + */ +export interface OptionFromNullOr extends decodeTo>, NullOr> {} + +/** + * Decodes a nullable, required value `T` to a required `Option` value. + * + * Decoding: + * - `null` is decoded as `None` + * - other values are decoded as `Some` + * + * Encoding: + * - `None` is encoded as `null` + * - `Some` is encoded as the value + * + * @category Option + * @since 4.0.0 + */ +export function OptionFromNullOr(schema: S): OptionFromNullOr { + return NullOr(schema).pipe(decodeTo( + Option(typeCodec(schema)), + Transformation.optionFromNullOr() // TODO: fix this + )) +} + /** * @since 4.0.0 */ diff --git a/packages/effect/src/schema/Transformation.ts b/packages/effect/src/schema/Transformation.ts index dc92245061..414bfc6f97 100644 --- a/packages/effect/src/schema/Transformation.ts +++ b/packages/effect/src/schema/Transformation.ts @@ -2,7 +2,7 @@ * @since 4.0.0 */ -import type * as Option from "../data/Option.ts" +import * as Option from "../data/Option.ts" import * as Predicate from "../data/Predicate.ts" import type * as Effect from "../Effect.ts" import type * as AST from "./AST.ts" @@ -300,3 +300,13 @@ export function error(): Transformation(): Transformation>, T | null> { + return transform({ + decode: Option.fromNullOr, + encode: Option.getOrNull + }) +} diff --git a/packages/effect/src/time/Cron.ts b/packages/effect/src/time/Cron.ts index 92eaabe0e6..09867db1e5 100644 --- a/packages/effect/src/time/Cron.ts +++ b/packages/effect/src/time/Cron.ts @@ -243,7 +243,7 @@ export const make = (values: { o.days = new Set(Arr.sort(values.days, N.Order)) o.months = new Set(Arr.sort(values.months, N.Order)) o.weekdays = new Set(Arr.sort(values.weekdays, N.Order)) - o.tz = Option.fromNullable(values.tz) + o.tz = Option.fromUndefinedOr(values.tz) const seconds = Array.from(o.seconds) const minutes = Array.from(o.minutes) diff --git a/packages/effect/src/unstable/httpapi/HttpApi.ts b/packages/effect/src/unstable/httpapi/HttpApi.ts index 8e4ce0073d..fe0032bf15 100644 --- a/packages/effect/src/unstable/httpapi/HttpApi.ts +++ b/packages/effect/src/unstable/httpapi/HttpApi.ts @@ -366,7 +366,7 @@ const extractPayloads = (topAst: AST.AST): ReadonlyMap => { const annotations: Record = ast.annotations ?? {} as any - return Option.fromNullable(annotations.description ?? annotations.identfier) + return Option.fromUndefinedOr(annotations.description ?? annotations.identfier) } /** diff --git a/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts b/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts index 2dbdf009be..dc599fd030 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts @@ -443,7 +443,7 @@ const handlerToRoute = ( Option.getOrElse(constFalse) ) const multipartLimits = endpoint.payloadSchema.pipe( - Option.flatMapNullable(({ ast }) => ast.annotations?.httpApiMultipartStream ?? ast.annotations?.httpApiMultipart) + Option.flatMapNullishOr(({ ast }) => ast.annotations?.httpApiMultipartStream ?? ast.annotations?.httpApiMultipart) ) const decodePath = Option.map(endpoint.pathSchema, Schema.decodeUnknownEffect) const decodePayload = handler.withFullRequest || isMultipartStream diff --git a/packages/effect/src/unstable/httpapi/HttpApiEndpoint.ts b/packages/effect/src/unstable/httpapi/HttpApiEndpoint.ts index 80ecefb435..eab87b5be6 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiEndpoint.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiEndpoint.ts @@ -1076,21 +1076,21 @@ export const make = (method: Method) => Headers extends Schema.Struct.Fields ? Schema.Struct : Headers, Success extends Schema.Struct.Fields ? Schema.Struct : Success, Error extends ReadonlyArray ? Error[number] : Error -> => - makeProto({ +> => { + return makeProto({ name, path, method, - pathSchema: Option.fromNullable(options?.path).pipe( + pathSchema: Option.fromNullishOr(options?.path).pipe( Option.map(structToSchema) ), - urlParamsSchema: Option.fromNullable(options?.urlParams).pipe( + urlParamsSchema: Option.fromNullishOr(options?.urlParams).pipe( Option.map(structToSchema) ), - payloadSchema: Option.fromNullable(options?.payload).pipe( + payloadSchema: Option.fromNullishOr(options?.payload).pipe( Option.map(structToSchema) ), - headersSchema: Option.fromNullable(options?.headers).pipe( + headersSchema: Option.fromNullishOr(options?.headers).pipe( Option.map(structToSchema) ), successSchema: options?.success ? structToSchema(options.success) : HttpApiSchema.NoContent as any, @@ -1103,6 +1103,7 @@ export const make = (method: Method) => annotations: ServiceMap.empty(), middlewares: new Set() }) +} const structToSchema = ( schema: S diff --git a/packages/effect/test/data/Result.test.ts b/packages/effect/test/data/Result.test.ts index e4baf07308..7cb99d1734 100644 --- a/packages/effect/test/data/Result.test.ts +++ b/packages/effect/test/data/Result.test.ts @@ -46,9 +46,9 @@ describe("Result", () => { }) it("fromNullable", () => { - deepStrictEqual(Result.fromNullable(null, () => "fallback"), Result.fail("fallback")) - deepStrictEqual(Result.fromNullable(undefined, () => "fallback"), Result.fail("fallback")) - deepStrictEqual(Result.fromNullable(1, () => "fallback"), Result.succeed(1)) + deepStrictEqual(Result.fromNullishOr(null, () => "fallback"), Result.fail("fallback")) + deepStrictEqual(Result.fromNullishOr(undefined, () => "fallback"), Result.fail("fallback")) + deepStrictEqual(Result.fromNullishOr(1, () => "fallback"), Result.succeed(1)) }) it("fromOption", () => { diff --git a/packages/effect/test/schema/Schema.test.ts b/packages/effect/test/schema/Schema.test.ts index 0af33f5203..c2fc715d8c 100644 --- a/packages/effect/test/schema/Schema.test.ts +++ b/packages/effect/test/schema/Schema.test.ts @@ -1975,6 +1975,16 @@ Expected a value with a size of at most 2, got Map([["a",1],["b",NaN],["c",3]])` }) }) + it("OptionFromNullOr", async () => { + const schema = Schema.OptionFromNullOr(Schema.FiniteFromString) + await assertions.decoding.succeed(schema, null, { expected: Option.none() }) + await assertions.decoding.succeed(schema, "1", { expected: Option.some(1) }) + await assertions.decoding.fail(schema, "a", `Expected a finite number, got NaN`) + + await assertions.encoding.succeed(schema, Option.none(), { expected: null }) + await assertions.encoding.succeed(schema, Option.some(1), { expected: "1" }) + }) + describe("Defect", () => { const noPrototypeObject = Object.create(null) noPrototypeObject.message = "a" diff --git a/packages/platform-bun/src/BunHttpServer.ts b/packages/platform-bun/src/BunHttpServer.ts index 9c4dea176f..8be91ff911 100644 --- a/packages/platform-bun/src/BunHttpServer.ts +++ b/packages/platform-bun/src/BunHttpServer.ts @@ -330,7 +330,7 @@ class BunServerRequest extends Inspectable.Class implements ServerRequest.HttpSe get remoteAddress(): Option.Option { return this.remoteAddressOverride ? Option.some(this.remoteAddressOverride) - : Option.fromNullable(this.bunServer.requestIP(this.source)?.address) + : Option.fromUndefinedOr(this.bunServer.requestIP(this.source)?.address) } get headers(): Headers.Headers { this.headersOverride ??= Headers.fromInput(this.source.headers) diff --git a/packages/platform-node-shared/src/NodeFileSystem.ts b/packages/platform-node-shared/src/NodeFileSystem.ts index c257daa052..d6a2fa46d2 100644 --- a/packages/platform-node-shared/src/NodeFileSystem.ts +++ b/packages/platform-node-shared/src/NodeFileSystem.ts @@ -471,19 +471,19 @@ const makeFileInfo = (stat: NFS.Stats): FileSystem.File.Info => ({ stat.isSocket() ? "Socket" : "Unknown", - mtime: Option.fromNullable(stat.mtime), - atime: Option.fromNullable(stat.atime), - birthtime: Option.fromNullable(stat.birthtime), + mtime: Option.fromNullishOr(stat.mtime), // TODO: why Option.fromNullishOr? + atime: Option.fromNullishOr(stat.atime), + birthtime: Option.fromNullishOr(stat.birthtime), dev: stat.dev, - rdev: Option.fromNullable(stat.rdev), - ino: Option.fromNullable(stat.ino), + rdev: Option.fromNullishOr(stat.rdev), + ino: Option.fromNullishOr(stat.ino), mode: stat.mode, - nlink: Option.fromNullable(stat.nlink), - uid: Option.fromNullable(stat.uid), - gid: Option.fromNullable(stat.gid), + nlink: Option.fromNullishOr(stat.nlink), + uid: Option.fromNullishOr(stat.uid), + gid: Option.fromNullishOr(stat.gid), size: FileSystem.Size(stat.size), - blksize: Option.fromNullable(FileSystem.Size(stat.blksize)), - blocks: Option.fromNullable(stat.blocks) + blksize: Option.fromNullishOr(FileSystem.Size(stat.blksize)), + blocks: Option.fromNullishOr(stat.blocks) }) const stat = (() => { const nodeStat = effectify( diff --git a/packages/platform-node/src/NodeHttpIncomingMessage.ts b/packages/platform-node/src/NodeHttpIncomingMessage.ts index b859dc1700..6c8a5a5a22 100644 --- a/packages/platform-node/src/NodeHttpIncomingMessage.ts +++ b/packages/platform-node/src/NodeHttpIncomingMessage.ts @@ -43,7 +43,7 @@ export abstract class NodeHttpIncomingMessage extends Inspectable.Class } get remoteAddress() { - return Option.fromNullable(this.remoteAddressOverride ?? this.source.socket.remoteAddress) + return Option.fromUndefinedOr(this.remoteAddressOverride ?? this.source.socket.remoteAddress) } private textEffect: Effect.Effect | undefined