From a52950d6b07636fb97ebfe3d397a0c5262bce189 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Thu, 28 May 2026 19:28:32 +0200 Subject: [PATCH 01/29] docs: refine JSDoc usage guidance Clarify usage guidance for APIs with overlapping descriptions and improve wording around service references, type terms, and runtime entry points. --- .../openai-compat/src/OpenAiLanguageModel.ts | 4 ++-- packages/ai/openai/src/OpenAiLanguageModel.ts | 4 ++-- packages/effect/src/Array.ts | 6 +++--- packages/effect/src/BigInt.ts | 4 ++-- packages/effect/src/Clock.ts | 6 +++--- packages/effect/src/ConfigProvider.ts | 6 ++---- packages/effect/src/Crypto.ts | 8 ++++---- packages/effect/src/Effect.ts | 19 ++++++++----------- packages/effect/src/Equivalence.ts | 2 +- packages/effect/src/Function.ts | 9 ++++----- packages/effect/src/Layer.ts | 4 +--- packages/effect/src/Logger.ts | 4 ++-- packages/effect/src/Match.ts | 2 +- packages/effect/src/Number.ts | 4 ++-- packages/effect/src/Ref.ts | 4 ++-- packages/effect/src/References.ts | 8 ++++---- packages/effect/src/Scheduler.ts | 4 ++-- packages/effect/src/Schema.ts | 6 +++--- packages/effect/src/SchemaGetter.ts | 3 ++- packages/effect/src/SynchronizedRef.ts | 3 ++- packages/effect/src/TxSubscriptionRef.ts | 3 ++- .../effect/src/unstable/ai/EmbeddingModel.ts | 2 +- packages/effect/src/unstable/cli/Command.ts | 7 ++++--- packages/platform-bun/src/BunRuntime.ts | 5 ++--- packages/platform-node/src/NodeRuntime.ts | 6 +++--- 25 files changed, 64 insertions(+), 69 deletions(-) diff --git a/packages/ai/openai-compat/src/OpenAiLanguageModel.ts b/packages/ai/openai-compat/src/OpenAiLanguageModel.ts index 6d4790ea53..82fa543a2c 100644 --- a/packages/ai/openai-compat/src/OpenAiLanguageModel.ts +++ b/packages/ai/openai-compat/src/OpenAiLanguageModel.ts @@ -575,8 +575,8 @@ export const model = ( * * **When to use** * - * Use when an Effect needs to construct a `LanguageModel.Service` value backed - * by `OpenAiClient`. + * Use to construct an OpenAI-compatible chat-completions language model service + * backed by `OpenAiClient`. * * **Details** * diff --git a/packages/ai/openai/src/OpenAiLanguageModel.ts b/packages/ai/openai/src/OpenAiLanguageModel.ts index ae460d5afb..45f903ee34 100644 --- a/packages/ai/openai/src/OpenAiLanguageModel.ts +++ b/packages/ai/openai/src/OpenAiLanguageModel.ts @@ -591,8 +591,8 @@ export const model = ( * * **When to use** * - * Use when an Effect needs to construct a `LanguageModel.Service` value backed - * by `OpenAiClient`. + * Use to construct an OpenAI Responses API language model service backed by + * `OpenAiClient`. * * **Details** * diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 00e6b13d66..5313d23d27 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -249,7 +249,7 @@ export const allocate = (n: number): Array => new Arra * * Use when you need an array whose values depend on the index. * - `n` is normalized to an integer >= 1 — always returns at least one element. - * - Dual: `Array.makeBy(5, f)` or `pipe(5, Array.makeBy(f))`. + * - Supports both data-first and data-last usage. * * **Example** (Generating values from indices) * @@ -312,7 +312,7 @@ export const range = (start: number, end: number): NonEmptyArray => * * Use when you need multiple copies of the same value. * - `n` is normalized to an integer >= 1 — always returns at least one element. - * - Dual: `Array.replicate("a", 3)` or `pipe("a", Array.replicate(3))`. + * - Supports both data-first and data-last usage. * * **Example** (Repeating a value) * @@ -4691,7 +4691,7 @@ export const cartesian: { * * **When to use** * - * Use when begin a pipeline with `Do`, then use {@link bind} to introduce array variables and {@link let_ let} for plain values. + * Use when beginning a do-notation pipeline, then use {@link bind} to introduce array variables and {@link let_ let} for plain values. * - Each `bind` produces the cartesian product of all bound variables (like nested loops). * - Use `filter` and `map` in the pipeline to add conditions and transformations. * diff --git a/packages/effect/src/BigInt.ts b/packages/effect/src/BigInt.ts index e3dea271b6..9f5ad1674b 100644 --- a/packages/effect/src/BigInt.ts +++ b/packages/effect/src/BigInt.ts @@ -254,8 +254,8 @@ export const divide: { * * **When to use** * - * Use when the divisor is known to be non-zero and division by zero should be a - * thrown exception. + * Use to divide `bigint` values when the divisor is known to be non-zero and + * division by zero should be a thrown exception. * * **Details** * diff --git a/packages/effect/src/Clock.ts b/packages/effect/src/Clock.ts index 5916c2a4f7..0ce952eef1 100644 --- a/packages/effect/src/Clock.ts +++ b/packages/effect/src/Clock.ts @@ -135,12 +135,12 @@ export interface Clock { } /** - * Context reference for the current Clock service in the environment. + * Context reference for the active time service in the environment. * * **When to use** * - * Use when you need to access or provide the full Clock service rather than a - * single timestamp accessor. + * Use when you need to access or provide the full time service, including sleep + * operations, rather than a single timestamp accessor. * * **Example** (Accessing the Clock service) * diff --git a/packages/effect/src/ConfigProvider.ts b/packages/effect/src/ConfigProvider.ts index 81ef100924..240f53f944 100644 --- a/packages/effect/src/ConfigProvider.ts +++ b/packages/effect/src/ConfigProvider.ts @@ -367,10 +367,8 @@ export interface ConfigProvider extends Pipeable { * * **When to use** * - * Use to override the provider for an entire program via - * `Effect.provideService(ConfigProvider.ConfigProvider, myProvider)`, or to - * retrieve the current provider inside an Effect with - * `yield* ConfigProvider.ConfigProvider`. + * Use to override the active raw configuration provider for an entire program, + * or to retrieve the current provider inside an Effect. * * **Example** (Providing a custom provider) * diff --git a/packages/effect/src/Crypto.ts b/packages/effect/src/Crypto.ts index 420f42bc27..81f3606d05 100644 --- a/packages/effect/src/Crypto.ts +++ b/packages/effect/src/Crypto.ts @@ -202,13 +202,13 @@ export interface Crypto { * * **When to use** * - * Use when you need to provide or retrieve the full platform Crypto service - * from an effect's context. + * Use when you need to provide or retrieve the full platform cryptography + * service from an effect's context. * * **Details** * - * Providing this service supplies the cryptographic operations described by the - * `Crypto` interface. + * Providing this service supplies platform-agnostic cryptographic operations + * such as hashing, UUID generation, and secure random values. * * @see {@link make} for constructing a Crypto service from primitive operations * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 96459f98a9..e8e33cc8d6 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1419,14 +1419,13 @@ export const bind: { * * **When to use** * - * Use when `gen` allows you to write code that looks and behaves like synchronous - * code, but it can handle asynchronous tasks, errors, and complex control flow - * (like loops and conditions). It helps make asynchronous code more readable - * and easier to manage. + * Use when you want to write effectful code that looks and behaves like + * synchronous code, while still handling asynchronous tasks, errors, and complex + * control flow such as loops and conditions. * - * The generator functions work similarly to `async/await` but with more - * explicit control over the execution of effects. You can `yield*` values from - * effects and return the final result at the end. + * Generator functions work similarly to `async/await` but keep errors, + * requirements, and interruption in the Effect type. You can `yield*` values + * from effects and return the final result at the end. * * **Example** (Sequencing effects with generators) * @@ -1676,10 +1675,8 @@ export { * * **When to use** * - * Use when in situations where you need to perform synchronous operations that might - * fail, such as parsing JSON, you can use the `try` constructor. This - * constructor is designed to handle operations that could throw exceptions by - * capturing those exceptions and transforming them into manageable errors. + * Use when you need to perform synchronous operations that might throw, such + * as parsing JSON, and convert thrown exceptions into typed Effect failures. * * **Details** * diff --git a/packages/effect/src/Equivalence.ts b/packages/effect/src/Equivalence.ts index 4f2c42c644..f0afb6b984 100644 --- a/packages/effect/src/Equivalence.ts +++ b/packages/effect/src/Equivalence.ts @@ -888,7 +888,7 @@ export function makeReducer() { * * **When to use** * - * Use when comparing `Date` values by their millisecond timestamp. + * Use when comparing JavaScript date objects by their millisecond timestamp. * * **Details** * diff --git a/packages/effect/src/Function.ts b/packages/effect/src/Function.ts index e55f8699da..742530bfa2 100644 --- a/packages/effect/src/Function.ts +++ b/packages/effect/src/Function.ts @@ -613,14 +613,13 @@ export const untupled = , B>(f: (a: A) => B): ( * * **When to use** * - * Use when you use `pipe` with data-last functions to build readable transformation - * pipelines and to write method-style chains as ordinary function calls. + * Use when composing data-last functions into readable transformation pipelines, + * or when replacing method-style chains with ordinary function calls. * * **Details** * - * `pipe` takes an initial value, passes it to the first function, then passes - * each result to the next function in order. The final function result is - * returned. + * Takes an initial value, passes it to the first function, then passes each + * result to the next function in order. The final function result is returned. * * **Gotchas** * diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index bbdd7adadb..c4f3083c59 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -868,9 +868,7 @@ export const succeedContext = (context: Context.Context): Layer => * * **When to use** * - * Use when you use `Layer.empty` as the no-op branch when conditionally composing layers. - * If you need to run an effect during layer construction while still providing - * no services, use `effectDiscard`. + * Use as the no-op branch when conditionally composing layers. * * **Example** (Disabling optional lifecycle work) * diff --git a/packages/effect/src/Logger.ts b/packages/effect/src/Logger.ts index de07962a7d..d981b94065 100644 --- a/packages/effect/src/Logger.ts +++ b/packages/effect/src/Logger.ts @@ -245,8 +245,8 @@ export const CurrentLoggers: Context.Reference> * * **When to use** * - * Use to keep stdout reserved for protocol messages or data output while still - * allowing Effect runtime logs to be emitted. + * Use to route built-in logger output to stderr while keeping stdout reserved + * for protocol messages or data output. * * **Details** * diff --git a/packages/effect/src/Match.ts b/packages/effect/src/Match.ts index d522391c9f..32bf30fa6d 100644 --- a/packages/effect/src/Match.ts +++ b/packages/effect/src/Match.ts @@ -1528,7 +1528,7 @@ export { * * **When to use** * - * Use when a match branch should handle only the literal `null` value. + * Use to handle only the `null` literal in a match branch. * * **Details** * diff --git a/packages/effect/src/Number.ts b/packages/effect/src/Number.ts index 6cf4701fba..21364b4d18 100644 --- a/packages/effect/src/Number.ts +++ b/packages/effect/src/Number.ts @@ -231,8 +231,8 @@ export const divide: { * * **When to use** * - * Use when the divisor is known to be non-zero and division by zero should be a - * thrown exception. + * Use to divide `number` values when the divisor is known to be non-zero and + * division by zero should be a thrown exception. * * **Example** (Dividing numbers unsafely) * diff --git a/packages/effect/src/Ref.ts b/packages/effect/src/Ref.ts index 7c2207cfb3..2529a9cb73 100644 --- a/packages/effect/src/Ref.ts +++ b/packages/effect/src/Ref.ts @@ -296,7 +296,7 @@ export const set = dual< * * **When to use** * - * Use to replace the value while returning the previous value. + * Use to replace a plain `Ref` value while returning the previous value. * * **Example** (Replacing a value atomically) * @@ -543,7 +543,7 @@ export const modify = dual< * * **When to use** * - * Use to compute a return value while optionally updating the stored value. + * Use to compute a return value while optionally updating a plain `Ref`. * * **Details** * diff --git a/packages/effect/src/References.ts b/packages/effect/src/References.ts index ad47523829..c8aa36aee4 100644 --- a/packages/effect/src/References.ts +++ b/packages/effect/src/References.ts @@ -108,8 +108,8 @@ export { * * **When to use** * - * Use to tune scheduler fairness for CPU-bound fibers by changing the - * operation budget that triggers a scheduler yield. + * Use to configure the runtime reference for the fiber operation budget that + * triggers a scheduler yield. * * **Details** * @@ -780,8 +780,8 @@ export const CurrentLoggers: Context.Reference> * * **When to use** * - * Use to keep stdout reserved for protocol messages or data output while still - * allowing Effect runtime logs to be emitted. + * Use to configure the runtime reference that controls whether built-in console + * loggers write to stderr. * * **Details** * diff --git a/packages/effect/src/Scheduler.ts b/packages/effect/src/Scheduler.ts index 7f43ac4a75..edfebfe909 100644 --- a/packages/effect/src/Scheduler.ts +++ b/packages/effect/src/Scheduler.ts @@ -250,8 +250,8 @@ class MixedSchedulerDispatcher implements SchedulerDispatcher { * * **When to use** * - * Use to tune scheduler fairness for CPU-bound fibers by changing the operation - * budget that triggers a scheduler yield. + * Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler + * operation budget that triggers a yield. * * **Details** * diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 97e2d23ff5..f741c137c2 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -1186,7 +1186,7 @@ export const is = Parser.is * **When to use** * * Use to validate unknown input at runtime while narrowing the value with a - * TypeScript `asserts` predicate. + * TypeScript assertion signature. * * **Details** * @@ -9717,8 +9717,8 @@ const DateString = String.annotate({ expected: "a string in ISO 8601 format that * * **When to use** * - * Use to validate in-memory values that must already be JavaScript `Date` - * instances. + * Use to validate in-memory values that must already be JavaScript date + * objects. * * **Details** * diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index 25a06382e9..209203cff6 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -832,7 +832,8 @@ export function BigInt(): Getter( * * **When to use** * - * Use when you use `run` at an application entry point when arguments should come from - * `Stdio`; use `runWith` when you need an explicit argument array, such as in - * tests. + * Use when command-line arguments should come from `Stdio` at the application + * entry point. * * **Example** (Running commands with standard input) * @@ -1446,6 +1445,8 @@ const showHelp = ( * }) * ``` * + * @see {@link runWith} for running a command with an explicit argument array + * * @category command execution * @since 4.0.0 */ diff --git a/packages/platform-bun/src/BunRuntime.ts b/packages/platform-bun/src/BunRuntime.ts index 35c8937517..c192dcf00c 100644 --- a/packages/platform-bun/src/BunRuntime.ts +++ b/packages/platform-bun/src/BunRuntime.ts @@ -39,9 +39,8 @@ import type { Teardown } from "effect/Runtime" * * **When to use** * - * Use to run an Effect as your application's main program, - * especially when you need structured error handling, log management, - * interrupt support, or advanced teardown capabilities. + * Use to run a Bun application's main Effect with structured error handling, + * log management, interrupt support, or advanced teardown capabilities. * * **Details** * diff --git a/packages/platform-node/src/NodeRuntime.ts b/packages/platform-node/src/NodeRuntime.ts index c54234992b..bb8d7175ac 100644 --- a/packages/platform-node/src/NodeRuntime.ts +++ b/packages/platform-node/src/NodeRuntime.ts @@ -38,9 +38,9 @@ import type * as Runtime from "effect/Runtime" * * **When to use** * - * Use to run an Effect as your application's main program, especially - * when you need structured error handling, log management, interrupt support, - * or advanced teardown capabilities. + * Use to run a Node.js application's main Effect with structured error + * handling, log management, interrupt support, or advanced teardown + * capabilities. * * **Details** * From 595857e6cac13e01db1ed87655765a8378f20cb3 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Thu, 28 May 2026 21:08:57 +0200 Subject: [PATCH 02/29] wip --- packages/effect/src/Array.ts | 4 +- packages/effect/src/Cause.ts | 24 ++++---- packages/effect/src/Config.ts | 4 +- packages/effect/src/ConfigProvider.ts | 29 ++++------ packages/effect/src/Context.ts | 40 +++++-------- packages/effect/src/Data.ts | 12 ++-- packages/effect/src/Effect.ts | 57 +++++++------------ packages/effect/src/Equal.ts | 8 +-- packages/effect/src/Layer.ts | 51 ++++++----------- packages/effect/src/Logger.ts | 12 ++-- packages/effect/src/Metric.ts | 6 +- packages/effect/src/Option.ts | 4 +- packages/effect/src/Order.ts | 50 ++++++++-------- packages/effect/src/Schedule.ts | 34 ++++------- packages/effect/src/SchemaTransformation.ts | 16 +++--- packages/effect/src/Struct.ts | 4 +- packages/effect/src/Tuple.ts | 6 +- packages/effect/src/unstable/ai/AiError.ts | 3 +- packages/effect/src/unstable/ai/Chat.ts | 3 +- .../effect/src/unstable/ai/IdGenerator.ts | 5 +- packages/effect/src/unstable/ai/Prompt.ts | 4 +- .../src/unstable/ai/ResponseIdTracker.ts | 2 +- packages/effect/src/unstable/ai/Tool.ts | 4 +- packages/effect/src/unstable/cli/Command.ts | 8 +-- packages/effect/src/unstable/cli/Flag.ts | 8 +-- packages/effect/src/unstable/cli/Param.ts | 4 +- .../src/unstable/cluster/ClusterCron.ts | 3 +- .../src/unstable/cluster/RunnerServer.ts | 4 +- .../observability/PrometheusMetrics.ts | 6 +- 29 files changed, 175 insertions(+), 240 deletions(-) diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 5313d23d27..ab9cac4f72 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -138,8 +138,8 @@ export interface ReadonlyArrayTypeLambda extends TypeLambda { * * **When to use** * - * Use when you use this type when you need to ensure non-emptiness at the type level while - * preventing mutation. Many Array module functions accept or return this type. + * Use when non-emptiness must be tracked at the type level while preventing mutation. + * Many Array module functions accept or return this type. * * **Example** (Typing a non-empty array) * diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index 2bcac7073a..afb2654683 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -855,7 +855,7 @@ export const hasFails: (self: Cause) => boolean = effect.hasFails * * **When to use** * - * Use when you use {@link findError} if you only need the unwrapped error value `E`. + * Use when you need the full `Fail` reason, including annotations. * * **Example** (extracting the first Fail reason) * @@ -884,8 +884,7 @@ export const findFail: (self: Cause) => Result.Result, Cause(self: Cause) => Result.Result> = * * **When to use** * - * Use when this is the `Option`-returning variant of {@link findError} for code that - * does not need the original cause returned in a failed `Result`. + * Use when code needs the first typed error as an `Option` and does not need the original + * cause returned in a failed `Result`. * * **Example** (extracting an error as Option) * @@ -1072,9 +1071,8 @@ export const findInterrupt: (self: Cause) => Result.Result(self: Cause) => ReadonlySet = effect.c * * **When to use** * - * Use when you use {@link interruptors} if you always want a `Set` without `Result` - * wrapping. + * Use when the absence of interrupt reasons should be represented as a failed `Result` + * containing the original cause. * * **Gotchas** * @@ -1432,8 +1430,7 @@ export declare namespace Done { * * **When to use** * - * Use when you need the completion signal value itself. Use {@link done} - * when you need an `Effect` that fails with the signal. + * Use when you need the completion signal value itself. * * @see {@link done} — create a failing `Effect` with `Done` * @@ -1448,8 +1445,7 @@ export const Done: (value?: A) => Done = core.Done * * **When to use** * - * Use when you use this in effect workflows that model stream or queue completion through - * the error channel. + * Use when effect workflows model stream or queue completion through the error channel. * * **Example** (failing with Done) * diff --git a/packages/effect/src/Config.ts b/packages/effect/src/Config.ts index 064d2edba5..d0c1df2ebe 100644 --- a/packages/effect/src/Config.ts +++ b/packages/effect/src/Config.ts @@ -238,8 +238,8 @@ export function make( * * **When to use** * - * Use when post-processing a config value (e.g. trimming, uppercasing, wrapping). - * - The transformation cannot fail. Use {@link mapOrFail} if it can. + * Use when post-processing a config value (e.g. trimming, uppercasing, wrapping) + * with a transformation that cannot fail. * * **Details** * diff --git a/packages/effect/src/ConfigProvider.ts b/packages/effect/src/ConfigProvider.ts index 240f53f944..c4ae486c5a 100644 --- a/packages/effect/src/ConfigProvider.ts +++ b/packages/effect/src/ConfigProvider.ts @@ -239,9 +239,9 @@ export function makeArray(length: number, value?: string): Node { * * **When to use** * - * Use when you use this from a custom provider's `get` callback when the underlying store - * is unreachable or produces an I/O error, or match on it in error channels - * when consuming provider output directly. + * Use when writing a custom provider's `get` callback for an underlying store that is + * unreachable or produces an I/O error, or when matching on error channels while consuming + * provider output directly. * * **Gotchas** * @@ -515,9 +515,8 @@ export const orElse: { * * **When to use** * - * Use when you use this for renaming or re-casing path segments, or for adding suffixes and - * other per-segment transformations. See {@link constantCase} for a common - * specialization. + * Use when path segments need renaming, re-casing, suffixes, or other per-segment + * transformations. See {@link constantCase} for a common specialization. * * **Details** * @@ -737,9 +736,8 @@ export const layerAdd = ( * * **When to use** * - * Use when you use this in unit or integration tests where you want deterministic config - * without touching the environment, or when embedding config directly in code - * or reading a JSON file. + * Use when unit or integration tests need deterministic config without touching the + * environment, or when config is embedded directly in code or read from a JSON file. * * **Details** * @@ -944,9 +942,8 @@ function trieNodeAt(root: EnvTrieNode, path: Path): EnvTrieNode | undefined { * * **When to use** * - * Use when you already have the `.env` contents as a string, such as - * contents fetched from a remote store or embedded in a test. Use - * {@link fromDotEnv} instead if you want to read a `.env` file from disk. + * Use when you already have the `.env` contents as a string, such as contents + * fetched from a remote store or embedded in a test. * * **Details** * @@ -1086,9 +1083,7 @@ function searchLast(str: string, rgx: RegExp): number { * * **When to use** * - * Use to load environment config from a `.env` file at application - * startup. Use {@link fromDotEnvContents} if you already have the file - * contents as a string. + * Use to load environment config from a `.env` file at application startup. * * **Details** * @@ -1132,8 +1127,8 @@ export const fromDotEnv: (options?: { * * **When to use** * - * Use when you use this for Kubernetes ConfigMap or Secret volume mounts, where each key is - * a file under a mount path, or for any file-per-key configuration layout. + * Use when Kubernetes ConfigMap or Secret volume mounts expose each key as a file under a + * mount path, or for any file-per-key configuration layout. * * **Details** * diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index d49a9a62c8..47bbf0fdfa 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -193,8 +193,7 @@ export declare namespace ServiceClass { * * **When to use** * - * Use when a dependency must be provided by the surrounding context. Use - * `Reference` when a dependency should have a default value. + * Use when a dependency must be provided by the surrounding context. * * **Details** * @@ -686,8 +685,7 @@ export const make = ( * * **When to use** * - * Use when you always have a service value to store. Use `addOrOmit` - * when the value is optional and a missing value should remove the service. + * Use when you always have a service value to store. * * **Details** * @@ -744,7 +742,6 @@ export const add: { * **When to use** * * Use when service presence is already represented as an `Option`. - * Use `add` when you always want to store a service value. * * **Details** * @@ -801,8 +798,7 @@ export const addOrOmit: { * * **When to use** * - * Use when you want a fallback value for a missing regular - * service. Use `getOption` when you need to distinguish presence from absence. + * Use when you want a fallback value for a missing regular service. * * **Details** * @@ -860,8 +856,7 @@ export const getOrElse: { * * **When to use** * - * Use when you need raw map-style lookup. Use `getOption` when you want the - * usual `Context.Reference` default-value behavior. + * Use when you need raw map-style lookup. * * **Gotchas** * @@ -887,9 +882,7 @@ export const getOrUndefined: { * * **When to use** * - * Use when the context type cannot prove that the service is present. Use - * `get` when the service requirement is tracked in the context type, or - * `getOption` when absence is expected. + * Use when the context type cannot prove that the service is present. * * **Details** * @@ -937,8 +930,7 @@ export const getUnsafe: { * * **When to use** * - * Use when the context type proves that the service is present. Use - * `getOption` or `getOrElse` when a service may be absent. + * Use when the context type proves that the service is present. * * **Example** (Getting a service from a context) * @@ -1051,8 +1043,7 @@ const serviceNotFoundError = (service: Key) => { * * **When to use** * - * Use when service absence is expected and should be represented - * as data. Use `getOrElse` when you want to provide a fallback value directly. + * Use when service absence is expected and should be represented as data. * * **Details** * @@ -1098,8 +1089,7 @@ export const getOption: { * * **When to use** * - * Use when combining two contexts. Use `mergeAll` when combining a - * variadic list of contexts. + * Use when combining two contexts. * * **Details** * @@ -1145,8 +1135,7 @@ export const merge: { * * **When to use** * - * Use when the number of contexts is variadic. Use `merge` when - * combining exactly two contexts. + * Use when combining a variadic list of contexts. * * **Details** * @@ -1200,8 +1189,7 @@ export const mergeAll = >( * * **When to use** * - * Use when you want to keep a small allowlist of services. Use `omit` - * when it is easier to name the services to remove. + * Use when you want to keep a small allowlist of services. * * **Example** (Picking services from a context) * @@ -1248,8 +1236,7 @@ export const pick = >>( * * **When to use** * - * Use when you want to remove a small denylist of services. Use `pick` - * when it is easier to name the services to keep. + * Use when you want to remove a small denylist of services. * * **Example** (Omitting services from a context) * @@ -1338,9 +1325,8 @@ const withMapUnsafe = (self: Context, f: (map: Map = {}>( * * **When to use** * - * Use when you need a single-variant tagged type or an ad-hoc discriminator. For multi-variant unions, prefer {@link TaggedEnum} with {@link taggedEnum}; for yieldable errors, use {@link TaggedError}. + * Use when you need a single-variant tagged type or an ad-hoc discriminator. * * **Details** * @@ -174,7 +174,7 @@ export const TaggedClass = ( * * **When to use** * - * Use when you have two or more variants that share a common `_tag` discriminator. For generic tagged enums, see {@link TaggedEnum.WithGenerics}. + * Use when you have two or more variants that share a common `_tag` discriminator. * * **Details** * @@ -254,7 +254,7 @@ export declare namespace TaggedEnum { * * **When to use** * - * Use when variant payloads need to be parameterized, such as `Result`. Pass the interface, not the type alias, to {@link taggedEnum} to get generic-aware constructors and matchers. + * Use when variant payloads need to be parameterized, such as `Result`. * * **Details** * @@ -586,7 +586,7 @@ export declare namespace TaggedEnum { * * **When to use** * - * Use when you have a `TaggedEnum` type and need constructors and matchers for its values. For generic enums, pass a {@link TaggedEnum.WithGenerics} interface. + * Use when you have a `TaggedEnum` type and need constructors and matchers for its values. * * **Details** * @@ -752,7 +752,7 @@ function taggedMatch< * **When to use** * * Use when defining yieldable errors that do **not** need tag-based - * discrimination. If you need tag-based recovery, use {@link TaggedError}. + * discrimination. * * **Details** * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index e8e33cc8d6..ea068a42b9 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1015,8 +1015,8 @@ export const tryPromise: ( * * **When to use** * - * Use when you use this function when you need an effect that completes successfully with a - * specific value without any errors or external dependencies. + * Use when an effect should complete successfully with a specific value without any errors + * or external dependencies. * * **Example** (Creating a successful effect) * @@ -2157,9 +2157,8 @@ export const tap: { * * **When to use** * - * Use when you want to handle typed failures as data while preserving - * the original error value. Use `option` when you only care whether the effect - * succeeded, and `exit` when you need the full failure cause. + * Use when you want to handle typed failures as data while preserving the original + * error value. * * **Details** * @@ -2214,8 +2213,6 @@ export const result: (self: Effect) => Effect(self: Effect) => Effect, never * * **When to use** * - * Use when you need to inspect the full outcome, including typed - * failures, defects, and interruptions. Use `result` or `option` when you only - * need to handle typed failures. + * Use when you need to inspect the full outcome, including typed failures, defects, + * and interruptions. * * **Details** * @@ -3207,8 +3203,7 @@ export const catchCause: { * * **When to use** * - * Use when you use this sparingly, usually at integration boundaries where defects must be - * reported or translated for an external system. + * Use when defects must be reported or translated at integration boundaries. * * **Details** * @@ -4417,9 +4412,7 @@ export const firstSuccessOf: >( * * **When to use** * - * Use when exceeding the time limit should be represented as a typed - * failure. Use `timeoutOption` when a timeout should become `Option.none`, and - * `timeoutOrElse` when you want to run a fallback effect. + * Use when exceeding the time limit should be represented as a typed failure. * * **Details** * @@ -4485,9 +4478,7 @@ export const timeout: { * * **When to use** * - * Use when a timeout should be handled as absence. Use - * `timeout` when a timeout should fail the effect, and `timeoutOrElse` when - * you want to run a fallback effect. + * Use when a timeout should be handled as absence. * * **Details** * @@ -4545,9 +4536,7 @@ export const timeoutOption: { * * **When to use** * - * Use when a timeout should switch to a fallback effect. Use - * `timeout` when a timeout should fail the effect, and `timeoutOption` when a - * timeout should become `Option.none`. + * Use when a timeout should switch to a fallback effect. * * **Details** * @@ -5241,8 +5230,8 @@ export const when: { * * **When to use** * - * Use when this is useful for structuring your code to respond differently to success or - * failure without triggering side effects. + * Use when code should respond differently to success or failure without triggering side + * effects. * * **Details** * @@ -5356,9 +5345,8 @@ export const matchEager: { * * **When to use** * - * Use when this is useful for differentiating between different types of errors, such as - * regular failures, defects, or interruptions. You can provide specific - * handling logic for each failure type based on the cause. + * Use when failure handling depends on the full cause, such as typed failures, defects, or + * interruptions. * * **Details** * @@ -5406,9 +5394,9 @@ export const matchCause: { * * **When to use** * - * Use when this is useful when you have effects that are likely to be already resolved - * and you want to avoid the overhead of the effect pipeline. For pending effects, - * it automatically falls back to the regular `matchCause` behavior. + * Use when effects are likely to be already resolved and matching the cause should avoid + * the overhead of the regular effect pipeline. For pending effects, it automatically falls + * back to the regular `matchCause` behavior. * * **Details** * @@ -6943,10 +6931,9 @@ export const onExitFilter: { * * **When to use** * - * Use when you use this function when you have an expensive or time-consuming operation that - * you want to avoid repeating. The first evaluation will compute the result, - * and all following evaluations will immediately return the cached value, - * improving performance and reducing unnecessary work. + * Use when an expensive or time-consuming operation should be evaluated once and reused by + * later callers. The first evaluation computes the result, and later evaluations return the + * cached value. * * **Details** * @@ -7008,8 +6995,8 @@ export const cached: (self: Effect) => Effect> * * **When to use** * - * Use when you use this function when you have an effect that involves costly operations or - * computations, and you want to avoid repeating them within a short time frame. + * Use when an effect with costly operations or computations should be reused for a bounded + * duration before being recomputed. * * It's ideal for scenarios where the result of an effect doesn't change * frequently and can be reused for a specified duration. diff --git a/packages/effect/src/Equal.ts b/packages/effect/src/Equal.ts index 25290f2ca2..540af91af9 100644 --- a/packages/effect/src/Equal.ts +++ b/packages/effect/src/Equal.ts @@ -118,7 +118,7 @@ export const symbol = "~effect/interfaces/Equal" * * **When to use** * - * Use when when you need value-based equality for a class (e.g. domain IDs, + * Use when you need value-based equality for a class (e.g. domain IDs, * coordinates, money values). * - When your type will be stored in `HashMap` or `HashSet`. * - When the default structural comparison is too broad or too narrow for @@ -506,7 +506,7 @@ export const isEqual = (u: unknown): u is Equal => hasProperty(u, symbol) * * **When to use** * - * Use when when an API (e.g. `Array.dedupeWith`, `Equivalence.mapInput`) requires an + * Use when an API (e.g. `Array.dedupeWith`, `Equivalence.mapInput`) requires an * `Equivalence` and you want to reuse `Equal.equals`. * * **Details** @@ -536,7 +536,7 @@ export const asEquivalence: () => Equivalence = () => equals * * **When to use** * - * Use when when you have a plain object or array that should be compared by identity + * Use when you have a plain object or array that should be compared by identity * (reference), not by contents. * - When you want to preserve the original object unchanged and get a new * reference-equal handle. @@ -580,7 +580,7 @@ export const byReference = (obj: T): T => byReferenceUnsafe(ne * * **When to use** * - * Use when when you want reference equality semantics and can accept that the + * Use when you want reference equality semantics and can accept that the * original object is **permanently** modified. * - When proxy overhead is unacceptable (hot paths, large collections). * diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index c4f3083c59..c34cae181b 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -782,9 +782,8 @@ export const buildWithScope: { * * **When to use** * - * Use when the service implementation is already constructed and does - * not need effectful acquisition. Use `sync` when the service should be created - * lazily during layer construction. + * Use when the service implementation is already constructed and does not need + * effectful acquisition. * * **Example** (Creating a layer from a service implementation) * @@ -821,9 +820,7 @@ export const succeed: { * * **When to use** * - * Use when you already have a `Context` or need to provide - * multiple services at once. Use `succeed` when you only need to provide one - * service value. + * Use when you already have a `Context` or need to provide multiple services at once. * * **Details** * @@ -894,9 +891,8 @@ export const empty: Layer = succeedContext(Context.empty()) * * **When to use** * - * Use when the service can be created synchronously but should be - * deferred until the layer is built. Use `succeed` when the service value is - * already available. + * Use when the service can be created synchronously but should be deferred until the + * layer is built. * * **Details** * @@ -937,9 +933,8 @@ export const sync: { * * **When to use** * - * Use when multiple services can be created synchronously and - * should be deferred until the layer is built. Use `sync` when you only need to - * provide one service. + * Use when multiple services can be created synchronously and should be deferred until + * the layer is built. * * **Details** * @@ -976,10 +971,8 @@ export const syncContext = (evaluate: LazyArg>): Layer * * **When to use** * - * Use when constructing the service requires effects, dependencies, or - * scoped resource acquisition. Use `effectContext` when the effect produces - * multiple services in a `Context`, and `effectDiscard` when construction work - * should provide no services. + * Use when constructing the service requires effects, dependencies, or scoped resource + * acquisition. * * **Details** * @@ -1035,8 +1028,7 @@ const effectImpl = ( * * **When to use** * - * Use when effectful construction needs to provide multiple - * services at once. Use `effect` when the effect produces one service value. + * Use when effectful construction needs to provide multiple services at once. * * **Details** * @@ -1076,8 +1068,8 @@ export const effectContext = ( * * **When to use** * - * Use when this is useful when you want to run an Effect for its side effects during - * layer construction, but don't need to provide any services. + * Use when layer construction should run an Effect for its side effects while providing no + * services. * * **Example** (Running an effect during layer construction) * @@ -1243,8 +1235,7 @@ export const mergeAll = , ...Array = effect.LogToStderr * * **When to use** * - * Use when this allows you to modify, enhance, or completely change the output format - * of an existing logger without recreating the entire logging logic. + * Use when an existing logger's output should be transformed without recreating the + * logging logic. * * **Example** (Transforming logger output) * @@ -316,8 +316,8 @@ export const map = dual< * * **When to use** * - * Use when this is useful for taking any logger that produces string or object output - * and routing it to the console for development or debugging purposes. + * Use when a logger's string or object output should be routed to `console.log` for + * development or debugging. * * **Example** (Writing logger output with console.log) * @@ -353,8 +353,8 @@ export const withConsoleLog = ( * * **When to use** * - * Use when this is particularly useful for error logging where you want to ensure - * log messages appear in the error stream (stderr) rather than standard output. + * Use when logger output should be routed to `console.error`, such as error logs that + * should appear on stderr instead of stdout. * * **Example** (Writing logger output with console.error) * diff --git a/packages/effect/src/Metric.ts b/packages/effect/src/Metric.ts index 39a69dbaaf..77999c2b8d 100644 --- a/packages/effect/src/Metric.ts +++ b/packages/effect/src/Metric.ts @@ -3999,9 +3999,9 @@ export const enableRuntimeMetrics: (self: Effect) => Effect( * * **When to use** * - * Use when when `null` is a meaningful value but `undefined` means absent + * Use when `null` is a meaningful value but `undefined` means absent * * **Details** * @@ -924,7 +924,7 @@ export const fromUndefinedOr = ( * * **When to use** * - * Use when when `undefined` is a meaningful value but `null` means absent + * Use when `undefined` is a meaningful value but `null` means absent * * **Details** * diff --git a/packages/effect/src/Order.ts b/packages/effect/src/Order.ts index 05f9a018e2..9116e29469 100644 --- a/packages/effect/src/Order.ts +++ b/packages/effect/src/Order.ts @@ -88,7 +88,7 @@ import * as Reducer from "./Reducer.ts" * * **When to use** * - * Use when when you need to define how values of a type should be compared + * Use when you need to define how values of a type should be compared * - When implementing sorting, searching, or ordered data structures * - When composing multiple comparison criteria * @@ -129,7 +129,7 @@ export interface Order { * * **When to use** * - * Use when when working with type-level operations that require higher-kinded types + * Use when working with type-level operations that require higher-kinded types * - When implementing generic type classes that work with orders * * **Details** @@ -149,7 +149,7 @@ export interface OrderTypeLambda extends TypeLambda { * * **When to use** * - * Use when when creating a custom order for a type that doesn't have a built-in order + * Use when creating a custom order for a type that doesn't have a built-in order * - When you need fine-grained control over comparison logic * - When implementing orders for complex types * @@ -190,7 +190,7 @@ export function make( * * **When to use** * - * Use when when comparing strings alphabetically + * Use when comparing strings alphabetically * - When sorting string collections * - As a base for creating orders on types containing strings * @@ -222,7 +222,7 @@ export const String: Order = make((self, that) => self < that ? -1 : 1) * * **When to use** * - * Use when when comparing numbers for sorting or searching + * Use when comparing numbers for sorting or searching * - As a base for creating orders on types containing numbers * - When implementing numeric comparisons in data structures * @@ -263,7 +263,7 @@ export const Number: Order = make((self, that) => { * * **When to use** * - * Use when when comparing booleans for sorting or searching + * Use when comparing booleans for sorting or searching * - As a base for creating orders on types containing booleans * - When implementing boolean-based comparisons * @@ -293,7 +293,7 @@ export const Boolean: Order = make((self, that) => self < that ? -1 : 1 * * **When to use** * - * Use when when comparing bigint values for sorting or searching + * Use when comparing bigint values for sorting or searching * - As a base for creating orders on types containing bigints * - When working with large integers that exceed number precision * @@ -324,7 +324,7 @@ export const BigInt: Order = make((self, that) => self < that ? -1 : 1) * * **When to use** * - * Use when when you need descending order instead of ascending + * Use when you need descending order instead of ascending * - When reversing an existing order without modifying the original * - When creating orders that compare in the opposite direction * @@ -360,7 +360,7 @@ export function flip(O: Order): Order { * * **When to use** * - * Use when when you need multi-criteria comparison (e.g., sort by age, then by name) + * Use when you need multi-criteria comparison (e.g., sort by age, then by name) * - When creating composite orders from simpler orders * - When implementing lexicographic ordering * @@ -415,7 +415,7 @@ export const combine: { * * **When to use** * - * Use when when you need an order that doesn't distinguish between values + * Use when you need an order that doesn't distinguish between values * - As a default or fallback order when no meaningful comparison exists * - When implementing optional ordering where equality is sufficient * @@ -450,7 +450,7 @@ export function alwaysEqual(): Order { * * **When to use** * - * Use when when you have a variable number of orders to combine + * Use when you have a variable number of orders to combine * - When combining orders from a collection or array * - When implementing dynamic multi-criteria sorting * @@ -507,7 +507,7 @@ export function combineAll(collection: Iterable>): Order { * * **When to use** * - * Use when when you have an order for a property type and want to compare objects by that property + * Use when you have an order for a property type and want to compare objects by that property * - When extracting a comparable value from a complex type * - When creating orders for types that contain comparable values * @@ -547,7 +547,7 @@ export const mapInput: { * * **When to use** * - * Use when when comparing dates for sorting or searching + * Use when comparing dates for sorting or searching * - As a base for creating orders on types containing dates * - When implementing time-based comparisons * @@ -581,7 +581,7 @@ export const Date: Order = mapInput(Number, (date) => date.getTime()) * * **When to use** * - * Use when when comparing tuples with different types for each position + * Use when comparing tuples with different types for each position * - When you need type-safe tuple ordering * - When working with fixed-length heterogeneous collections * @@ -647,7 +647,7 @@ export { * * **When to use** * - * Use when when comparing arrays of the same element type + * Use when comparing arrays of the same element type * - When you want shorter arrays to be considered less than longer arrays * - When sorting collections of arrays * @@ -683,7 +683,7 @@ export { * * **When to use** * - * Use when when comparing objects with multiple properties + * Use when comparing objects with multiple properties * - When you need multi-field comparison for structs * - When creating orders for complex data types * @@ -738,7 +738,7 @@ export function Struct }>( * * **When to use** * - * Use when when you need a boolean predicate instead of an ordering result + * Use when you need a boolean predicate instead of an ordering result * - When checking if a value is less than another in conditional logic * - When implementing range checks or comparisons * @@ -775,7 +775,7 @@ export const isLessThan = (O: Order): { * * **When to use** * - * Use when when you need a boolean predicate instead of an ordering result + * Use when you need a boolean predicate instead of an ordering result * - When checking if a value is greater than another in conditional logic * - When implementing range checks or comparisons * @@ -812,7 +812,7 @@ export const isGreaterThan = (O: Order): { * * **When to use** * - * Use when when you need a boolean predicate for non-strict comparison + * Use when you need a boolean predicate for non-strict comparison * - When checking if a value is within a range (inclusive lower bound) * - When implementing inclusive comparisons * @@ -849,7 +849,7 @@ export const isLessThanOrEqualTo = (O: Order): { * * **When to use** * - * Use when when you need a boolean predicate for non-strict comparison + * Use when you need a boolean predicate for non-strict comparison * - When checking if a value is within a range (inclusive upper bound) * - When implementing inclusive comparisons * @@ -886,7 +886,7 @@ export const isGreaterThanOrEqualTo = (O: Order): { * * **When to use** * - * Use when when you need to find the smaller of two values + * Use when you need to find the smaller of two values * - When implementing min/max operations * - When selecting values based on ordering * @@ -923,7 +923,7 @@ export const min = (O: Order): { * * **When to use** * - * Use when when you need to find the larger of two values + * Use when you need to find the larger of two values * - When implementing min/max operations * - When selecting values based on ordering * @@ -960,7 +960,7 @@ export const max = (O: Order): { * * **When to use** * - * Use when when you need to restrict a value to a specific range + * Use when you need to restrict a value to a specific range * - When implementing bounds checking and normalization * - When ensuring values stay within valid ranges * @@ -1013,7 +1013,7 @@ export const clamp = (O: Order): { * * **When to use** * - * Use when when validating that a value is within a valid range + * Use when validating that a value is within a valid range * - When implementing range checks for bounds validation * - When filtering or selecting values within a range * @@ -1067,7 +1067,7 @@ export const isBetween = (O: Order): { * * **When to use** * - * Use when when you need to combine multiple orders from a collection using reducer patterns + * Use when you need to combine multiple orders from a collection using reducer patterns * - When implementing fold operations over collections of orders * - When working with reducers that operate on orders * diff --git a/packages/effect/src/Schedule.ts b/packages/effect/src/Schedule.ts index 28d82448e0..b21c5010c1 100644 --- a/packages/effect/src/Schedule.ts +++ b/packages/effect/src/Schedule.ts @@ -852,9 +852,7 @@ export const andThenResult: { * * **When to use** * - * Use when the combined schedule should continue only while both - * schedules still recur. Use `either` when either schedule should be enough to - * continue. + * Use when the combined schedule should continue only while both schedules still recur. * * **Example** (Combining time and attempt limits) * @@ -1543,8 +1541,7 @@ export const delays = (self: Schedule): Schedule => * * **When to use** * - * Use when the combined schedule should continue while at least one - * schedule still recurs. Use `both` when both schedules must continue. + * Use when the combined schedule should continue while at least one schedule still recurs. * * **Example** (Combining schedules with either semantics) * @@ -2142,8 +2137,7 @@ export const fibonacci = (one: Duration.Input): Schedule => { * * **When to use** * - * Use when recurrences should stay aligned to a regular cadence. Use - * `spaced` when each delay should start after the previous action completes. + * Use when recurrences should stay aligned to a regular cadence. * * **Gotchas** * @@ -2457,9 +2451,7 @@ export const passthrough = ( * * **When to use** * - * Use when you need a counter schedule with no additional delay. Use `take` - * to limit an existing schedule while preserving its output and delay - * behavior. + * Use when you need a counter schedule with no additional delay. * * **Gotchas** * @@ -2683,9 +2675,7 @@ export const reduce: { * * **When to use** * - * Use when each delay should start after the previous action - * completes. Use `fixed` when recurrences should stay aligned to a regular - * cadence. + * Use when each delay should start after the previous action completes. * * **Example** (Repeating with fixed spacing) * @@ -3051,9 +3041,7 @@ export const tapOutput: { * * **When to use** * - * Use to limit an existing schedule while preserving its output and - * delay behavior. Use `recurs` when you only need an immediate counter - * schedule. + * Use to limit an existing schedule while preserving its output and delay behavior. * * **Gotchas** * @@ -3433,8 +3421,7 @@ export { * * **When to use** * - * Use to check an existing schedule input type. Use - * `setInputType` to adapt a schedule that does not depend on its input values. + * Use to check an existing schedule input type. * * **Details** * @@ -3473,8 +3460,7 @@ export const satisfiesInputType = () => * * **When to use** * - * Use to adapt a schedule that does not depend on its input - * values. Use `satisfiesInputType` to check an existing schedule input type. + * Use to adapt a schedule that does not depend on its input values. * * **Details** * diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index 20ce8afd07..69a0eb9d32 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -1032,8 +1032,8 @@ export const durationFromNanos: Transformation = tran * * **When to use** * - * Use when you use this for timeouts, delays, elapsed intervals, or other duration values - * stored as millisecond counts. + * Use when timeouts, delays, elapsed intervals, or other duration values are stored as + * millisecond counts. * * **Details** * @@ -1550,8 +1550,8 @@ export const stringFromUriComponent: Transformation = new Transf * * **When to use** * - * Use when you use this for JSON stored or transmitted as a string, usually before composing - * with another schema that validates the parsed structure. + * Use when JSON is stored or transmitted as a string, usually before composing with another + * schema that validates the parsed structure. * * **Details** * @@ -1585,8 +1585,8 @@ export const fromJsonString = new Transformation( * * **When to use** * - * Use when you use this for form or multipart payloads where keys such as `user[name]` or - * `items[0]` should become nested data. + * Use when form or multipart payloads contain keys such as `user[name]` or `items[0]` that + * should become nested data. * * **Details** * @@ -1621,8 +1621,8 @@ export const fromFormData = new Transformation( * * **When to use** * - * Use when you use this for query strings where keys such as `filter[name]` or `items[0]` - * should become nested data. + * Use when query strings contain keys such as `filter[name]` or `items[0]` that should + * become nested data. * * **Details** * diff --git a/packages/effect/src/Struct.ts b/packages/effect/src/Struct.ts index 126da33b55..5001be85f5 100644 --- a/packages/effect/src/Struct.ts +++ b/packages/effect/src/Struct.ts @@ -617,8 +617,8 @@ export const makeOrder = order.Struct * * **When to use** * - * Use when you use this interface when defining a typed function for {@link map}, - * {@link mapPick}, or {@link mapOmit}. + * Use when defining a typed function for {@link map}, {@link mapPick}, or + * {@link mapOmit}. * * **Details** * diff --git a/packages/effect/src/Tuple.ts b/packages/effect/src/Tuple.ts index c1806a22a0..1b1efbd823 100644 --- a/packages/effect/src/Tuple.ts +++ b/packages/effect/src/Tuple.ts @@ -80,8 +80,8 @@ import type { Apply, Lambda } from "./Struct.ts" * * **When to use** * - * Use when you use this instead of `[a, b, c] as const` when you want a properly typed tuple - * without a manual cast. + * Use when a properly typed tuple is needed without writing `[a, b, c] as const` + * or another manual cast. * * **Details** * @@ -111,7 +111,7 @@ type Indices> = Exclude["length"], T * * **When to use** * - * Use when you use this in a pipeline when you need to extract a single element. + * Use when a single tuple element should be extracted in a pipeline. * * **Details** * diff --git a/packages/effect/src/unstable/ai/AiError.ts b/packages/effect/src/unstable/ai/AiError.ts index fa3a15226d..e6ba66a459 100644 --- a/packages/effect/src/unstable/ai/AiError.ts +++ b/packages/effect/src/unstable/ai/AiError.ts @@ -1647,7 +1647,8 @@ export const make = (params: { * * **When to use** * - * Use when provider packages can use this as a base for provider-specific mapping. + * Use as the base mapping when provider packages translate HTTP status codes into + * provider-specific error reasons. * * **Example** (Mapping an HTTP status to a reason) * diff --git a/packages/effect/src/unstable/ai/Chat.ts b/packages/effect/src/unstable/ai/Chat.ts index 31a45b4097..b9ffdd2ffe 100644 --- a/packages/effect/src/unstable/ai/Chat.ts +++ b/packages/effect/src/unstable/ai/Chat.ts @@ -505,8 +505,7 @@ const makeUnsafe = (history: Ref.Ref) => { * * **When to use** * - * Use when this is the most common way to start a fresh chat session without - * any initial context or system prompts. + * Use when starting a fresh chat session without initial context or system prompts. * * **Example** (Creating an empty chat) * diff --git a/packages/effect/src/unstable/ai/IdGenerator.ts b/packages/effect/src/unstable/ai/IdGenerator.ts index 3b3f16119f..51059e62b1 100644 --- a/packages/effect/src/unstable/ai/IdGenerator.ts +++ b/packages/effect/src/unstable/ai/IdGenerator.ts @@ -306,9 +306,8 @@ export const make = Effect.fnUntraced(function*({ * * **When to use** * - * Use when this is the recommended way to provide ID generation capabilities to your - * application. The layer will fail during construction if the configuration is - * invalid. + * Use when an application should provide ID generation capabilities from validated + * configuration. The layer will fail during construction if the configuration is invalid. * * **Example** (Providing an ID generator layer) * diff --git a/packages/effect/src/unstable/ai/Prompt.ts b/packages/effect/src/unstable/ai/Prompt.ts index fcedd0c8dd..1b1fdcc5a5 100644 --- a/packages/effect/src/unstable/ai/Prompt.ts +++ b/packages/effect/src/unstable/ai/Prompt.ts @@ -775,8 +775,8 @@ export const toolResultPart = (params: PartConstructorParams): T * * **When to use** * - * Use when you use this part in tool messages to approve or deny tool execution when tools - * have the `needsApproval` property set. + * Use when tool messages must approve or deny tool execution for tools with the + * `needsApproval` property set. * * **Example** (Creating tool approval responses) * diff --git a/packages/effect/src/unstable/ai/ResponseIdTracker.ts b/packages/effect/src/unstable/ai/ResponseIdTracker.ts index 4127d333ba..6cd17acd9a 100644 --- a/packages/effect/src/unstable/ai/ResponseIdTracker.ts +++ b/packages/effect/src/unstable/ai/ResponseIdTracker.ts @@ -83,7 +83,7 @@ export interface Service { * * **When to use** * - * Use when when provided, language model operations can use the tracker to send only new + * Use when provided, language model operations can use the tracker to send only new * prompt messages together with the provider's prior response ID. * * @category services diff --git a/packages/effect/src/unstable/ai/Tool.ts b/packages/effect/src/unstable/ai/Tool.ts index 8af047e976..32bbe9511f 100644 --- a/packages/effect/src/unstable/ai/Tool.ts +++ b/packages/effect/src/unstable/ai/Tool.ts @@ -1318,8 +1318,8 @@ export const make = < * * **When to use** * - * Use when this is useful for tools where the schema isn't known at compile time, - * such as MCP tools discovered at runtime or tools from external configurations. + * Use when a tool schema is not known at compile time, such as MCP tools discovered at + * runtime or tools from external configurations. * * **Details** * diff --git a/packages/effect/src/unstable/cli/Command.ts b/packages/effect/src/unstable/cli/Command.ts index 78f4894311..13b79500c8 100644 --- a/packages/effect/src/unstable/cli/Command.ts +++ b/packages/effect/src/unstable/cli/Command.ts @@ -1046,8 +1046,8 @@ export const withAlias: { * * **When to use** * - * Use when you use this for experimental or internal subcommands that should be accepted but - * not advertised on the public CLI surface. + * Use when experimental or internal subcommands should be accepted but not advertised on + * the public CLI surface. * * **Example** (Hiding a subcommand) * @@ -1480,8 +1480,8 @@ export const run: { * * **When to use** * - * Use when you use this function for testing CLI applications or when you want to - * programmatically execute commands with specific arguments. + * Use when testing CLI applications or programmatically executing commands with specific + * arguments. * * **Example** (Running commands with explicit arguments) * diff --git a/packages/effect/src/unstable/cli/Flag.ts b/packages/effect/src/unstable/cli/Flag.ts index 87ca0f5998..5944dfd5e8 100644 --- a/packages/effect/src/unstable/cli/Flag.ts +++ b/packages/effect/src/unstable/cli/Flag.ts @@ -374,7 +374,7 @@ export const fileSchema = ( * * **When to use** * - * Use when you use this for options that accept configuration values. + * Use when options accept configuration values. * * **Details** * @@ -516,9 +516,9 @@ export const withMetavar: { * * **When to use** * - * Use when you use this for experimental or internal flags that should be accepted but not - * advertised, such as `--experimental-foo`, debug toggles, or escape hatches - * that are not yet committed to the public CLI surface. + * Use when experimental or internal flags should be accepted but not advertised, such as + * `--experimental-foo`, debug toggles, or escape hatches that are not yet committed to the + * public CLI surface. * * **Example** (Hiding a flag from help) * diff --git a/packages/effect/src/unstable/cli/Param.ts b/packages/effect/src/unstable/cli/Param.ts index 4b6ee53c5f..d75bd5c726 100644 --- a/packages/effect/src/unstable/cli/Param.ts +++ b/packages/effect/src/unstable/cli/Param.ts @@ -935,7 +935,7 @@ export const keyValuePair = ( * * **When to use** * - * Use when this is useful for creating placeholder parameters or for combinators. + * Use when placeholder parameters or combinators need an empty parameter sentinel. * * **Example** (Creating sentinel parameters) * @@ -1659,7 +1659,7 @@ export const atLeast: { * * **When to use** * - * Use when you use this combinator for validation and transformation in a single step. + * Use when validation and transformation should happen in a single parameter combinator. * * **Example** (Filtering and transforming values) * diff --git a/packages/effect/src/unstable/cluster/ClusterCron.ts b/packages/effect/src/unstable/cluster/ClusterCron.ts index 4ea8453173..c921739705 100644 --- a/packages/effect/src/unstable/cluster/ClusterCron.ts +++ b/packages/effect/src/unstable/cluster/ClusterCron.ts @@ -87,8 +87,7 @@ export const make = (options: { * * **When to use** * - * Use when this is useful to prevent running jobs that were scheduled too far in the - * past. + * Use to prevent running jobs that were scheduled too far in the past. * * **Details** * diff --git a/packages/effect/src/unstable/cluster/RunnerServer.ts b/packages/effect/src/unstable/cluster/RunnerServer.ts index e276863b90..7a39633eb0 100644 --- a/packages/effect/src/unstable/cluster/RunnerServer.ts +++ b/packages/effect/src/unstable/cluster/RunnerServer.ts @@ -212,8 +212,8 @@ export const layerWithClients: Layer.Layer< * * **When to use** * - * Use when you use this layer to embed a cluster client inside another Effect application - * without registering with the ShardManager or receiving shard assignments. + * Use to embed a cluster client inside another Effect application without registering with + * the ShardManager or receiving shard assignments. * * @category layers * @since 4.0.0 diff --git a/packages/effect/src/unstable/observability/PrometheusMetrics.ts b/packages/effect/src/unstable/observability/PrometheusMetrics.ts index b4a298c8df..e060099e75 100644 --- a/packages/effect/src/unstable/observability/PrometheusMetrics.ts +++ b/packages/effect/src/unstable/observability/PrometheusMetrics.ts @@ -143,8 +143,10 @@ export const format: (options?: FormatOptions | undefined) => Effect.Effect Date: Thu, 28 May 2026 21:37:28 +0200 Subject: [PATCH 03/29] wip --- packages/ai/openai/src/OpenAiClient.ts | 4 +-- .../ai/openai/src/OpenAiEmbeddingModel.ts | 8 ++--- packages/effect/src/Array.ts | 29 ++++++++-------- packages/effect/src/BigDecimal.ts | 8 ++--- packages/effect/src/Cause.ts | 4 +-- packages/effect/src/ChannelSchema.ts | 6 ++-- packages/effect/src/Context.ts | 5 +-- packages/effect/src/Effect.ts | 34 +++++++++---------- packages/effect/src/Equal.ts | 6 ++-- packages/effect/src/ErrorReporter.ts | 2 +- packages/effect/src/Fiber.ts | 4 +-- packages/effect/src/Function.ts | 19 +++++------ packages/effect/src/HKT.ts | 4 +-- packages/effect/src/JsonSchema.ts | 4 +-- packages/effect/src/Latch.ts | 4 +-- packages/effect/src/Layer.ts | 15 ++++---- packages/effect/src/Match.ts | 2 +- packages/effect/src/Option.ts | 7 ++-- packages/effect/src/PartitionedSemaphore.ts | 4 +-- packages/effect/src/Path.ts | 2 +- packages/effect/src/PubSub.ts | 4 +-- packages/effect/src/Request.ts | 4 +-- packages/effect/src/Result.ts | 5 ++- packages/effect/src/Runtime.ts | 4 +-- packages/effect/src/Schema.ts | 2 +- packages/effect/src/SchemaGetter.ts | 20 +++++------ packages/effect/src/SchemaRepresentation.ts | 4 +-- packages/effect/src/SchemaTransformation.ts | 4 +-- packages/effect/src/Sink.ts | 5 ++- packages/effect/src/Stream.ts | 4 +-- packages/effect/src/SynchronizedRef.ts | 3 +- packages/effect/src/Tracer.ts | 8 ++--- packages/effect/src/unstable/cli/Flag.ts | 4 +-- packages/effect/src/unstable/cli/Param.ts | 3 +- .../src/unstable/cluster/ClusterSchema.ts | 4 +-- .../src/unstable/cluster/ShardingConfig.ts | 8 ++--- packages/effect/src/unstable/http/Etag.ts | 5 ++- .../src/unstable/http/HttpServerResponse.ts | 12 +++---- .../observability/PrometheusMetrics.ts | 4 +-- packages/effect/src/unstable/sql/SqlSchema.ts | 8 ++--- packages/opentelemetry/src/Tracer.ts | 4 +-- .../platform-browser/src/BrowserSocket.ts | 4 +-- .../platform-browser/src/BrowserWorker.ts | 4 +-- 43 files changed, 148 insertions(+), 150 deletions(-) diff --git a/packages/ai/openai/src/OpenAiClient.ts b/packages/ai/openai/src/OpenAiClient.ts index 4ecc8ba735..523cd19e3e 100644 --- a/packages/ai/openai/src/OpenAiClient.ts +++ b/packages/ai/openai/src/OpenAiClient.ts @@ -378,7 +378,7 @@ export const layer = (options: Options): Layer.Layer, B>( * * **When to use** * - * Use when mapping and filtering in one step, where the mapper can return + * Use when you need to map and filter in one step, where the mapper can return * `null` or `undefined` to skip elements. * * **Example** (FlatMapping with nullable) @@ -4560,8 +4559,8 @@ export const join: { * * **When to use** * - * Use when mapping needs state threaded through each element and the final state - * is also needed. + * Use when you need to map while threading state through each element and keep + * the final state. * * **Details** * diff --git a/packages/effect/src/BigDecimal.ts b/packages/effect/src/BigDecimal.ts index 4452b39f83..890ed770e5 100644 --- a/packages/effect/src/BigDecimal.ts +++ b/packages/effect/src/BigDecimal.ts @@ -1311,8 +1311,8 @@ export const fromBigInt = (n: bigint): BigDecimal => make(n, 0) * * **When to use** * - * Use when a finite JavaScript number must become a `BigDecimal` and invalid - * input should throw. + * Use when you need to convert a finite JavaScript number to a `BigDecimal` and + * invalid input should throw. * * **Gotchas** * @@ -1474,7 +1474,7 @@ export const fromString = (s: string): Option.Option => { * * **When to use** * - * Use when decimal text is expected to be valid and parse errors should throw. + * Use when you expect decimal text to be valid and want parse errors to throw. * * **Details** * @@ -1606,7 +1606,7 @@ export const toExponential = (n: BigDecimal): string => { * * **When to use** * - * Use when an interop boundary requires a JavaScript number and can tolerate + * Use when you need a JavaScript number at an interop boundary and can tolerate * precision loss. * * **Gotchas** diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index afb2654683..60cd102c74 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -911,8 +911,8 @@ export const findError: (self: Cause) => Result.Result> = * * **When to use** * - * Use when code needs the first typed error as an `Option` and does not need the original - * cause returned in a failed `Result`. + * Use when you need the first typed error as an `Option` and do not need the + * original cause returned in a failed `Result`. * * **Example** (extracting an error as Option) * diff --git a/packages/effect/src/ChannelSchema.ts b/packages/effect/src/ChannelSchema.ts index ce37de6733..a6ddb6c240 100644 --- a/packages/effect/src/ChannelSchema.ts +++ b/packages/effect/src/ChannelSchema.ts @@ -280,9 +280,9 @@ export const duplex: { * * **When to use** * - * Use when a bidirectional channel crosses an encoded boundary whose chunk types - * are intentionally erased, while callers should send and receive schema-typed - * chunks. + * Use when you need a bidirectional channel to cross an encoded boundary whose + * chunk types are intentionally erased, while callers send and receive + * schema-typed chunks. * * **Details** * diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index 47bbf0fdfa..019474968b 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -193,7 +193,7 @@ export declare namespace ServiceClass { * * **When to use** * - * Use when a dependency must be provided by the surrounding context. + * Use when you need a dependency to be provided by the surrounding context. * * **Details** * @@ -1043,7 +1043,8 @@ const serviceNotFoundError = (service: Key) => { * * **When to use** * - * Use when service absence is expected and should be represented as data. + * Use when you expect a service to be absent and want absence represented as + * data. * * **Details** * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index ea068a42b9..d098ce2e72 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1228,8 +1228,8 @@ export { * * **When to use** * - * Use when integrating APIs that complete through callbacks - * instead of returning a `Promise`. + * Use when you need to integrate APIs that complete through callbacks instead + * of returning a `Promise`. * * **Details** * @@ -1996,8 +1996,8 @@ export const flatten: (self: Effect, E2, R2>) = * * **When to use** * - * Use when one effect must run after another and the second effect - * may depend on the first effect's success value. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * @@ -3155,8 +3155,8 @@ export const unwrapReason: { * * **When to use** * - * Use when recovery needs the full `Cause`, including recoverable failures, - * defects, and interruptions, instead of only the typed error value. + * Use when you need recovery to inspect the full `Cause`, including recoverable + * failures, defects, and interruptions, instead of only the typed error value. * * **Details** * @@ -3203,7 +3203,7 @@ export const catchCause: { * * **When to use** * - * Use when defects must be reported or translated at integration boundaries. + * Use when you need to report or translate defects at integration boundaries. * * **Details** * @@ -3576,8 +3576,8 @@ export const mapBoth: { * * **When to use** * - * Use when a typed failure represents an unrecoverable bug or invalid - * state and should not be handled as a recoverable error. + * Use when you need to turn a typed failure that represents an unrecoverable bug + * or invalid state into a defect. * * **Example** (Converting typed failures into defects) * @@ -4951,8 +4951,8 @@ export const filterMap: { * * **When to use** * - * Use when filtering each iterable element requires effects and accepted - * elements should be transformed into successful output values. + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. * * **Details** * @@ -5230,8 +5230,8 @@ export const when: { * * **When to use** * - * Use when code should respond differently to success or failure without triggering side - * effects. + * Use when you need to respond differently to success or failure without + * triggering side effects. * * **Details** * @@ -5394,7 +5394,7 @@ export const matchCause: { * * **When to use** * - * Use when effects are likely to be already resolved and matching the cause should avoid + * Use when you expect effects to already be resolved and want to match the cause without * the overhead of the regular effect pipeline. For pending effects, it automatically falls * back to the regular `matchCause` behavior. * @@ -5474,8 +5474,8 @@ export const matchCauseEffectEager: { * * **When to use** * - * Use when both success and failure handling must return effects and the - * failure branch needs the full `Cause`. + * Use when you need both success and failure handlers to return effects and the + * failure handler to inspect the full `Cause`. * * **Details** * @@ -5547,7 +5547,7 @@ export const matchCauseEffect: { * * **When to use** * - * Use when the failure or success branch must run additional effects. + * Use when you need the failure or success handler to run additional effects. * * **Details** * diff --git a/packages/effect/src/Equal.ts b/packages/effect/src/Equal.ts index 540af91af9..083141a733 100644 --- a/packages/effect/src/Equal.ts +++ b/packages/effect/src/Equal.ts @@ -462,10 +462,8 @@ const compareSets = makeCompareSet(compareBoth) * * **When to use** * - * Use when to branch on whether a value supports custom equality before calling - * its `[Equal.symbol]` method directly. - * - In generic utility code that needs to distinguish `Equal` implementors - * from plain values. + * Use when you need generic utility code to distinguish `Equal` implementors + * from plain values before calling `[Equal.symbol]` directly. * * **Details** * diff --git a/packages/effect/src/ErrorReporter.ts b/packages/effect/src/ErrorReporter.ts index 19a7d44a38..67ce4358ee 100644 --- a/packages/effect/src/ErrorReporter.ts +++ b/packages/effect/src/ErrorReporter.ts @@ -199,7 +199,7 @@ export const make = ( * * **When to use** * - * Use when low-level code needs to read or replace the current set of reporters + * Use when you need to read or replace the current set of error reporters * directly. * * @category references diff --git a/packages/effect/src/Fiber.ts b/packages/effect/src/Fiber.ts index 5d77318463..f307728423 100644 --- a/packages/effect/src/Fiber.ts +++ b/packages/effect/src/Fiber.ts @@ -323,8 +323,8 @@ export const join: (self: Fiber) => Effect = effect.fiberJoin * * **When to use** * - * Use when every fiber must succeed and you want the successful values rather - * than the `Exit` values. + * Use when you need every fiber to succeed and want the successful values + * rather than the `Exit` values. * * **Details** * diff --git a/packages/effect/src/Function.ts b/packages/effect/src/Function.ts index 742530bfa2..9c446671d2 100644 --- a/packages/effect/src/Function.ts +++ b/packages/effect/src/Function.ts @@ -340,8 +340,8 @@ export const cast: (a: A) => B = identity as any * * **When to use** * - * Use when an API expects a thunk or callback and every invocation - * should return the same value. + * Use when you need a thunk or callback that returns the same value on every + * invocation. * * **Example** (Creating a constant thunk) * @@ -365,7 +365,7 @@ export const constant = (value: A): LazyArg => () => value * * **When to use** * - * Use when an API expects a thunk and every invocation should return `true`. + * Use when you need a thunk that returns `true` on every invocation. * * **Example** (Returning true from a thunk) * @@ -386,7 +386,7 @@ export const constTrue: LazyArg = constant(true) * * **When to use** * - * Use when an API expects a thunk and every invocation should return `false`. + * Use when you need a thunk that returns `false` on every invocation. * * **Example** (Returning false from a thunk) * @@ -407,7 +407,7 @@ export const constFalse: LazyArg = constant(false) * * **When to use** * - * Use when an API expects a thunk and every invocation should return `null`. + * Use when you need a thunk that returns `null` on every invocation. * * **Example** (Returning null from a thunk) * @@ -428,8 +428,7 @@ export const constNull: LazyArg = constant(null) * * **When to use** * - * Use when an API expects a thunk and every invocation should return - * `undefined`. + * Use when you need a thunk that returns `undefined` on every invocation. * * **Example** (Returning undefined from a thunk) * @@ -450,7 +449,7 @@ export const constUndefined: LazyArg = constant(undefined) * * **When to use** * - * Use when an API expects a thunk used only for its call effect and not for a + * Use when you need a thunk that is called only for its effect and has no * meaningful return value. * * **Example** (Returning void from a thunk) @@ -532,8 +531,8 @@ export const compose: { * * **When to use** * - * Use when exhaustive checks prove a branch cannot be reached, but - * TypeScript still needs a return value. + * Use when you need a return value in a branch that exhaustive checks prove + * cannot be reached. * * **Gotchas** * diff --git a/packages/effect/src/HKT.ts b/packages/effect/src/HKT.ts index 8a32d50e18..3cb4b1894b 100644 --- a/packages/effect/src/HKT.ts +++ b/packages/effect/src/HKT.ts @@ -58,8 +58,8 @@ import type * as Types from "./Types.ts" * * **When to use** * - * Use when defining a custom type class that needs to expose the `TypeLambda` it - * operates on. + * Use when you need to define a custom type class that exposes the `TypeLambda` + * it operates on. * * **Details** * diff --git a/packages/effect/src/JsonSchema.ts b/packages/effect/src/JsonSchema.ts index 4a96c3a816..da3d748ef2 100644 --- a/packages/effect/src/JsonSchema.ts +++ b/packages/effect/src/JsonSchema.ts @@ -478,7 +478,7 @@ export function fromSchemaDraft2020_12(js: JsonSchema): Document<"draft-2020-12" * * **When to use** * - * Use when consuming schemas from an OpenAPI 3.1 specification. + * Use when you need to consume schemas from an OpenAPI 3.1 specification. * * **Details** * @@ -517,7 +517,7 @@ export function fromSchemaOpenApi3_1(js: JsonSchema): Document<"draft-2020-12"> * * **When to use** * - * Use when consuming schemas from an OpenAPI 3.0 specification. + * Use when you need to consume schemas from an OpenAPI 3.0 specification. * * **Details** * diff --git a/packages/effect/src/Latch.ts b/packages/effect/src/Latch.ts index 9a9ac36d84..1bf9ef845c 100644 --- a/packages/effect/src/Latch.ts +++ b/packages/effect/src/Latch.ts @@ -248,8 +248,8 @@ export const open = (self: Latch): Effect.Effect => self.open * * **When to use** * - * Use when synchronous code needs to open a latch immediately and release the - * fibers waiting on it. + * Use when you need synchronous code to open a latch immediately and release + * the fibers waiting on it. * * **Details** * diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index c34cae181b..40ed87d472 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -933,8 +933,8 @@ export const sync: { * * **When to use** * - * Use when multiple services can be created synchronously and should be deferred until - * the layer is built. + * Use when you need to create multiple services synchronously but defer that + * work until the layer is built. * * **Details** * @@ -1028,7 +1028,8 @@ const effectImpl = ( * * **When to use** * - * Use when effectful construction needs to provide multiple services at once. + * Use when you need effectful construction to provide multiple services at + * once. * * **Details** * @@ -1440,7 +1441,7 @@ export const provide: { * * **When to use** * - * Use when callers need access to both the service being built and the + * Use when you need callers to access both the service being built and the * dependency used to build it, such as a health check that needs both a * repository and its database. Prefer `provide` when the dependency should stay * private. @@ -1934,8 +1935,8 @@ export const catchTag: { * * **When to use** * - * Use when recovery needs more than the typed error, such as defects or interruption - * information. + * Use when you need recovery to inspect more than the typed error, such as + * defects or interruption information. * * **Details** * @@ -2047,7 +2048,7 @@ export const updateService: { * * **When to use** * - * Use when two parts of an application must receive separate instances + * Use when you need two parts of an application to receive separate instances * of a resource, such as two independent client sessions. Do not use it just to * work around confusing composition: by default, sharing the same layer value is * usually the desired behavior. diff --git a/packages/effect/src/Match.ts b/packages/effect/src/Match.ts index 32bf30fa6d..5985fb562e 100644 --- a/packages/effect/src/Match.ts +++ b/packages/effect/src/Match.ts @@ -1776,7 +1776,7 @@ export const instanceOf: any>( * * **When to use** * - * Use when constructor matching needs the unsafe refinement type. + * Use when you need constructor matching to use the unsafe refinement type. * * **Details** * diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index 744d9a8b3d..f6ba60c148 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -1868,7 +1868,8 @@ export const zipWith: { * * **When to use** * - * Use when aggregating values from a collection where some may be absent + * Use when you need to aggregate values from a collection where some may be + * absent. * * **Details** * @@ -2036,8 +2037,8 @@ export const filterMap: { * * **When to use** * - * Use when discarding values that don't meet a condition - * - Narrowing the type via a refinement predicate + * Use when you need to discard values that don't meet a condition and narrow + * the type via a refinement predicate. * * **Details** * diff --git a/packages/effect/src/PartitionedSemaphore.ts b/packages/effect/src/PartitionedSemaphore.ts index ed82a96504..d3c1b9f1ac 100644 --- a/packages/effect/src/PartitionedSemaphore.ts +++ b/packages/effect/src/PartitionedSemaphore.ts @@ -126,8 +126,8 @@ export interface Partitioned extends PartitionedSemaphore {} * * **When to use** * - * Use when a partitioned semaphore must be constructed synchronously outside an - * `Effect` workflow. + * Use when you need to construct a partitioned semaphore synchronously outside + * an `Effect` workflow. * * **Details** * diff --git a/packages/effect/src/Path.ts b/packages/effect/src/Path.ts index 0d11955bb8..094170dcde 100644 --- a/packages/effect/src/Path.ts +++ b/packages/effect/src/Path.ts @@ -876,7 +876,7 @@ const posixImpl = Path.of({ * * **When to use** * - * Use when an effect requires the `Path` service and should run with the + * Use when you need an effect that requires the `Path` service to run with the * built-in POSIX path implementation. * * **Details** diff --git a/packages/effect/src/PubSub.ts b/packages/effect/src/PubSub.ts index dd8d7968d0..de192b16fc 100644 --- a/packages/effect/src/PubSub.ts +++ b/packages/effect/src/PubSub.ts @@ -904,8 +904,8 @@ export const awaitShutdown = (self: PubSub): Effect.Effect => self.s * * **When to use** * - * Use when publishing from effectful code and the configured PubSub strategy - * should handle surplus messages. + * Use when you need to publish from effectful code and let the configured + * PubSub strategy handle surplus messages. * * **Details** * diff --git a/packages/effect/src/Request.ts b/packages/effect/src/Request.ts index 562003d9da..52096dd67c 100644 --- a/packages/effect/src/Request.ts +++ b/packages/effect/src/Request.ts @@ -535,8 +535,8 @@ export const fail: { * * **When to use** * - * Use when a `RequestResolver` needs to complete an entry with structured cause - * information rather than only the request's typed error value. + * Use when you need a `RequestResolver` to complete an entry with structured + * cause information rather than only the request's typed error value. * * @see {@link fail} for completing an entry with a typed error value * @see {@link complete} for completing an entry with an existing `Exit` diff --git a/packages/effect/src/Result.ts b/packages/effect/src/Result.ts index a4aaff4676..c4228d797f 100644 --- a/packages/effect/src/Result.ts +++ b/packages/effect/src/Result.ts @@ -437,9 +437,8 @@ export const failVoid: Result = fail(void 0) * * **When to use** * - * Use when an input may be `null` or `undefined` and absence should be - * represented as a `Failure` while present values should remain available as - * `Success`. + * Use when you need `null` or `undefined` input to become a `Failure` while + * present values remain available as `Success`. * * **Details** * diff --git a/packages/effect/src/Runtime.ts b/packages/effect/src/Runtime.ts index 50990f2f16..511fc6d580 100644 --- a/packages/effect/src/Runtime.ts +++ b/packages/effect/src/Runtime.ts @@ -403,8 +403,8 @@ export type errorReported = "~effect/Runtime/errorReported" * * **When to use** * - * Use when error classes are already reported by application code and should - * not be logged again by the default main runner. + * Use when you need error classes reported by application code to avoid being + * logged again by the default main runner. * * **Details** * diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index f741c137c2..9cffb12a8a 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -10025,7 +10025,7 @@ const BigDecimalString = String.annotate({ expected: "a string that will be deco * * **When to use** * - * Use when values are already Effect decimal instances and need schema + * Use when you already have Effect decimal instances and need schema * validation, formatting, equivalence, and JSON string serialization. * * **Details** diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index 209203cff6..da4aacfc94 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -271,8 +271,8 @@ function isPassthrough(getter: Getter): getter is typeof passt * * **When to use** * - * Use when no transformation is needed between encoded and decoded types. - * - One side of a `decodeTo` pair (encode or decode) should be a no-op. + * Use when you need one side of a `decodeTo` pair, either encode or decode, to + * pass values through unchanged. * * **Details** * @@ -313,9 +313,8 @@ export function passthrough(): Getter { * * **When to use** * - * Use when no runtime conversion is needed but the getter should be typed - * as producing a decoded/output type that is narrower than the encoded/input - * type. + * Use when you need an identity getter whose decoded/output type is narrower + * than the encoded/input type. * * **Details** * @@ -415,8 +414,8 @@ export function onNone( * * **When to use** * - * Use when a struct field must be present in the encoded input. - * - You want schema validation to report a missing key error. + * Use when you need a struct field to be present in the encoded input and want + * schema validation to report a missing key error. * * **Details** * @@ -679,7 +678,8 @@ export function omit(): Getter { * * **When to use** * - * Use when a field may be `undefined` in the encoded input and should have a fallback. + * Use when you need a fallback for a field that may be `undefined` in the + * encoded input. * * **Details** * @@ -1029,7 +1029,7 @@ type ParseJsonOptions = { * * **When to use** * - * Use when an encoded value is a JSON string that needs to be parsed during decoding. + * Use when you need to parse an encoded JSON string during decoding. * * **Details** * @@ -1555,7 +1555,7 @@ export function decodeUriComponent(): Getter { * * **When to use** * - * Use when an encoded value represents a date/time and should be decoded to a `DateTime.Utc`. + * Use when you need to decode an encoded date/time value to a `DateTime.Utc`. * * **Details** * diff --git a/packages/effect/src/SchemaRepresentation.ts b/packages/effect/src/SchemaRepresentation.ts index 9088d0df80..1a784e8174 100644 --- a/packages/effect/src/SchemaRepresentation.ts +++ b/packages/effect/src/SchemaRepresentation.ts @@ -1758,8 +1758,8 @@ export const MultiDocumentFromJson: Schema.Codec = S * * **When to use** * - * Use when an API expects a `MultiDocument` but you only have a single - * `Document`. + * Use when you need to pass a single `Document` where an API expects a + * `MultiDocument`. * * @see {@link Document} * @see {@link MultiDocument} diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index 69a0eb9d32..60537965be 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -778,8 +778,8 @@ export function passthrough(): Transformation { * * **When to use** * - * Use when the runtime value is unchanged but the decoded side should be - * narrower than the encoded side. + * Use when you need a no-op transformation whose decoded side is narrower than + * the encoded side. * * **Details** * diff --git a/packages/effect/src/Sink.ts b/packages/effect/src/Sink.ts index 98d4d6f752..8308104754 100644 --- a/packages/effect/src/Sink.ts +++ b/packages/effect/src/Sink.ts @@ -448,7 +448,7 @@ export declare namespace make { * * **When to use** * - * Use when the effect needs to provide both the result value and optional + * Use when you need an effect to provide both the result value and optional * leftovers. * * @category constructors @@ -1498,8 +1498,7 @@ export const find: { * * **When to use** * - * Use when deciding whether an input matches requires an effect, can fail, or - * needs services. + * Use when you need matching an input to run effects, fail, or use services. * * **Details** * diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 0c8466f25c..60d588a443 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -4568,8 +4568,8 @@ export const partitionQueue: { * * **When to use** * - * Use when each stream element must be classified by an effectful `Filter` and - * both passing and failing mapped values need to be consumed as streams. + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. * * **Details** * diff --git a/packages/effect/src/SynchronizedRef.ts b/packages/effect/src/SynchronizedRef.ts index c139f9c029..c9175fa409 100644 --- a/packages/effect/src/SynchronizedRef.ts +++ b/packages/effect/src/SynchronizedRef.ts @@ -188,7 +188,8 @@ export const getAndUpdate: { * * **When to use** * - * Use when an effectful state transition must return the previous stored value. + * Use when you need an effectful state transition to return the previous stored + * value. * * @see {@link getAndUpdate} for pure updates that return the previous value * @see {@link updateEffect} for effectful updates without returning a value diff --git a/packages/effect/src/Tracer.ts b/packages/effect/src/Tracer.ts index bf04b58abd..6c493f898b 100644 --- a/packages/effect/src/Tracer.ts +++ b/packages/effect/src/Tracer.ts @@ -159,8 +159,8 @@ export type AnySpan = Span | ExternalSpan * * **When to use** * - * Use when integrating lower-level tracing code that needs the raw context key - * for parent span lookup. + * Use when you need the raw context key for parent span lookup in lower-level + * tracing code. * * **Example** (Reading the parent span key) * @@ -579,8 +579,8 @@ export const MinimumTraceLevel = Context.Reference< * * **When to use** * - * Use when integrating lower-level tracing code that needs the raw context key - * for active tracer lookup. + * Use when you need the raw context key for active tracer lookup in lower-level + * tracing code. * * @category references * @since 4.0.0 diff --git a/packages/effect/src/unstable/cli/Flag.ts b/packages/effect/src/unstable/cli/Flag.ts index 5944dfd5e8..6d8b578325 100644 --- a/packages/effect/src/unstable/cli/Flag.ts +++ b/packages/effect/src/unstable/cli/Flag.ts @@ -166,8 +166,8 @@ export const choiceWithValue = ): boo * * **When to use** * - * Use when client-side cluster request handling needs to decide whether an - * interrupt should be ignored. + * Use when you need client-side cluster request handling to decide whether to + * ignore an interrupt. * * **Details** * diff --git a/packages/effect/src/unstable/cluster/ShardingConfig.ts b/packages/effect/src/unstable/cluster/ShardingConfig.ts index 952e9854d2..75d177a2cf 100644 --- a/packages/effect/src/unstable/cluster/ShardingConfig.ts +++ b/packages/effect/src/unstable/cluster/ShardingConfig.ts @@ -203,10 +203,10 @@ export const defaults: ShardingConfig["Service"] = { * * **When to use** * - * Use when wiring a cluster runner with explicit `ShardingConfig` values, - * especially in tests, local development, or code paths where configuration - * should be provided programmatically instead of loaded from environment - * variables. + * Use when you need to wire a cluster runner with explicit `ShardingConfig` + * values, especially in tests, local development, or code paths where + * configuration should be provided programmatically instead of loaded from + * environment variables. * * **Details** * diff --git a/packages/effect/src/unstable/http/Etag.ts b/packages/effect/src/unstable/http/Etag.ts index 0a6f09f6e3..ce2eb77d06 100644 --- a/packages/effect/src/unstable/http/Etag.ts +++ b/packages/effect/src/unstable/http/Etag.ts @@ -119,9 +119,8 @@ const fromFileWeb = (file: Body.HttpBody.FileLike) => { * * **When to use** * - * Use when file size and modification time reliably change for every byte-level - * change and the consuming HTTP code needs strong ETags from the `Generator` - * service. + * Use when you need the `Generator` service to produce strong ETags and file + * size plus modification time reliably change for every byte-level change. * * **Gotchas** * diff --git a/packages/effect/src/unstable/http/HttpServerResponse.ts b/packages/effect/src/unstable/http/HttpServerResponse.ts index bc738c9bd2..cbe2eb9c30 100644 --- a/packages/effect/src/unstable/http/HttpServerResponse.ts +++ b/packages/effect/src/unstable/http/HttpServerResponse.ts @@ -703,8 +703,8 @@ export const expireCookie: { * * **When to use** * - * Use when setting one trusted cookie and encoding failures should throw - * instead of being represented as `CookiesError` failures. + * Use when you need to set one trusted cookie and want encoding failures to + * throw instead of being represented as `CookiesError` failures. * * @category combinators * @since 4.0.0 @@ -741,8 +741,8 @@ export const setCookieUnsafe: { * * **When to use** * - * Use when expiring one trusted cookie and encoding failures should throw - * instead of being represented as `CookiesError` failures. + * Use when you need to expire one trusted cookie and want encoding failures to + * throw instead of being represented as `CookiesError` failures. * * @category combinators * @since 4.0.0 @@ -881,8 +881,8 @@ export const setCookies: { * * **When to use** * - * Use when setting multiple trusted cookies and encoding failures should throw - * instead of being represented as `CookiesError` failures. + * Use when you need to set multiple trusted cookies and want encoding failures + * to throw instead of being represented as `CookiesError` failures. * * @category combinators * @since 4.0.0 diff --git a/packages/effect/src/unstable/observability/PrometheusMetrics.ts b/packages/effect/src/unstable/observability/PrometheusMetrics.ts index e060099e75..cb5d1b0d68 100644 --- a/packages/effect/src/unstable/observability/PrometheusMetrics.ts +++ b/packages/effect/src/unstable/observability/PrometheusMetrics.ts @@ -143,8 +143,8 @@ export const format: (options?: FormatOptions | undefined) => Effect.Effect( * * **When to use** * - * Use when a query must return at least one row and an empty result should be - * treated as a failure. + * Use when you need to run a query that must return at least one row and treat + * an empty result as a failure. * * @see {@link findAll} for queries where an empty result should return an empty array * diff --git a/packages/opentelemetry/src/Tracer.ts b/packages/opentelemetry/src/Tracer.ts index a785b5a332..f01f55a57c 100644 --- a/packages/opentelemetry/src/Tracer.ts +++ b/packages/opentelemetry/src/Tracer.ts @@ -358,8 +358,8 @@ const convertOtelTimeInput = (input: Otel.TimeInput | undefined, clock: Clock.Cl * * **When to use** * - * Use when OpenTelemetry instrumentation outside Effect has already - * produced a parent span context and an effect should continue that trace. + * Use when you need an effect to continue a trace from a parent span context + * produced by OpenTelemetry instrumentation outside Effect. * * @category propagation * @since 4.0.0 diff --git a/packages/platform-browser/src/BrowserSocket.ts b/packages/platform-browser/src/BrowserSocket.ts index a7fee86218..921b788cc8 100644 --- a/packages/platform-browser/src/BrowserSocket.ts +++ b/packages/platform-browser/src/BrowserSocket.ts @@ -46,8 +46,8 @@ import * as Socket from "effect/unstable/socket/Socket" * * **When to use** * - * Use when browser or client-side code needs a complete `Socket` layer - * connected to a WebSocket URL. + * Use when you need a complete browser `Socket` layer connected to a WebSocket + * URL. * * **Details** * diff --git a/packages/platform-browser/src/BrowserWorker.ts b/packages/platform-browser/src/BrowserWorker.ts index df5579efc6..69fc7f8ec3 100644 --- a/packages/platform-browser/src/BrowserWorker.ts +++ b/packages/platform-browser/src/BrowserWorker.ts @@ -48,8 +48,8 @@ import { WorkerError, WorkerReceiveError } from "effect/unstable/workers/WorkerE * * **When to use** * - * Use when browser parent or client code needs both the browser - * `WorkerPlatform` and a `Spawner` from one layer. + * Use when you need both the browser `WorkerPlatform` and a `Spawner` from one + * layer. * * **Details** * From 91eddb103b17e363a0fd6ecb2c030c971ada3272 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Thu, 28 May 2026 21:43:42 +0200 Subject: [PATCH 04/29] wip --- packages/effect/src/Path.ts | 2 +- packages/effect/src/SchemaGetter.ts | 5 +++-- packages/effect/src/Stdio.ts | 4 ++-- packages/effect/src/unstable/ai/McpSchema.ts | 4 ++-- packages/effect/src/unstable/ai/Tool.ts | 2 +- packages/effect/src/unstable/cluster/ClusterSchema.ts | 2 +- packages/platform-browser/src/BrowserKeyValueStore.ts | 4 ++-- packages/platform-browser/src/Clipboard.ts | 4 ++-- packages/platform-browser/src/Geolocation.ts | 4 ++-- packages/platform-browser/src/Permissions.ts | 4 ++-- 10 files changed, 18 insertions(+), 17 deletions(-) diff --git a/packages/effect/src/Path.ts b/packages/effect/src/Path.ts index 094170dcde..9bf9eab674 100644 --- a/packages/effect/src/Path.ts +++ b/packages/effect/src/Path.ts @@ -216,7 +216,7 @@ export declare namespace Path { * * **When to use** * - * Use when an effect needs path operations supplied by its environment. + * Use when you need path operations supplied by an effect's environment. * * **Example** (Providing a custom Path service) * diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index da4aacfc94..66551cc69e 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -1073,7 +1073,7 @@ type StringifyJsonOptions = { * * **When to use** * - * Use when a decoded value needs to be serialized to JSON text during encoding. + * Use when you need to serialize a decoded value to JSON text during encoding. * * **Details** * @@ -1159,7 +1159,8 @@ export function splitKeyValue(options?: { * * **When to use** * - * Use when a decoded record needs to be serialized as a delimited key-value string. + * Use when you need to serialize a decoded record as a delimited key-value + * string. * * **Details** * diff --git a/packages/effect/src/Stdio.ts b/packages/effect/src/Stdio.ts index 1a5be7c2f5..772043f793 100644 --- a/packages/effect/src/Stdio.ts +++ b/packages/effect/src/Stdio.ts @@ -95,8 +95,8 @@ export interface Stdio { * * **When to use** * - * Use when an effect needs command-line arguments or standard I/O streams - * supplied by its environment. + * Use when you need command-line arguments or standard I/O streams supplied by + * an effect's environment. * * @see {@link make} for constructing a `Stdio` service directly * @see {@link layerTest} for a test layer with defaults and overrides diff --git a/packages/effect/src/unstable/ai/McpSchema.ts b/packages/effect/src/unstable/ai/McpSchema.ts index 2bf3d20313..fdd61e992c 100644 --- a/packages/effect/src/unstable/ai/McpSchema.ts +++ b/packages/effect/src/unstable/ai/McpSchema.ts @@ -1815,8 +1815,8 @@ export class CreateMessageResult extends Schema.Class( * * **When to use** * - * Use when an MCP server needs the client to perform model sampling on its - * behalf. + * Use when you need to request model sampling from an MCP client on behalf of a + * server. * * **Details** * diff --git a/packages/effect/src/unstable/ai/Tool.ts b/packages/effect/src/unstable/ai/Tool.ts index 32bbe9511f..4859485ed0 100644 --- a/packages/effect/src/unstable/ai/Tool.ts +++ b/packages/effect/src/unstable/ai/Tool.ts @@ -2027,7 +2027,7 @@ export interface EmptyParams extends Schema.$Record * * **When to use** * - * Use when a tool needs an explicit no-parameter `parameters` schema. + * Use when you need an explicit no-parameter `parameters` schema for a tool. * * **Details** * diff --git a/packages/effect/src/unstable/cluster/ClusterSchema.ts b/packages/effect/src/unstable/cluster/ClusterSchema.ts index 76047d91d1..21384b4cd7 100644 --- a/packages/effect/src/unstable/cluster/ClusterSchema.ts +++ b/packages/effect/src/unstable/cluster/ClusterSchema.ts @@ -71,7 +71,7 @@ export const Persisted = Context.Reference("effect/cluster/ClusterSchem * * **When to use** * - * Use when a request needs server-side handling or storage work wrapped in the + * Use when you need server-side request handling or storage work wrapped in the * storage transaction. * * **Details** diff --git a/packages/platform-browser/src/BrowserKeyValueStore.ts b/packages/platform-browser/src/BrowserKeyValueStore.ts index 45eb433795..5092c0893b 100644 --- a/packages/platform-browser/src/BrowserKeyValueStore.ts +++ b/packages/platform-browser/src/BrowserKeyValueStore.ts @@ -82,8 +82,8 @@ export const layerSessionStorage: Layer.Layer = Key * * **When to use** * - * Use when a browser `KeyValueStore` needs persistent asynchronous IndexedDB - * storage instead of the synchronous Web Storage APIs. + * Use when you need persistent asynchronous IndexedDB storage for a browser + * `KeyValueStore` instead of the synchronous Web Storage APIs. * * **Details** * diff --git a/packages/platform-browser/src/Clipboard.ts b/packages/platform-browser/src/Clipboard.ts index 7fc5fcb9ce..acf7a618a8 100644 --- a/packages/platform-browser/src/Clipboard.ts +++ b/packages/platform-browser/src/Clipboard.ts @@ -88,8 +88,8 @@ export class ClipboardError extends Data.TaggedError("ClipboardError")<{ * * **When to use** * - * Use when an Effect needs to require or provide clipboard capabilities through - * the context. + * Use when you need to require or provide clipboard capabilities through + * Effect's context. * * @see {@link make} for building a custom clipboard service * @see {@link layer} for providing the browser-backed clipboard service diff --git a/packages/platform-browser/src/Geolocation.ts b/packages/platform-browser/src/Geolocation.ts index f8b1df4991..e014378712 100644 --- a/packages/platform-browser/src/Geolocation.ts +++ b/packages/platform-browser/src/Geolocation.ts @@ -89,8 +89,8 @@ export interface Geolocation { * * **When to use** * - * Use when an Effect needs to access or provide geolocation capabilities - * through the context. + * Use when you need to access or provide geolocation capabilities through + * Effect's context. * * @see {@link layer} for providing the browser-backed geolocation service * diff --git a/packages/platform-browser/src/Permissions.ts b/packages/platform-browser/src/Permissions.ts index 5b60344313..1cbb08db93 100644 --- a/packages/platform-browser/src/Permissions.ts +++ b/packages/platform-browser/src/Permissions.ts @@ -128,8 +128,8 @@ export class PermissionsError extends Data.TaggedError("PermissionsError")<{ * * **When to use** * - * Use when an Effect needs to require or provide browser permission querying - * through the context. + * Use when you need to require or provide browser permission querying through + * Effect's context. * * @category services * @since 4.0.0 From bea29288bbabaf8f33188c6ce43216bfe54c8622 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Thu, 28 May 2026 21:49:00 +0200 Subject: [PATCH 05/29] wip --- packages/effect/src/Channel.ts | 2 +- packages/effect/src/Effect.ts | 9 +++++---- packages/effect/src/Metric.ts | 4 ++-- packages/effect/src/PartitionedSemaphore.ts | 4 ++-- packages/effect/src/Schema.ts | 6 ++++-- packages/effect/src/Semaphore.ts | 6 +++--- packages/effect/src/Sink.ts | 4 ++-- packages/effect/src/Stream.ts | 2 +- packages/effect/src/unstable/ai/EmbeddingModel.ts | 4 ++-- packages/platform-browser/src/IndexedDbDatabase.ts | 2 +- 10 files changed, 23 insertions(+), 20 deletions(-) diff --git a/packages/effect/src/Channel.ts b/packages/effect/src/Channel.ts index f2fcbd03c1..c7fb1a88b4 100644 --- a/packages/effect/src/Channel.ts +++ b/packages/effect/src/Channel.ts @@ -4209,7 +4209,7 @@ export const catchCauseIf: { * **When to use** * * Use when you need to recover a channel only from causes selected by a - * `Filter`, and the recovery needs both the selected value and the original + * `Filter`, while giving the recovery both the selected value and the original * `Cause`. * * **Details** diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index d098ce2e72..423678d51a 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -3450,8 +3450,8 @@ export const catchCauseIf: { * * **When to use** * - * Use when you need to recover only from causes selected by a `Filter`, and the - * recovery needs both the selected value and the original `Cause`. + * Use when you need to recover only from causes selected by a `Filter`, while + * giving the recovery both the selected value and the original `Cause`. * * **Details** * @@ -3793,8 +3793,9 @@ export const tapCauseIf: { * * **When to use** * - * Use when you need to observe only failure causes selected by a `Filter`, and - * the side effect needs both the selected value and the original `Cause`. + * Use when you need to observe only failure causes selected by a `Filter`, + * while giving the side effect both the selected value and the original + * `Cause`. * * **Details** * diff --git a/packages/effect/src/Metric.ts b/packages/effect/src/Metric.ts index 77999c2b8d..7c837b784d 100644 --- a/packages/effect/src/Metric.ts +++ b/packages/effect/src/Metric.ts @@ -1765,8 +1765,8 @@ const MetricRegistryKey = "~effect/observability/Metric/MetricRegistryKey" * * **When to use** * - * Use to provide a custom metric registry when a program or test needs metrics - * isolated from the default registry. + * Use to provide a custom metric registry for a program or test that needs + * metrics isolated from the default registry. * * **Details** * diff --git a/packages/effect/src/PartitionedSemaphore.ts b/packages/effect/src/PartitionedSemaphore.ts index d3c1b9f1ac..2cab39aee0 100644 --- a/packages/effect/src/PartitionedSemaphore.ts +++ b/packages/effect/src/PartitionedSemaphore.ts @@ -437,8 +437,8 @@ export const take: { * * **When to use** * - * Use to manually return permits acquired with `take` when a lower-level - * partitioned permit protocol needs explicit release control. + * Use to manually return permits acquired with `take` for a lower-level + * partitioned permit protocol that needs explicit release control. * * **Details** * diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 9cffb12a8a..718b65c423 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -4720,7 +4720,8 @@ export function catchDecoding( * * **When to use** * - * Use when decoding fallback logic needs services from the Effect context. + * Use when you need decoding fallback logic to require services from the Effect + * context. * * **Details** * @@ -4764,7 +4765,8 @@ export function catchEncoding( * * **When to use** * - * Use when encoding fallback logic needs services from the Effect context. + * Use when you need encoding fallback logic to require services from the Effect + * context. * * **Details** * diff --git a/packages/effect/src/Semaphore.ts b/packages/effect/src/Semaphore.ts index 1d1d3736e8..b06f3001a1 100644 --- a/packages/effect/src/Semaphore.ts +++ b/packages/effect/src/Semaphore.ts @@ -469,7 +469,7 @@ export const withPermitsIfAvailable: { * * **When to use** * - * Use to manually acquire permits when a lower-level permit protocol needs + * Use to manually acquire permits for a lower-level permit protocol that needs * explicit acquisition and release control. * * **Details** @@ -494,8 +494,8 @@ export const take: { * * **When to use** * - * Use to manually return permits acquired with `take` when a lower-level - * permit protocol needs explicit release control. + * Use to manually return permits acquired with `take` for a lower-level permit + * protocol that needs explicit release control. * * **Details** * diff --git a/packages/effect/src/Sink.ts b/packages/effect/src/Sink.ts index 8308104754..729668ff89 100644 --- a/packages/effect/src/Sink.ts +++ b/packages/effect/src/Sink.ts @@ -1073,8 +1073,8 @@ export const mapEffectEnd: { * * **When to use** * - * Use when transforming a sink result itself is effectful, can fail, or needs - * services. + * Use when you need a sink result transformation that is effectful, can fail, + * or requires services. * * **Details** * diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 60d588a443..eb7327b189 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -5849,7 +5849,7 @@ export const catchCauseIf: { * **When to use** * * Use when you need to recover a stream only from causes selected by a - * `Filter`, and the recovery needs both the selected value and the original + * `Filter`, while giving the recovery both the selected value and the original * `Cause`. * * **Details** diff --git a/packages/effect/src/unstable/ai/EmbeddingModel.ts b/packages/effect/src/unstable/ai/EmbeddingModel.ts index 285e540a3e..8f7fd7a8c1 100644 --- a/packages/effect/src/unstable/ai/EmbeddingModel.ts +++ b/packages/effect/src/unstable/ai/EmbeddingModel.ts @@ -60,8 +60,8 @@ import * as AiError from "./AiError.ts" * * **When to use** * - * Use to retrieve or provide the embedding model service when an `Effect` - * program needs to embed text into vectors. + * Use to retrieve or provide the embedding model service for an `Effect` + * program that embeds text into vectors. * * @see {@link Service} for the service contract provided by this tag * @see {@link make} for constructing an embedding model service from a provider diff --git a/packages/platform-browser/src/IndexedDbDatabase.ts b/packages/platform-browser/src/IndexedDbDatabase.ts index 6bbc21849a..42cf0c7cc2 100644 --- a/packages/platform-browser/src/IndexedDbDatabase.ts +++ b/packages/platform-browser/src/IndexedDbDatabase.ts @@ -125,7 +125,7 @@ export class IndexedDbDatabaseError extends Data.TaggedError( * * **When to use** * - * Use when an effect needs access to the live database service after an + * Use when you need access to the live database service after an * `IndexedDbSchema` layer has been provided, especially for `rebuild` or * lower-level database primitives. * From 17f6fc74ee8bbe7a502cb3d5941ba2338ce2a882 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Thu, 28 May 2026 21:57:44 +0200 Subject: [PATCH 06/29] wip --- .agents/skills/jsdocs/SKILL.md | 6 ++++ packages/effect/src/Array.ts | 4 +-- packages/effect/src/ChannelSchema.ts | 4 +-- packages/effect/src/Context.ts | 6 ++-- packages/effect/src/Cron.ts | 4 +-- packages/effect/src/Effect.ts | 2 +- packages/effect/src/Fiber.ts | 2 +- packages/effect/src/Layer.ts | 4 +-- packages/effect/src/Redacted.ts | 2 +- packages/effect/src/Schema.ts | 28 +++++++++---------- packages/effect/src/SchemaGetter.ts | 7 +++-- packages/effect/src/SchemaParser.ts | 22 +++++++-------- packages/effect/src/SchemaTransformation.ts | 4 +-- packages/effect/src/Stream.ts | 6 ++-- packages/effect/src/Tuple.ts | 2 +- packages/effect/src/unstable/ai/Tool.ts | 4 +-- .../src/unstable/http/HttpServerResponse.ts | 4 +-- 17 files changed, 60 insertions(+), 51 deletions(-) diff --git a/.agents/skills/jsdocs/SKILL.md b/.agents/skills/jsdocs/SKILL.md index 50da1b9bdf..fd15d34387 100644 --- a/.agents/skills/jsdocs/SKILL.md +++ b/.agents/skills/jsdocs/SKILL.md @@ -81,6 +81,12 @@ Use a normal multiline JSDoc comment in TypeScript source: - `**When to use**` describes the positive use case for the documented API. Do not use it as a routing section for sibling APIs. If neighboring APIs need to be mentioned, put that boundary in `@see` tag text instead. - `**When to use**` is important when the API has close alternatives, trade-offs, or `@see` tags. If `@see` tags are present, inspect the referenced APIs and add `**When to use**` when it clarifies the documented API's own use case. - `**When to use**` must start with one of these practical guidance forms: `Use to`, `Use when`, `Use as`, or `Use with`. Avoid bullet lists and vague openers such as `Use this...` or `Useful for...`. +- Prefer reader-centered `**When to use**` wording, especially `Use when you ...`, + when the sentence describes a user's goal. Avoid third-person noun-phrase + subjects such as `the input is ...`, `a service needs ...`, or + `values should ...` when they would become awkward in generated prompts. +- A good `**When to use**` sentence should still read naturally if reused as + a user intent prompt, for example after `I need ...` or `I have ...`. - Keep `short` and `**When to use**` distinct: the short description says what the API is or does; `**When to use**` says when to choose it. - Add internal `@see` tags only for semantically useful related public APIs. diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 42abd31a0b..f6726018af 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -2983,8 +2983,8 @@ export const window: { * * **When to use** * - * Use when a non-empty array is already arranged so matching elements are - * adjacent and you need a custom equivalence function. + * Use when you already have a non-empty array arranged so matching elements are + * adjacent and need a custom equivalence function. * * **Details** * diff --git a/packages/effect/src/ChannelSchema.ts b/packages/effect/src/ChannelSchema.ts index a6ddb6c240..cbce60ce07 100644 --- a/packages/effect/src/ChannelSchema.ts +++ b/packages/effect/src/ChannelSchema.ts @@ -152,8 +152,8 @@ export const decode = ( * * **When to use** * - * Use when the encoded input type is intentionally unknown or untyped, so - * that only the decoded output is statically typed according to the schema. + * Use when you need an intentionally unknown or untyped encoded input while + * keeping only the decoded output statically typed according to the schema. * * **Details** * diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index 019474968b..4ac7ee2293 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -882,7 +882,8 @@ export const getOrUndefined: { * * **When to use** * - * Use when the context type cannot prove that the service is present. + * Use when you need to read a service from a context whose type does not prove + * the service is present. * * **Details** * @@ -930,7 +931,8 @@ export const getUnsafe: { * * **When to use** * - * Use when the context type proves that the service is present. + * Use when you need type-checked access to a service already included in the + * context type. * * **Example** (Getting a service from a context) * diff --git a/packages/effect/src/Cron.ts b/packages/effect/src/Cron.ts index 477e0384dc..4bdc661bc6 100644 --- a/packages/effect/src/Cron.ts +++ b/packages/effect/src/Cron.ts @@ -632,8 +632,8 @@ export const parse = (cron: string, tz?: DateTime.TimeZone | string): Result.Res * * **When to use** * - * Use when the input is expected to be valid and you want to avoid - * handling the `Result` type. + * Use when you expect the input to be valid and want to avoid handling the + * `Result` type. * * **Example** (Parsing cron expressions unsafely) * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 423678d51a..20844d400f 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -2212,7 +2212,7 @@ export const result: (self: Effect) => Effect(schema: S, options?: AST.Pars * * **When to use** * - * Use when the input is already typed as the schema's `Encoded` type. + * Use when you already have input typed as the schema's `Encoded` type. * * **Details** * @@ -1274,8 +1274,8 @@ export const decodeEffect: ( * * **When to use** * - * Use when the input type is not statically known and decoding should return an - * `Exit` instead of failing or throwing. + * Use when you do not know the input type statically and want decoding to + * return an `Exit` instead of failing or throwing. * * **Details** * @@ -1326,7 +1326,7 @@ export const decodeExit: >( * * **When to use** * - * Use when the input type is not statically known and you only need to know + * Use when you do not know the input type statically and only need to know * whether decoding succeeded. * * **Details** @@ -1367,8 +1367,8 @@ export const decodeOption = Parser.decodeOption * * **When to use** * - * Use when the input type is not statically known and decoding should return a - * `Result` with structured issue data. + * Use when you do not know the input type statically and want decoding to + * return a `Result` with structured issue data. * * **Details** * @@ -1548,7 +1548,7 @@ export function encodeUnknownEffect(schema: S, options?: AST.Pars * * **When to use** * - * Use when the input is already typed as the schema's `Type`. + * Use when you already have input typed as the schema's `Type`. * * **Details** * @@ -1572,8 +1572,8 @@ export const encodeEffect: ( * * **When to use** * - * Use when the input type is not statically known and encoding should return an - * `Exit` instead of failing or throwing. + * Use when you do not know the input type statically and want encoding to + * return an `Exit` instead of failing or throwing. * * **Details** * @@ -1623,7 +1623,7 @@ export const encodeExit: >( * * **When to use** * - * Use when the input type is not statically known and you only need to know + * Use when you do not know the input type statically and only need to know * whether encoding succeeded. * * **Details** @@ -1664,8 +1664,8 @@ export const encodeOption = Parser.encodeOption * * **When to use** * - * Use when the input type is not statically known and encoding should return a - * `Result` with structured issue data. + * Use when you do not know the input type statically and want encoding to + * return a `Result` with structured issue data. * * **Details** * @@ -12330,8 +12330,8 @@ export function toFormatter(schema: Schema, options?: { * * **When to use** * - * Use when the default structural equivalence derived by {@link toEquivalence} - * is not appropriate for a type. + * Use when you need a custom equivalence instead of the default structural + * equivalence derived by {@link toEquivalence}. * * @category instances * @since 4.0.0 diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index 66551cc69e..db0d6cc05b 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -345,8 +345,8 @@ export function passthroughSupertype(): Getter { * * **When to use** * - * Use when the encoded type is narrower than the decoded type. - * - You need type-safe passthrough without `{ strict: false }`. + * Use when you need type-safe passthrough without `{ strict: false }` for an + * encoded type that narrows the decoded type. * * **Details** * @@ -1197,7 +1197,8 @@ export function joinKeyValue>(options?: { * * **When to use** * - * Use when an encoded string is a delimited list (e.g. CSV values). + * Use when you need to split an encoded string containing a delimited list, + * such as CSV values. * * **Details** * diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaParser.ts index 36a316e1b0..fc69eea5ef 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaParser.ts @@ -264,9 +264,9 @@ export function decodeUnknownEffect( * * **When to use** * - * Use when the input is already typed as the schema's `Encoded` type and - * decoding should stay in `Effect`, including parse failures and required - * decoding services. + * Use when you already have input typed as the schema's `Encoded` type and want + * decoding to stay in `Effect`, including parse failures and required decoding + * services. * * **Details** * @@ -318,8 +318,8 @@ export function decodeUnknownPromise>( * * **When to use** * - * Use when the input is already typed as the schema's `Encoded` type and you - * need a native `Promise` boundary. + * Use when you already have input typed as the schema's `Encoded` type and need + * a native `Promise` boundary. * * **Details** * @@ -432,8 +432,8 @@ export function decodeUnknownOption>( * * **When to use** * - * Use when the input is already typed as the schema's `Encoded` type and you - * only need to know whether decoding succeeds. + * Use when you already have input typed as the schema's `Encoded` type and only + * need to know whether decoding succeeds. * * **Details** * @@ -489,8 +489,8 @@ export function decodeUnknownResult>( * * **When to use** * - * Use when the input is already typed as the schema's `Encoded` type and you - * want schema decoding failures represented as `Result.fail`. + * Use when you already have input typed as the schema's `Encoded` type and want + * schema decoding failures represented as `Result.fail`. * * **Details** * @@ -811,8 +811,8 @@ export function encodeUnknownResult>( * * **When to use** * - * Use when the input is already typed as the schema's decoded `Type` and - * encoding failures should be returned as a `Result` instead of thrown or run in + * Use when you already have input typed as the schema's decoded `Type` and want + * encoding failures returned as a `Result` instead of thrown or run in * `Effect`. * * **Details** diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index 60537965be..7ee213a5b9 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -368,8 +368,8 @@ export function transformOrFail(options: { * * **When to use** * - * Use when the conversion cannot fail. - * - No Effect services are needed. + * Use when you need an infallible conversion that does not require Effect + * services. * * **Details** * diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index eb7327b189..a0b883dcc8 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -8417,9 +8417,9 @@ const groupByImpl = ( * * **When to use** * - * Use when a stream is already ordered by the grouping key and you want to emit - * each consecutive run as a non-empty array while keeping later non-adjacent - * runs separate. + * Use when you already have a stream ordered by the grouping key and want to + * emit each consecutive run as a non-empty array while keeping later + * non-adjacent runs separate. * * **Details** * diff --git a/packages/effect/src/Tuple.ts b/packages/effect/src/Tuple.ts index 1b1efbd823..bf7bcc9dcf 100644 --- a/packages/effect/src/Tuple.ts +++ b/packages/effect/src/Tuple.ts @@ -80,7 +80,7 @@ import type { Apply, Lambda } from "./Struct.ts" * * **When to use** * - * Use when a properly typed tuple is needed without writing `[a, b, c] as const` + * Use when you need a properly typed tuple without writing `[a, b, c] as const` * or another manual cast. * * **Details** diff --git a/packages/effect/src/unstable/ai/Tool.ts b/packages/effect/src/unstable/ai/Tool.ts index 4859485ed0..b7afac0a17 100644 --- a/packages/effect/src/unstable/ai/Tool.ts +++ b/packages/effect/src/unstable/ai/Tool.ts @@ -1318,8 +1318,8 @@ export const make = < * * **When to use** * - * Use when a tool schema is not known at compile time, such as MCP tools discovered at - * runtime or tools from external configurations. + * Use when you do not know a tool schema at compile time, such as MCP tools + * discovered at runtime or tools from external configurations. * * **Details** * diff --git a/packages/effect/src/unstable/http/HttpServerResponse.ts b/packages/effect/src/unstable/http/HttpServerResponse.ts index cbe2eb9c30..9cd40d559c 100644 --- a/packages/effect/src/unstable/http/HttpServerResponse.ts +++ b/packages/effect/src/unstable/http/HttpServerResponse.ts @@ -421,8 +421,8 @@ export const urlParams = ( * * **When to use** * - * Use when the underlying runtime already understands the body value, such - * as a Web `Response`, `Blob`, or `ReadableStream`; the body is passed through + * Use when you want to pass through a body value already understood by the + * underlying runtime, such as a Web `Response`, `Blob`, or `ReadableStream`, * for later platform conversion. * * @category constructors From ae6085e048e018802fc8f9bebf0dbad05adf8049 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Thu, 28 May 2026 22:28:20 +0200 Subject: [PATCH 07/29] wip --- packages/ai/anthropic/src/AnthropicConfig.ts | 4 +- .../anthropic/src/AnthropicLanguageModel.ts | 17 +++--- packages/ai/anthropic/src/AnthropicTool.ts | 47 +++++++------- packages/ai/openai/src/OpenAiConfig.ts | 4 +- .../ai/openrouter/src/OpenRouterConfig.ts | 4 +- .../openrouter/src/OpenRouterLanguageModel.ts | 4 +- packages/effect/src/Array.ts | 60 ++++++++++++------ packages/effect/src/ConfigProvider.ts | 5 +- packages/effect/src/Context.ts | 2 +- packages/effect/src/Equivalence.ts | 61 ++++++------------- packages/effect/src/Latch.ts | 2 +- packages/effect/src/Layer.ts | 3 +- packages/effect/src/Metric.ts | 24 ++++---- packages/effect/src/Option.ts | 13 ++-- packages/effect/src/PartitionedSemaphore.ts | 8 +-- packages/effect/src/SchemaGetter.ts | 3 +- packages/effect/src/SchemaIssue.ts | 6 +- packages/effect/src/SchemaTransformation.ts | 11 ++-- packages/effect/src/Semaphore.ts | 6 +- packages/effect/src/Sink.ts | 3 +- packages/effect/src/SynchronizedRef.ts | 2 +- packages/effect/src/UndefinedOr.ts | 4 +- packages/effect/src/unstable/ai/Tool.ts | 3 +- 23 files changed, 150 insertions(+), 146 deletions(-) diff --git a/packages/ai/anthropic/src/AnthropicConfig.ts b/packages/ai/anthropic/src/AnthropicConfig.ts index 101867b3db..311819a575 100644 --- a/packages/ai/anthropic/src/AnthropicConfig.ts +++ b/packages/ai/anthropic/src/AnthropicConfig.ts @@ -29,8 +29,8 @@ import type { HttpClient } from "effect/unstable/http/HttpClient" * * **When to use** * - * Use when a layer or integration needs to provide or read Anthropic client - * configuration through Effect's context. + * Use when you need to provide or read Anthropic client configuration through + * Effect's context from a layer or integration. * * @see {@link withClientTransform} for scoping an HTTP client transformation * diff --git a/packages/ai/anthropic/src/AnthropicLanguageModel.ts b/packages/ai/anthropic/src/AnthropicLanguageModel.ts index 752bff242c..c00037eecf 100644 --- a/packages/ai/anthropic/src/AnthropicLanguageModel.ts +++ b/packages/ai/anthropic/src/AnthropicLanguageModel.ts @@ -7,13 +7,12 @@ * * **When to use** * - * Use when create an Anthropic-backed model with {@link model} - * - Build or provide a `LanguageModel.LanguageModel` layer with {@link layer} - * or {@link make} - * - Supply default request options through {@link Config} - * - Override configuration for a scoped operation with {@link withConfigOverride} - * - Attach Anthropic provider options for prompt caching, document citations, - * reasoning signatures, MCP metadata, and server-side tools + * Use when you need an Anthropic-backed model. Create a model with {@link model}, + * build or provide a `LanguageModel.LanguageModel` layer with {@link layer} or + * {@link make}, supply default request options through {@link Config}, override + * configuration for a scoped operation with {@link withConfigOverride}, or attach + * Anthropic provider options for prompt caching, document citations, reasoning + * signatures, MCP metadata, and server-side tools. * * **Gotchas** * @@ -669,8 +668,8 @@ export const model = ( * * **When to use** * - * Use when an Effect needs to construct a `LanguageModel.Service` value backed - * by `AnthropicClient`. + * Use when you need to construct a `LanguageModel.Service` value backed by + * `AnthropicClient` inside an Effect. * * **Details** * diff --git a/packages/ai/anthropic/src/AnthropicTool.ts b/packages/ai/anthropic/src/AnthropicTool.ts index b168c167e5..edeb55d3a7 100644 --- a/packages/ai/anthropic/src/AnthropicTool.ts +++ b/packages/ai/anthropic/src/AnthropicTool.ts @@ -104,8 +104,8 @@ export type AnthropicTool = * * **When to use** * - * Use when you need the model to execute bash commands and require the 2024-10-22 - * version of the Anthropic computer-use beta. + * Use when you want the model to execute bash commands with the 2024-10-22 + * Anthropic computer-use beta. * * **Details** * @@ -134,8 +134,8 @@ export const Bash_20241022 = Tool.providerDefined({ * * **When to use** * - * Use when you need the model to execute bash commands and require the 2025-01-24 - * version of the Anthropic computer-use beta. + * Use when you want the model to execute bash commands with the 2025-01-24 + * Anthropic computer-use beta. * * **Details** * @@ -442,8 +442,8 @@ export type CodeExecution_20250825_Parameters = typeof CodeExecution_20250825_Pa * * **When to use** * - * Use when you need the model to execute code in a sandboxed environment and - * require the 2025-05-22 version of the Anthropic code-execution beta. + * Use when you want the model to execute code in a sandboxed environment with + * the 2025-05-22 Anthropic code-execution beta. * * **Details** * @@ -470,8 +470,8 @@ export const CodeExecution_20250522 = Tool.providerDefined({ * * **When to use** * - * Use when you need the model to execute code in a sandboxed environment and - * require the 2025-08-25 version of the Anthropic code-execution beta. + * Use when you want the model to execute code in a sandboxed environment with + * the 2025-08-25 Anthropic code-execution beta. * * **Details** * @@ -1322,7 +1322,7 @@ export const ComputerUse_20241022 = Tool.providerDefined({ * * **When to use** * - * Use when configuring Anthropic computer use for Claude 4 models or Claude + * Use when you need Anthropic computer use for Claude 4 models or Claude * Sonnet 3.7 with the 2025-01-24 action set. * * **Details** @@ -1353,7 +1353,7 @@ export const ComputerUse_20250124 = Tool.providerDefined({ * * **When to use** * - * Use when configuring Anthropic computer use for Claude Opus 4.5 with the + * Use when you need Anthropic computer use for Claude Opus 4.5 with the * 2025-11-24 action set and zoom-capable screen inspection. * * **Details** @@ -1902,8 +1902,8 @@ const TextEditor_StrReplaceBasedEdit_Args = Schema.Struct({ * * **When to use** * - * Use when configuring the 2024-10-22 `str_replace_editor` compatibility path - * for Claude 3.5 Sonnet. + * Use when you need the 2024-10-22 `str_replace_editor` compatibility path for + * Claude 3.5 Sonnet. * * **Details** * @@ -1930,7 +1930,7 @@ export const TextEditor_20241022 = Tool.providerDefined({ * * **When to use** * - * Use when configuring the 2025-01-24 Claude Sonnet 3.7 text editor tool using + * Use when you need the 2025-01-24 Claude Sonnet 3.7 text editor tool using * `str_replace_editor`. * * **Details** @@ -1958,7 +1958,7 @@ export const TextEditor_20250124 = Tool.providerDefined({ * * **When to use** * - * Use when configuring the 2025-04-29 Claude 4 `str_replace_based_edit_tool` + * Use when you need the 2025-04-29 Claude 4 `str_replace_based_edit_tool` * version. * * **Details** @@ -2023,8 +2023,8 @@ export const TextEditor_20250728 = Tool.providerDefined({ * * **When to use** * - * Use when providing location helps return more relevant results for - * location-dependent queries like weather, local businesses, or events. + * Use when you need to localize search results for location-dependent queries + * like weather, local businesses, or events. * * **Details** * @@ -2069,8 +2069,8 @@ export const WebSearchUserLocation = Schema.Struct({ * * **When to use** * - * Use when configuring `WebSearch_20250305` with search limits, domain filters, - * or user location. + * Use when you need to configure `WebSearch_20250305` with search limits, + * domain filters, or user location. * * **Details** * @@ -2167,7 +2167,7 @@ export type WebSearchParameters = typeof WebSearchParameters.Type * * **When to use** * - * Use when Claude should search the web for real-time information. + * Use when you want Claude to search the web for real-time information. * * **Details** * @@ -2203,7 +2203,7 @@ export const WebSearch_20250305 = Tool.providerDefined({ * * **When to use** * - * Use when configuring whether web fetch results should include citations. + * Use when you need to enable or disable citations on web fetch results. * * **Details** * @@ -2245,8 +2245,8 @@ export type WebFetchCitationsConfig = typeof WebFetchCitationsConfig.Type * * **When to use** * - * Use when configuring `WebFetch_20250910` with usage limits, domain filters, - * citations, or content token limits. + * Use when you need to configure `WebFetch_20250910` with usage limits, domain + * filters, citations, or content token limits. * * **Details** * @@ -2364,7 +2364,8 @@ export type WebFetchParameters = typeof WebFetchParameters.Type * * **When to use** * - * Use when Claude should retrieve the content of a specific web page or PDF. + * Use when you want Claude to retrieve the content of a specific web page or + * PDF. * * **Details** * diff --git a/packages/ai/openai/src/OpenAiConfig.ts b/packages/ai/openai/src/OpenAiConfig.ts index 02cc86ac14..afdcc9532d 100644 --- a/packages/ai/openai/src/OpenAiConfig.ts +++ b/packages/ai/openai/src/OpenAiConfig.ts @@ -88,8 +88,8 @@ export declare namespace OpenAiConfig { * * **When to use** * - * Use when a single effect or workflow needs temporary OpenAI HTTP client - * customization without rebuilding the client layer. + * Use when you need temporary OpenAI HTTP client customization for a single + * effect or workflow without rebuilding the client layer. * * **Details** * diff --git a/packages/ai/openrouter/src/OpenRouterConfig.ts b/packages/ai/openrouter/src/OpenRouterConfig.ts index 7e6774e429..edfa2ee20e 100644 --- a/packages/ai/openrouter/src/OpenRouterConfig.ts +++ b/packages/ai/openrouter/src/OpenRouterConfig.ts @@ -90,8 +90,8 @@ export declare namespace OpenRouterConfig { * * **When to use** * - * Use when a single effect or workflow needs temporary OpenRouter HTTP client - * customization without rebuilding the client layer. + * Use when you need temporary OpenRouter HTTP client customization for a + * single effect or workflow without rebuilding the client layer. * * **Details** * diff --git a/packages/ai/openrouter/src/OpenRouterLanguageModel.ts b/packages/ai/openrouter/src/OpenRouterLanguageModel.ts index f2ef7d9f32..56bd4a1216 100644 --- a/packages/ai/openrouter/src/OpenRouterLanguageModel.ts +++ b/packages/ai/openrouter/src/OpenRouterLanguageModel.ts @@ -548,8 +548,8 @@ export const model = ( * * **When to use** * - * Use when an Effect needs to construct a `LanguageModel.Service` value backed - * by `OpenRouterClient`. + * Use when you need to construct a `LanguageModel.Service` value backed by + * `OpenRouterClient` inside an Effect. * * **Details** * diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index f6726018af..3c47c14866 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -222,9 +222,11 @@ export const make = >( * * **When to use** * - * Use when you need a pre-sized array and will fill it imperatively. - * - Elements are typed as `A | undefined` since slots are empty. - * - Prefer {@link makeBy} when you can compute each element from its index. + * Use when you need a pre-sized array that you will fill imperatively. + * + * **Details** + * + * Elements are typed as `A | undefined` because the slots are empty. * * **Example** (Allocating a fixed-size array) * @@ -247,9 +249,13 @@ export const allocate = (n: number): Array => new Arra * * **When to use** * - * Use when you need an array whose values depend on the index. - * - `n` is normalized to an integer >= 1 — always returns at least one element. - * - Supports both data-first and data-last usage. + * Use when you need to compute each array element from its index. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to 1, so this function + * always returns at least one element. Supports both data-first and data-last + * usage. * * **Example** (Generating values from indices) * @@ -284,9 +290,11 @@ export const makeBy: { * * **When to use** * - * Use when you need a sequence of consecutive integers. - * - If `start > end`, returns `[start]`. - * - Always returns a `NonEmptyArray`. + * Use when you need a non-empty sequence of consecutive integers. + * + * **Details** + * + * If `start > end`, returns `[start]`. * * **Example** (Creating a range) * @@ -310,9 +318,13 @@ export const range = (start: number, end: number): NonEmptyArray => * * **When to use** * - * Use when you need multiple copies of the same value. - * - `n` is normalized to an integer >= 1 — always returns at least one element. - * - Supports both data-first and data-last usage. + * Use when you need a non-empty array containing repeated copies of one value. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to 1, so this function + * always returns at least one element. Supports both data-first and data-last + * usage. * * **Example** (Repeating a value) * @@ -454,9 +466,12 @@ export const fromOption: (self: Option.Option) => Array = Option.toArra * * **When to use** * - * Use when you need to branch on whether an array has elements. - * - `onNonEmpty` receives a `NonEmptyReadonlyArray`. - * - Dual: data-first or data-last. + * Use when you need to branch on whether an array is empty. + * + * **Details** + * + * `onNonEmpty` receives a `NonEmptyReadonlyArray`. Supports both data-first and + * data-last usage. * * **Example** (Branching on emptiness) * @@ -3033,8 +3048,8 @@ export const groupWith: { * * **When to use** * - * Use when equal values are already adjacent and Effect's default equality is - * the right comparison. + * Use when you already have adjacent equal values and Effect's default equality + * is the right comparison. * * **Details** * @@ -4690,9 +4705,14 @@ export const cartesian: { * * **When to use** * - * Use when beginning a do-notation pipeline, then use {@link bind} to introduce array variables and {@link let_ let} for plain values. - * - Each `bind` produces the cartesian product of all bound variables (like nested loops). - * - Use `filter` and `map` in the pipeline to add conditions and transformations. + * Use when you want array-comprehension style code with do notation. + * + * **Details** + * + * Use {@link bind} to introduce array variables and {@link let_ let} for plain + * values. Each `bind` produces the cartesian product of all bound variables, + * like nested loops. Use `filter` and `map` in the pipeline to add conditions + * and transformations. * * **Example** (Array comprehension with do notation) * diff --git a/packages/effect/src/ConfigProvider.ts b/packages/effect/src/ConfigProvider.ts index c4ae486c5a..75bdf50f95 100644 --- a/packages/effect/src/ConfigProvider.ts +++ b/packages/effect/src/ConfigProvider.ts @@ -736,8 +736,9 @@ export const layerAdd = ( * * **When to use** * - * Use when unit or integration tests need deterministic config without touching the - * environment, or when config is embedded directly in code or read from a JSON file. + * Use when you need deterministic config for unit or integration tests without + * touching the environment, or when config is embedded directly in code or read + * from a JSON file. * * **Details** * diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index 4ac7ee2293..3ab81746ee 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -741,7 +741,7 @@ export const add: { * * **When to use** * - * Use when service presence is already represented as an `Option`. + * Use when you already have service presence represented as an `Option`. * * **Details** * diff --git a/packages/effect/src/Equivalence.ts b/packages/effect/src/Equivalence.ts index f0afb6b984..f658d94337 100644 --- a/packages/effect/src/Equivalence.ts +++ b/packages/effect/src/Equivalence.ts @@ -60,9 +60,7 @@ import * as Reducer from "./Reducer.ts" * * **When to use** * - * Use as a type annotation for equivalence functions - * - Use when implementing custom equivalence logic - * - Use when working with collection operations that require equivalence relations + * Use as a type annotation when you accept or return an equivalence function. * * **Details** * @@ -108,9 +106,7 @@ export type Equivalence = (self: A, that: A) => boolean * * **When to use** * - * Use when rarely needed in application code - * - Use primarily for internal type system operations and HKT (Higher-Kinded Types) abstractions - * - Use when working with generic type constructors that require type lambdas + * Use when you need to abstract over `Equivalence` in higher-kinded type code. * * **Details** * @@ -147,9 +143,7 @@ export interface EquivalenceTypeLambda extends TypeLambda { * * **When to use** * - * Use when you need a custom equivalence that is not just strict equality - * - Use when creating equivalences for complex types with custom comparison logic - * - Use when you want the performance benefit of reference equality optimization + * Use when you need a custom equivalence relation. * * **Details** * @@ -200,16 +194,15 @@ const isStrictEquivalent = (x: unknown, y: unknown) => x === y * * **When to use** * - * Use when you need primitive types where `===` is appropriate - * - Use when you need reference equality for objects - * - Use as a building block for more complex equivalences via {@link mapInput} or {@link combine} - * - Use when performance is critical and you do not need structural equality + * Use when JavaScript strict equality is the intended comparison. * * **Details** * * - Uses JavaScript's strict equality operator (`===`) * - For primitives: compares values directly * - For objects: compares by reference, so only the same object instance is equivalent + * - Can be used as a building block for more complex equivalences via + * {@link mapInput} or {@link combine} * * **Gotchas** * @@ -343,9 +336,7 @@ export const BigInt: Equivalence = isStrictEquivalent * * **When to use** * - * Use when you need to combine exactly two equivalences - * - Use when building complex equivalences from simpler ones - * - Use when you want both conditions to be satisfied + * Use when you need to combine exactly two equivalences with AND semantics. * * **Details** * @@ -398,10 +389,7 @@ export const combine: { * * **When to use** * - * Use when you need to combine three or more equivalences - * - Use when you have a dynamic collection of equivalences to combine - * - Use when building equivalences from arrays or iterables - * - Prefer this over multiple `combine` calls when you have many equivalences + * Use when you need to combine many equivalences from an iterable. * * **Details** * @@ -474,10 +462,7 @@ export const combineAll = (collection: Iterable>): Equivalence * * **When to use** * - * Use when you need an equivalence for a complex type based on a single property - * - Use when you want to normalize values before comparison, such as case-insensitive strings - * - Use when creating equivalences that focus on specific fields of objects - * - Use as a building block for creating equivalences via {@link combine} or {@link combineAll} + * Use when you need an equivalence for one type by comparing a derived value. * * **Details** * @@ -485,6 +470,8 @@ export const combineAll = (collection: Iterable>): Equivalence * - The transformation function should be pure and have no side effects * - The resulting equivalence compares the transformed values using the provided equivalence * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * - Useful for comparing by one property or normalizing values before + * comparison, such as case-insensitive strings * * **Example** (Equivalence based on object property) * @@ -543,10 +530,8 @@ export const mapInput: { * * **When to use** * - * Use when comparing tuples with different types at each position - * - Use when you need different equivalence logic for each tuple element - * - Use when working with fixed-length tuples instead of arrays - * - Prefer this over `Array` when you have a known tuple structure with different types + * Use when you need to compare fixed-length tuples with per-position + * equivalences. * * **Details** * @@ -634,10 +619,7 @@ export { * * **When to use** * - * Use when comparing arrays with homogeneous element types - * - Use when all elements should use the same equivalence logic - * - Use when working with variable-length arrays instead of fixed tuples - * - Prefer this over `Tuple` when you have arrays of the same type + * Use when you need to compare arrays with one equivalence for every element. * * **Details** * @@ -688,10 +670,7 @@ export { * * **When to use** * - * Use when comparing objects with known, fixed property names - * - Use when you need different equivalence logic for different properties - * - Use when working with struct or interface types with specific fields - * - Prefer this over `Record` when you have a fixed set of known properties + * Use when you need to compare objects with known, fixed property names. * * **Details** * @@ -770,10 +749,8 @@ export function Struct>>( * * **When to use** * - * Use when comparing objects with dynamic or unknown property names - * - Use when all property values should use the same equivalence logic - * - Use when working with record or dictionary types - * - Prefer this over `Struct` when you have variable properties or need to compare all properties uniformly + * Use when you need to compare records with the same equivalence for every + * property value. * * **Details** * @@ -841,9 +818,7 @@ export function Record(value: Equivalence): Equivalence(self: Layer): Layer => * * **When to use** * - * Use when your entire application is a layer, such as an HTTP server. + * Use when you model your entire application as a layer, such as an HTTP + * server. * * **Details** * diff --git a/packages/effect/src/Metric.ts b/packages/effect/src/Metric.ts index 7c837b784d..2f88589d70 100644 --- a/packages/effect/src/Metric.ts +++ b/packages/effect/src/Metric.ts @@ -1765,8 +1765,8 @@ const MetricRegistryKey = "~effect/observability/Metric/MetricRegistryKey" * * **When to use** * - * Use to provide a custom metric registry for a program or test that needs - * metrics isolated from the default registry. + * Use when you need a custom metric registry for an isolated program or test + * instead of the default registry. * * **Details** * @@ -2272,8 +2272,8 @@ export const counter: { * * **When to use** * - * Use when gauges are most suitable for metrics that represent instantaneous values, - * such as memory usage or CPU load. + * Use when you need a metric for instantaneous values, such as memory usage or + * CPU load. * * **Details** * @@ -2351,8 +2351,8 @@ export const gauge: { * * **When to use** * - * Use when frequency metrics are most suitable for counting the number of times a - * specific event or incident occurs. + * Use when you need a metric for counting how often a specific event or + * incident occurs. * * **Details** * @@ -2434,8 +2434,8 @@ export const frequency = (name: string, options?: { * * **When to use** * - * Use when histogram metrics are most suitable for measuring the distribution of values - * within a range. + * Use when you need a metric for measuring the distribution of values within a + * range. * * **Details** * @@ -2514,8 +2514,8 @@ export const histogram = (name: string, options: { * * **When to use** * - * Use when summary metrics are most suitable for providing statistical information about - * a set of values, including quantiles. + * Use when you need a metric that records statistical information about a set + * of values, including quantiles. * * **Details** * @@ -2610,8 +2610,8 @@ export const summary = (name: string, options: { * * **When to use** * - * Use when summary metrics are most suitable for statistical information about a set of - * values. + * Use when you need a metric that records statistical information about a set + * of values together with timestamps. * * **Details** * diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index f6ba60c148..901481a435 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -886,7 +886,8 @@ export const fromNullishOr = ( * * **When to use** * - * Use when `null` is a meaningful value but `undefined` means absent + * Use when you want to treat only `undefined` as absent while preserving `null` + * as a meaningful value. * * **Details** * @@ -924,7 +925,8 @@ export const fromUndefinedOr = ( * * **When to use** * - * Use when `undefined` is a meaningful value but `null` means absent + * Use when you want to treat only `null` as absent while preserving + * `undefined` as a meaningful value. * * **Details** * @@ -1110,8 +1112,8 @@ export const liftThrowable = , B>( * * **When to use** * - * Use when fail-fast unwrapping when absence is unexpected - * - Providing a descriptive error for debugging + * Use when you need fail-fast unwrapping for unexpected absence and want to + * provide a descriptive debugging error. * * **Details** * @@ -1151,7 +1153,8 @@ export const getOrThrowWith: { * * **When to use** * - * Use when quick fail-fast unwrapping when a generic error is acceptable + * Use when you need quick fail-fast unwrapping and a generic error is + * acceptable. * * **Details** * diff --git a/packages/effect/src/PartitionedSemaphore.ts b/packages/effect/src/PartitionedSemaphore.ts index 2cab39aee0..3b15ba3c52 100644 --- a/packages/effect/src/PartitionedSemaphore.ts +++ b/packages/effect/src/PartitionedSemaphore.ts @@ -405,8 +405,8 @@ export const capacity = (self: PartitionedSemaphore): number => self.capac * * **When to use** * - * Use to manually acquire permits for a partition when acquisition and release - * must be controlled as separate effects. + * Use when you need manual permit acquisition for a partition and want to + * control acquisition and release as separate effects. * * **Details** * @@ -437,8 +437,8 @@ export const take: { * * **When to use** * - * Use to manually return permits acquired with `take` for a lower-level - * partitioned permit protocol that needs explicit release control. + * Use when you need to return permits acquired with `take` in a lower-level + * partitioned permit protocol with explicit release control. * * **Details** * diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index db0d6cc05b..a6a8482b3a 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -1114,7 +1114,8 @@ export function stringifyJson(options?: StringifyJsonOptions): Getter(check: AST.Check): string { * * **When to use** * - * Use when produce error messages for logging, CLI output, or developer-facing - * diagnostics. - * - This is the default formatter used by `Issue.toString()`. + * Use when you need error messages for logging, CLI output, or + * developer-facing diagnostics. This is the default formatter used by + * `Issue.toString()`. * * **Details** * diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index 7ee213a5b9..e32970469b 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -811,7 +811,8 @@ export function passthroughSupertype(): Transformation { * * **When to use** * - * Use when narrowing: the encoded side is more specific than the decoded side. + * Use when you need a no-op transformation whose encoded side is more specific + * than its decoded side. * * **Details** * @@ -1032,8 +1033,8 @@ export const durationFromNanos: Transformation = tran * * **When to use** * - * Use when timeouts, delays, elapsed intervals, or other duration values are stored as - * millisecond counts. + * Use when you need to decode timeouts, delays, elapsed intervals, or other + * duration values stored as millisecond counts. * * **Details** * @@ -1550,8 +1551,8 @@ export const stringFromUriComponent: Transformation = new Transf * * **When to use** * - * Use when JSON is stored or transmitted as a string, usually before composing with another - * schema that validates the parsed structure. + * Use when you need to decode JSON stored or transmitted as a string, usually + * before composing with another schema that validates the parsed structure. * * **Details** * diff --git a/packages/effect/src/Semaphore.ts b/packages/effect/src/Semaphore.ts index b06f3001a1..e0f8cf4686 100644 --- a/packages/effect/src/Semaphore.ts +++ b/packages/effect/src/Semaphore.ts @@ -469,7 +469,7 @@ export const withPermitsIfAvailable: { * * **When to use** * - * Use to manually acquire permits for a lower-level permit protocol that needs + * Use when you need manual permit acquisition for a lower-level protocol with * explicit acquisition and release control. * * **Details** @@ -494,8 +494,8 @@ export const take: { * * **When to use** * - * Use to manually return permits acquired with `take` for a lower-level permit - * protocol that needs explicit release control. + * Use when you need to return permits acquired with `take` in a lower-level + * permit protocol with explicit release control. * * **Details** * diff --git a/packages/effect/src/Sink.ts b/packages/effect/src/Sink.ts index 729668ff89..a4e1467acb 100644 --- a/packages/effect/src/Sink.ts +++ b/packages/effect/src/Sink.ts @@ -1444,7 +1444,8 @@ const last_ = reduceArray(Option.none, (_, arr) => Arr.last(arr)) * * **When to use** * - * Use when consuming all upstream input and only the final element is needed. + * Use when you need to consume all upstream input and keep only the final + * element. * * **Details** * diff --git a/packages/effect/src/SynchronizedRef.ts b/packages/effect/src/SynchronizedRef.ts index c9175fa409..64183fb0e3 100644 --- a/packages/effect/src/SynchronizedRef.ts +++ b/packages/effect/src/SynchronizedRef.ts @@ -69,7 +69,7 @@ const Proto = { * * **When to use** * - * Use when synchronous construction is required outside an Effect workflow. + * Use when you need synchronous construction outside an Effect workflow. * * @category constructors * @since 4.0.0 diff --git a/packages/effect/src/UndefinedOr.ts b/packages/effect/src/UndefinedOr.ts index ee814a4151..ec1d65bb5a 100644 --- a/packages/effect/src/UndefinedOr.ts +++ b/packages/effect/src/UndefinedOr.ts @@ -118,8 +118,8 @@ export const match: { * * **When to use** * - * Use when fail-fast unwrapping of an `A | undefined` value is appropriate and - * callers need to provide the thrown error for the undefined case. + * Use when you need fail-fast unwrapping of an `A | undefined` value and want + * to provide the thrown error for the undefined case. * * **Details** * diff --git a/packages/effect/src/unstable/ai/Tool.ts b/packages/effect/src/unstable/ai/Tool.ts index b7afac0a17..ded2f171d4 100644 --- a/packages/effect/src/unstable/ai/Tool.ts +++ b/packages/effect/src/unstable/ai/Tool.ts @@ -1987,7 +1987,8 @@ function filter(obj: any) { * * **When to use** * - * Use when thrown parse and security failures are acceptable. + * Use when you need a JSON parser that throws for invalid JSON or unsafe + * object shapes. * * **Gotchas** * From f4a5573a8544afe7a084e3458b58b5fd14fe4f8d Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 00:50:22 +0200 Subject: [PATCH 08/29] wip --- packages/effect/src/Array.ts | 2 +- packages/effect/src/Cause.ts | 22 ++--- packages/effect/src/Config.ts | 39 ++++---- packages/effect/src/ConfigProvider.ts | 14 +-- packages/effect/src/Context.ts | 4 +- packages/effect/src/Data.ts | 5 +- packages/effect/src/DateTime.ts | 4 +- packages/effect/src/Effect.ts | 32 +++--- packages/effect/src/Equal.ts | 17 ++-- packages/effect/src/Equivalence.ts | 2 +- packages/effect/src/Exit.ts | 3 +- packages/effect/src/JsonPointer.ts | 8 +- packages/effect/src/Layer.ts | 10 +- packages/effect/src/Order.ts | 99 +++++-------------- packages/effect/src/SchemaGetter.ts | 4 +- packages/effect/src/SchemaTransformation.ts | 4 +- packages/effect/src/Struct.ts | 4 +- packages/effect/src/unstable/cli/Param.ts | 3 +- .../effect/src/unstable/http/HttpRouter.ts | 2 +- .../src/unstable/httpapi/HttpApiMiddleware.ts | 6 +- .../src/unstable/rpc/RpcSerialization.ts | 4 +- packages/opentelemetry/src/Tracer.ts | 5 +- .../platform-browser/src/BrowserHttpClient.ts | 4 +- .../src/BrowserWorkerRunner.ts | 4 +- 24 files changed, 116 insertions(+), 185 deletions(-) diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 3c47c14866..3d1679f59e 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -4227,7 +4227,7 @@ export const some: { * * **When to use** * - * Use when a computation depends on every suffix of an array, such as + * Use when you need to compute a result from every suffix of an array, such as * cumulative aggregations from each position. * * **Details** diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index 60cd102c74..b946dba4a6 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -688,8 +688,7 @@ export const makeInterruptReason: (fiberId?: number | undefined) => Interrupt = * * **When to use** * - * Use when deciding whether a failure was entirely due to interruption and - * can be silently discarded. + * Use when you need to detect failures caused only by interruption. * * **Example** (checking interrupt-only causes) * @@ -965,7 +964,7 @@ export const hasDies: (self: Cause) => boolean = effect.hasDies * * **When to use** * - * Use when you use {@link findDefect} if you only need the unwrapped defect value. + * Use when you need the full `Die` reason, including annotations. * * **Example** (extracting the first Die reason) * @@ -993,8 +992,7 @@ export const findDie: (self: Cause) => Result.Result> = effe * * **When to use** * - * Use when you use {@link findDie} if you need the full `Die` reason (including - * annotations). + * Use when you only need the unwrapped defect value. * * **Example** (extracting the first defect) * @@ -1071,8 +1069,8 @@ export const findInterrupt: (self: Cause) => Result.Result(self: Cause) => ReadonlySet = effect.c * * **When to use** * - * Use when the absence of interrupt reasons should be represented as a failed `Result` - * containing the original cause. + * Use when you need absence of interrupt reasons to fail with the original + * cause. * * **Gotchas** * @@ -1445,7 +1443,7 @@ export const Done: (value?: A) => Done = core.Done * * **When to use** * - * Use when effect workflows model stream or queue completion through the error channel. + * Use when you model stream or queue completion through the error channel. * * **Example** (failing with Done) * @@ -1984,8 +1982,8 @@ export class StackTrace extends Context.Service()("effec * * **When to use** * - * Use when attaching or reading the stack-frame annotation consumed by - * interrupt-only cause rendering. + * Use when you need the stack-frame annotation used by interrupt-only cause + * rendering. * * **Details** * diff --git a/packages/effect/src/Config.ts b/packages/effect/src/Config.ts index d0c1df2ebe..d7fb364a55 100644 --- a/packages/effect/src/Config.ts +++ b/packages/effect/src/Config.ts @@ -93,8 +93,8 @@ const TypeId = "~effect/Config" * * **When to use** * - * Use when runtime type-checking before calling `.parse()` on an unknown value. - * - Distinguishing a `Config` from a plain value inside {@link unwrap}. + * Use when you need to distinguish a `Config` from an unknown value before + * calling `.parse` or {@link unwrap}. * * **Example** (Type guard) * @@ -115,9 +115,7 @@ export const isConfig = (u: unknown): u is Config => Predicate.hasPrope * * **When to use** * - * Use when match on `error.cause._tag` to distinguish source failures from - * validation failures. - * - Pass to {@link fail} to create a Config that always errors. + * Use when you need to inspect config loading or validation failures. * * **Details** * @@ -238,8 +236,8 @@ export function make( * * **When to use** * - * Use when post-processing a config value (e.g. trimming, uppercasing, wrapping) - * with a transformation that cannot fail. + * Use when you need to transform a parsed config value with a function that + * cannot fail. * * **Details** * @@ -275,8 +273,8 @@ export const map: { * * **When to use** * - * Use to validate or converting a config value where the transformation can - * produce a `ConfigError` (e.g. parsing a URL, checking a range). + * Use when you need to transform a parsed config value with a function that can + * produce a `ConfigError` (e.g. parsing a URL, checking a range). * * **Details** * @@ -309,8 +307,8 @@ export const mapOrFail: { * * **When to use** * - * Use when trying an alternative config source when the primary one errors. - * - Providing environment-specific overrides. + * Use when you need to try an alternative config source after the primary one + * fails. * * **Details** * @@ -347,7 +345,7 @@ export const orElse: { * * **When to use** * - * Use when grouping related configs into a tuple or named struct. + * Use when you need to group related configs into a tuple or named struct. * * **Details** * @@ -427,7 +425,7 @@ function isMissingDataOnly(issue: Issue.Issue): boolean { * * **When to use** * - * Use when making a config key optional with a sensible default. + * Use when you need to make a config key optional with a sensible default. * * **Details** * @@ -478,8 +476,7 @@ export const withDefault: { * * **When to use** * - * Use when a config key may or may not be present and you want to handle both - * cases explicitly. + * Use when you need to handle a config key that may or may not be present. * * **Gotchas** * @@ -886,8 +883,8 @@ export const Record = (key: K * * **When to use** * - * Use when inside {@link orElse} to re-raise a specific error. - * - Testing error handling paths. + * Use when you need to re-raise a specific config error, such as inside + * {@link orElse}. * * @category constructors * @since 2.0.0 @@ -902,8 +899,8 @@ export function fail(err: SourceError | Schema.SchemaError) { * * **When to use** * - * Use when providing a hardcoded constant inside {@link orElse}. - * - Testing. + * Use when you need a hardcoded config value, such as inside {@link orElse} or + * tests. * * **Example** (Constant fallback) * @@ -1416,9 +1413,7 @@ export function date(name?: string) { * * **When to use** * - * Use when grouping related config keys under a common namespace (e.g. - * `"database"`, `"redis"`). - * - Building reusable config fragments that callers nest at different paths. + * Use when you need to group related config keys under a common namespace. * * **Details** * diff --git a/packages/effect/src/ConfigProvider.ts b/packages/effect/src/ConfigProvider.ts index 75bdf50f95..035ca2bed0 100644 --- a/packages/effect/src/ConfigProvider.ts +++ b/packages/effect/src/ConfigProvider.ts @@ -173,7 +173,7 @@ export function makeValue(value: string): Node { * * **When to use** * - * Use when describing a directory or JSON object inside a custom + * Use when you need to describe a directory or JSON object inside a custom * provider. * * **Details** @@ -207,8 +207,8 @@ export function makeRecord(keys: ReadonlySet, value?: string): Node { * * **When to use** * - * Use when describing a JSON array or a set of numerically-indexed env - * vars inside a custom provider. + * Use when you need to describe a JSON array or numerically indexed env vars + * inside a custom provider. * * **Details** * @@ -515,8 +515,8 @@ export const orElse: { * * **When to use** * - * Use when path segments need renaming, re-casing, suffixes, or other per-segment - * transformations. See {@link constantCase} for a common specialization. + * Use when you need to rename, re-case, or otherwise transform config path + * segments before lookup. * * **Details** * @@ -1128,8 +1128,8 @@ export const fromDotEnv: (options?: { * * **When to use** * - * Use when Kubernetes ConfigMap or Secret volume mounts expose each key as a file under a - * mount path, or for any file-per-key configuration layout. + * Use when you expose each config key as a file under a directory, such as + * Kubernetes ConfigMap or Secret volume mounts. * * **Details** * diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index 3ab81746ee..f9f32ab11a 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -1092,7 +1092,7 @@ export const getOption: { * * **When to use** * - * Use when combining two contexts. + * Use when you need to combine two contexts. * * **Details** * @@ -1138,7 +1138,7 @@ export const merge: { * * **When to use** * - * Use when combining a variadic list of contexts. + * Use when you need to combine a variadic list of contexts. * * **Details** * diff --git a/packages/effect/src/Data.ts b/packages/effect/src/Data.ts index c8cfdfb4bf..e741558ed9 100644 --- a/packages/effect/src/Data.ts +++ b/packages/effect/src/Data.ts @@ -751,7 +751,7 @@ function taggedMatch< * * **When to use** * - * Use when defining yieldable errors that do **not** need tag-based + * Use when you need yieldable errors that do **not** need tag-based * discrimination. * * **Details** @@ -794,8 +794,7 @@ export const Error: new = {}>( * * **When to use** * - * Use when modeling domain errors in Effect applications where you want - * discriminated-union error handling. + * Use when you need domain errors with discriminated-union handling. * * **Details** * diff --git a/packages/effect/src/DateTime.ts b/packages/effect/src/DateTime.ts index cbab7a651f..d3e47fdca5 100644 --- a/packages/effect/src/DateTime.ts +++ b/packages/effect/src/DateTime.ts @@ -477,8 +477,8 @@ export const isTimeZone: (u: unknown) => u is TimeZone = Internal.isTimeZone * * **When to use** * - * Use when narrowing an unknown or union `TimeZone` value to the fixed-offset - * variant before reading its offset in milliseconds. + * Use when you need to narrow an unknown or union `TimeZone` value to the + * fixed-offset variant before reading its offset in milliseconds. * * @see {@link isTimeZone} for checking either time zone variant * @see {@link isTimeZoneNamed} for narrowing to named time zones diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 20844d400f..f6826e9374 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1626,8 +1626,7 @@ export const failCauseSync: ( * * **When to use** * - * Use when encountering unexpected conditions in your code that should - * not be handled as regular errors but instead represent unrecoverable defects. + * Use when you need to report an unrecoverable defect instead of a typed error. * * **Details** * @@ -2658,8 +2657,8 @@ export { * * **When to use** * - * Use when recovering from one specific tagged error in an effect error - * channel. + * Use when you need to recover from one specific tagged error in an effect + * error channel. * * **Details** * @@ -3970,8 +3969,8 @@ export declare namespace Retry { * * **When to use** * - * Use when typed failures may be transient, such as network issues or - * temporary resource unavailability. + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * @@ -5346,8 +5345,7 @@ export const matchEager: { * * **When to use** * - * Use when failure handling depends on the full cause, such as typed failures, defects, or - * interruptions. + * Use when you need failure handling to inspect the full cause. * * **Details** * @@ -5395,9 +5393,8 @@ export const matchCause: { * * **When to use** * - * Use when you expect effects to already be resolved and want to match the cause without - * the overhead of the regular effect pipeline. For pending effects, it automatically falls - * back to the regular `matchCause` behavior. + * Use when you expect effects to already be resolved and want to match the + * cause without regular effect pipeline overhead. * * **Details** * @@ -5438,9 +5435,8 @@ export const matchCauseEager: { * * **When to use** * - * Use when success and cause-aware failure handlers return effects and the - * input may already be resolved, so the selected handler can run immediately - * while unresolved inputs keep normal effectful matching behavior. + * Use when you need effectful success and cause-aware failure handlers for + * inputs that may already be resolved. * * **Details** * @@ -6460,8 +6456,8 @@ export const acquireRelease: ( * * **When to use** * - * Use with JavaScript `Disposable` or `AsyncDisposable` resources that should - * be closed with the surrounding scope. + * Use when you work with JavaScript `Disposable` or `AsyncDisposable` resources + * that should be closed with the surrounding scope. * * **Details** * @@ -8720,9 +8716,7 @@ export interface RunOptions { * * **When to use** * - * Use when an effect should start in the background and return a fiber that can - * be observed or interrupted. Prefer this when you do not need a `Promise` or - * synchronous result. + * Use when you need to start an effect in the background and receive a fiber. * * **Example** (Running an effect in the background) * diff --git a/packages/effect/src/Equal.ts b/packages/effect/src/Equal.ts index 083141a733..2e8472f0c8 100644 --- a/packages/effect/src/Equal.ts +++ b/packages/effect/src/Equal.ts @@ -79,10 +79,8 @@ import { hasProperty } from "./Predicate.ts" * * **When to use** * - * Use when you use it as the computed property key when implementing custom equality on a - * class or object literal. - * - Use it to check manually whether an object carries an equality method (prefer - * {@link isEqual} instead). + * Use when you implement custom equality and need the computed property key for + * the equality method. * * **Details** * @@ -174,10 +172,7 @@ export interface Equal extends Hash.Hash { * * **When to use** * - * Use when as the default equality check throughout Effect code. - * - In data-level assertions or conditional logic where structural comparison - * is needed. - * - In its curried (single-argument) form to build reusable predicates. + * Use when you need Effect's default structural equality check. * * **Details** * @@ -198,6 +193,8 @@ export interface Equal extends Hash.Hash { * - Hash values are checked first as a fast-path rejection. * - Supports dual (data-last) usage: call with one argument to get a curried * predicate. + * - Useful in data-level assertions or conditional logic where structural + * comparison is needed. * * **Gotchas** * @@ -504,8 +501,8 @@ export const isEqual = (u: unknown): u is Equal => hasProperty(u, symbol) * * **When to use** * - * Use when an API (e.g. `Array.dedupeWith`, `Equivalence.mapInput`) requires an - * `Equivalence` and you want to reuse `Equal.equals`. + * Use when you want to pass `Equal.equals` to APIs that require an + * `Equivalence`. * * **Details** * diff --git a/packages/effect/src/Equivalence.ts b/packages/effect/src/Equivalence.ts index f658d94337..01f998d5dc 100644 --- a/packages/effect/src/Equivalence.ts +++ b/packages/effect/src/Equivalence.ts @@ -194,7 +194,7 @@ const isStrictEquivalent = (x: unknown, y: unknown) => x === y * * **When to use** * - * Use when JavaScript strict equality is the intended comparison. + * Use when you need strict equality (`===`) as the comparison. * * **Details** * diff --git a/packages/effect/src/Exit.ts b/packages/effect/src/Exit.ts index c20360b1e1..378893106b 100644 --- a/packages/effect/src/Exit.ts +++ b/packages/effect/src/Exit.ts @@ -241,8 +241,7 @@ export const isExit: (u: unknown) => u is Exit = core.isExit * * **When to use** * - * Use to wrap a known success value into an Exit - * - Use when constructing test data or returning explicit results + * Use when you need an Exit that contains a known success value. * * **Details** * diff --git a/packages/effect/src/JsonPointer.ts b/packages/effect/src/JsonPointer.ts index 12413b7623..57001d86c2 100644 --- a/packages/effect/src/JsonPointer.ts +++ b/packages/effect/src/JsonPointer.ts @@ -57,9 +57,7 @@ * * **When to use** * - * Use to build JSON Pointers from object keys or path segments that may contain special characters - * - Escaping tokens before joining them with `/` to form a complete JSON Pointer - * - Preparing reference tokens for use in JSON Patch operations or schema references + * Use when you need to escape a single JSON Pointer path segment. * * **Details** * @@ -95,9 +93,7 @@ export function escapeToken(token: string): string { * * **When to use** * - * Use to parse JSON Pointers to extract the original token values from escaped segments - * - Converting escaped tokens back to their original form for use as object keys or identifiers - * - Resolving schema references or JSON Patch paths that use escaped tokens + * Use when you need to decode a single escaped JSON Pointer path segment. * * **Details** * diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index c4585c836f..f3b6cf2cfa 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -1441,10 +1441,12 @@ export const provide: { * * **When to use** * - * Use when you need callers to access both the service being built and the - * dependency used to build it, such as a health check that needs both a - * repository and its database. Prefer `provide` when the dependency should stay - * private. + * Use when you need both the constructed service and the dependency used to + * build it to remain available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. * * **Example** (Providing dependencies while retaining services) * diff --git a/packages/effect/src/Order.ts b/packages/effect/src/Order.ts index 9116e29469..b70cc25def 100644 --- a/packages/effect/src/Order.ts +++ b/packages/effect/src/Order.ts @@ -88,9 +88,7 @@ import * as Reducer from "./Reducer.ts" * * **When to use** * - * Use when you need to define how values of a type should be compared - * - When implementing sorting, searching, or ordered data structures - * - When composing multiple comparison criteria + * Use when you need to define how values of a type are compared. * * **Details** * @@ -129,8 +127,7 @@ export interface Order { * * **When to use** * - * Use when working with type-level operations that require higher-kinded types - * - When implementing generic type classes that work with orders + * Use when you need to abstract over `Order` in higher-kinded type code. * * **Details** * @@ -149,9 +146,7 @@ export interface OrderTypeLambda extends TypeLambda { * * **When to use** * - * Use when creating a custom order for a type that doesn't have a built-in order - * - When you need fine-grained control over comparison logic - * - When implementing orders for complex types + * Use when you need a custom order for a type. * * **Details** * @@ -190,9 +185,7 @@ export function make( * * **When to use** * - * Use when comparing strings alphabetically - * - When sorting string collections - * - As a base for creating orders on types containing strings + * Use when you need lexicographic string ordering. * * **Details** * @@ -222,9 +215,7 @@ export const String: Order = make((self, that) => self < that ? -1 : 1) * * **When to use** * - * Use when comparing numbers for sorting or searching - * - As a base for creating orders on types containing numbers - * - When implementing numeric comparisons in data structures + * Use when you need numeric ordering for numbers. * * **Details** * @@ -263,9 +254,7 @@ export const Number: Order = make((self, that) => { * * **When to use** * - * Use when comparing booleans for sorting or searching - * - As a base for creating orders on types containing booleans - * - When implementing boolean-based comparisons + * Use when you need boolean ordering where `false` comes before `true`. * * **Details** * @@ -293,9 +282,7 @@ export const Boolean: Order = make((self, that) => self < that ? -1 : 1 * * **When to use** * - * Use when comparing bigint values for sorting or searching - * - As a base for creating orders on types containing bigints - * - When working with large integers that exceed number precision + * Use when you need numeric ordering for `bigint` values. * * **Details** * @@ -324,9 +311,7 @@ export const BigInt: Order = make((self, that) => self < that ? -1 : 1) * * **When to use** * - * Use when you need descending order instead of ascending - * - When reversing an existing order without modifying the original - * - When creating orders that compare in the opposite direction + * Use when you need the reverse of an existing order. * * **Details** * @@ -360,9 +345,7 @@ export function flip(O: Order): Order { * * **When to use** * - * Use when you need multi-criteria comparison (e.g., sort by age, then by name) - * - When creating composite orders from simpler orders - * - When implementing lexicographic ordering + * Use when you need tie-breaking with exactly two orders. * * **Details** * @@ -415,9 +398,7 @@ export const combine: { * * **When to use** * - * Use when you need an order that doesn't distinguish between values - * - As a default or fallback order when no meaningful comparison exists - * - When implementing optional ordering where equality is sufficient + * Use when you need an order that treats all values as equal. * * **Details** * @@ -450,9 +431,7 @@ export function alwaysEqual(): Order { * * **When to use** * - * Use when you have a variable number of orders to combine - * - When combining orders from a collection or array - * - When implementing dynamic multi-criteria sorting + * Use when you need tie-breaking across a variable number of orders. * * **Details** * @@ -507,9 +486,7 @@ export function combineAll(collection: Iterable>): Order { * * **When to use** * - * Use when you have an order for a property type and want to compare objects by that property - * - When extracting a comparable value from a complex type - * - When creating orders for types that contain comparable values + * Use when you need to compare a larger value by one derived property. * * **Details** * @@ -547,9 +524,7 @@ export const mapInput: { * * **When to use** * - * Use when comparing dates for sorting or searching - * - As a base for creating orders on types containing dates - * - When implementing time-based comparisons + * Use when you need chronological ordering for JavaScript date values. * * **Details** * @@ -581,9 +556,7 @@ export const Date: Order = mapInput(Number, (date) => date.getTime()) * * **When to use** * - * Use when comparing tuples with different types for each position - * - When you need type-safe tuple ordering - * - When working with fixed-length heterogeneous collections + * Use when you need fixed-length tuple ordering with per-position orders. * * **Details** * @@ -647,9 +620,7 @@ export { * * **When to use** * - * Use when comparing arrays of the same element type - * - When you want shorter arrays to be considered less than longer arrays - * - When sorting collections of arrays + * Use when you need lexicographic ordering for arrays of one element type. * * **Details** * @@ -683,9 +654,7 @@ export { * * **When to use** * - * Use when comparing objects with multiple properties - * - When you need multi-field comparison for structs - * - When creating orders for complex data types + * Use when you need multi-field ordering for objects with known properties. * * **Details** * @@ -738,9 +707,7 @@ export function Struct }>( * * **When to use** * - * Use when you need a boolean predicate instead of an ordering result - * - When checking if a value is less than another in conditional logic - * - When implementing range checks or comparisons + * Use when you need a boolean less-than predicate. * * **Details** * @@ -775,9 +742,7 @@ export const isLessThan = (O: Order): { * * **When to use** * - * Use when you need a boolean predicate instead of an ordering result - * - When checking if a value is greater than another in conditional logic - * - When implementing range checks or comparisons + * Use when you need a boolean greater-than predicate. * * **Details** * @@ -812,9 +777,7 @@ export const isGreaterThan = (O: Order): { * * **When to use** * - * Use when you need a boolean predicate for non-strict comparison - * - When checking if a value is within a range (inclusive lower bound) - * - When implementing inclusive comparisons + * Use when you need a boolean less-than-or-equal predicate. * * **Details** * @@ -849,9 +812,7 @@ export const isLessThanOrEqualTo = (O: Order): { * * **When to use** * - * Use when you need a boolean predicate for non-strict comparison - * - When checking if a value is within a range (inclusive upper bound) - * - When implementing inclusive comparisons + * Use when you need a boolean greater-than-or-equal predicate. * * **Details** * @@ -886,9 +847,7 @@ export const isGreaterThanOrEqualTo = (O: Order): { * * **When to use** * - * Use when you need to find the smaller of two values - * - When implementing min/max operations - * - When selecting values based on ordering + * Use when you need to select the smaller of two values. * * **Details** * @@ -923,9 +882,7 @@ export const min = (O: Order): { * * **When to use** * - * Use when you need to find the larger of two values - * - When implementing min/max operations - * - When selecting values based on ordering + * Use when you need to select the larger of two values. * * **Details** * @@ -960,9 +917,7 @@ export const max = (O: Order): { * * **When to use** * - * Use when you need to restrict a value to a specific range - * - When implementing bounds checking and normalization - * - When ensuring values stay within valid ranges + * Use when you need to clamp a value to an inclusive range. * * **Details** * @@ -1013,9 +968,7 @@ export const clamp = (O: Order): { * * **When to use** * - * Use when validating that a value is within a valid range - * - When implementing range checks for bounds validation - * - When filtering or selecting values within a range + * Use when you need to check whether a value is within an inclusive range. * * **Details** * @@ -1067,9 +1020,7 @@ export const isBetween = (O: Order): { * * **When to use** * - * Use when you need to combine multiple orders from a collection using reducer patterns - * - When implementing fold operations over collections of orders - * - When working with reducers that operate on orders + * Use when you need a reducer that combines orders. * * **Details** * diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index a6a8482b3a..7782ff6533 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -574,8 +574,8 @@ export function transform(f: (e: E) => T): Getter { * * **When to use** * - * Use when the transformation may fail (e.g. parsing, validation). - * - The transformation needs Effect services or is async. + * Use when you need a transformation that may fail, require Effect services, + * or run asynchronously. * * **Details** * diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index e32970469b..20181ea76a 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -315,8 +315,8 @@ export const make = (options: { * * **When to use** * - * Use when the transformation can fail (e.g. parsing, validation). - * - The transformation requires Effect services. + * Use when you need a schema transformation that may fail or require Effect + * services. * * **Details** * diff --git a/packages/effect/src/Struct.ts b/packages/effect/src/Struct.ts index 5001be85f5..8b149708c7 100644 --- a/packages/effect/src/Struct.ts +++ b/packages/effect/src/Struct.ts @@ -205,8 +205,8 @@ export const get: { * * **When to use** * - * Use when you use instead of `Object.keys` when you want the return type narrowed to the - * known keys of the struct. + * Use when you want a typed replacement for `Object.keys` that narrows the result + * to the known string keys of the struct. * * **Gotchas** * diff --git a/packages/effect/src/unstable/cli/Param.ts b/packages/effect/src/unstable/cli/Param.ts index 825de34c9f..7c098d33d8 100644 --- a/packages/effect/src/unstable/cli/Param.ts +++ b/packages/effect/src/unstable/cli/Param.ts @@ -890,7 +890,8 @@ export const fileSchema = ( * * **When to use** * - * Use when you use it for options that accept configuration values. + * Use when you need command-line options or arguments that collect `key=value` + * configuration entries. * * **Details** * diff --git a/packages/effect/src/unstable/http/HttpRouter.ts b/packages/effect/src/unstable/http/HttpRouter.ts index eebd51cab9..f0b3b2f51a 100644 --- a/packages/effect/src/unstable/http/HttpRouter.ts +++ b/packages/effect/src/unstable/http/HttpRouter.ts @@ -475,7 +475,7 @@ export const schemaPathParams = = Layer.succeed(RpcSeriali * * **When to use** * - * Use when the transport protocol does not provide message framing. + * Use when you have a transport protocol that does not provide message framing. * * @see {@link layerJson} for transports that already provide message framing * diff --git a/packages/opentelemetry/src/Tracer.ts b/packages/opentelemetry/src/Tracer.ts index f01f55a57c..9ef619f77b 100644 --- a/packages/opentelemetry/src/Tracer.ts +++ b/packages/opentelemetry/src/Tracer.ts @@ -224,9 +224,8 @@ export const layerWithoutOtelTracer: Layer.Layer = Lay * * **When to use** * - * Use when your application already supplies an `OtelTracerProvider` and a - * `Resource`, and you want Effect spans to be created by an OpenTelemetry - * tracer derived from those services. + * Use when you already provide an `OtelTracerProvider` and a `Resource`, and + * want Effect spans backed by a tracer derived from them. * * @see {@link layerTracer} for creating only the OpenTelemetry tracer service * @see {@link layerGlobal} for installing the Effect tracer from the global provider diff --git a/packages/platform-browser/src/BrowserHttpClient.ts b/packages/platform-browser/src/BrowserHttpClient.ts index 5a57cea86e..fe7c3d130b 100644 --- a/packages/platform-browser/src/BrowserHttpClient.ts +++ b/packages/platform-browser/src/BrowserHttpClient.ts @@ -101,8 +101,8 @@ export type XHRResponseType = "arraybuffer" | "text" * * **When to use** * - * Use when XHR-backed HTTP requests need to receive response bodies as text or - * as raw `ArrayBuffer` values. + * Use when you need XHR-backed HTTP requests to receive response bodies as text + * or raw `ArrayBuffer` values. * * @see {@link XHRResponseType} for the allowed response body modes * @see {@link withXHRArrayBuffer} for scoping XHR response handling to `ArrayBuffer` diff --git a/packages/platform-browser/src/BrowserWorkerRunner.ts b/packages/platform-browser/src/BrowserWorkerRunner.ts index 0b6476770b..a600ecc3fd 100644 --- a/packages/platform-browser/src/BrowserWorkerRunner.ts +++ b/packages/platform-browser/src/BrowserWorkerRunner.ts @@ -187,8 +187,8 @@ export const make = (self: MessagePort | Window): WorkerRunner.WorkerRunnerPlatf * * **When to use** * - * Use when a browser worker entry point uses the ambient `self` object as the - * worker transport. + * Use when you need a browser worker entry point to use the ambient `self` + * object as the worker transport. * * **Details** * From e5003fbfda6f6758dac62827654ac91d691c9ba7 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 01:02:52 +0200 Subject: [PATCH 09/29] wip --- packages/effect/src/BigDecimal.ts | 4 ++-- packages/effect/src/BigInt.ts | 8 +++++--- packages/effect/src/Boolean.ts | 4 ++-- packages/effect/src/Channel.ts | 4 ++-- packages/effect/src/Combiner.ts | 5 ++--- packages/effect/src/Effect.ts | 4 ++-- packages/effect/src/Number.ts | 4 ++-- packages/effect/src/Optic.ts | 3 ++- packages/effect/src/Reducer.ts | 5 ++--- packages/effect/src/SchemaIssue.ts | 11 +++++------ packages/effect/src/ScopedCache.ts | 2 +- packages/effect/src/unstable/ai/ResponseIdTracker.ts | 5 +++-- packages/effect/src/unstable/cli/Flag.ts | 3 ++- packages/effect/src/unstable/cli/Param.ts | 7 ++++--- packages/effect/src/unstable/eventlog/EventGroup.ts | 3 ++- packages/effect/src/unstable/httpapi/HttpApi.ts | 5 +++-- 16 files changed, 41 insertions(+), 36 deletions(-) diff --git a/packages/effect/src/BigDecimal.ts b/packages/effect/src/BigDecimal.ts index 890ed770e5..8664985d21 100644 --- a/packages/effect/src/BigDecimal.ts +++ b/packages/effect/src/BigDecimal.ts @@ -708,8 +708,8 @@ export const divideUnsafe: { * * **When to use** * - * Use when sorting or comparing decimal values through APIs that accept an - * ordering instance. + * Use when you need to sort or compare decimal values through APIs that accept + * an ordering instance. * * **Example** (Comparing decimals) * diff --git a/packages/effect/src/BigInt.ts b/packages/effect/src/BigInt.ts index 9f5ad1674b..2f9406bc86 100644 --- a/packages/effect/src/BigInt.ts +++ b/packages/effect/src/BigInt.ts @@ -333,8 +333,8 @@ export const decrement = (n: bigint): bigint => n - bigint1 * * **When to use** * - * Use when sorting or comparing bigint values through APIs that accept an - * ordering instance. + * Use when you need to sort or compare bigint values through APIs that accept + * an ordering instance. * * **Example** (Comparing bigints with Order) * @@ -725,7 +725,9 @@ export const lcm: { * * **When to use** * - * Use when the input is known to be non-negative and invalid input should throw. + * Use when you need to compute an integer square root for a `bigint` that has + * already been validated as non-negative, and you want negative input to throw + * instead of returning `Option.none`. * * **Details** * diff --git a/packages/effect/src/Boolean.ts b/packages/effect/src/Boolean.ts index 3ff858e4c5..f2eca12dc8 100644 --- a/packages/effect/src/Boolean.ts +++ b/packages/effect/src/Boolean.ts @@ -163,8 +163,8 @@ export const match: { * * **When to use** * - * Use when sorting or comparing boolean values through APIs that accept an - * ordering instance where `false` comes before `true`. + * Use when you need to sort or compare boolean values through APIs that accept + * an ordering instance where `false` comes before `true`. * * **Example** (Comparing booleans) * diff --git a/packages/effect/src/Channel.ts b/packages/effect/src/Channel.ts index c7fb1a88b4..0b237e92c0 100644 --- a/packages/effect/src/Channel.ts +++ b/packages/effect/src/Channel.ts @@ -7604,8 +7604,8 @@ export const bind: { * * **When to use** * - * Use when starting a Channel Do-notation chain from an existing output value - * by assigning that value to a field name. + * Use when you need to start a Channel Do-notation chain from an existing + * output value by assigning that value to a field name. * * @see {@link Do} for starting Do notation from an empty object * @see {@link bind} for adding a field produced by another channel diff --git a/packages/effect/src/Combiner.ts b/packages/effect/src/Combiner.ts index c4349c9bb7..6a5f5ccda2 100644 --- a/packages/effect/src/Combiner.ts +++ b/packages/effect/src/Combiner.ts @@ -138,9 +138,8 @@ export function make(combine: (self: A, that: A) => A): Combiner { * * **When to use** * - * Use when the "right" value should act as the accumulator side, or when - * you want to reverse the natural direction of a non-commutative combiner such - * as string concatenation. + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative combiner such as string concatenation. * * **Details** * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index f6826e9374..3529f76466 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -5180,8 +5180,8 @@ export const filterMapOrFail: { * * **When to use** * - * Use when an effectful check decides whether to run another effect while - * representing the skipped case explicitly. + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. * * **Details** * diff --git a/packages/effect/src/Number.ts b/packages/effect/src/Number.ts index 21364b4d18..36881b8aaa 100644 --- a/packages/effect/src/Number.ts +++ b/packages/effect/src/Number.ts @@ -305,8 +305,8 @@ export const decrement = (n: number): number => n - 1 * * **When to use** * - * Use when sorting or comparing numbers through APIs that accept an ordering - * instance. + * Use when you need to sort or compare numbers through APIs that accept an + * ordering instance. * * **Example** (Comparing numbers) * diff --git a/packages/effect/src/Optic.ts b/packages/effect/src/Optic.ts index 3073ec1182..d66bc89202 100644 --- a/packages/effect/src/Optic.ts +++ b/packages/effect/src/Optic.ts @@ -1026,7 +1026,8 @@ export interface Optional { * * **When to use** * - * Use when both reading and writing can fail. + * Use when you need an optic for a focus that may be missing on read and may + * reject updates on write. * * **Details** * diff --git a/packages/effect/src/Reducer.ts b/packages/effect/src/Reducer.ts index 1cade8a001..3500a7d1ea 100644 --- a/packages/effect/src/Reducer.ts +++ b/packages/effect/src/Reducer.ts @@ -201,9 +201,8 @@ export function make( * * **When to use** * - * Use when you need the "right" value to act as the accumulator side. - * - You want to reverse the natural direction of a non-commutative reducer - * (e.g. string concatenation becomes prepend). + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative reducer such as string concatenation. * * **Details** * diff --git a/packages/effect/src/SchemaIssue.ts b/packages/effect/src/SchemaIssue.ts index aaab9c2e98..bfc4ec9593 100644 --- a/packages/effect/src/SchemaIssue.ts +++ b/packages/effect/src/SchemaIssue.ts @@ -813,8 +813,8 @@ export class OneOf extends Base { * * **When to use** * - * Use when retrieve the offending value for logging or custom error rendering. - * - Uniformly access `actual` regardless of which issue variant you have. + * Use when you need to retrieve an `Issue`'s offending input value for logging + * or custom error rendering. * * **Details** * @@ -1034,10 +1034,9 @@ export const defaultCheckHook: CheckHook = (issue): string | undefined => { * * **When to use** * - * Use when integrate with libraries that consume the - * [Standard Schema V1](https://github.com/standard-schema/standard-schema) - * error format. - * - Customise error rendering by providing `leafHook` and/or `checkHook`. + * Use when you need schema parse errors in + * [Standard Schema V1](https://github.com/standard-schema/standard-schema) + * format, optionally customizing leaf or check issue rendering. * * **Details** * diff --git a/packages/effect/src/ScopedCache.ts b/packages/effect/src/ScopedCache.ts index 2b3b11c60c..529e5f6017 100644 --- a/packages/effect/src/ScopedCache.ts +++ b/packages/effect/src/ScopedCache.ts @@ -128,7 +128,7 @@ export interface Entry { * * **When to use** * - * Use when cached scoped resources need different lifetimes based on the lookup + * Use when you need a scoped cache whose entry lifetime depends on each lookup * result or key. * * **Details** diff --git a/packages/effect/src/unstable/ai/ResponseIdTracker.ts b/packages/effect/src/unstable/ai/ResponseIdTracker.ts index 6cd17acd9a..231923efe1 100644 --- a/packages/effect/src/unstable/ai/ResponseIdTracker.ts +++ b/packages/effect/src/unstable/ai/ResponseIdTracker.ts @@ -83,8 +83,9 @@ export interface Service { * * **When to use** * - * Use when provided, language model operations can use the tracker to send only new - * prompt messages together with the provider's prior response ID. + * Use when you provide a language model with previous-response ID tracking so + * later calls can send only new prompt messages together with the provider's + * prior response ID. * * @category services * @since 4.0.0 diff --git a/packages/effect/src/unstable/cli/Flag.ts b/packages/effect/src/unstable/cli/Flag.ts index 6d8b578325..e766286036 100644 --- a/packages/effect/src/unstable/cli/Flag.ts +++ b/packages/effect/src/unstable/cli/Flag.ts @@ -374,7 +374,8 @@ export const fileSchema = ( * * **When to use** * - * Use when options accept configuration values. + * Use when you need a CLI flag that accepts one or more `key=value` + * configuration entries. * * **Details** * diff --git a/packages/effect/src/unstable/cli/Param.ts b/packages/effect/src/unstable/cli/Param.ts index 7c098d33d8..f586553bf5 100644 --- a/packages/effect/src/unstable/cli/Param.ts +++ b/packages/effect/src/unstable/cli/Param.ts @@ -936,7 +936,8 @@ export const keyValuePair = ( * * **When to use** * - * Use when placeholder parameters or combinators need an empty parameter sentinel. + * Use when you need an empty CLI parameter sentinel for optional parameter + * construction or internal combinators. * * **Example** (Creating sentinel parameters) * @@ -971,8 +972,8 @@ const FLAG_DASH_REGEXP = /^-+/ * * **When to use** * - * Use when aliases allow params to be specified with alternative names, - * typically single-character shortcuts like "-f" for "--force". + * Use when you need a CLI parameter to accept an alternate name, such as "-f" + * for "--force". * * **Details** * diff --git a/packages/effect/src/unstable/eventlog/EventGroup.ts b/packages/effect/src/unstable/eventlog/EventGroup.ts index 9e7cdb122d..ea41066ed9 100644 --- a/packages/effect/src/unstable/eventlog/EventGroup.ts +++ b/packages/effect/src/unstable/eventlog/EventGroup.ts @@ -199,7 +199,8 @@ const makeProto = < * * **When to use** * - * Use when call `.add(...)` to add event definitions and build a typed `EventGroup`. + * Use when you need the starting `EventGroup` value before adding event + * definitions with `.add(...)`. * * @category constructors * @since 4.0.0 diff --git a/packages/effect/src/unstable/httpapi/HttpApi.ts b/packages/effect/src/unstable/httpapi/HttpApi.ts index 29784e7df3..d3c66239d3 100644 --- a/packages/effect/src/unstable/httpapi/HttpApi.ts +++ b/packages/effect/src/unstable/httpapi/HttpApi.ts @@ -236,8 +236,9 @@ const makeProto = ( * * **When to use** * - * Use when add groups with `add` or `addHttpApi`, provide endpoint implementations with - * `HttpApiBuilder.group`, and register the API with `HttpApiBuilder.layer`. + * Use when you need to start defining an HTTP API, add groups with `add` or + * `addHttpApi`, provide endpoint implementations with `HttpApiBuilder.group`, + * and register the API with `HttpApiBuilder.layer`. * * @category constructors * @since 4.0.0 From 1a711ebf11471bbd1875a0317007cb3568016aa8 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 07:02:37 +0200 Subject: [PATCH 10/29] wip --- packages/atom/solid/src/RegistryContext.ts | 4 +- packages/effect/src/Array.ts | 5 +- packages/effect/src/Cause.ts | 4 +- packages/effect/src/Effect.ts | 5 +- packages/effect/src/Equal.ts | 5 +- packages/effect/src/Filter.ts | 4 +- packages/effect/src/Layer.ts | 4 +- packages/effect/src/Newtype.ts | 4 +- packages/effect/src/Optic.ts | 2 +- packages/effect/src/Option.ts | 111 ++++++++++-------- packages/effect/src/PlatformError.ts | 4 +- packages/effect/src/PubSub.ts | 4 +- packages/effect/src/Pull.ts | 4 +- packages/effect/src/Queue.ts | 5 +- packages/effect/src/Redactable.ts | 4 +- packages/effect/src/Result.ts | 4 +- packages/effect/src/Schema.ts | 8 +- packages/effect/src/SchemaAST.ts | 13 +- packages/effect/src/SchemaGetter.ts | 4 +- packages/effect/src/SchemaIssue.ts | 5 +- packages/effect/src/SchemaTransformation.ts | 11 +- packages/effect/src/Stream.ts | 9 +- packages/effect/src/unstable/ai/Chat.ts | 3 +- .../effect/src/unstable/ai/EmbeddingModel.ts | 4 +- packages/effect/src/unstable/ai/McpSchema.ts | 4 +- packages/effect/src/unstable/cli/Command.ts | 7 +- packages/effect/src/unstable/cli/Flag.ts | 4 +- .../src/unstable/cluster/RunnerHealth.ts | 3 +- .../effect/src/unstable/cluster/Sharding.ts | 6 +- .../effect/src/unstable/eventlog/EventLog.ts | 6 +- packages/platform-browser/src/IndexedDb.ts | 4 +- packages/platform-browser/src/Permissions.ts | 4 +- 32 files changed, 145 insertions(+), 123 deletions(-) diff --git a/packages/atom/solid/src/RegistryContext.ts b/packages/atom/solid/src/RegistryContext.ts index b69f3160bb..4376de990a 100644 --- a/packages/atom/solid/src/RegistryContext.ts +++ b/packages/atom/solid/src/RegistryContext.ts @@ -34,8 +34,8 @@ import { createComponent, createContext, onCleanup } from "solid-js" * * **When to use** * - * Use when integrating lower-level Solid atom APIs that need direct access to, - * or direct provisioning of, the `AtomRegistry` for the current owner tree. + * Use when you need lower-level Solid atom APIs to access an `AtomRegistry`, or + * when you need to provide a registry directly for the current owner tree. * * **Details** * diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 3d1679f59e..f288335a0b 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -194,7 +194,10 @@ export type NonEmptyArray = [A, ...Array] * * **When to use** * - * Use when you have literal values and want a typed non-empty array. + * Use when you need to create a typed non-empty array from literal values. + * + * **Details** + * * - The element type is inferred as the union of all arguments. * - Always returns a `NonEmptyArray` since at least one argument is required. * diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index b946dba4a6..cb896c6654 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -910,8 +910,8 @@ export const findError: (self: Cause) => Result.Result> = * * **When to use** * - * Use when you need the first typed error as an `Option` and do not need the - * original cause returned in a failed `Result`. + * Use when you need the first typed error value from a `Cause` as an `Option`, + * discarding the original cause. * * **Example** (extracting an error as Option) * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 3529f76466..0ef3625bcc 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -2087,9 +2087,8 @@ export const andThen: { * * **When to use** * - * Use when you want to perform a side effect, like logging or tracking, - * without modifying the main value. This is useful when you need to observe or - * record an action but want the original value to be passed to the next step. + * Use when you need to run an effectful observation, such as logging or + * tracking, while passing the original success value to the next step. * * **Details** * diff --git a/packages/effect/src/Equal.ts b/packages/effect/src/Equal.ts index 2e8472f0c8..5ffc141279 100644 --- a/packages/effect/src/Equal.ts +++ b/packages/effect/src/Equal.ts @@ -575,9 +575,8 @@ export const byReference = (obj: T): T => byReferenceUnsafe(ne * * **When to use** * - * Use when you want reference equality semantics and can accept that the - * original object is **permanently** modified. - * - When proxy overhead is unacceptable (hot paths, large collections). + * Use when you need reference equality without proxy allocation and accept + * permanently marking the original object for reference-only equality. * * **Details** * diff --git a/packages/effect/src/Filter.ts b/packages/effect/src/Filter.ts index 693a37793c..0ce4873c5f 100644 --- a/packages/effect/src/Filter.ts +++ b/packages/effect/src/Filter.ts @@ -447,8 +447,8 @@ export const symbol: Filter = fromPredicate(Predicate.isSymbol) * * **When to use** * - * Use when narrowing unknown input to JavaScript `Date` instances with a - * reusable `Filter`. + * Use when you need to narrow unknown input to JavaScript `Date` instances with + * a reusable `Filter`. * * **Details** * diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index f3b6cf2cfa..0c8769e4fb 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -782,8 +782,8 @@ export const buildWithScope: { * * **When to use** * - * Use when you already have a constructed service implementation and do not - * need effectful acquisition. + * Use when you need to provide a service from an already constructed + * implementation without effectful acquisition. * * **Example** (Creating a layer from a service implementation) * diff --git a/packages/effect/src/Newtype.ts b/packages/effect/src/Newtype.ts index fbdb4cc475..4df67e2d52 100644 --- a/packages/effect/src/Newtype.ts +++ b/packages/effect/src/Newtype.ts @@ -169,8 +169,8 @@ export declare namespace Newtype { * * **When to use** * - * Use when you only need to read the inner value and do not need to wrap - * new values. For both wrapping and unwrapping, prefer {@link makeIso}. + * Use when you need to unwrap a newtype value and do not need to wrap new + * values. * * **Details** * diff --git a/packages/effect/src/Optic.ts b/packages/effect/src/Optic.ts index d66bc89202..7f7db5178e 100644 --- a/packages/effect/src/Optic.ts +++ b/packages/effect/src/Optic.ts @@ -1521,7 +1521,7 @@ const identityIso = make(identityNode) * * **When to use** * - * Use when starting an optic chain with a focus on the whole value. + * Use when you need to start an optic chain with a focus on the whole value. * * **Details** * diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index 901481a435..d5c20512ae 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -392,7 +392,7 @@ export const isOption: (input: unknown) => input is Option = option.isO * * **When to use** * - * Use when branching on absence before accessing `.value` + * Use when you need to branch on an absent `Option` before accessing `.value`. * * **Details** * @@ -422,7 +422,7 @@ export const isNone: (self: Option) => self is None = option.isNone * * **When to use** * - * Use when branching on presence before accessing `.value` + * Use when you need to branch on a present `Option` before accessing `.value`. * * **Details** * @@ -452,8 +452,8 @@ export const isSome: (self: Option) => self is Some = option.isSome * * **When to use** * - * Use when exhaustively handling both branches in one expression - * - Transforming an `Option` into a plain value + * Use when you need to handle both `Some` and `None` in one expression and + * transform an `Option` into a plain value. * * **Details** * @@ -502,8 +502,8 @@ export const match: { * * **When to use** * - * Use when turning a parsing function into a type-narrowing predicate - * - Filtering arrays with `Array.prototype.filter` + * Use when you need to turn an `Option`-returning parser into a type-narrowing + * predicate, such as for `Array.prototype.filter`. * * **Details** * @@ -545,8 +545,8 @@ export const toRefinement = (f: (a: A) => Option): (a: A) => * * **When to use** * - * Use when safely extracting the head of a collection - * - Working with generators or lazy iterables + * Use when you need to safely extract the head of a collection, including + * generators or lazy iterables. * * **Details** * @@ -582,7 +582,8 @@ export const fromIterable = (collection: Iterable): Option => { * * **When to use** * - * Use when discarding the failure channel when you only care about success + * Use when you need to discard a `Result` failure and keep only the success + * value as an `Option`. * * **Details** * @@ -685,8 +686,8 @@ export const getOrElse: { * * **When to use** * - * Use when chaining fallback `Option` computations - * - Building priority chains of optional values + * Use when you need a lazy fallback `Option`, such as when building priority + * chains of optional values. * * **Details** * @@ -763,8 +764,8 @@ export const orElseSome: { * * **When to use** * - * Use when distinguishing whether a value came from the primary or fallback - * `Option`. + * Use when you need to know whether a present value came from the primary or + * fallback `Option`. * * **Details** * @@ -804,7 +805,7 @@ export const orElseResult: { * * **When to use** * - * Use when searching for the first available value in a priority list + * Use when you need the first available `Some` value from a priority list. * * **Details** * @@ -846,8 +847,8 @@ export const firstSomeOf = > = Iterable, B>( * * **When to use** * - * Use when interoping with APIs that use `null` for missing values + * Use when you need to pass missing optional values to APIs that expect `null`. * * **Details** * @@ -1038,7 +1039,8 @@ export const getOrNull: (self: Option) => A | null = getOrElse(constNull) * * **When to use** * - * Use when interoping with APIs that use `undefined` for missing values + * Use when you need to pass missing optional values to APIs that expect + * `undefined`. * * **Details** * @@ -1226,7 +1228,8 @@ export const map: { * * **When to use** * - * Use when preserving presence/absence while discarding the original value + * Use when you need to replace a present `Option` value while preserving + * whether it was `Some` or `None`. * * **Details** * @@ -1262,7 +1265,8 @@ export const as: { * * **When to use** * - * Use when discarding the value while preserving presence/absence + * Use when you need to discard a present `Option` value while preserving + * whether it was `Some` or `None`. * * **Details** * @@ -1320,8 +1324,8 @@ export { * * **When to use** * - * Use when chaining dependent optional computations where each step may return - * `None`. + * Use when you need to chain dependent optional computations where each step + * may return `None`. * * **Details** * @@ -1373,8 +1377,8 @@ export const flatMap: { * * **When to use** * - * Use when flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * * **Details** * @@ -1431,8 +1435,8 @@ export const andThen: { * * **When to use** * - * Use when chaining with functions that use `null`/`undefined` instead of `Option` - * - Navigating deeply nested optional properties + * Use when you need to chain optional computations that use `null` or + * `undefined` instead of `Option`, such as nested property access. * * **Details** * @@ -1480,7 +1484,7 @@ export const flatMapNullishOr: { * * **When to use** * - * Use when removing one layer of `Option` nesting + * Use when you need to remove one layer of nested `Option`. * * **Details** * @@ -1512,7 +1516,8 @@ export const flatten: (self: Option>) => Option = flatMap(identi * * **When to use** * - * Use to run a side-condition that must succeed, then using the second value + * Use when you need two `Option` values to both be `Some`, then keep only the + * second value. * * **Details** * @@ -1547,7 +1552,8 @@ export const zipRight: { * * **When to use** * - * Use to run a validation that must succeed, but keeping the original value + * Use when you need two `Option` values to both be `Some`, then keep only the + * first value. * * **Details** * @@ -1667,7 +1673,8 @@ export const tap: { * * **When to use** * - * Use when pairing two optional values together + * Use when you need to require two `Option` values to both be `Some` and keep + * both values as a tuple. * * **Details** * @@ -1701,7 +1708,8 @@ export const product = (self: Option, that: Option): Option<[A, B]> * * **When to use** * - * Use when collecting several `Option`s of the same type into a non-empty tuple + * Use when you need several `Option` values of the same type to all be `Some` + * and return them as a non-empty tuple. * * **Details** * @@ -1752,8 +1760,8 @@ export const productMany = ( * * **When to use** * - * Use when collecting multiple `Option`s into one, preserving the input shape - * - "All or nothing" combination — any `None` makes the result `None` + * Use when you need to combine multiple `Option` values into one while + * preserving the input shape; any `None` makes the result `None`. * * **Details** * @@ -1828,7 +1836,8 @@ export const all: > | Record(self: Option): Array => isNone(self) ? [] : [se * * **When to use** * - * Use when categorizing an optional value into "left" (failure) and "right" (success) channels + * Use when you need to split an optional value into "left" and "right" + * channels using a `Result`-returning function. * * **Details** * @@ -2162,7 +2172,8 @@ export const makeOrder = (O: Order): Order> => * * **When to use** * - * Use when reusing an existing binary function in an `Option` context + * Use when you need to reuse an existing binary function with two `Option` + * values. * * **Details** * @@ -2250,7 +2261,8 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * * **When to use** * - * Use when testing membership with a custom equality check + * Use when you need to test whether an `Option` contains a value using a + * custom equality check. * * **Details** * @@ -2290,7 +2302,8 @@ export const containsWith = (isEquivalent: (self: A, that: A) => boolean): { * * **When to use** * - * Use when quick membership test with standard equality + * Use when you need a quick membership test for an `Option` value using + * standard equality. * * **Details** * @@ -2381,7 +2394,8 @@ export const exists: { * * **When to use** * - * Use when beginning a do notation chain by naming the first value + * Use when you need to start an `Option` do notation chain by naming the first + * value. * * **Example** (Starting do notation) * @@ -2428,7 +2442,8 @@ export { * * **When to use** * - * Use when binding a derived (non-`Option`) value in a do notation pipeline + * Use when you need to bind a derived non-`Option` value in an `Option` do + * notation pipeline. * * **Example** (Adding a computed value) * @@ -2461,7 +2476,7 @@ export { * * **When to use** * - * Use when sequencing `Option` computations in do notation + * Use when you need to sequence `Option` computations in do notation. * * **Example** (Binding Option values) * @@ -2504,7 +2519,8 @@ export const bind: { * * **When to use** * - * Use when starting a do notation pipeline before adding bindings + * Use when you need to start an `Option` do notation pipeline before adding + * bindings. * * **Example** (Do notation pipeline) * @@ -2537,8 +2553,8 @@ export const Do: Option<{}> = some({}) * * **When to use** * - * Use when writing imperative-style code that chains multiple `Option`s - * - Readability when many sequential optional steps are involved + * Use when you need generator syntax for a sequence of optional steps that + * should short-circuit on `None`. * * **Details** * @@ -2630,7 +2646,8 @@ export function makeReducer(combiner: Combiner.Combiner): Reducer.Reducer< * * **When to use** * - * Use when operations that require both values to be present + * Use when you need a combiner that returns `None` unless both operands are + * `Some`. * * **Details** * diff --git a/packages/effect/src/PlatformError.ts b/packages/effect/src/PlatformError.ts index e04e6d7e50..66368711ab 100644 --- a/packages/effect/src/PlatformError.ts +++ b/packages/effect/src/PlatformError.ts @@ -40,8 +40,8 @@ const TypeId = "~effect/platform/PlatformError" * * **When to use** * - * Use when a platform API rejects caller input before performing the underlying - * operation and callers need invalid-argument reason data directly. + * Use when you need to model caller input rejected before a platform operation + * runs, including invalid-argument reason data. * * **Details** * diff --git a/packages/effect/src/PubSub.ts b/packages/effect/src/PubSub.ts index de192b16fc..d6482f6e21 100644 --- a/packages/effect/src/PubSub.ts +++ b/packages/effect/src/PubSub.ts @@ -1476,8 +1476,8 @@ export const remaining = (self: Subscription): Effect.Effect => * * **When to use** * - * Use when polling from synchronous code and you can handle the `Option.none()` - * shutdown case directly. + * Use when you need a synchronous check of messages currently available in a + * subscription and can handle `Option.none()` when it is shut down. * * **Example** (Checking remaining messages synchronously) * diff --git a/packages/effect/src/Pull.ts b/packages/effect/src/Pull.ts index 19239e4a49..391d26dde2 100644 --- a/packages/effect/src/Pull.ts +++ b/packages/effect/src/Pull.ts @@ -190,8 +190,8 @@ export const catchDone: { * * **When to use** * - * Use to test a whole pull failure cause for normal completion when you only - * need a boolean branch and do not need the done payload. + * Use when you need to test whether a pull failure cause represents normal + * completion and only need a boolean result. * * @see {@link isDoneFailure} for checking a single `Cause.Reason` * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` diff --git a/packages/effect/src/Queue.ts b/packages/effect/src/Queue.ts index 55aa4fc167..d0d26e7ffb 100644 --- a/packages/effect/src/Queue.ts +++ b/packages/effect/src/Queue.ts @@ -624,9 +624,8 @@ export const dropping = (capacity: number): Effect> => * * **When to use** * - * Use when producers should never be blocked; unbounded queues never apply backpressure, so producers - * can always add messages successfully. This is useful when you want to prioritize - * producer throughput over memory usage control. + * Use when you need producers to add messages without backpressure and accept + * unbounded memory growth. * * **Example** (Creating unbounded queues) * diff --git a/packages/effect/src/Redactable.ts b/packages/effect/src/Redactable.ts index 8975968388..68626b003f 100644 --- a/packages/effect/src/Redactable.ts +++ b/packages/effect/src/Redactable.ts @@ -193,8 +193,8 @@ export function redact(u: unknown): unknown { * * **When to use** * - * Use when you have already verified the value is `Redactable`, for - * example with {@link isRedactable}, and want to avoid a second check. + * Use when you need to read the redacted representation from a value already + * verified as `Redactable`. * * **Details** * diff --git a/packages/effect/src/Result.ts b/packages/effect/src/Result.ts index c4228d797f..a4c865805c 100644 --- a/packages/effect/src/Result.ts +++ b/packages/effect/src/Result.ts @@ -1567,8 +1567,8 @@ export const flip = (self: Result): Result => * * **When to use** * - * Use when sequential `Result` composition is clearer with generator syntax - * than nested `flatMap` calls. + * Use when you need generator syntax to compose sequential `Result` + * computations instead of nested `flatMap` calls. * * **Details** * diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index d5ee062465..91e606dc69 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -1408,7 +1408,7 @@ export const decodeResult = Parser.decodeResult * * **When to use** * - * Use when integrating unknown input validation with Promise-based APIs. + * Use when you need to decode unknown input in Promise-based APIs. * * **Details** * @@ -1428,7 +1428,7 @@ export const decodeUnknownPromise = Parser.decodeUnknownPromise * * **When to use** * - * Use when integrating typed input decoding with Promise-based APIs. + * Use when you need to decode typed encoded input in Promise-based APIs. * * **Details** * @@ -1704,7 +1704,7 @@ export const encodeResult = Parser.encodeResult * * **When to use** * - * Use when integrating unknown input serialization with Promise-based APIs. + * Use when you need to encode unknown input in Promise-based APIs. * * **Details** * @@ -1724,7 +1724,7 @@ export const encodeUnknownPromise = Parser.encodeUnknownPromise * * **When to use** * - * Use when integrating typed input serialization with Promise-based APIs. + * Use when you need to encode typed schema values in Promise-based APIs. * * **Details** * diff --git a/packages/effect/src/SchemaAST.ts b/packages/effect/src/SchemaAST.ts index d56280b779..f2d8dbb97c 100644 --- a/packages/effect/src/SchemaAST.ts +++ b/packages/effect/src/SchemaAST.ts @@ -238,7 +238,7 @@ export const isNever = makeGuard("Never") * * **When to use** * - * Use when inspecting a schema AST and you need to handle the `Unknown` node + * Use when you need to inspect a schema AST and handle the `Unknown` node * variant specifically. * * @see {@link isAny} for the guard for the `Any` node, whose parsed result is typed as `any` rather than `unknown` @@ -253,7 +253,7 @@ export const isUnknown = makeGuard("Unknown") * * **When to use** * - * Use when inspecting a schema AST and you need to handle the `Any` node + * Use when you need to inspect a schema AST and handle the `Any` node * variant specifically. * * @see {@link isUnknown} for the guard for the `Unknown` node, whose parsed result is typed as `unknown` rather than `any` @@ -693,8 +693,9 @@ export abstract class Base { * * **When to use** * - * Use when none of the built-in AST nodes fit. The `run` function receives - * `typeParameters` and returns a parser that validates/transforms raw input. + * Use when you need a custom schema AST node because none of the built-in + * nodes fit. The `run` function receives `typeParameters` and returns a parser + * that validates or transforms raw input. * * **Details** * @@ -1474,8 +1475,8 @@ export const boolean = new Boolean() * * **When to use** * - * Use when defining or inspecting the AST node class for schemas that match any - * JavaScript symbol value. + * Use when you need the AST node class for schemas that match any JavaScript + * symbol value. * * **Details** * diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index 7782ff6533..c18ef46bcc 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -102,8 +102,8 @@ import * as Str from "./String.ts" * * **When to use** * - * Use to build custom schema transformations with `Schema.decodeTo` or `Schema.decode`. - * - Composing multiple transformation steps into a single getter. + * Use when you need to build and compose custom schema transformations for + * `Schema.decodeTo` or `Schema.decode`. * * **Details** * diff --git a/packages/effect/src/SchemaIssue.ts b/packages/effect/src/SchemaIssue.ts index bfc4ec9593..cb4b4ae4c8 100644 --- a/packages/effect/src/SchemaIssue.ts +++ b/packages/effect/src/SchemaIssue.ts @@ -95,8 +95,9 @@ const TypeId = "~effect/SchemaIssue/Issue" * * **When to use** * - * Use when narrowing an `unknown` value to `Issue` in error-handling code. - * - Distinguishing an `Issue` from other error types in a catch-all handler. + * Use when you need to narrow an `unknown` value to `Issue` in error-handling + * code, such as distinguishing an `Issue` from other error types in a catch-all + * handler. * * **Details** * diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index 20181ea76a..e4a624a0dc 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -738,9 +738,9 @@ const passthrough_ = new Transformation( * * **When to use** * - * Use when connecting two schemas that share the same type with no conversion. - * - As a placeholder when `Schema.decodeTo` requires a transformation but - * no actual conversion is needed. + * Use when you need to connect two schemas that share the same type with no + * conversion, such as when `Schema.decodeTo` requires a transformation but no + * actual conversion is needed. * * **Details** * @@ -1515,8 +1515,9 @@ export const stringFromHexString: Transformation = new Transform * * **When to use** * - * Use when storing structured data in URL query parameters or fragments. - * - Composing with `Schema.parseJson` to round-trip JSON through a URL. + * Use when you need to store structured data in URL query parameters or + * fragments, such as composing with `Schema.parseJson` to round-trip JSON + * through a URL. * * **Details** * diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index a0b883dcc8..56f0342dcc 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -5251,8 +5251,8 @@ export const catchFilter: { * * **When to use** * - * Use when your error type is a tagged union with a readonly `_tag` - * field and you want to handle a specific error case. + * Use when you need to handle a specific error case from a stream whose error + * type is a tagged union with a readonly `_tag` field. * * **Example** (Catching tagged failures) * @@ -6066,9 +6066,8 @@ export const ignore: < * * **When to use** * - * Use when a stream may fail with defects and you want to silently suppress the - * entire failure cause — including both typed errors and defects — rather than - * propagate it downstream. + * Use when you need to silently suppress a stream's entire failure cause, + * including both typed errors and defects, rather than propagate it downstream. * * **Example** (Ignoring stream failure causes) * diff --git a/packages/effect/src/unstable/ai/Chat.ts b/packages/effect/src/unstable/ai/Chat.ts index b9ffdd2ffe..7d930cf778 100644 --- a/packages/effect/src/unstable/ai/Chat.ts +++ b/packages/effect/src/unstable/ai/Chat.ts @@ -505,7 +505,8 @@ const makeUnsafe = (history: Ref.Ref) => { * * **When to use** * - * Use when starting a fresh chat session without initial context or system prompts. + * Use when you need to start a fresh chat session without initial context or + * system prompts. * * **Example** (Creating an empty chat) * diff --git a/packages/effect/src/unstable/ai/EmbeddingModel.ts b/packages/effect/src/unstable/ai/EmbeddingModel.ts index 8f7fd7a8c1..97f521c140 100644 --- a/packages/effect/src/unstable/ai/EmbeddingModel.ts +++ b/packages/effect/src/unstable/ai/EmbeddingModel.ts @@ -171,8 +171,8 @@ export interface ProviderResponse { * * **When to use** * - * Use when building or calling a low-level embedding request resolver and you - * need a typed request for one input that resolves to `EmbedResponse`. + * Use when you need a typed request for one embedding input while building or + * calling a low-level embedding request resolver. * * @see {@link Service} for the resolver-bearing service contract * @see {@link make} for constructing the request resolver from a provider implementation diff --git a/packages/effect/src/unstable/ai/McpSchema.ts b/packages/effect/src/unstable/ai/McpSchema.ts index fdd61e992c..a435b5a683 100644 --- a/packages/effect/src/unstable/ai/McpSchema.ts +++ b/packages/effect/src/unstable/ai/McpSchema.ts @@ -1555,8 +1555,8 @@ export class CallToolResult extends Schema.Class("@effect/ai/Mcp * * **When to use** * - * Use when a client already knows the tool name and wants the server to execute - * it with argument values. + * Use when you need to represent a client request that already knows the tool + * name and asks the server to execute it with argument values. * * @see {@link ListTools} for discovering available tools before calling one * @see {@link CallToolResult} for the successful tool-call result shape diff --git a/packages/effect/src/unstable/cli/Command.ts b/packages/effect/src/unstable/cli/Command.ts index 13b79500c8..30d019b175 100644 --- a/packages/effect/src/unstable/cli/Command.ts +++ b/packages/effect/src/unstable/cli/Command.ts @@ -1121,7 +1121,8 @@ export const annotate: { * * **When to use** * - * Use when attaching an already-built `Context.Context` of command annotations. + * Use when you need to attach an already-built `Context.Context` of command + * annotations. * * **Details** * @@ -1480,8 +1481,8 @@ export const run: { * * **When to use** * - * Use when testing CLI applications or programmatically executing commands with specific - * arguments. + * Use when you need to test CLI applications or programmatically execute + * commands with specific arguments. * * **Example** (Running commands with explicit arguments) * diff --git a/packages/effect/src/unstable/cli/Flag.ts b/packages/effect/src/unstable/cli/Flag.ts index e766286036..268653c721 100644 --- a/packages/effect/src/unstable/cli/Flag.ts +++ b/packages/effect/src/unstable/cli/Flag.ts @@ -166,8 +166,8 @@ export const choiceWithValue = = Context.Se * * **When to use** * - * Use when browser programs need a live `Permissions` service backed by the - * ambient `navigator.permissions` implementation. + * Use when you need a live browser `Permissions` service backed by the ambient + * `navigator.permissions` implementation. * * **Details** * From 31c38e3ce4c5d5ddd142975421eb89498ead0b6c Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 07:24:54 +0200 Subject: [PATCH 11/29] wip --- .../ai/openai/src/OpenAiEmbeddingModel.ts | 3 +-- packages/atom/solid/src/RegistryContext.ts | 4 ++-- packages/effect/src/Array.ts | 2 +- packages/effect/src/Combiner.ts | 17 ++++++------- packages/effect/src/Config.ts | 7 +++--- packages/effect/src/ConfigProvider.ts | 10 ++++---- packages/effect/src/Effect.ts | 24 +++++++------------ packages/effect/src/Equal.ts | 6 ++--- packages/effect/src/Formatter.ts | 11 ++++----- packages/effect/src/Function.ts | 4 ++-- packages/effect/src/Iterable.ts | 4 ++-- packages/effect/src/Metric.ts | 5 ++-- packages/effect/src/Option.ts | 2 +- packages/effect/src/PlatformError.ts | 4 ++-- packages/effect/src/Pool.ts | 5 ++-- packages/effect/src/Predicate.ts | 5 ++-- packages/effect/src/Pull.ts | 4 ++-- packages/effect/src/Schema.ts | 4 ++-- packages/effect/src/SchemaAST.ts | 6 ++--- packages/effect/src/SchemaParser.ts | 9 +++---- packages/effect/src/Sink.ts | 3 ++- packages/effect/src/UndefinedOr.ts | 2 +- .../effect/src/unstable/ai/IdGenerator.ts | 4 ++-- packages/effect/src/unstable/ai/Toolkit.ts | 4 ++-- packages/effect/src/unstable/cli/Flag.ts | 4 ++-- packages/effect/src/unstable/cli/Param.ts | 2 +- packages/effect/src/unstable/cli/Primitive.ts | 2 +- 27 files changed, 72 insertions(+), 85 deletions(-) diff --git a/packages/ai/openai/src/OpenAiEmbeddingModel.ts b/packages/ai/openai/src/OpenAiEmbeddingModel.ts index 5b64f8d783..270a082ab9 100644 --- a/packages/ai/openai/src/OpenAiEmbeddingModel.ts +++ b/packages/ai/openai/src/OpenAiEmbeddingModel.ts @@ -126,8 +126,7 @@ export const model = ( * **When to use** * * Use to construct the `EmbeddingModel.Service` effectfully when - * `OpenAiClient` is already available in the environment or when the service - * value is needed directly. + * `OpenAiClient` is already available in the environment. * * **Details** * diff --git a/packages/atom/solid/src/RegistryContext.ts b/packages/atom/solid/src/RegistryContext.ts index 4376de990a..be6924466f 100644 --- a/packages/atom/solid/src/RegistryContext.ts +++ b/packages/atom/solid/src/RegistryContext.ts @@ -34,8 +34,8 @@ import { createComponent, createContext, onCleanup } from "solid-js" * * **When to use** * - * Use when you need lower-level Solid atom APIs to access an `AtomRegistry`, or - * when you need to provide a registry directly for the current owner tree. + * Use when you need to access or provide an `AtomRegistry` directly for the + * current Solid owner tree. * * **Details** * diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index f288335a0b..ced7307075 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -225,7 +225,7 @@ export const make = >( * * **When to use** * - * Use when you need a pre-sized array that you will fill imperatively. + * Use when you need a pre-sized array that will be filled imperatively. * * **Details** * diff --git a/packages/effect/src/Combiner.ts b/packages/effect/src/Combiner.ts index 6a5f5ccda2..b2f89bb5fa 100644 --- a/packages/effect/src/Combiner.ts +++ b/packages/effect/src/Combiner.ts @@ -242,8 +242,7 @@ export function max(order: Order.Order): Combiner { * * **When to use** * - * Use when you want "first write wins" semantics while merging values, or - * when the combining logic should keep the existing value. + * Use when you want "first write wins" semantics while merging values. * * **Details** * @@ -273,8 +272,7 @@ export function first(): Combiner { * * **When to use** * - * Use when you want "last write wins" semantics while merging values, or - * when each new value should replace the accumulator. + * Use when you want "last write wins" semantics while merging values. * * **Details** * @@ -305,9 +303,8 @@ export function last(): Combiner { * * **When to use** * - * Use when a combiner should produce a fixed result regardless of input, - * or when a generic API needs a combiner but the combined value is - * predetermined. + * Use when you need a combiner that always returns a fixed value, including + * when a generic API requires a combiner but the result is predetermined. * * **Details** * @@ -339,9 +336,9 @@ export function constant(a: A): Combiner { * * **When to use** * - * Use when you are building delimited strings (CSV, paths, etc.) by - * repeated combination, or when you need to inject a fixed separator between - * accumulated values. + * Use when you need to inject a fixed separator between accumulated values, + * such as when building delimited strings, paths, or CSV-like output by + * repeated combination. * * **Details** * diff --git a/packages/effect/src/Config.ts b/packages/effect/src/Config.ts index d7fb364a55..56938a6f21 100644 --- a/packages/effect/src/Config.ts +++ b/packages/effect/src/Config.ts @@ -689,15 +689,16 @@ const recur: ( * * **When to use** * - * Use when reading structured or validated config (structs, arrays, unions, branded - * types, etc.). - * - All convenience constructors (`string`, `number`, …) delegate to this. + * Use when you need to read structured or schema-validated configuration. * * **Details** * * The optional `path` sets the root path segment(s) for the config lookup. * Pass a single string for a flat key or an array for nested paths. * + * Convenience constructors such as `string`, `number`, and `boolean` delegate + * to this API. + * * The codec is used to decode the raw `StringTree` produced by the provider * into `T`. Schema validation errors are wrapped in `ConfigError`. * diff --git a/packages/effect/src/ConfigProvider.ts b/packages/effect/src/ConfigProvider.ts index 035ca2bed0..5751f22aff 100644 --- a/packages/effect/src/ConfigProvider.ts +++ b/packages/effect/src/ConfigProvider.ts @@ -239,9 +239,8 @@ export function makeArray(length: number, value?: string): Node { * * **When to use** * - * Use when writing a custom provider's `get` callback for an underlying store that is - * unreachable or produces an I/O error, or when matching on error channels while consuming - * provider output directly. + * Use when you need to report that a custom provider's underlying store is + * unreachable or produced an I/O error while reading configuration data. * * **Gotchas** * @@ -736,9 +735,8 @@ export const layerAdd = ( * * **When to use** * - * Use when you need deterministic config for unit or integration tests without - * touching the environment, or when config is embedded directly in code or read - * from a JSON file. + * Use when you need deterministic config from an in-memory JavaScript value, + * such as in tests, embedded config, or parsed JSON. * * **Details** * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 0ef3625bcc..7e67d62b3a 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -4147,6 +4147,8 @@ export const sandbox: ( * Use when an effect should run for its side effects while both success and * failure values are discarded. * + * **Details** + * * Use the `log` option to emit the full {@link Cause} when the effect fails, * and `message` to prepend a custom log message. * @@ -4411,7 +4413,7 @@ export const firstSuccessOf: >( * * **When to use** * - * Use when exceeding the time limit should be represented as a typed failure. + * Use when you need to represent exceeding the time limit as a typed failure. * * **Details** * @@ -5295,9 +5297,8 @@ export const match: { * * **When to use** * - * Use when you need to handle both success and failure cases and want - * optimal performance for resolved effects. This is particularly useful in - * scenarios where you frequently work with already computed values. + * Use when you need to handle both success and failure cases and want optimized + * handling for effects that may already be resolved. * * **Details** * @@ -6927,9 +6928,8 @@ export const onExitFilter: { * * **When to use** * - * Use when an expensive or time-consuming operation should be evaluated once and reused by - * later callers. The first evaluation computes the result, and later evaluations return the - * cached value. + * Use when you need an expensive or time-consuming operation to be evaluated + * once and reused by later callers. * * **Details** * @@ -6991,14 +6991,8 @@ export const cached: (self: Effect) => Effect> * * **When to use** * - * Use when an effect with costly operations or computations should be reused for a bounded - * duration before being recomputed. - * - * It's ideal for scenarios where the result of an effect doesn't change - * frequently and can be reused for a specified duration. - * - * By caching the result, you can improve efficiency and reduce unnecessary - * computations, especially in performance-critical applications. + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. * * **Details** * diff --git a/packages/effect/src/Equal.ts b/packages/effect/src/Equal.ts index 5ffc141279..69e25ed9fa 100644 --- a/packages/effect/src/Equal.ts +++ b/packages/effect/src/Equal.ts @@ -531,10 +531,8 @@ export const asEquivalence: () => Equivalence = () => equals * * **When to use** * - * Use when you have a plain object or array that should be compared by identity - * (reference), not by contents. - * - When you want to preserve the original object unchanged and get a new - * reference-equal handle. + * Use when you need to compare a plain object or array by identity without + * mutating the original value. * * **Details** * diff --git a/packages/effect/src/Formatter.ts b/packages/effect/src/Formatter.ts index 2bfdc5cfd3..9930bce4cc 100644 --- a/packages/effect/src/Formatter.ts +++ b/packages/effect/src/Formatter.ts @@ -91,16 +91,16 @@ export interface Formatter { * * **When to use** * - * Use to pretty-print values for debugging, logging, or error messages. - * - You need to handle `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, - * or class instances that `JSON.stringify` cannot represent. - * - You want circular references shown as `"[Circular]"` instead of - * throwing. + * Use when you need to format arbitrary JavaScript values for debugging, + * logging, or error messages. * * **Details** * * - Output is **not** valid JSON; use {@link formatJson} when you need * parseable JSON. + * - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class + * instances that `JSON.stringify` cannot represent. + * - Circular references are shown as `"[Circular]"` instead of throwing. * - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). * Strings are JSON-quoted. * - Objects with a custom `toString` (not `Object.prototype.toString`): @@ -112,7 +112,6 @@ export interface Formatter { * - `Redactable` values are automatically redacted. * - Arrays/objects with 0–1 entries are inline; larger ones are * pretty-printed when `space` is set. - * - Circular references are replaced with `"[Circular]"`. * - `space` — indentation unit (number of spaces, or a string like * `"\t"`). Defaults to `0` (compact). * - `ignoreToString` — skip calling `toString()`. Defaults to `false`. diff --git a/packages/effect/src/Function.ts b/packages/effect/src/Function.ts index 9c446671d2..dfc684d19c 100644 --- a/packages/effect/src/Function.ts +++ b/packages/effect/src/Function.ts @@ -612,8 +612,8 @@ export const untupled = , B>(f: (a: A) => B): ( * * **When to use** * - * Use when composing data-last functions into readable transformation pipelines, - * or when replacing method-style chains with ordinary function calls. + * Use when you need to compose data-last functions into readable + * transformation pipelines instead of method-style chains. * * **Details** * diff --git a/packages/effect/src/Iterable.ts b/packages/effect/src/Iterable.ts index cc7e472b95..921bf56f12 100644 --- a/packages/effect/src/Iterable.ts +++ b/packages/effect/src/Iterable.ts @@ -1424,8 +1424,8 @@ const constEmptyIterator: Iterator = { * * **When to use** * - * Use as a base case for operations or when you - * need to represent "no data" in a type-safe way. + * Use when you need an empty iterable as a typed "no data" value or a base + * case for iterable operations. * * **Example** (Creating an empty iterable) * diff --git a/packages/effect/src/Metric.ts b/packages/effect/src/Metric.ts index 2f88589d70..354411a25d 100644 --- a/packages/effect/src/Metric.ts +++ b/packages/effect/src/Metric.ts @@ -3999,9 +3999,8 @@ export const enableRuntimeMetrics: (self: Effect) => Effect( * **When to use** * * Use when you need to combine multiple `Option` values into one while - * preserving the input shape; any `None` makes the result `None`. + * preserving the input shape, with any `None` making the result `None`. * * **Details** * diff --git a/packages/effect/src/PlatformError.ts b/packages/effect/src/PlatformError.ts index 66368711ab..860fc32599 100644 --- a/packages/effect/src/PlatformError.ts +++ b/packages/effect/src/PlatformError.ts @@ -112,8 +112,8 @@ export type SystemErrorTag = * * **When to use** * - * Use as the reason data for failures reported by a host platform or operating - * system when you need a normalized system error tag plus operation details. + * Use when you need normalized reason data for a platform or system operation + * failure, including the operation details. * * **Details** * diff --git a/packages/effect/src/Pool.ts b/packages/effect/src/Pool.ts index bf0cfe5fd1..464dd45bc4 100644 --- a/packages/effect/src/Pool.ts +++ b/packages/effect/src/Pool.ts @@ -530,9 +530,8 @@ const getPoolItemInner = Effect.fnUntraced(function*( * * **When to use** * - * Use to prevent a pooled item from being reused after you determine it is no - * longer suitable, such as a stale connection or a resource that failed a - * health check. + * Use to prevent a pooled item from being reused after it becomes unsuitable, + * such as a stale connection or a resource that failed a health check. * * **Gotchas** * diff --git a/packages/effect/src/Predicate.ts b/packages/effect/src/Predicate.ts index 7854eee5d7..cedd375bd1 100644 --- a/packages/effect/src/Predicate.ts +++ b/packages/effect/src/Predicate.ts @@ -1745,11 +1745,12 @@ export const eqv: { * * **When to use** * - * Use when you want a rule that only applies when a precondition holds. - * - You model constraints like "if A then B". + * Use when you need to encode logical implication for a predicate rule that + * only applies when a precondition holds. * * **Details** * + * - Models constraints like "if A then B". * - Returns `true` when the antecedent is `false`. * * **Example** (Implication) diff --git a/packages/effect/src/Pull.ts b/packages/effect/src/Pull.ts index 391d26dde2..bd8147697a 100644 --- a/packages/effect/src/Pull.ts +++ b/packages/effect/src/Pull.ts @@ -208,8 +208,8 @@ export const isDoneCause = (cause: Cause.Cause): boolean => cause.reasons. * * **When to use** * - * Use as a predicate when traversing `cause.reasons` and you need to identify - * done completion reasons before handling ordinary failures. + * Use when you need to identify done completion reasons while traversing + * `cause.reasons`, before handling ordinary failures. * * @see {@link isDoneCause} for checking an entire `Cause` for any done reason * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 91e606dc69..38bdc63199 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -11202,8 +11202,8 @@ export interface DateTimeUtcFromDate extends decodeTo { * * **When to use** * - * Use when a boundary provides valid JavaScript `Date` objects but the decoded - * model should use `DateTime.Utc`. + * Use when you need to decode valid JavaScript `Date` objects into + * `DateTime.Utc` values. * * **Details** * diff --git a/packages/effect/src/SchemaAST.ts b/packages/effect/src/SchemaAST.ts index f2d8dbb97c..8ef8ebc248 100644 --- a/packages/effect/src/SchemaAST.ts +++ b/packages/effect/src/SchemaAST.ts @@ -694,14 +694,14 @@ export abstract class Base { * **When to use** * * Use when you need a custom schema AST node because none of the built-in - * nodes fit. The `run` function receives `typeParameters` and returns a parser - * that validates or transforms raw input. + * nodes fit. * * **Details** * * - `typeParameters` — inner schemas this declaration is parameterized over * (e.g. the element type for a custom collection). - * - `run` — factory producing the actual parse function. + * - `run` — factory that receives `typeParameters` and returns a parser that + * validates or transforms raw input. * * @see {@link isDeclaration} * @category models diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaParser.ts index fc69eea5ef..06fdfd2888 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaParser.ts @@ -119,8 +119,8 @@ export function makeEffect(schema: S) { * * **When to use** * - * Use when you only need to know whether constructor input is valid and do - * not need error details. + * Use when you need to validate constructor input and only care whether + * construction succeeds. * * @category constructors * @since 4.0.0 @@ -405,8 +405,9 @@ export const decodeExit: >( * * **When to use** * - * Use when you need a synchronous yes/no decode from untyped input and do not - * need schema issue details. + * Use when decoding unknown input and you want a synchronous `Option` result + * that keeps the decoded value on success but discards issue details on + * failure. * * **Details** * diff --git a/packages/effect/src/Sink.ts b/packages/effect/src/Sink.ts index a4e1467acb..e7c7cd933e 100644 --- a/packages/effect/src/Sink.ts +++ b/packages/effect/src/Sink.ts @@ -1499,7 +1499,8 @@ export const find: { * * **When to use** * - * Use when you need matching an input to run effects, fail, or use services. + * Use when you need to run effects, fail, or use services while searching for + * the first matching input. * * **Details** * diff --git a/packages/effect/src/UndefinedOr.ts b/packages/effect/src/UndefinedOr.ts index ec1d65bb5a..099a5470c8 100644 --- a/packages/effect/src/UndefinedOr.ts +++ b/packages/effect/src/UndefinedOr.ts @@ -148,7 +148,7 @@ export const getOrThrowWith: { * * **When to use** * - * Use when a value should already be defined at this point and throwing a + * Use when you need to unwrap a value that should already be defined and a * generic missing-value `Error` is acceptable. * * **Details** diff --git a/packages/effect/src/unstable/ai/IdGenerator.ts b/packages/effect/src/unstable/ai/IdGenerator.ts index 51059e62b1..d9e7c677e0 100644 --- a/packages/effect/src/unstable/ai/IdGenerator.ts +++ b/packages/effect/src/unstable/ai/IdGenerator.ts @@ -306,8 +306,8 @@ export const make = Effect.fnUntraced(function*({ * * **When to use** * - * Use when an application should provide ID generation capabilities from validated - * configuration. The layer will fail during construction if the configuration is invalid. + * Use when you need to provide ID generation capabilities from validated + * configuration. * * **Example** (Providing an ID generator layer) * diff --git a/packages/effect/src/unstable/ai/Toolkit.ts b/packages/effect/src/unstable/ai/Toolkit.ts index c093a2d8e0..ff34d0e57b 100644 --- a/packages/effect/src/unstable/ai/Toolkit.ts +++ b/packages/effect/src/unstable/ai/Toolkit.ts @@ -497,8 +497,8 @@ const resolveInput = >( * * **When to use** * - * Use as a starting point for building toolkits or as a default value. Can - * be extended using the merge function to add tools. + * Use when you need an empty starting point for building toolkits or a default + * toolkit value that can be extended with `merge`. * * @category constructors * @since 4.0.0 diff --git a/packages/effect/src/unstable/cli/Flag.ts b/packages/effect/src/unstable/cli/Flag.ts index 268653c721..c980da6c48 100644 --- a/packages/effect/src/unstable/cli/Flag.ts +++ b/packages/effect/src/unstable/cli/Flag.ts @@ -166,8 +166,8 @@ export const choiceWithValue = = makePrimitive("None", () => Effect.fail("T * * **When to use** * - * Use when you need generating help documentation. + * Use when you need to generate help documentation. * * **Example** (Getting primitive type names) * From 8d39ca119c21ade5781eac8bad8f5191c6637a68 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 07:35:58 +0200 Subject: [PATCH 12/29] wip --- packages/effect/src/Context.ts | 5 +++-- packages/effect/src/Effect.ts | 6 ++++-- packages/effect/src/Exit.ts | 8 ++++---- packages/effect/src/Fiber.ts | 6 ++++-- packages/effect/src/Schedule.ts | 2 +- packages/effect/src/unstable/cli/Primitive.ts | 2 +- 6 files changed, 17 insertions(+), 12 deletions(-) diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index f9f32ab11a..57f10e659a 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -685,7 +685,7 @@ export const make = ( * * **When to use** * - * Use when you always have a service value to store. + * Use when you need to store a known service value in a `Context`. * * **Details** * @@ -856,7 +856,8 @@ export const getOrElse: { * * **When to use** * - * Use when you need raw map-style lookup. + * Use when you need to read the service stored for a key without resolving + * `Context.Reference` defaults. * * **Gotchas** * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 7e67d62b3a..98667d47cd 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1169,7 +1169,8 @@ export const suspend: ( * * **When to use** * - * Use when you are sure the operation will not fail. + * Use when you need to wrap a synchronous side-effectful operation that is not + * expected to throw. * * **Details** * @@ -2210,7 +2211,8 @@ export const result: (self: Effect) => Effect(cause: Cause.Cause) => Exit = core.exit * * **When to use** * - * Use when you need expected, recoverable failures + * Use when you need to represent an expected typed failure as an `Exit`. * * **Details** * @@ -395,12 +395,12 @@ export { * * **When to use** * - * Use when you need a success Exit but do not care about the value - * - Avoids allocating a new Exit for a common case + * Use when you need a shared successful `Exit` with no meaningful value. * * **Details** * - * Equivalent to `Exit.succeed(undefined)` but shared as a single instance. + * Equivalent to `Exit.succeed(undefined)` but shared as a single instance, + * avoiding allocation for a common case. * * **Example** (Using the void Exit) * diff --git a/packages/effect/src/Fiber.ts b/packages/effect/src/Fiber.ts index 741d363f9f..bc68325837 100644 --- a/packages/effect/src/Fiber.ts +++ b/packages/effect/src/Fiber.ts @@ -358,7 +358,8 @@ export const joinAll: >>( * * **When to use** * - * Use when a forked fiber is no longer needed and should be cancelled. + * Use when you need to cancel a forked fiber and wait for its cleanup to + * complete. * * **Details** * @@ -448,7 +449,8 @@ export const interruptAs: { * * **When to use** * - * Use when you no longer need a group of forked fibers. + * Use when you need to cancel several forked fibers and wait for their cleanup + * to complete. * * **Details** * diff --git a/packages/effect/src/Schedule.ts b/packages/effect/src/Schedule.ts index b21c5010c1..0221d8f33c 100644 --- a/packages/effect/src/Schedule.ts +++ b/packages/effect/src/Schedule.ts @@ -1541,7 +1541,7 @@ export const delays = (self: Schedule): Schedule> = makePrimitive( * * **When to use** * - * Use when you need flags that don't accept values. + * Use when you need a CLI primitive for flags that do not accept values. * * **Example** (Rejecting option values) * From fcb69f8b41646a0564f568eb64683293b9e9ff5d Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 07:44:57 +0200 Subject: [PATCH 13/29] wip --- packages/effect/src/Brand.ts | 12 ++++---- packages/effect/src/Cause.ts | 2 +- packages/effect/src/Effect.ts | 28 +++++++++++++------ packages/effect/src/Layer.ts | 9 ++++-- packages/effect/src/Pipeable.ts | 4 +-- packages/effect/src/Predicate.ts | 2 +- packages/effect/src/Queue.ts | 4 +-- packages/effect/src/Resource.ts | 4 +-- packages/effect/src/Runtime.ts | 11 +++++--- packages/effect/src/SchemaIssue.ts | 5 ++-- packages/effect/src/Stream.ts | 14 ++++++++-- .../eventlog/EventLogServerUnencrypted.ts | 3 +- 12 files changed, 62 insertions(+), 36 deletions(-) diff --git a/packages/effect/src/Brand.ts b/packages/effect/src/Brand.ts index 9ad5d9ea96..f7fdff5bfa 100644 --- a/packages/effect/src/Brand.ts +++ b/packages/effect/src/Brand.ts @@ -261,8 +261,10 @@ export type Branded = A & Brand * **When to use** * * Use to create nominal types that allow distinguishing between two values - * of the same type but with different meanings. If you also want to perform - * some validation, see {@link make} or {@link check}. + * of the same type but with different meanings. + * + * @see {@link make} for constructing branded values with validation. + * @see {@link check} for constructing branded values from schema checks. * * @category constructors * @since 2.0.0 @@ -281,9 +283,9 @@ export function nominal>(): Constructor { * * **When to use** * - * Use when you want validation while constructing the branded type. If you - * don't want to perform any validation but only distinguish between two values - * of the same type but with different meanings, see {@link nominal}. + * Use when you want validation while constructing the branded type. + * + * @see {@link nominal} for a brand constructor that performs no validation. * * @category constructors * @since 4.0.0 diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index cb896c6654..bd822d1f58 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -1428,7 +1428,7 @@ export declare namespace Done { * * **When to use** * - * Use when you need the completion signal value itself. + * Use when you need to construct a low-level pull completion signal directly. * * @see {@link done} — create a failing `Effect` with `Done` * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 98667d47cd..c74e501d34 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1079,7 +1079,7 @@ export const succeedSome: (value: A) => Effect> = internal.succeedS * * **When to use** * - * Use when you need to defer the evaluation of an effect until it is required. This is particularly useful for optimizing expensive computations, managing circular dependencies, or resolving type inference issues. + * Use when you need to defer the evaluation of an effect until it is required. * * **Details** * @@ -1512,9 +1512,12 @@ export declare namespace gen { * * **When to use** * - * Use to explicitly signal an error in an `Effect`. The error - * will keep propagating unless it is handled. You can handle the error with - * functions like {@link catchTag} or {@link catchTags}. + * Use to explicitly signal a recoverable error in an `Effect`. + * + * **Details** + * + * The error keeps propagating unless it is handled. You can handle tagged + * errors with functions like {@link catchTag} or {@link catchTags}. * * **Example** (Creating a failed effect) * @@ -2754,10 +2757,14 @@ export const catchTag: { * **When to use** * * Use when one recovery step should handle several tagged error types by - * matching their readonly `_tag` fields. Pass a handler table whose keys are - * tags, plus an optional fallback for unmatched errors. + * matching their readonly `_tag` fields. + * + * **Details** * - * The error type must have a readonly `_tag` field to use `catchTag`. This + * Pass a handler table whose keys are tags, plus an optional fallback for + * unmatched errors. + * + * The error type must have a readonly `_tag` field to use `catchTags`. This * field is used to identify and match errors. * * **Example** (Handling multiple tagged errors) @@ -3252,8 +3259,11 @@ export const catchDefect: { * * **When to use** * - * Use when you need to recover from errors that match a condition. Use a - * `Refinement` for type narrowing or a `Predicate` for simple boolean + * Use when you need to recover from errors that match a condition. + * + * **Details** + * + * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean * matching. Non-matching errors re-fail with the original cause. Defects and * interrupts are not caught. * diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index 0c8769e4fb..519de0abc9 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -2051,9 +2051,12 @@ export const updateService: { * **When to use** * * Use when you need two parts of an application to receive separate instances - * of a resource, such as two independent client sessions. Do not use it just to - * work around confusing composition: by default, sharing the same layer value is - * usually the desired behavior. + * of a resource, such as two independent client sessions. + * + * **Gotchas** + * + * Do not use it just to work around confusing composition. By default, sharing + * the same layer value is usually the desired behavior. * * **Example** (Creating non-shared layer instances) * diff --git a/packages/effect/src/Pipeable.ts b/packages/effect/src/Pipeable.ts index b637ee393f..64f7464259 100644 --- a/packages/effect/src/Pipeable.ts +++ b/packages/effect/src/Pipeable.ts @@ -626,8 +626,8 @@ export const Prototype: Pipeable = { * * **When to use** * - * Use when extend or compose this constructor when defining a class that should support - * Effect-style method chaining through `.pipe(...)`. + * Use when you need to define a class that supports Effect-style method + * chaining through `.pipe(...)`. * * @category constructors * @since 3.15.0 diff --git a/packages/effect/src/Predicate.ts b/packages/effect/src/Predicate.ts index cedd375bd1..3aea5e4960 100644 --- a/packages/effect/src/Predicate.ts +++ b/packages/effect/src/Predicate.ts @@ -792,7 +792,7 @@ export function isFunction(input: unknown): input is Function { * * **When to use** * - * Use when you need a guard for optional values. + * Use when you need to guard unknown values that are exactly `undefined`. * * **Details** * diff --git a/packages/effect/src/Queue.ts b/packages/effect/src/Queue.ts index d0d26e7ffb..8b549a09fc 100644 --- a/packages/effect/src/Queue.ts +++ b/packages/effect/src/Queue.ts @@ -553,8 +553,8 @@ export const bounded = (capacity: number): Effect> => * * **When to use** * - * Use when producers should not block and message loss is acceptable. - * Useful when you want to maintain a rolling window of the most recent messages. + * Use when producers should not block and message loss is acceptable, such as + * when maintaining a rolling window of the most recent messages. * * **Example** (Creating sliding queues) * diff --git a/packages/effect/src/Resource.ts b/packages/effect/src/Resource.ts index d845fb7569..185ee6e113 100644 --- a/packages/effect/src/Resource.ts +++ b/packages/effect/src/Resource.ts @@ -113,8 +113,8 @@ const makeUnsafe = ( * * **When to use** * - * Use when you need to control the timing of resource refreshes yourself rather - * than relying on an automatic schedule. + * Use when you need manual control over resource refresh timing rather than an + * automatic schedule. * * @see {@link auto} for schedule-driven automatic refreshes * @see {@link refresh} to manually trigger a resource refresh diff --git a/packages/effect/src/Runtime.ts b/packages/effect/src/Runtime.ts index 511fc6d580..8cedc29f93 100644 --- a/packages/effect/src/Runtime.ts +++ b/packages/effect/src/Runtime.ts @@ -176,13 +176,16 @@ export const defaultTeardown: Teardown = ( * * **When to use** * - * Use when building a runtime adapter for a host platform. Most applications - * should use a platform-provided runner, such as `NodeRuntime.runMain`, rather - * than constructing one directly. + * Use when building a runtime adapter for a host platform. * * **Details** * - * The runner executes Effect programs as main entry points. The provided function receives a forked fiber and a teardown callback so it can install platform-specific signal handling, fiber observers, and final exit behavior. + * The runner executes Effect programs as main entry points. The provided + * function receives a forked fiber and a teardown callback so it can install + * platform-specific signal handling, fiber observers, and final exit behavior. + * + * Most applications should use a platform-provided runner, such as + * `NodeRuntime.runMain`, rather than constructing one directly. * * `disableErrorReporting` disables the automatic log emitted for unreported * non-interruption failures. It does not change exit-code calculation or the diff --git a/packages/effect/src/SchemaIssue.ts b/packages/effect/src/SchemaIssue.ts index cb4b4ae4c8..5bb5e02af9 100644 --- a/packages/effect/src/SchemaIssue.ts +++ b/packages/effect/src/SchemaIssue.ts @@ -1143,11 +1143,12 @@ function formatCheck(check: AST.Check): string { * **When to use** * * Use when you need error messages for logging, CLI output, or - * developer-facing diagnostics. This is the default formatter used by - * `Issue.toString()`. + * developer-facing diagnostics. * * **Details** * + * This is the default formatter used by `Issue.toString()`. + * * - Flattens the issue tree into `{ message, path }` entries using * {@link defaultLeafHook} and {@link defaultCheckHook}. * - Each entry is rendered as `""` or `"\n at "`. diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 56f0342dcc..6dbe6ce4da 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -5479,7 +5479,11 @@ export const catchTags: { * **When to use** * * Use to handle nested error causes without removing the parent error - * from the error channel. The handler receives the unwrapped reason. + * from the error channel. + * + * **Details** + * + * The handler receives the unwrapped reason. * * **Example** (Catching a tagged error reason) * @@ -5999,8 +6003,12 @@ export const orDie = (self: Stream): Stream => fr * **When to use** * * Use when you want a failing stream to end gracefully rather than propagate - * the error. The `log` option controls whether the failure is logged before - * the stream terminates. + * the error. + * + * **Details** + * + * The `log` option controls whether the failure is logged before the stream + * terminates. * * **Example** (Ignoring stream failures) * diff --git a/packages/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts b/packages/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts index bab8d8a6a7..fb10f2a06f 100644 --- a/packages/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts +++ b/packages/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts @@ -703,8 +703,7 @@ export const layerStorageMemory: Layer.Layer = Layer.effect(Storage)(ma * **When to use** * * Use to construct the unencrypted event-log server service directly when you - * already provide `Storage` and an event-log `Registry` and want to supply the - * service yourself. + * already provide `Storage` and an event-log `Registry`. * * **Details** * From bde9fc8d62ff23a51affea318725c6cb81b9b64f Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 08:09:27 +0200 Subject: [PATCH 14/29] wip --- packages/ai/openai-compat/src/OpenAiClient.ts | 3 +- packages/ai/openai-compat/src/OpenAiConfig.ts | 4 +- packages/ai/openai/src/OpenAiClient.ts | 3 +- .../ai/openrouter/src/OpenRouterClient.ts | 3 +- packages/effect/src/Array.ts | 24 ++++----- packages/effect/src/Cause.ts | 4 +- packages/effect/src/Context.ts | 4 +- packages/effect/src/Effect.ts | 9 ++-- packages/effect/src/Graph.ts | 4 +- packages/effect/src/Layer.ts | 3 +- packages/effect/src/MutableRef.ts | 50 +++++++++-------- packages/effect/src/Option.ts | 2 +- packages/effect/src/Pool.ts | 3 +- packages/effect/src/Queue.ts | 8 +-- packages/effect/src/Ref.ts | 25 ++++----- packages/effect/src/Request.ts | 8 +-- packages/effect/src/Runtime.ts | 4 +- packages/effect/src/Schema.ts | 5 +- packages/effect/src/SchemaIssue.ts | 7 +-- packages/effect/src/SchemaParser.ts | 10 ++-- packages/effect/src/Sink.ts | 3 +- packages/effect/src/Stdio.ts | 5 +- packages/effect/src/String.ts | 5 +- packages/effect/src/SubscriptionRef.ts | 14 ++--- packages/effect/src/SynchronizedRef.ts | 53 +++++++++++-------- packages/effect/src/TxRef.ts | 16 +++--- packages/effect/src/TxSubscriptionRef.ts | 29 +++++----- packages/effect/src/unstable/ai/Chat.ts | 5 +- .../effect/src/unstable/cli/Completions.ts | 2 +- .../effect/src/unstable/cluster/Runners.ts | 6 +-- .../effect/src/unstable/cluster/Snowflake.ts | 2 +- .../eventlog/EventLogServerEncrypted.ts | 5 +- .../eventlog/EventLogServerUnencrypted.ts | 4 +- .../effect/src/unstable/reactivity/Atom.ts | 6 +-- packages/opentelemetry/src/Metrics.ts | 4 +- 35 files changed, 172 insertions(+), 170 deletions(-) diff --git a/packages/ai/openai-compat/src/OpenAiClient.ts b/packages/ai/openai-compat/src/OpenAiClient.ts index c93ecd49b2..8d17b84a85 100644 --- a/packages/ai/openai-compat/src/OpenAiClient.ts +++ b/packages/ai/openai-compat/src/OpenAiClient.ts @@ -125,8 +125,7 @@ const RedactedOpenAiHeaders = { * * **When to use** * - * Use to construct the OpenAI-compatible client service inside an effect when - * you need the service value directly. + * Use when you need the OpenAI-compatible client service value inside an effect. * * **Details** * diff --git a/packages/ai/openai-compat/src/OpenAiConfig.ts b/packages/ai/openai-compat/src/OpenAiConfig.ts index 6f7e3808bd..0d0b73a9e5 100644 --- a/packages/ai/openai-compat/src/OpenAiConfig.ts +++ b/packages/ai/openai-compat/src/OpenAiConfig.ts @@ -32,8 +32,8 @@ import type { HttpClient } from "effect/unstable/http/HttpClient" * * **When to use** * - * Use as the context service for OpenAI-compatible client configuration when you - * need to provide or read scoped HTTP client transforms through Effect context. + * Use as the context service for scoped OpenAI-compatible client configuration + * and HTTP client transforms. * * @see {@link withClientTransform} for scoping an HTTP client transformation * diff --git a/packages/ai/openai/src/OpenAiClient.ts b/packages/ai/openai/src/OpenAiClient.ts index 523cd19e3e..7925fdb94d 100644 --- a/packages/ai/openai/src/OpenAiClient.ts +++ b/packages/ai/openai/src/OpenAiClient.ts @@ -189,8 +189,7 @@ const RedactedOpenAiHeaders = { * * **When to use** * - * Use to construct the OpenAI client service inside an effect when you need the - * service value directly. + * Use when you need the OpenAI client service value inside an effect. * * **Details** * diff --git a/packages/ai/openrouter/src/OpenRouterClient.ts b/packages/ai/openrouter/src/OpenRouterClient.ts index e92e293961..7d031bb202 100644 --- a/packages/ai/openrouter/src/OpenRouterClient.ts +++ b/packages/ai/openrouter/src/OpenRouterClient.ts @@ -159,8 +159,7 @@ export type Options = { * * **When to use** * - * Use to construct the OpenRouter client service inside an effect when you need - * the service value directly. + * Use when you need the OpenRouter client service value inside an effect. * * **Details** * diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index ced7307075..dfce3cd8ea 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -523,8 +523,8 @@ export const match: { * * **When to use** * - * Use to pattern-match when you need the first element and remaining elements as - * separate values. + * Use when you need to branch on an array and handle the non-empty case as the + * first element plus the remaining elements. * * **Details** * @@ -577,8 +577,8 @@ export const matchLeft: { * * **When to use** * - * Use to pattern-match when you need all but the last element and the last element - * as separate values. + * Use when you need to branch on an array and handle the non-empty case as the + * elements before the last plus the last element. * * **Details** * @@ -1107,8 +1107,8 @@ export const unprepend = ( * * **When to use** * - * Use to split a non-empty array from the end when you need both the elements - * before the last element and the last element. + * Use when you need to split a non-empty array into the elements before the + * last element and the last element. * * **Details** * @@ -1514,8 +1514,8 @@ const spanIndex = (self: Iterable, predicate: (a: A, i: number) => boolean * * **When to use** * - * Use to split an iterable into the longest prefix that satisfies a predicate - * and the elements after that prefix when you need both parts. + * Use when you need both the longest predicate-matching prefix and the + * remaining elements. * * **Details** * @@ -2263,7 +2263,7 @@ export const sortBy = >( * * **When to use** * - * Use to pair corresponding elements from two iterables when you need simple pairs without a custom combiner. + * Use when you need simple pairs of corresponding elements from two iterables. * * **Details** * @@ -2806,7 +2806,8 @@ export const split: { * * **When to use** * - * Use to split an array at a condition boundary when you know which element marks the transition point. + * Use when you need to split an array at the first element that marks a + * condition boundary. * * **Example** (Splitting at a condition) * @@ -4901,8 +4902,7 @@ export function makeReducerConcat(): Reducer.Reducer> { * * **When to use** * - * Use to count how many elements satisfy a predicate when you only need the - * number of matches instead of the matching elements. + * Use when you only need the number of elements that satisfy a predicate. * * **Details** * diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index bd822d1f58..b3675cf08a 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -1041,8 +1041,8 @@ export const hasInterrupts: (self: Cause) => boolean = effect.hasInterrupt * * **When to use** * - * Use to extract the first interruption reason when you need its fiber ID and - * annotations. + * Use when you need the fiber ID and annotations from the first interruption + * reason. * * **Example** (extracting the first interrupt) * diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index 57f10e659a..0f98d3b6e4 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -969,8 +969,8 @@ export const get: { * * **When to use** * - * Use to resolve a `Context.Reference` against a context when you want either - * the stored override or the reference's default value. + * Use when you need a `Context.Reference` value resolved from either a stored + * override or the reference's default value. * * **Details** * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index c74e501d34..983e8e81cd 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -7599,9 +7599,8 @@ export const repeatOrElse: { * * **When to use** * - * Use to create an array containing the same effect multiple times when you - * want to pass those effects to another collector or control execution - * separately. + * Use when you need an array of identical effect values without running them + * yet. * * **Details** * @@ -8328,9 +8327,7 @@ export const withParentSpan: { * * **When to use** * - * Use to execute a typed `Request` through a `RequestResolver` when you want - * concurrent requests made with the same resolver to be collected and completed - * by resolver logic. + * Use when you need resolver-driven batching for a typed `Request`. * * **Example** (Executing a request through a resolver) * diff --git a/packages/effect/src/Graph.ts b/packages/effect/src/Graph.ts index 3b2b6eed5e..3bdbe5d76a 100644 --- a/packages/effect/src/Graph.ts +++ b/packages/effect/src/Graph.ts @@ -119,8 +119,8 @@ export type EdgeIndex = number * * **When to use** * - * Use as the graph edge value returned by `getEdge` and `edges` when you need - * the source node, target node, and stored edge data together. + * Use as the graph edge value that carries source node, target node, and stored + * edge data together. * * @see {@link getEdge} for reading a single edge by identifier * @see {@link addEdge} for adding edges to a graph diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index 519de0abc9..7ea156b04a 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -1331,8 +1331,7 @@ const provideWith = ( * * **When to use** * - * Use when the dependency layer is an implementation detail of the layer being built - * and should not be exposed to callers. + * Use when you need to hide an implementation dependency layer from callers. * * **Details** * diff --git a/packages/effect/src/MutableRef.ts b/packages/effect/src/MutableRef.ts index 821a023038..f94f70c4c8 100644 --- a/packages/effect/src/MutableRef.ts +++ b/packages/effect/src/MutableRef.ts @@ -109,7 +109,7 @@ const MutableRefProto: Omit, "current"> = { * * **When to use** * - * Use to create a synchronous mutable reference initialized with a value. + * Use to create a synchronous `MutableRef` initialized with a value. * * **Example** (Creating mutable refs) * @@ -146,8 +146,8 @@ export const make = (value: T): MutableRef => { * * **When to use** * - * Use to replace a value only when the current value still matches an expected - * value. + * Use to replace a `MutableRef` value only when the current value still matches + * an expected value. * * **Example** (Comparing and setting values) * @@ -200,8 +200,8 @@ export const compareAndSet: { * * **When to use** * - * Use to decrement a numeric reference in place when you want the same - * reference back. + * Use when you need an in-place `MutableRef` decrement that returns the same + * `MutableRef`. * * **Example** (Decrementing numeric refs) * @@ -237,7 +237,8 @@ export const decrement = (self: MutableRef): MutableRef => updat * * **When to use** * - * Use to decrement a numeric reference and immediately read the updated value. + * Use to decrement a numeric `MutableRef` and immediately read the updated + * value. * * **Example** (Decrementing and reading refs) * @@ -273,7 +274,7 @@ export const decrementAndGet = (self: MutableRef): number => updateAndGe * * **When to use** * - * Use to read the current value without mutating the reference. + * Use to read the current `MutableRef` value without mutating it. * * **Example** (Reading current values) * @@ -307,7 +308,7 @@ export const get = (self: MutableRef): T => self.current * * **When to use** * - * Use to read the current numeric value before decrementing it. + * Use to read the current numeric `MutableRef` value before decrementing it. * * **Example** (Reading before decrementing) * @@ -344,7 +345,7 @@ export const getAndDecrement = (self: MutableRef): number => getAndUpdat * * **When to use** * - * Use to read the current numeric value before incrementing it. + * Use to read the current numeric `MutableRef` value before incrementing it. * * **Example** (Reading before incrementing) * @@ -389,7 +390,8 @@ export const getAndIncrement = (self: MutableRef): number => getAndUpdat * * **When to use** * - * Use to replace the current value while keeping the previous value. + * Use to replace the current `MutableRef` value while keeping the previous + * value. * * **Example** (Reading before setting) * @@ -441,7 +443,8 @@ export const getAndSet: { * * **When to use** * - * Use to transform the current value while keeping the previous value. + * Use to transform the current `MutableRef` value while keeping the previous + * value. * * **Example** (Reading before updating) * @@ -494,8 +497,8 @@ export const getAndUpdate: { * * **When to use** * - * Use to increment a numeric reference in place when you want the same - * reference back. + * Use when you need an in-place `MutableRef` increment that returns the same + * `MutableRef`. * * **Example** (Incrementing numeric refs) * @@ -534,7 +537,8 @@ export const increment = (self: MutableRef): MutableRef => updat * * **When to use** * - * Use to increment a numeric reference and immediately read the updated value. + * Use to increment a numeric `MutableRef` and immediately read the updated + * value. * * **Example** (Incrementing and reading refs) * @@ -574,8 +578,8 @@ export const incrementAndGet = (self: MutableRef): number => updateAndGe * * **When to use** * - * Use to replace the current value in place when you want the same reference - * back. + * Use when you need an in-place `MutableRef` replacement that returns the same + * `MutableRef`. * * **Example** (Setting values) * @@ -629,7 +633,8 @@ export const set: { * * **When to use** * - * Use to replace the current value and immediately read the replacement. + * Use to replace the current `MutableRef` value and immediately read the + * replacement. * * **Example** (Setting and reading values) * @@ -680,8 +685,8 @@ export const setAndGet: { * * **When to use** * - * Use to transform the current value in place when you want the same reference - * back. + * Use when you need an in-place `MutableRef` value transformation that returns + * the same `MutableRef`. * * **Example** (Updating values) * @@ -737,7 +742,8 @@ export const update: { * * **When to use** * - * Use to transform the current value and immediately read the updated value. + * Use to transform the current `MutableRef` value and immediately read the + * updated value. * * **Example** (Updating and reading values) * @@ -795,8 +801,8 @@ export const updateAndGet: { * * **When to use** * - * Use to flip a boolean reference in place when you want the same reference - * back. + * Use when you need an in-place boolean `MutableRef` toggle that returns the + * same `MutableRef`. * * **Example** (Toggling boolean refs) * diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index 2e0468f7a0..75dab42b35 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -614,7 +614,7 @@ export const getSuccess: (self: Result) => Option = result.getSuc * * **When to use** * - * Use to extract the failure when you do not need the success value + * Use when you only need the failure value from a `Result`. * * **Details** * diff --git a/packages/effect/src/Pool.ts b/packages/effect/src/Pool.ts index 464dd45bc4..0bbe5e797d 100644 --- a/packages/effect/src/Pool.ts +++ b/packages/effect/src/Pool.ts @@ -230,8 +230,7 @@ export const isPool = (u: unknown): u is Pool => hasProperty(u * * **When to use** * - * Use to create a fixed-size pool when you know the exact number of resources - * needed upfront, without growth or shrinkage. + * Use when you need a fixed-size pool with no growth or shrinkage. * * **Details** * diff --git a/packages/effect/src/Queue.ts b/packages/effect/src/Queue.ts index 8b549a09fc..bd517de15c 100644 --- a/packages/effect/src/Queue.ts +++ b/packages/effect/src/Queue.ts @@ -553,8 +553,8 @@ export const bounded = (capacity: number): Effect> => * * **When to use** * - * Use when producers should not block and message loss is acceptable, such as - * when maintaining a rolling window of the most recent messages. + * Use when you need producer offers not to block and can accept dropping the + * oldest messages, such as when maintaining a rolling window of recent values. * * **Example** (Creating sliding queues) * @@ -588,8 +588,8 @@ export const sliding = (capacity: number): Effect> => * * **When to use** * - * Use when producers should not block and existing messages should be preserved, - * but new messages may be lost when the queue is full. + * Use when you need producer offers not to block while preserving existing + * queued messages, even if new messages may be dropped when the queue is full. * * **Example** (Creating dropping queues) * diff --git a/packages/effect/src/Ref.ts b/packages/effect/src/Ref.ts index 2529a9cb73..251312be9f 100644 --- a/packages/effect/src/Ref.ts +++ b/packages/effect/src/Ref.ts @@ -205,7 +205,7 @@ export const makeUnsafe = (value: A): Ref => { * * **When to use** * - * Use to create shared mutable state inside an Effect program. + * Use to create a `Ref` for shared mutable state inside an Effect program. * * **Example** (Creating a ref) * @@ -231,7 +231,7 @@ export const make = (value: A): Effect.Effect> => Effect.sync(() => ma * * **When to use** * - * Use to read the current value without changing it. + * Use to read the current `Ref` value without changing it. * * **Example** (Getting the current value) * @@ -257,7 +257,7 @@ export const get = (self: Ref) => Effect.sync(() => self.ref.current) * * **When to use** * - * Use to replace the current value with a known value. + * Use to replace the current `Ref` value with a known value. * * **Example** (Setting a value) * @@ -336,7 +336,7 @@ export const getAndSet = dual< * * **When to use** * - * Use to derive a new value while returning the previous value. + * Use to derive a new `Ref` value while returning the previous value. * * **Example** (Updating and returning the previous value) * @@ -376,7 +376,7 @@ export const getAndUpdate = dual< * * **When to use** * - * Use to return the previous value while applying a conditional update. + * Use to return the previous `Ref` value while applying a conditional update. * * **Details** * @@ -438,7 +438,7 @@ export const getAndUpdateSome = dual< * * **When to use** * - * Use when you want to set a value and immediately get it back in one + * Use when you want to set a `Ref` value and immediately get it back in one * atomic operation. * * **Example** (Setting and returning the new value) @@ -480,8 +480,8 @@ export const setAndGet = dual< * * **When to use** * - * Use to compute both a separate return value and the next stored value in one - * atomic update. + * Use to compute both a separate return value and the next stored `Ref` value + * in one atomic update. * * **Details** * @@ -618,7 +618,7 @@ export const modifySome: { * * **When to use** * - * Use to apply a state transition without returning a value. + * Use to apply a `Ref` state transition without returning a value. * * **Example** (Updating a value) * @@ -663,7 +663,7 @@ export const update = dual< * * **When to use** * - * Use to apply a state transition and return the new stored value. + * Use to apply a `Ref` state transition and return the new stored value. * * **Example** (Updating and returning the new value) * @@ -699,7 +699,7 @@ export const updateAndGet = dual< * * **When to use** * - * Use to apply a conditional update without returning a value. + * Use to apply a conditional `Ref` update without returning a value. * * **Details** * @@ -757,7 +757,8 @@ export const updateSome = dual< * * **When to use** * - * Use to apply a conditional update and return the resulting current value. + * Use to apply a conditional `Ref` update and return the resulting current + * value. * * **Details** * diff --git a/packages/effect/src/Request.ts b/packages/effect/src/Request.ts index 52096dd67c..57aaf8aa38 100644 --- a/packages/effect/src/Request.ts +++ b/packages/effect/src/Request.ts @@ -449,8 +449,8 @@ export const TaggedClass = ( * * **When to use** * - * Use to finish a `Request.Entry` when you already have the request's final - * `Exit` result. + * Use when you need to finish a `Request.Entry` with a prebuilt final `Exit` + * result. * * @see {@link completeEffect} for completing an entry from an effect that may succeed or fail * @see {@link succeed} for completing an entry with a successful value @@ -560,8 +560,8 @@ export const failCause: { * * **When to use** * - * Use to finish a `Request.Entry` when you have a successful value for the - * request. + * Use when you need to finish a `Request.Entry` with a successful request + * value. * * @see {@link complete} for completing an entry with a prebuilt `Exit` * @see {@link completeEffect} for completing an entry from an effect result diff --git a/packages/effect/src/Runtime.ts b/packages/effect/src/Runtime.ts index 8cedc29f93..e3958e4fe4 100644 --- a/packages/effect/src/Runtime.ts +++ b/packages/effect/src/Runtime.ts @@ -118,8 +118,8 @@ export interface Teardown { * * **When to use** * - * Use as the standard teardown for main programs when you want conventional - * process exit codes and support for {@link errorExitCode}. + * Use as the standard teardown for main programs with conventional process + * exit codes and support for {@link errorExitCode}. * * **Details** * diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 38bdc63199..41abf1449f 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -11828,9 +11828,8 @@ type MissingSelfGeneric = * * **When to use** * - * Use to define a schema-backed data class when you want validated - * construction, schema-derived decoding/encoding, and class-style methods or - * inheritance. + * Use when you need a schema-backed data class with validated construction, + * schema-derived decoding/encoding, and class-style methods or inheritance. * * **Details** * diff --git a/packages/effect/src/SchemaIssue.ts b/packages/effect/src/SchemaIssue.ts index 5bb5e02af9..ad089ca0b4 100644 --- a/packages/effect/src/SchemaIssue.ts +++ b/packages/effect/src/SchemaIssue.ts @@ -934,9 +934,7 @@ export type LeafHook = (issue: Leaf) => string * * **When to use** * - * Use as the default leaf renderer when you only need to customise the - * {@link CheckHook}. - * - Reference as a starting point for custom `LeafHook` implementations. + * Use as the default leaf renderer when customizing only the {@link CheckHook}. * * **Details** * @@ -1010,8 +1008,7 @@ export type CheckHook = (issue: Filter) => string | undefined * * **When to use** * - * Use as the default filter renderer when you only need to customise the - * {@link LeafHook}. + * Use as the default filter renderer when customizing only the {@link LeafHook}. * * **Details** * diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaParser.ts index 06fdfd2888..80bfa58a23 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaParser.ts @@ -381,8 +381,8 @@ export function decodeUnknownExit>( * * **When to use** * - * Use to synchronously decode already typed `Encoded` input when you want - * decoding failures returned as `Exit` values. + * Use when you need synchronous decoding of already typed `Encoded` input with + * failures returned as `Exit` values. * * **Details** * @@ -681,8 +681,8 @@ export const encodePromise: >( * * **When to use** * - * Use to encode unknown input synchronously when you want the encoded value or - * schema issue represented as an `Exit`. + * Use when you need synchronous encoding of unknown input with the encoded + * value or schema issue returned as an `Exit`. * * **Details** * @@ -708,7 +708,7 @@ export function encodeUnknownExit>( * * **When to use** * - * Use to synchronously encode already typed schema values when you want encoding + * Use when you need synchronous encoding of already typed schema values with * failures returned as `Exit` values. * * **Details** diff --git a/packages/effect/src/Sink.ts b/packages/effect/src/Sink.ts index e7c7cd933e..4cb0328706 100644 --- a/packages/effect/src/Sink.ts +++ b/packages/effect/src/Sink.ts @@ -1552,8 +1552,7 @@ export const count: Sink = reduceArray(() => 0, (s, arr) => s + * * **When to use** * - * Use to collect all upstream input elements into a single array when you need - * a sink result containing the complete input. + * Use when you need a sink result containing all upstream input elements. * * @see {@link take} for collecting only a fixed number of input elements * diff --git a/packages/effect/src/Stdio.ts b/packages/effect/src/Stdio.ts index 772043f793..d3bba544a0 100644 --- a/packages/effect/src/Stdio.ts +++ b/packages/effect/src/Stdio.ts @@ -112,9 +112,8 @@ export const Stdio: Context.Service = Context.Service(TypeI * * **When to use** * - * Use to assemble a concrete `Stdio` service when you already have - * implementations for command-line arguments, standard output, standard error, - * and standard input. + * Use when you need to assemble a concrete `Stdio` service from command-line + * arguments and standard I/O implementations. * * **Details** * diff --git a/packages/effect/src/String.ts b/packages/effect/src/String.ts index 18c14595b0..5bdc4b289b 100644 --- a/packages/effect/src/String.ts +++ b/packages/effect/src/String.ts @@ -1291,9 +1291,8 @@ const linesSeparated = (self: string, stripped: boolean): LinesIterator => new L * * **When to use** * - * Use to normalize mixed-case, snake_case, kebab-case, or spaced input into - * custom word-case output when you need a delimiter or part transform that the - * fixed case helpers do not provide. + * Use when you need custom word-case output with a delimiter or part transform + * that the fixed case helpers do not provide. * * @see {@link pascalCase} for fixed PascalCase output * @see {@link camelCase} for fixed lower-initial camelCase output diff --git a/packages/effect/src/SubscriptionRef.ts b/packages/effect/src/SubscriptionRef.ts index b903c0fa7a..79caa900a3 100644 --- a/packages/effect/src/SubscriptionRef.ts +++ b/packages/effect/src/SubscriptionRef.ts @@ -141,7 +141,7 @@ const Proto = { * * **When to use** * - * Use to create shared mutable state when consumers need to read the latest + * Use to create a `SubscriptionRef` when consumers need to read the latest * value and subscribe to every update. * * **Details** @@ -372,8 +372,8 @@ export const getAndUpdateEffect: { * * **When to use** * - * Use to read the old value while applying a synchronous update only when a - * new value is available. + * Use to read the old `SubscriptionRef` value while applying a synchronous + * update only when a new value is available. * * **Details** * @@ -425,8 +425,8 @@ export const getAndUpdateSome: { * * **When to use** * - * Use to read the old value while applying an effectful update only when a new - * value is available. + * Use to read the old `SubscriptionRef` value while applying an effectful + * update only when a new value is available. * * **Details** * @@ -568,7 +568,7 @@ export const modifyEffect: { * **When to use** * * Use to return a separate result while synchronously deciding whether to - * publish a new value. + * publish a new `SubscriptionRef` value. * * **Details** * @@ -624,7 +624,7 @@ export const modifySome: { * **When to use** * * Use to return a separate result while effectfully deciding whether to publish - * a new value. + * a new `SubscriptionRef` value. * * **Details** * diff --git a/packages/effect/src/SynchronizedRef.ts b/packages/effect/src/SynchronizedRef.ts index 64183fb0e3..45972fa767 100644 --- a/packages/effect/src/SynchronizedRef.ts +++ b/packages/effect/src/SynchronizedRef.ts @@ -69,7 +69,8 @@ const Proto = { * * **When to use** * - * Use when you need synchronous construction outside an Effect workflow. + * Use when you need synchronous `SynchronizedRef` construction outside an + * Effect workflow. * * @category constructors * @since 4.0.0 @@ -86,8 +87,8 @@ export const makeUnsafe = (value: A): SynchronizedRef => { * * **When to use** * - * Use to create a synchronized reference inside an Effect program when later - * updates may run effects and must be serialized. + * Use to create a `SynchronizedRef` inside an Effect program when later updates + * may run effects and must be serialized. * * **Details** * @@ -164,7 +165,8 @@ export const getAndSet: { * * **When to use** * - * Use to run a pure state update when the previous stored value is also needed. + * Use to run a pure `SynchronizedRef` state update when the previous stored + * value is also needed. * * @see {@link update} for updating without returning a value * @see {@link updateAndGet} for updating and returning the new value @@ -188,8 +190,8 @@ export const getAndUpdate: { * * **When to use** * - * Use when you need an effectful state transition to return the previous stored - * value. + * Use when you need an effectful `SynchronizedRef` state transition to return + * the previous stored value. * * @see {@link getAndUpdate} for pure updates that return the previous value * @see {@link updateEffect} for effectful updates without returning a value @@ -222,7 +224,8 @@ export const getAndUpdateEffect: { * * **When to use** * - * Use to return the previous value while applying a pure conditional update. + * Use to return the previous `SynchronizedRef` value while applying a pure + * conditional update. * * @see {@link getAndUpdate} for always applying a pure update * @see {@link updateSome} for applying a pure conditional update without returning the previous value @@ -246,8 +249,8 @@ export const getAndUpdateSome: { * * **When to use** * - * Use to return the previous value while running an effectful conditional - * update. + * Use to return the previous `SynchronizedRef` value while running an effectful + * conditional update. * * @see {@link getAndUpdateSome} for the pure conditional variant * @see {@link updateSomeEffect} for effectful conditional updates without returning the previous value @@ -279,8 +282,8 @@ export const getAndUpdateSomeEffect: { * * **When to use** * - * Use to derive a separate result and the next stored value from the same - * current value in one serialized pure update. + * Use to derive a separate result and the next stored `SynchronizedRef` value + * from the same current value in one serialized pure update. * * @see {@link modifyEffect} for effectfully deriving both the result and next stored value * @see {@link modifySome} for deriving a result and optionally updating the stored value @@ -305,7 +308,7 @@ export const modify: { * **When to use** * * Use to effectfully compute both a separate return value and the next stored - * value in one serialized update. + * `SynchronizedRef` value in one serialized update. * * @see {@link modify} for the pure variant * @see {@link updateEffect} for effectfully storing a new value without a separate result @@ -367,7 +370,7 @@ export const modifySome: { * **When to use** * * Use to effectfully compute a return value while optionally updating the - * stored value. + * stored `SynchronizedRef` value. * * @see {@link modifySome} for the pure variant * @see {@link updateSomeEffect} for effectful optional updates without a separate return value @@ -431,8 +434,8 @@ export const set: { * * **When to use** * - * Use to replace the current value with a known value and return that new - * value. + * Use to replace the current `SynchronizedRef` value with a known value and + * return that new value. * * @see {@link set} for setting without returning a value * @see {@link getAndSet} for setting while returning the previous value @@ -512,7 +515,8 @@ export const updateEffect: { * * **When to use** * - * Use to apply a pure state transition and return the new stored value. + * Use to apply a pure `SynchronizedRef` state transition and return the new + * stored value. * * @see {@link update} for updating without returning the new value * @see {@link getAndUpdate} for updating while returning the previous value @@ -535,7 +539,8 @@ export const updateAndGet: { * * **When to use** * - * Use to run an effectful state transition and return the new stored value. + * Use to run an effectful `SynchronizedRef` state transition and return the new + * stored value. * * @see {@link updateEffect} for effectful updates without returning the new value * @see {@link updateAndGet} for the pure variant @@ -564,7 +569,8 @@ export const updateAndGetEffect: { * * **When to use** * - * Use to apply a pure conditional update without returning a value. + * Use to apply a pure conditional `SynchronizedRef` update without returning a + * value. * * @see {@link update} for always applying a pure update * @see {@link updateSomeAndGet} for returning the resulting current value @@ -587,7 +593,8 @@ export const updateSome: { * * **When to use** * - * Use to run an effectful conditional update without returning a value. + * Use to run an effectful conditional `SynchronizedRef` update without + * returning a value. * * @see {@link updateSome} for the pure conditional variant * @see {@link updateEffect} for effectful updates that always store a new value @@ -621,8 +628,8 @@ export const updateSomeEffect: { * * **When to use** * - * Use to apply a pure conditional update and return the resulting current - * value. + * Use to apply a pure conditional `SynchronizedRef` update and return the + * resulting current value. * * @see {@link updateSome} for conditional updates without returning a value * @see {@link updateAndGet} for always applying a pure update and returning the new value @@ -646,8 +653,8 @@ export const updateSomeAndGet: { * * **When to use** * - * Use to run an effectful conditional update and return the resulting current - * value. + * Use to run an effectful conditional `SynchronizedRef` update and return the + * resulting current value. * * @see {@link updateSomeEffect} for effectful conditional updates without returning a value * @see {@link updateAndGetEffect} for effectful updates that always store and return a new value diff --git a/packages/effect/src/TxRef.ts b/packages/effect/src/TxRef.ts index f11578f2de..5bff1093d0 100644 --- a/packages/effect/src/TxRef.ts +++ b/packages/effect/src/TxRef.ts @@ -120,7 +120,7 @@ export interface TxRef extends Pipeable { * * **When to use** * - * Use to create a transactional reference inside an `Effect` workflow. + * Use to create a `TxRef` inside an `Effect` workflow. * * **Example** (Creating transactional references) * @@ -153,8 +153,8 @@ export const make = (initial: A) => Effect.sync(() => makeUnsafe(initial)) * * **When to use** * - * Use to construct a transactional reference synchronously when it must be - * created outside an `Effect` workflow. + * Use to construct a `TxRef` synchronously when it must be created outside an + * `Effect` workflow. * * **Example** (Creating transactional references unsafely) * @@ -188,8 +188,8 @@ export const makeUnsafe = (initial: A): TxRef => ({ * * **When to use** * - * Use to update a transactional reference and return a computed result from the - * same transaction step. + * Use to update a `TxRef` and return a computed result from the same + * transaction step. * * **Example** (Modifying transactional references) * @@ -237,7 +237,7 @@ export const modify: { * * **When to use** * - * Use to transform a transactional reference when no result value is needed. + * Use to transform a `TxRef` when no result value is needed. * * **Example** (Updating transactional references) * @@ -272,7 +272,7 @@ export const update: { * * **When to use** * - * Use to read the current value of a transactional reference. + * Use to read the current value of a `TxRef`. * * **Example** (Reading transactional references) * @@ -301,7 +301,7 @@ export const get = (self: TxRef): Effect.Effect => modify(self, (curren * * **When to use** * - * Use to replace the value of a transactional reference. + * Use to replace the value of a `TxRef`. * * **Example** (Setting transactional references) * diff --git a/packages/effect/src/TxSubscriptionRef.ts b/packages/effect/src/TxSubscriptionRef.ts index cb15334dcd..4239d48e39 100644 --- a/packages/effect/src/TxSubscriptionRef.ts +++ b/packages/effect/src/TxSubscriptionRef.ts @@ -123,8 +123,8 @@ const TxSubscriptionRefProto: Omit, typeof TypeId | "ref" * * **When to use** * - * Use to create transactional state that also publishes every committed update - * to subscribers. + * Use to create a `TxSubscriptionRef` that publishes every committed update to + * subscribers. * * **Example** (Creating a transactional subscription reference) * @@ -163,8 +163,8 @@ export const make = (value: A): Effect.Effect> => * * **When to use** * - * Use to read the current transactional value without subscribing to future - * changes. + * Use to read the current `TxSubscriptionRef` value without subscribing to + * future changes. * * **Example** (Reading the current value) * @@ -195,8 +195,8 @@ export const get = (self: TxSubscriptionRef): Effect.Effect => TxRef.ge * * **When to use** * - * Use to compute a separate return value and next state in one transactional - * update. + * Use to compute a separate return value and next `TxSubscriptionRef` state in + * one transactional update. * * **Example** (Modifying and returning a value) * @@ -245,7 +245,8 @@ export const modify: { * * **When to use** * - * Use to replace the current value with a known value and publish it. + * Use to replace the current `TxSubscriptionRef` value with a known value and + * publish it. * * **Example** (Setting a new value) * @@ -279,7 +280,8 @@ export const set: { * * **When to use** * - * Use to derive the next value from the current value and publish it. + * Use to derive the next `TxSubscriptionRef` value from the current value and + * publish it. * * **Example** (Updating a value) * @@ -350,7 +352,8 @@ export const getAndSet: { * * **When to use** * - * Use to derive and publish a new value while returning the previous value. + * Use to derive and publish a new `TxSubscriptionRef` value while returning the + * previous value. * * **Example** (Getting and updating atomically) * @@ -386,7 +389,8 @@ export const getAndUpdate: { * * **When to use** * - * Use to derive and publish a new value while returning that new value. + * Use to derive and publish a new `TxSubscriptionRef` value while returning + * that new value. * * **Example** (Updating and reading atomically) * @@ -428,7 +432,8 @@ export const updateAndGet: { * * **When to use** * - * Use to subscribe to committed changes through a scoped transactional queue. + * Use to subscribe to `TxSubscriptionRef` committed changes through a scoped + * transactional queue. * * **Example** (Subscribing to changes) * @@ -478,7 +483,7 @@ export const changes = ( * * **When to use** * - * Use to consume committed changes as a `Stream`. + * Use to consume `TxSubscriptionRef` committed changes as a `Stream`. * * **Example** (Streaming changes) * diff --git a/packages/effect/src/unstable/ai/Chat.ts b/packages/effect/src/unstable/ai/Chat.ts index 7d930cf778..172bbcf98c 100644 --- a/packages/effect/src/unstable/ai/Chat.ts +++ b/packages/effect/src/unstable/ai/Chat.ts @@ -797,9 +797,8 @@ export interface Persisted extends Service { * * **When to use** * - * Use to construct the `Chat.Persistence` service from the current - * `BackingPersistence` when you want to create and retrieve persisted chats - * programmatically by chat id. + * Use when you need programmatic persisted chat creation and retrieval backed + * by the current `BackingPersistence`. * * **Details** * diff --git a/packages/effect/src/unstable/cli/Completions.ts b/packages/effect/src/unstable/cli/Completions.ts index 7d5456fc9a..719980e0dd 100644 --- a/packages/effect/src/unstable/cli/Completions.ts +++ b/packages/effect/src/unstable/cli/Completions.ts @@ -117,7 +117,7 @@ export type ArgumentType = * * **When to use** * - * Use to produce an installable completion script when you already have a + * Use when you need an installable completion script from an existing * `CommandDescriptor`. * * **Details** diff --git a/packages/effect/src/unstable/cluster/Runners.ts b/packages/effect/src/unstable/cluster/Runners.ts index badd23da73..21ceb9ca75 100644 --- a/packages/effect/src/unstable/cluster/Runners.ts +++ b/packages/effect/src/unstable/cluster/Runners.ts @@ -152,9 +152,9 @@ export class Runners extends Context.Service = Layer.effect(Storage)(ma * * **When to use** * - * Use to construct the unencrypted event-log server service directly when you - * already provide `Storage` and an event-log `Registry`. + * Use when you need the unencrypted event-log server service from provided + * `Storage` and an event-log `Registry`. * * **Details** * diff --git a/packages/effect/src/unstable/reactivity/Atom.ts b/packages/effect/src/unstable/reactivity/Atom.ts index ac6252e173..90d5ac07a8 100644 --- a/packages/effect/src/unstable/reactivity/Atom.ts +++ b/packages/effect/src/unstable/reactivity/Atom.ts @@ -1108,8 +1108,8 @@ export interface AtomResultFn * * **When to use** * - * Use to write to an `AtomResultFn` when you need to clear the current async - * result and return it to the initial state. + * Use when you need an `AtomResultFn` write value that clears the current async + * result and returns it to the initial state. * * @category symbols * @since 4.0.0 @@ -1129,7 +1129,7 @@ export type Reset = typeof Reset * * **When to use** * - * Use to write to an `AtomResultFn` when you need to interrupt the currently + * Use when you need an `AtomResultFn` write value that interrupts the currently * running async computation. * * @category symbols diff --git a/packages/opentelemetry/src/Metrics.ts b/packages/opentelemetry/src/Metrics.ts index b453125936..09cd7d0e6f 100644 --- a/packages/opentelemetry/src/Metrics.ts +++ b/packages/opentelemetry/src/Metrics.ts @@ -64,8 +64,8 @@ export type TemporalityPreference = "cumulative" | "delta" * * **When to use** * - * Use to create a `MetricProducer` when you need to wire Effect metrics into - * OpenTelemetry manually instead of using the scoped `layer` helper. + * Use when you need a `MetricProducer` for manually wiring Effect metrics into + * OpenTelemetry instead of using the scoped `layer` helper. * * **Details** * From f1d38b06964252e32095e37e1c4e1f8a3a06585a Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 08:23:59 +0200 Subject: [PATCH 15/29] wip --- packages/effect/src/Config.ts | 12 +++++------ packages/effect/src/Schema.ts | 8 ++++---- packages/effect/src/SchemaParser.ts | 20 +++++++++---------- packages/effect/src/Stream.ts | 4 ++-- packages/effect/src/unstable/cli/Primitive.ts | 3 ++- 5 files changed, 24 insertions(+), 23 deletions(-) diff --git a/packages/effect/src/Config.ts b/packages/effect/src/Config.ts index 56938a6f21..2385cde757 100644 --- a/packages/effect/src/Config.ts +++ b/packages/effect/src/Config.ts @@ -760,8 +760,8 @@ export const FalseValues = Schema.Literals(["false", "no", "off", "0", "n"]) * * **When to use** * - * Use when passing to {@link schema} for custom paths, or use the - * {@link boolean} convenience constructor. + * Use when you need the reusable boolean schema value for `Config.schema` with + * custom paths. * * **Details** * @@ -788,8 +788,8 @@ export const Boolean = Schema.Literals([...TrueValues.literals, ...FalseValues.l * * **When to use** * - * Use when passing to {@link schema} for custom paths, or use the {@link port} - * convenience constructor. + * Use when you need the reusable port schema value for `Config.schema` with + * custom paths. * * @see {@link port} – convenience constructor * @@ -803,8 +803,8 @@ export const Port = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 655 * * **When to use** * - * Use when passing to {@link schema} for custom paths, or use the - * {@link logLevel} convenience constructor. + * Use when you need the reusable log-level schema value for `Config.schema` + * with custom paths. * * **Details** * diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 41abf1449f..9d60843fb6 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -1447,8 +1447,8 @@ export const decodePromise = Parser.decodePromise * * **When to use** * - * Use when validating unknown data at a boundary and treating schema mismatches - * as exceptions. + * Use when you need to validate unknown data at a synchronous boundary and want + * schema mismatches to throw. * * **Details** * @@ -1743,8 +1743,8 @@ export const encodePromise = Parser.encodePromise * * **When to use** * - * Use when serializing unknown data at a boundary and treating schema - * mismatches as unrecoverable errors. + * Use when you need to serialize unknown data at a synchronous boundary and + * want schema mismatches to throw. * * **Details** * diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaParser.ts index 80bfa58a23..dbb48d2d0a 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaParser.ts @@ -233,8 +233,8 @@ export function asserts(schema: S, input: I): asserts i * * **When to use** * - * Use when decoding untyped boundary input while preserving decoding failures, - * effectful transformations, and service requirements in an `Effect`. + * Use when you need to decode untyped boundary input while preserving decoding + * failures, effectful transformations, and service requirements in an `Effect`. * * **Details** * @@ -345,8 +345,8 @@ export function decodePromise>( * * **When to use** * - * Use when decoding unknown input synchronously and preserving the parser - * outcome as an `Exit` value. + * Use when you need to decode unknown input synchronously while preserving the + * parser outcome as an `Exit` value. * * **Details** * @@ -572,8 +572,8 @@ export const decodeSync: >( * * **When to use** * - * Use when encoding untyped boundary input and preserving encoding failures and - * service requirements in `Effect` is the desired result shape. + * Use when you need to encode untyped boundary input while preserving encoding + * failures and service requirements in an `Effect`. * * **Details** * @@ -603,8 +603,8 @@ export function encodeUnknownEffect( * * **When to use** * - * Use to encode values already typed as the schema's decoded `Type` when - * encoding should preserve service requirements and return failures in an + * Use when you need to encode values already typed as the schema's decoded + * `Type` while preserving service requirements and returning failures in an * `Effect`. * * **Details** @@ -837,8 +837,8 @@ export const encodeResult: >( * * **When to use** * - * Use when encoding values from untyped input in synchronous code and treating - * encoding failures as thrown errors is the desired boundary. + * Use when you need to encode values from untyped input in synchronous code and + * want encoding failures to throw. * * **Details** * diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 6dbe6ce4da..2601b87899 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -810,8 +810,8 @@ export const toChannel = ( * * **When to use** * - * Use when you can use the `Queue` with the apis from the `Queue` module to emit - * values to the stream or to signal the stream ending. + * Use when you need callback-based code to emit stream values by offering to a + * `Queue`, or to signal stream completion through the `Queue` module APIs. * * By default it uses an "unbounded" buffer size. * You can customize the buffer size and strategy by passing an object as the diff --git a/packages/effect/src/unstable/cli/Primitive.ts b/packages/effect/src/unstable/cli/Primitive.ts index 47ce9f4c23..1b454b5744 100644 --- a/packages/effect/src/unstable/cli/Primitive.ts +++ b/packages/effect/src/unstable/cli/Primitive.ts @@ -754,7 +754,8 @@ export const none: Primitive = makePrimitive("None", () => Effect.fail("T * * **When to use** * - * Use when you need to generate help documentation. + * Use when you need the display type name for a `Primitive`, such as when + * generating CLI help documentation. * * **Example** (Getting primitive type names) * From a3a5ce9bbda5afdeae97f3a5adce75baedfabb67 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 08:53:17 +0200 Subject: [PATCH 16/29] wip --- packages/effect/src/Schema.ts | 1002 +++++++++++++----------- packages/effect/src/SchemaParser.ts | 36 +- packages/effect/typetest/Effect.tst.ts | 2 +- 3 files changed, 543 insertions(+), 497 deletions(-) diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 9d60843fb6..a003b05549 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -125,12 +125,12 @@ import * as Record_ from "./Record.ts" import * as Redacted_ from "./Redacted.ts" import * as Result_ from "./Result.ts" import * as Scheduler from "./Scheduler.ts" -import * as AST from "./SchemaAST.ts" -import * as Getter from "./SchemaGetter.ts" -import * as Issue from "./SchemaIssue.ts" -import * as Parser from "./SchemaParser.ts" +import * as SchemaAST from "./SchemaAST.ts" +import * as SchemaGetter from "./SchemaGetter.ts" +import * as SchemaIssue from "./SchemaIssue.ts" +import * as SchemaParser from "./SchemaParser.ts" import type * as SchemaRepresentation from "./SchemaRepresentation.ts" -import * as Transformation from "./SchemaTransformation.ts" +import * as SchemaTransformation from "./SchemaTransformation.ts" import type { Assign, Lambda, Mutable, Simplify } from "./Struct.ts" import * as Struct_ from "./Struct.ts" import * as FastCheck from "./testing/FastCheck.ts" @@ -189,7 +189,7 @@ export interface MakeOptions { /** * The parse options to use for the schema. */ - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined /** * Whether to disable validation for the schema. */ @@ -220,7 +220,7 @@ export interface Bottom< out E, out RD, out RE, - out Ast extends AST.AST, + out Ast extends SchemaAST.AST, out Rebuild extends Top, out TypeMakeIn = T, out Iso = T, @@ -255,7 +255,7 @@ export interface Bottom< annotate(annotations: Annotations.Bottom): this["Rebuild"] annotateKey(annotations: Annotations.Key): this["Rebuild"] - check(...checks: readonly [AST.Check, ...Array>]): this["Rebuild"] + check(...checks: readonly [SchemaAST.Check, ...Array>]): this["Rebuild"] rebuild(ast: this["ast"]): this["Rebuild"] /** * Constructs a value from the make input representation synchronously. @@ -324,7 +324,7 @@ export interface declareConstructor, T, Iso, @@ -366,7 +366,7 @@ export interface declareConstructor * (u, ast, options) => { * if (!isBox(u)) { - * return Effect.fail(new Issue.InvalidType(ast, Option.some(u))) + * return Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(u))) * } * return Effect.map( * SchemaParser.decodeUnknownEffect(itemCodec)(u.value, options), @@ -388,12 +388,16 @@ export function declareConstructor() { typeParameters: { readonly [K in keyof TypeParameters]: Codec } - ) => (u: unknown, self: AST.Declaration, options: AST.ParseOptions) => Effect.Effect, + ) => ( + u: unknown, + self: SchemaAST.Declaration, + options: SchemaAST.ParseOptions + ) => Effect.Effect, annotations?: Annotations.Declaration ): declareConstructor => { return make( - new AST.Declaration( - typeParameters.map(AST.getAST), + new SchemaAST.Declaration( + typeParameters.map(SchemaAST.getAST), (typeParameters) => run(typeParameters.map((ast) => make(ast)) as any), annotations ) @@ -451,7 +455,7 @@ export function declare( () => (input, ast) => is(input) ? Effect.succeed(input) : - Effect.fail(new Issue.InvalidType(ast, Option_.some(input))), + Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))), annotations ) } @@ -605,7 +609,7 @@ export function annotateEncoded(annotations: Annotations.Bottom(annotations: Annotations.Key) { return (self: S): S["Rebuild"] => { - return self.rebuild(AST.annotateKey(self.ast, annotations)) + return self.rebuild(SchemaAST.annotateKey(self.ast, annotations)) } } @@ -633,7 +637,7 @@ export interface Top extends unknown, unknown, unknown, - AST.AST, + SchemaAST.AST, Top, unknown, unknown, @@ -921,7 +925,7 @@ export { * * **Details** * - * The `issue` field contains a structured {@link Issue.Issue} tree describing + * The `issue` field contains a structured {@link SchemaIssue.Issue} tree describing * every validation failure, including the path to the problematic value, * expected types, and actual values received. `message` renders the issue tree * as a human-readable string. @@ -1045,17 +1049,17 @@ function makeStandardResult(exit: Exit_.Exit>): St export function toStandardSchemaV1>( self: S, options?: { - readonly leafHook?: Issue.LeafHook | undefined - readonly checkHook?: Issue.CheckHook | undefined - readonly parseOptions?: AST.ParseOptions | undefined + readonly leafHook?: SchemaIssue.LeafHook | undefined + readonly checkHook?: SchemaIssue.CheckHook | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined } ): StandardSchemaV1 & S { - const decodeUnknownEffect = Parser.decodeUnknownEffect(self) as ( + const decodeUnknownEffect = SchemaParser.decodeUnknownEffect(self) as ( input: unknown, - options?: AST.ParseOptions - ) => Effect.Effect - const parseOptions: AST.ParseOptions = { errors: "all", ...options?.parseOptions } - const formatter = Issue.makeFormatterStandardSchemaV1(options) + options?: SchemaAST.ParseOptions + ) => Effect.Effect + const parseOptions: SchemaAST.ParseOptions = { errors: "all", ...options?.parseOptions } + const formatter = SchemaIssue.makeFormatterStandardSchemaV1(options) const validate: StandardSchemaV1["~standard"]["validate"] = (value: unknown) => { const scheduler = new Scheduler.MixedScheduler() const fiber = Effect.runFork( @@ -1177,7 +1181,7 @@ export function toStandardJSONSchemaV1(self: S): StandardJSONSche * @category guards * @since 3.10.0 */ -export const is = Parser.is +export const is = SchemaParser.is /** * Creates an assertion function that throws an error if the input doesn't match @@ -1216,7 +1220,7 @@ export const is = Parser.is * @category guards * @since 4.0.0 */ -export const asserts: (schema: S, input: I) => asserts input is I & S["Type"] = Parser.asserts +export const asserts: (schema: S, input: I) => asserts input is I & S["Type"] = SchemaParser.asserts /** * Decodes an `unknown` input against a schema, returning an `Effect` that @@ -1224,7 +1228,8 @@ export const asserts: (schema: S, input: I) => asserts input i * * **When to use** * - * Use when decoding input whose type is not statically known. + * Use when you need to decode unknown input in an `Effect` whose failure + * channel is `SchemaError`. * * **Details** * @@ -1233,12 +1238,17 @@ export const asserts: (schema: S, input: I) => asserts input i * Options may be provided either when creating the decoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.decodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly + * * @category decoding * @since 4.0.0 */ -export function decodeUnknownEffect(schema: S, options?: AST.ParseOptions) { - const parser = Parser.decodeUnknownEffect(schema, options) - return (input: unknown, options?: AST.ParseOptions): Effect.Effect => { +export function decodeUnknownEffect(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.decodeUnknownEffect(schema, options) + return ( + input: unknown, + options?: SchemaAST.ParseOptions + ): Effect.Effect => { return Effect.mapErrorEager(parser(input, options), (issue) => new SchemaError(issue)) } } @@ -1250,7 +1260,8 @@ export function decodeUnknownEffect(schema: S, options?: AST.Pars * * **When to use** * - * Use when you already have input typed as the schema's `Encoded` type. + * Use when you need to decode input already typed as the schema's `Encoded` + * type in an `Effect` whose failure channel is `SchemaError`. * * **Details** * @@ -1258,14 +1269,18 @@ export function decodeUnknownEffect(schema: S, options?: AST.Pars * Options may be provided either when creating the decoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.decodeEffect} for the adapter that fails with `SchemaIssue.Issue` directly + * * @category decoding * @since 4.0.0 */ export const decodeEffect: ( schema: S, - options?: AST.ParseOptions -) => (input: S["Encoded"], options?: AST.ParseOptions) => Effect.Effect = - decodeUnknownEffect + options?: SchemaAST.ParseOptions +) => ( + input: S["Encoded"], + options?: SchemaAST.ParseOptions +) => Effect.Effect = decodeUnknownEffect /** * Decodes an `unknown` input against a schema synchronously, returning an @@ -1274,8 +1289,8 @@ export const decodeEffect: ( * * **When to use** * - * Use when you do not know the input type statically and want decoding to - * return an `Exit` instead of failing or throwing. + * Use when you need to decode unknown input into an `Exit` whose failure + * contains `SchemaError`. * * **Details** * @@ -1285,12 +1300,14 @@ export const decodeEffect: ( * Options may be provided either when creating the decoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.decodeUnknownExit} for the adapter whose failure contains `SchemaIssue.Issue` directly + * * @category decoding * @since 4.0.0 */ -export function decodeUnknownExit>(schema: S, options?: AST.ParseOptions) { - const parser = Parser.decodeUnknownExit(schema, options) - return (input: unknown, options?: AST.ParseOptions): Exit_.Exit => { +export function decodeUnknownExit>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.decodeUnknownExit(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Exit_.Exit => { return Exit_.mapError(parser(input, options), (issue) => new SchemaError(issue)) } } @@ -1302,8 +1319,8 @@ export function decodeUnknownExit>(schema: S, options * * **When to use** * - * Use when typed input should be decoded into an `Exit` instead of failing or - * throwing. + * Use when you need to decode already typed `Encoded` input into an `Exit` + * whose failure contains `SchemaError`. * * **Details** * @@ -1312,13 +1329,15 @@ export function decodeUnknownExit>(schema: S, options * Options may be provided either when creating the decoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.decodeExit} for the adapter whose failure contains `SchemaIssue.Issue` directly + * * @category decoding * @since 4.0.0 */ export const decodeExit: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Encoded"], options?: AST.ParseOptions) => Exit_.Exit = decodeUnknownExit + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Exit_.Exit = decodeUnknownExit /** * Decodes an `unknown` input against a schema, returning an `Option` that is @@ -1339,7 +1358,7 @@ export const decodeExit: >( * @category decoding * @since 3.10.0 */ -export const decodeUnknownOption = Parser.decodeUnknownOption +export const decodeUnknownOption = SchemaParser.decodeUnknownOption /** * Decodes a typed input (the schema's `Encoded` type) against a schema, @@ -1359,7 +1378,7 @@ export const decodeUnknownOption = Parser.decodeUnknownOption * @category decoding * @since 3.10.0 */ -export const decodeOption = Parser.decodeOption +export const decodeOption = SchemaParser.decodeOption /** * Decodes an `unknown` input against a schema, returning a `Result` that @@ -1379,7 +1398,7 @@ export const decodeOption = Parser.decodeOption * @category decoding * @since 4.0.0 */ -export const decodeUnknownResult = Parser.decodeUnknownResult +export const decodeUnknownResult = SchemaParser.decodeUnknownResult /** * Decodes a typed input (the schema's `Encoded` type) against a schema, @@ -1400,7 +1419,7 @@ export const decodeUnknownResult = Parser.decodeUnknownResult * @category decoding * @since 4.0.0 */ -export const decodeResult = Parser.decodeResult +export const decodeResult = SchemaParser.decodeResult /** * Decodes an `unknown` input against a schema, returning a `Promise` that @@ -1419,7 +1438,7 @@ export const decodeResult = Parser.decodeResult * @category decoding * @since 3.10.0 */ -export const decodeUnknownPromise = Parser.decodeUnknownPromise +export const decodeUnknownPromise = SchemaParser.decodeUnknownPromise /** * Decodes a typed input (the schema's `Encoded` type) against a schema, @@ -1439,7 +1458,7 @@ export const decodeUnknownPromise = Parser.decodeUnknownPromise * @category decoding * @since 3.10.0 */ -export const decodePromise = Parser.decodePromise +export const decodePromise = SchemaParser.decodePromise /** * Decodes an `unknown` input against a schema synchronously, returning the @@ -1469,7 +1488,7 @@ export const decodePromise = Parser.decodePromise * // Output: 42 * * Schema.decodeUnknownSync(NumberFromString)("not a number") - * // throws SchemaError: NumberFromString + * // throws Error: NumberFromString * // └─ Encoded side transformation failure * // └─ NumberFromString * // └─ Expected a numeric string, actual "not a number" @@ -1478,7 +1497,7 @@ export const decodePromise = Parser.decodePromise * @category decoding * @since 4.0.0 */ -export const decodeUnknownSync = Parser.decodeUnknownSync +export const decodeUnknownSync = SchemaParser.decodeUnknownSync /** * Decodes a typed input (the schema's `Encoded` type) against a schema @@ -1500,7 +1519,7 @@ export const decodeUnknownSync = Parser.decodeUnknownSync * @category decoding * @since 4.0.0 */ -export const decodeSync = Parser.decodeSync +export const decodeSync = SchemaParser.decodeSync /** * Encodes an `unknown` input against a schema, returning an `Effect` that @@ -1508,7 +1527,8 @@ export const decodeSync = Parser.decodeSync * * **When to use** * - * Use when encoding input whose type is not statically known. + * Use when you need to encode unknown input in an `Effect` whose failure + * channel is `SchemaError`. * * **Details** * @@ -1528,14 +1548,16 @@ export const decodeSync = Parser.decodeSync * // Output: "42" * ``` * + * @see {@link SchemaParser.encodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly + * * @category encoding * @since 4.0.0 */ -export function encodeUnknownEffect(schema: S, options?: AST.ParseOptions) { - const parser = Parser.encodeUnknownEffect(schema, options) +export function encodeUnknownEffect(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.encodeUnknownEffect(schema, options) return ( input: unknown, - options?: AST.ParseOptions + options?: SchemaAST.ParseOptions ): Effect.Effect => { return Effect.mapErrorEager(parser(input, options), (issue) => new SchemaError(issue)) } @@ -1548,7 +1570,8 @@ export function encodeUnknownEffect(schema: S, options?: AST.Pars * * **When to use** * - * Use when you already have input typed as the schema's `Type`. + * Use when you need to encode input already typed as the schema's `Type` in + * an `Effect` whose failure channel is `SchemaError`. * * **Details** * @@ -1556,14 +1579,18 @@ export function encodeUnknownEffect(schema: S, options?: AST.Pars * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.encodeEffect} for the adapter that fails with `SchemaIssue.Issue` directly + * * @category encoding * @since 4.0.0 */ export const encodeEffect: ( schema: S, - options?: AST.ParseOptions -) => (input: S["Type"], options?: AST.ParseOptions) => Effect.Effect = - encodeUnknownEffect + options?: SchemaAST.ParseOptions +) => ( + input: S["Type"], + options?: SchemaAST.ParseOptions +) => Effect.Effect = encodeUnknownEffect /** * Encodes an `unknown` input against a schema synchronously, returning an @@ -1572,8 +1599,8 @@ export const encodeEffect: ( * * **When to use** * - * Use when you do not know the input type statically and want encoding to - * return an `Exit` instead of failing or throwing. + * Use when you need to encode unknown input into an `Exit` whose failure + * contains `SchemaError`. * * **Details** * @@ -1582,12 +1609,14 @@ export const encodeEffect: ( * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.encodeUnknownExit} for the adapter whose failure contains `SchemaIssue.Issue` directly + * * @category encoding * @since 4.0.0 */ -export function encodeUnknownExit>(schema: S, options?: AST.ParseOptions) { - const parser = Parser.encodeUnknownExit(schema, options) - return (input: unknown, options?: AST.ParseOptions): Exit_.Exit => { +export function encodeUnknownExit>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.encodeUnknownExit(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Exit_.Exit => { return Exit_.mapError(parser(input, options), (issue) => new SchemaError(issue)) } } @@ -1599,8 +1628,8 @@ export function encodeUnknownExit>(schema: S, options * * **When to use** * - * Use when typed input should be encoded into an `Exit` instead of failing or - * throwing. + * Use when you need to encode already typed schema values into an `Exit` whose + * failure contains `SchemaError`. * * **Details** * @@ -1609,13 +1638,15 @@ export function encodeUnknownExit>(schema: S, options * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.encodeExit} for the adapter whose failure contains `SchemaIssue.Issue` directly + * * @category encoding * @since 4.0.0 */ export const encodeExit: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Type"], options?: AST.ParseOptions) => Exit_.Exit = encodeUnknownExit + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Exit_.Exit = encodeUnknownExit /** * Encodes an `unknown` input against a schema, returning an `Option` that is @@ -1636,7 +1667,7 @@ export const encodeExit: >( * @category encoding * @since 3.10.0 */ -export const encodeUnknownOption = Parser.encodeUnknownOption +export const encodeUnknownOption = SchemaParser.encodeUnknownOption /** * Encodes a typed input (the schema's `Type`) against a schema, returning an @@ -1656,7 +1687,7 @@ export const encodeUnknownOption = Parser.encodeUnknownOption * @category encoding * @since 3.10.0 */ -export const encodeOption = Parser.encodeOption +export const encodeOption = SchemaParser.encodeOption /** * Encodes an `unknown` input against a schema, returning a `Result` that @@ -1676,7 +1707,7 @@ export const encodeOption = Parser.encodeOption * @category encoding * @since 4.0.0 */ -export const encodeUnknownResult = Parser.encodeUnknownResult +export const encodeUnknownResult = SchemaParser.encodeUnknownResult /** * Encodes a typed input (the schema's `Type`) against a schema, returning a @@ -1696,7 +1727,7 @@ export const encodeUnknownResult = Parser.encodeUnknownResult * @category encoding * @since 4.0.0 */ -export const encodeResult = Parser.encodeResult +export const encodeResult = SchemaParser.encodeResult /** * Encodes an `unknown` input against a schema, returning a `Promise` that @@ -1715,12 +1746,11 @@ export const encodeResult = Parser.encodeResult * @category encoding * @since 3.10.0 */ -export const encodeUnknownPromise = Parser.encodeUnknownPromise +export const encodeUnknownPromise = SchemaParser.encodeUnknownPromise /** * Encodes a typed input (the schema's `Type`) against a schema, returning a - * `Promise` that resolves with the encoded value or rejects with a - * {@link SchemaError}. + * `Promise` that resolves with the encoded value or rejects with a schema issue. * * **When to use** * @@ -1735,11 +1765,11 @@ export const encodeUnknownPromise = Parser.encodeUnknownPromise * @category encoding * @since 3.10.0 */ -export const encodePromise = Parser.encodePromise +export const encodePromise = SchemaParser.encodePromise /** - * Encodes an `unknown` input against a schema synchronously, throwing a - * {@link SchemaError} on failure. + * Encodes an `unknown` input against a schema synchronously, throwing an `Error` + * whose cause contains the schema issue on failure. * * **When to use** * @@ -1757,11 +1787,11 @@ export const encodePromise = Parser.encodePromise * @category encoding * @since 4.0.0 */ -export const encodeUnknownSync = Parser.encodeUnknownSync +export const encodeUnknownSync = SchemaParser.encodeUnknownSync /** * Encodes a typed input (the schema's `Type`) against a schema synchronously, - * throwing a {@link SchemaError} on failure. + * throwing an `Error` whose cause contains the schema issue on failure. * * **When to use** * @@ -1777,7 +1807,7 @@ export const encodeUnknownSync = Parser.encodeUnknownSync * @category encoding * @since 4.0.0 */ -export const encodeSync = Parser.encodeSync +export const encodeSync = SchemaParser.encodeSync /** * Creates a schema from an AST (Abstract Syntax Tree) node. @@ -1890,7 +1920,9 @@ interface optionalKeyLambda extends Lambda { * @category combinators * @since 4.0.0 */ -export const optionalKey = Struct_.lambda((schema) => make(AST.optionalKey(schema.ast), { schema })) +export const optionalKey = Struct_.lambda((schema) => + make(SchemaAST.optionalKey(schema.ast), { schema }) +) interface requiredKeyLambda extends Lambda { (self: optionalKey): S @@ -2020,7 +2052,9 @@ interface mutableKeyLambda extends Lambda { * @category combinators * @since 4.0.0 */ -export const mutableKey = Struct_.lambda((schema) => make(AST.mutableKey(schema.ast), { schema })) +export const mutableKey = Struct_.lambda((schema) => + make(SchemaAST.mutableKey(schema.ast), { schema }) +) interface readonlyKeyLambda extends Lambda { (self: mutableKey): S @@ -2079,7 +2113,7 @@ interface toTypeLambda extends Lambda { * @category transforming * @since 4.0.0 */ -export const toType = Struct_.lambda((schema) => make(AST.toType(schema.ast), { schema })) +export const toType = Struct_.lambda((schema) => make(SchemaAST.toType(schema.ast), { schema })) /** * Type-level representation returned by {@link toEncoded}. @@ -2093,7 +2127,7 @@ export interface toEncoded extends S["Encoded"], never, never, - AST.AST, + SchemaAST.AST, toEncoded, S["Encoded"], S["Encoded"], @@ -2119,7 +2153,7 @@ interface toEncodedLambda extends Lambda { * @category transforming * @since 4.0.0 */ -export const toEncoded = Struct_.lambda((schema) => make(AST.toEncoded(schema.ast), { schema })) +export const toEncoded = Struct_.lambda((schema) => make(SchemaAST.toEncoded(schema.ast), { schema })) const FlipTypeId = "~effect/Schema/flip" @@ -2135,7 +2169,7 @@ export interface flip extends S["Type"], S["EncodingServices"], S["DecodingServices"], - AST.AST, + SchemaAST.AST, flip, S["Encoded"], S["Encoded"], @@ -2183,9 +2217,9 @@ function isFlip$(schema: Top): schema is flip { export function flip(schema: S): S extends flip ? F["Rebuild"] : flip export function flip(schema: S): flip { if (isFlip$(schema)) { - return schema.schema.rebuild(AST.flip(schema.ast)) + return schema.schema.rebuild(SchemaAST.flip(schema.ast)) } - return make(AST.flip(schema.ast), { [FlipTypeId]: FlipTypeId, schema }) + return make(SchemaAST.flip(schema.ast), { [FlipTypeId]: FlipTypeId, schema }) } /** @@ -2194,9 +2228,11 @@ export function flip(schema: S): flip { * @category models * @since 3.10.0 */ -export interface Literal extends Bottom> { +export interface Literal + extends Bottom> +{ readonly literal: L - transform(to: L2): decodeTo, Literal> + transform(to: L2): decodeTo, Literal> } /** @@ -2217,13 +2253,13 @@ export interface Literal extends Bottom(literal: L): Literal { - const out = make>(new AST.Literal(literal), { +export function Literal(literal: L): Literal { + const out = make>(new SchemaAST.Literal(literal), { literal, - transform(to: L2): decodeTo, Literal> { + transform(to: L2): decodeTo, Literal> { return out.pipe(decodeTo(Literal(to), { - decode: Getter.transform(() => to), - encode: Getter.transform(() => literal) + decode: SchemaGetter.transform(() => to), + encode: SchemaGetter.transform(() => literal) })) } }) @@ -2306,7 +2342,7 @@ export interface TemplateLiteral extends TemplateLiteral.Encoded, never, never, - AST.TemplateLiteral, + SchemaAST.TemplateLiteral, TemplateLiteral > { @@ -2314,7 +2350,7 @@ export interface TemplateLiteral extends } function templateLiteralFromParts(parts: Parts) { - return new AST.TemplateLiteral(parts.map((part) => isSchema(part) ? part.ast : new AST.Literal(part))) + return new SchemaAST.TemplateLiteral(parts.map((part) => isSchema(part) ? part.ast : new SchemaAST.Literal(part))) } /** @@ -2376,7 +2412,7 @@ export interface TemplateLiteralParser exte TemplateLiteral.Encoded, never, never, - AST.Arrays, + SchemaAST.Arrays, TemplateLiteralParser > { @@ -2422,7 +2458,7 @@ export function TemplateLiteralParser * @since 4.0.0 */ export interface Enum - extends Bottom> + extends Bottom> { readonly enums: A } @@ -2449,7 +2485,7 @@ export interface Enum */ export function Enum(enums: A): Enum { return make( - new AST.Enum( + new SchemaAST.Enum( Object.keys(enums).filter( (key) => typeof enums[enums[key]] !== "number" ).map((key) => [key, enums[key]]) @@ -2464,7 +2500,7 @@ export function Enum(enums: A): Enum * @category models * @since 3.10.0 */ -export interface Never extends Bottom {} +export interface Never extends Bottom {} /** * Schema for the `never` type. Always fails validation — no value satisfies it. @@ -2472,7 +2508,7 @@ export interface Never extends Bottom {} +export interface Any extends Bottom {} /** * Schema for the `any` type. Accepts any value without validation. @@ -2489,7 +2525,7 @@ export interface Any extends Bottom {} * @category schemas * @since 3.10.0 */ -export const Any: Any = make(AST.any) +export const Any: Any = make(SchemaAST.any) /** * Type-level representation of {@link Unknown}. @@ -2497,7 +2533,7 @@ export const Any: Any = make(AST.any) * @category models * @since 3.10.0 */ -export interface Unknown extends Bottom {} +export interface Unknown extends Bottom {} /** * Schema for the `unknown` type. Accepts any value without validation. @@ -2506,7 +2542,7 @@ export interface Unknown extends Bottom {} +export interface Null extends Bottom {} /** * Schema for the `null` literal. Validates that the input is strictly `null`. @@ -2523,7 +2559,7 @@ export interface Null extends Bottom { * @category schemas * @since 3.10.0 */ -export const Null: Null = make(AST.null) +export const Null: Null = make(SchemaAST.null) /** * Type-level representation of {@link Undefined}. @@ -2531,7 +2567,7 @@ export const Null: Null = make(AST.null) * @category models * @since 3.10.0 */ -export interface Undefined extends Bottom {} +export interface Undefined extends Bottom {} /** * Schema for the `undefined` literal. Validates that the input is strictly `undefined`. @@ -2540,7 +2576,7 @@ export interface Undefined extends Bottom {} +export interface String extends Bottom {} /** * Schema for `string` values. Validates that the input is `typeof` `"string"`. @@ -2556,7 +2592,7 @@ export interface String extends Bottom {} +export interface Number extends Bottom {} /** * Schema for `number` values, including `NaN`, `Infinity`, and `-Infinity`. @@ -2580,7 +2616,7 @@ export interface Number extends Bottom {} +export interface Boolean extends Bottom {} /** * Schema for `boolean` values. Validates that the input is `typeof` `"boolean"`. @@ -2602,7 +2638,7 @@ export interface Boolean extends Bottom {} +export interface Symbol extends Bottom {} /** * Schema for `symbol` values. Validates that the input is `typeof` `"symbol"`. @@ -2619,7 +2655,7 @@ export interface Symbol extends Bottom {} +export interface BigInt extends Bottom {} /** * Schema for `bigint` values. Validates that the input is `typeof` `"bigint"`. @@ -2642,7 +2678,7 @@ export interface BigInt extends Bottom {} +export interface Void extends Bottom {} /** * Schema for the `void` type. Accepts `undefined` as the encoded value. @@ -2658,7 +2694,7 @@ export interface Void extends Bottom { * @category schemas * @since 3.10.0 */ -export const Void: Void = make(AST.void) +export const Void: Void = make(SchemaAST.void) /** * Type-level representation of {@link ObjectKeyword}. @@ -2666,7 +2702,7 @@ export const Void: Void = make(AST.void) * @category models * @since 4.0.0 */ -export interface ObjectKeyword extends Bottom {} +export interface ObjectKeyword extends Bottom {} /** * Schema for the `object` type. Validates that the input is a non-null object or function @@ -2675,7 +2711,7 @@ export interface ObjectKeyword extends Bottom - extends Bottom> + extends Bottom> {} /** @@ -2704,7 +2740,7 @@ export interface UniqueSymbol * @since 4.0.0 */ export function UniqueSymbol(symbol: sym): UniqueSymbol { - return make(new AST.UniqueSymbol(symbol)) + return make(new SchemaAST.UniqueSymbol(symbol)) } /** @@ -2880,7 +2916,7 @@ export interface Struct extends Struct.Encoded, Struct.DecodingServices, Struct.EncodingServices, - AST.Objects, + SchemaAST.Objects, Struct, Struct.MakeIn, Struct.Iso @@ -2932,7 +2968,7 @@ export interface Struct extends ): Struct>> } -function makeStruct(ast: AST.Objects, fields: Fields): Struct { +function makeStruct(ast: SchemaAST.Objects, fields: Fields): Struct { return make(ast, { fields, mapFields( @@ -2943,7 +2979,7 @@ function makeStruct(ast: AST.Objects, fields } | undefined ): Struct { const fields = f(this.fields) - return makeStruct(AST.struct(fields, options?.unsafePreserveChecks ? this.ast.checks : undefined), fields) + return makeStruct(SchemaAST.struct(fields, options?.unsafePreserveChecks ? this.ast.checks : undefined), fields) } }) } @@ -2982,7 +3018,7 @@ function makeStruct(ast: AST.Objects, fields * @since 3.10.0 */ export function Struct(fields: Fields): Struct { - return makeStruct(AST.struct(fields, undefined), fields) + return makeStruct(SchemaAST.struct(fields, undefined), fields) } interface fieldsAssign extends Lambda { @@ -3091,7 +3127,7 @@ export function encodeKeys< } return Struct(fields).pipe(decodeTo( self, - Transformation.transform({ + SchemaTransformation.transform({ decode: Struct_.renameKeys(reverseMapping), encode: Struct_.renameKeys(mapping) }) @@ -3143,7 +3179,7 @@ export function extendTo, const Fields extends S const to = Struct({ ...f, ...fields }) return self.pipe(decodeTo( to, - Transformation.transform({ + SchemaTransformation.transform({ decode: (input) => { const out: any = { ...input } for (const k in fields) { @@ -3302,7 +3338,7 @@ export interface $Record extends Record.Encoded, Record.DecodingServices, Record.EncodingServices, - AST.Objects, + SchemaAST.Objects, $Record, Simplify>, Record.Iso @@ -3344,9 +3380,9 @@ export function Record( } ): $Record { const keyValueCombiner = options?.keyValueCombiner?.decode || options?.keyValueCombiner?.encode - ? new AST.KeyValueCombiner(options.keyValueCombiner.decode, options.keyValueCombiner.encode) + ? new SchemaAST.KeyValueCombiner(options.keyValueCombiner.decode, options.keyValueCombiner.encode) : undefined - return make(AST.record(key.ast, value.ast, keyValueCombiner), { key, value }) + return make(SchemaAST.record(key.ast, value.ast, keyValueCombiner), { key, value }) } /** @@ -3367,7 +3403,7 @@ export declare namespace StructWithRest { * @category utility types * @since 4.0.0 */ - export type Objects = Top & { readonly ast: AST.Objects } + export type Objects = Top & { readonly ast: SchemaAST.Objects } /** * Readonly list of record schemas that provide the additional index signatures @@ -3465,7 +3501,7 @@ export interface StructWithRest< Simplify>, StructWithRest.DecodingServices, StructWithRest.EncodingServices, - AST.Objects, + SchemaAST.Objects, StructWithRest, Simplify>, Simplify> @@ -3503,7 +3539,7 @@ export function StructWithRest< schema: S, records: Records ): StructWithRest { - return make(AST.structWithRest(schema.ast, records.map(AST.getAST)), { schema, records }) + return make(SchemaAST.structWithRest(schema.ast, records.map(SchemaAST.getAST)), { schema, records }) } /** @@ -3649,7 +3685,7 @@ export interface Tuple extends Tuple.Encoded, Tuple.DecodingServices, Tuple.EncodingServices, - AST.Arrays, + SchemaAST.Arrays, Tuple, Tuple.MakeIn, Tuple.Iso @@ -3680,7 +3716,7 @@ export interface Tuple extends ): Tuple>> } -function makeTuple(ast: AST.Arrays, elements: Elements): Tuple { +function makeTuple(ast: SchemaAST.Arrays, elements: Elements): Tuple { return make(ast, { elements, mapElements( @@ -3691,7 +3727,7 @@ function makeTuple(ast: AST.Arrays, elements: E } | undefined ): Tuple>> { const elements = f(this.elements) - return makeTuple(AST.tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements) + return makeTuple(SchemaAST.tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements) } }) } @@ -3715,7 +3751,7 @@ function makeTuple(ast: AST.Arrays, elements: E * @since 3.10.0 */ export function Tuple>(elements: Elements): Tuple { - return makeTuple(AST.tuple(elements), elements) + return makeTuple(SchemaAST.tuple(elements), elements) } /** @@ -3741,7 +3777,7 @@ export declare namespace TupleWithRest { export type TupleType = Top & { readonly Type: ReadonlyArray readonly Encoded: ReadonlyArray - readonly ast: AST.Arrays + readonly ast: SchemaAST.Arrays readonly "~type.make": ReadonlyArray readonly "Iso": ReadonlyArray } @@ -3855,7 +3891,7 @@ export interface TupleWithRest< TupleWithRest.Encoded, S["DecodingServices"] | Rest[number]["DecodingServices"], S["EncodingServices"] | Rest[number]["EncodingServices"], - AST.Arrays, + SchemaAST.Arrays, TupleWithRest, TupleWithRest.MakeIn, TupleWithRest.Iso @@ -3899,7 +3935,7 @@ export function TupleWithRest, const Rest extend schema: S, rest: Rest ): TupleWithRest { - return make(AST.tupleWithRest(schema.ast, rest.map(AST.getAST)), { schema, rest }) + return make(SchemaAST.tupleWithRest(schema.ast, rest.map(SchemaAST.getAST)), { schema, rest }) } /** @@ -3914,7 +3950,7 @@ export interface $Array extends ReadonlyArray, S["DecodingServices"], S["EncodingServices"], - AST.Arrays, + SchemaAST.Arrays, $Array, ReadonlyArray, ReadonlyArray @@ -3933,7 +3969,7 @@ interface ArrayLambda extends Lambda { * @since 4.0.0 */ const ArraySchema = Struct_.lambda((schema) => - make(new AST.Arrays(false, [], [schema.ast]), { value: schema }) + make(new SchemaAST.Arrays(false, [], [schema.ast]), { value: schema }) ) export { @@ -3970,7 +4006,7 @@ export interface NonEmptyArray extends readonly [S["Encoded"], ...Array], S["DecodingServices"], S["EncodingServices"], - AST.Arrays, + SchemaAST.Arrays, NonEmptyArray, readonly [S["~type.make"], ...Array], readonly [S["Iso"], ...Array] @@ -4003,7 +4039,7 @@ interface NonEmptyArrayLambda extends Lambda { * @since 3.10.0 */ export const NonEmptyArray = Struct_.lambda((schema) => - make(new AST.Arrays(false, [schema.ast], [schema.ast]), { value: schema }) + make(new SchemaAST.Arrays(false, [schema.ast], [schema.ast]), { value: schema }) ) /** @@ -4045,7 +4081,7 @@ export interface ArrayEnsure extends decodeTo<$Array>, export function ArrayEnsure(schema: S): ArrayEnsure { return Union([schema, ArraySchema(schema)]).pipe(decodeTo( ArraySchema(toType(schema)), - Transformation.transform({ + SchemaTransformation.transform({ decode: Arr.ensure, encode: (array) => array.length === 1 ? array[0] : array }) @@ -4083,7 +4119,7 @@ export function UniqueArray(item: S): UniqueArray { * @category transforming * @since 3.10.0 */ -export interface mutable extends +export interface mutable extends Bottom< Mutable, Mutable, @@ -4107,8 +4143,9 @@ export interface mutable extends } interface mutableLambda extends Lambda { - (self: S): mutable - readonly "~lambda.out": this["~lambda.in"] extends Top & { readonly "ast": AST.Arrays } ? mutable + (self: S): mutable + readonly "~lambda.out": this["~lambda.in"] extends Top & { readonly "ast": SchemaAST.Arrays } ? + mutable : "Error: schema not eligible for mutable" } @@ -4130,7 +4167,7 @@ interface mutableLambda extends Lambda { * @since 3.10.0 */ export const mutable = Struct_.lambda((schema) => { - return make(new AST.Arrays(true, schema.ast.elements, schema.ast.rest), { schema }) + return make(new SchemaAST.Arrays(true, schema.ast.elements, schema.ast.rest), { schema }) }) /** @@ -4145,7 +4182,7 @@ export interface Union> extends { [K in keyof Members]: Members[K]["Encoded"] }[number], { [K in keyof Members]: Members[K]["DecodingServices"] }[number], { [K in keyof Members]: Members[K]["EncodingServices"] }[number], - AST.Union<{ [K in keyof Members]: Members[K]["ast"] }[number]>, + SchemaAST.Union<{ [K in keyof Members]: Members[K]["ast"] }[number]>, Union, { [K in keyof Members]: Members[K]["~type.make"] }[number], { [K in keyof Members]: Members[K]["Iso"] }[number] @@ -4177,7 +4214,7 @@ export interface Union> extends } function makeUnion>( - ast: AST.Union, + ast: SchemaAST.Union, members: Members ): Union { return make(ast, { @@ -4191,7 +4228,7 @@ function makeUnion>( ): Union>> { const members = f(this.members) return makeUnion( - AST.union(members, this.ast.mode, options?.unsafePreserveChecks ? this.ast.checks : undefined), + SchemaAST.union(members, this.ast.mode, options?.unsafePreserveChecks ? this.ast.checks : undefined), members ) } @@ -4226,7 +4263,7 @@ export function Union>( members: Members, options?: { mode?: "anyOf" | "oneOf" } ): Union { - return makeUnion(AST.union(members, options?.mode ?? "anyOf", undefined), members) + return makeUnion(SchemaAST.union(members, options?.mode ?? "anyOf", undefined), members) } /** @@ -4235,8 +4272,8 @@ export function Union>( * @category models * @since 4.0.0 */ -export interface Literals> - extends Bottom, Literals> +export interface Literals> + extends Bottom, Literals> { readonly literals: L readonly members: { readonly [K in keyof L]: Literal } @@ -4247,7 +4284,7 @@ export interface Literals> pick>(literals: L2): Literals - transform( + transform( to: L2 ): Union<{ [I in keyof L]: decodeTo, Literal> }> } @@ -4268,9 +4305,9 @@ export interface Literals> * @category constructors * @since 4.0.0 */ -export function Literals>(literals: L): Literals { +export function Literals>(literals: L): Literals { const members = literals.map(Literal) as { readonly [K in keyof L]: Literal } - return make(AST.union(members, "anyOf", undefined), { + return make(SchemaAST.union(members, "anyOf", undefined), { literals, members, mapMembers>( @@ -4282,7 +4319,7 @@ export function Literals>(litera pick>(literals: L2): Literals { return Literals(literals) }, - transform( + transform( to: L2 ): Union<{ [I in keyof L]: decodeTo, Literal> }> { return Union(members.map((member, index) => member.transform(to[index]))) as any @@ -4371,7 +4408,7 @@ export interface suspend extends S["Encoded"], S["DecodingServices"], S["EncodingServices"], - AST.Suspend, + SchemaAST.Suspend, suspend, S["~type.make.in"], S["Iso"], @@ -4410,7 +4447,7 @@ export interface suspend extends * @since 3.10.0 */ export function suspend(f: () => S): suspend { - return make(new AST.Suspend(() => f().ast)) + return make(new SchemaAST.Suspend(() => f().ast)) } /** @@ -4430,7 +4467,9 @@ export function suspend(f: () => S): suspend { * @category filtering * @since 4.0.0 */ -export function check(...checks: readonly [AST.Check, ...Array>]) { +export function check( + ...checks: readonly [SchemaAST.Check, ...Array>] +) { return (self: S): S["Rebuild"] => self.check(...checks) } @@ -4482,7 +4521,7 @@ export function refine( annotations?: Annotations.Filter ) { return (schema: S): refine => - make(AST.appendChecks(schema.ast, [AST.makeFilterByGuard(refinement, annotations)]), { schema }) + make(SchemaAST.appendChecks(schema.ast, [SchemaAST.makeFilterByGuard(refinement, annotations)]), { schema }) } type DistributeBrands = UnionToIntersection : never> @@ -4537,7 +4576,7 @@ export interface brand extends */ export function brand(identifier: B) { return (schema: S): brand => - make(AST.brand(schema.ast, identifier), { schema, identifier }) + make(SchemaAST.brand(schema.ast, identifier), { schema, identifier }) } /** @@ -4610,13 +4649,13 @@ export interface middlewareDecoding extends */ export function middlewareDecoding( decode: ( - effect: Effect.Effect, Issue.Issue, S["DecodingServices"]>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, RD> + effect: Effect.Effect, SchemaIssue.Issue, S["DecodingServices"]>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, RD> ) { return (schema: S): middlewareDecoding => make( - AST.middlewareDecoding(schema.ast, new Transformation.Middleware(decode, identity)), + SchemaAST.middlewareDecoding(schema.ast, new SchemaTransformation.Middleware(decode, identity)), { schema } ) } @@ -4676,13 +4715,13 @@ export interface middlewareEncoding extends */ export function middlewareEncoding( encode: ( - effect: Effect.Effect, Issue.Issue, S["EncodingServices"]>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, RE> + effect: Effect.Effect, SchemaIssue.Issue, S["EncodingServices"]>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, RE> ) { return (schema: S): middlewareEncoding => make( - AST.middlewareEncoding(schema.ast, new Transformation.Middleware(identity, encode)), + SchemaAST.middlewareEncoding(schema.ast, new SchemaTransformation.Middleware(identity, encode)), { schema } ) } @@ -4710,7 +4749,7 @@ export function middlewareEncoding( * @since 4.0.0 */ export function catchDecoding( - f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue> + f: (issue: SchemaIssue.Issue) => Effect.Effect, SchemaIssue.Issue> ): (self: S) => S["Rebuild"] { return catchDecodingWithContext(f) } @@ -4736,7 +4775,7 @@ export function catchDecoding( * @since 4.0.0 */ export function catchDecodingWithContext( - f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue, R> + f: (issue: SchemaIssue.Issue) => Effect.Effect, SchemaIssue.Issue, R> ) { return (self: S): middlewareDecoding => self.pipe(middlewareDecoding(Effect.catchEager(f))) @@ -4755,7 +4794,7 @@ export function catchDecodingWithContext( * @since 4.0.0 */ export function catchEncoding( - f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue> + f: (issue: SchemaIssue.Issue) => Effect.Effect, SchemaIssue.Issue> ): (self: S) => S["Rebuild"] { return catchEncodingWithContext(f) } @@ -4781,7 +4820,7 @@ export function catchEncoding( * @since 4.0.0 */ export function catchEncodingWithContext( - f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue, R> + f: (issue: SchemaIssue.Issue) => Effect.Effect, SchemaIssue.Issue, R> ) { return (self: S): middlewareEncoding => self.pipe(middlewareEncoding(Effect.catchEager(f))) @@ -4835,7 +4874,7 @@ export interface compose extends decodeTo(to: To): (from: From) export function decodeTo( to: To, transformation: { - readonly decode: Getter.Getter, NoInfer, RD> - readonly encode: Getter.Getter, NoInfer, RE> + readonly decode: SchemaGetter.Getter, NoInfer, RD> + readonly encode: SchemaGetter.Getter, NoInfer, RE> } ): (from: From) => decodeTo export function decodeTo( to: To, transformation?: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter } | undefined ) { return (from: From) => { return make( - AST.decodeTo( + SchemaAST.decodeTo( from.ast, to.ast, - transformation ? Transformation.make(transformation) : Transformation.passthrough() + transformation ? SchemaTransformation.make(transformation) : SchemaTransformation.passthrough() ), { from, @@ -4940,8 +4979,8 @@ export function decodeTo(transformation: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter }) { return (self: S): decodeTo, S, RD, RE> => { return self.pipe(decodeTo(toType(self), transformation)) @@ -4983,15 +5022,15 @@ export function encodeTo( export function encodeTo( to: To, transformation: { - readonly decode: Getter.Getter, NoInfer, RD> - readonly encode: Getter.Getter, NoInfer, RE> + readonly decode: SchemaGetter.Getter, NoInfer, RD> + readonly encode: SchemaGetter.Getter, NoInfer, RE> } ): (from: From) => decodeTo export function encodeTo( to: To, transformation?: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter } ) { return (from: From): decodeTo => { @@ -5027,8 +5066,8 @@ export function encodeTo(transformation: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter }) { return (self: S): decodeTo, RD, RE> => { return toEncoded(self).pipe(decodeTo(self, transformation)) @@ -5110,7 +5149,7 @@ export function withConstructorDefault ) { return (schema: S): withConstructorDefault => - make(AST.withConstructorDefault(schema.ast, Effect.mapErrorEager(defaultValue, (e) => e.issue)), { schema }) + make(SchemaAST.withConstructorDefault(schema.ast, Effect.mapErrorEager(defaultValue, (e) => e.issue)), { schema }) } /** @@ -5177,10 +5216,10 @@ export function withDecodingDefaultKey( defaultValue: Effect.Effect, options?: DecodingDefaultOptions ) { - const encode = options?.encodingStrategy === "omit" ? Getter.omit() : Getter.passthrough() + const encode = options?.encodingStrategy === "omit" ? SchemaGetter.omit() : SchemaGetter.passthrough() return (self: S): withDecodingDefaultKey => { return optionalKey(toEncoded(self)).pipe(decodeTo(self, { - decode: Getter.withDefault(Effect.mapErrorEager(defaultValue, (e) => e.issue)), + decode: SchemaGetter.withDefault(Effect.mapErrorEager(defaultValue, (e) => e.issue)), encode })) } @@ -5280,10 +5319,10 @@ export function withDecodingDefault( defaultValue: Effect.Effect, options?: DecodingDefaultOptions ) { - const encode = options?.encodingStrategy === "omit" ? Getter.omit() : Getter.passthrough() + const encode = options?.encodingStrategy === "omit" ? SchemaGetter.omit() : SchemaGetter.passthrough() return (self: S): withDecodingDefault => { return optional(toEncoded(self)).pipe(decodeTo(self, { - decode: Getter.withDefault(Effect.mapErrorEager(defaultValue, (e) => e.issue)), + decode: SchemaGetter.withDefault(Effect.mapErrorEager(defaultValue, (e) => e.issue)), encode })) } @@ -5341,7 +5380,7 @@ export function withDecodingDefaultType( * @category constructors * @since 3.10.0 */ -export interface tag extends withConstructorDefault> {} +export interface tag extends withConstructorDefault> {} /** * Combines a {@link Literal} schema with {@link withConstructorDefault}, making it ideal @@ -5365,7 +5404,7 @@ export interface tag extends withConstructorDefaul * @category constructors * @since 3.10.0 */ -export function tag(literal: Tag): tag { +export function tag(literal: Tag): tag { return Literal(literal).pipe(withConstructorDefault(Effect.succeed(literal))) } @@ -5401,7 +5440,7 @@ export function tag(literal: Tag): tag { * @category constructors * @since 4.0.0 */ -export function tagDefaultOmit(literal: Tag) { +export function tagDefaultOmit(literal: Tag) { return tag(literal).pipe(withDecodingDefaultKey(Effect.succeed(literal), { encodingStrategy: "omit" })) } @@ -5411,7 +5450,7 @@ export function tagDefaultOmit(literal: Tag) { * @category models * @since 3.10.0 */ -export type TaggedStruct = Struct< +export type TaggedStruct = Struct< Simplify<{ readonly _tag: tag } & Fields> > @@ -5461,7 +5500,7 @@ export type TaggedStruct( +export function TaggedStruct( value: Tag, fields: Fields ): TaggedStruct { @@ -5556,13 +5595,13 @@ export function toTaggedUnion(tag: Tag) { const ast = schema.ast if ( - AST.isUnion(ast) && "members" in schema && globalThis.Array.isArray(schema.members) && + SchemaAST.isUnion(ast) && "members" in schema && globalThis.Array.isArray(schema.members) && schema.members.every(isSchema) ) { return schema.members.forEach(walk) } - const sentinels = AST.collectSentinels(ast) + const sentinels = SchemaAST.collectSentinels(ast) if (sentinels.length > 0) { const literal = sentinels.find((s) => s.key === tag)?.literal if (Predicate.isPropertyKey(literal)) { @@ -5601,7 +5640,7 @@ export interface TaggedUnion> extends { [K in keyof Cases]: Cases[K]["Encoded"] }[keyof Cases], { [K in keyof Cases]: Cases[K]["DecodingServices"] }[keyof Cases], { [K in keyof Cases]: Cases[K]["EncodingServices"] }[keyof Cases], - AST.Union, + SchemaAST.Union, TaggedUnion, { [K in keyof Cases]: Cases[K]["~type.make"] }[keyof Cases] > @@ -5757,7 +5796,7 @@ export function instanceOf any, Iso = In } /** - * Constructs an `AST.Link` that describes how a value of type `T` encodes to and decodes from a `To` schema. + * Constructs an `SchemaAST.Link` that describes how a value of type `T` encodes to and decodes from a `To` schema. * Used when building low-level AST transformations that bridge two schema types. * * @category transforming @@ -5767,11 +5806,11 @@ export function link() { return ( encodeTo: To, transformation: { - readonly decode: Getter.Getter> - readonly encode: Getter.Getter, T> + readonly decode: SchemaGetter.Getter> + readonly encode: SchemaGetter.Getter, T> } - ): AST.Link => { - return new AST.Link(encodeTo.ast, Transformation.make(transformation)) + ): SchemaAST.Link => { + return new SchemaAST.Link(encodeTo.ast, SchemaTransformation.make(transformation)) } } @@ -5838,10 +5877,10 @@ export function link() { * @since 4.0.0 */ export const makeFilter: ( - filter: (input: T, ast: AST.AST, options: AST.ParseOptions) => FilterOutput, + filter: (input: T, ast: SchemaAST.AST, options: SchemaAST.ParseOptions) => FilterOutput, annotations?: Annotations.Filter | undefined, abort?: boolean -) => AST.Filter = AST.makeFilter +) => SchemaAST.Filter = SchemaAST.makeFilter /** * A single failure reported by a filter predicate. Used as the element type @@ -5850,20 +5889,20 @@ export const makeFilter: ( * **Details** * * - `string`: failure with that string as the message. Produces an - * {@link Issue.InvalidValue} wrapping the input, with the string used as + * {@link SchemaIssue.InvalidValue} wrapping the input, with the string used as * the issue's `message` annotation. - * - {@link Issue.Issue}: a fully-formed issue, returned as-is. + * - {@link SchemaIssue.Issue}: a fully-formed issue, returned as-is. * - `{ path, issue }`: failure attached to a nested path. `issue` is either - * a `string` (wrapped in an {@link Issue.InvalidValue}) or a full - * {@link Issue.Issue}; the result is wrapped in an {@link Issue.Pointer} + * a `string` (wrapped in an {@link SchemaIssue.InvalidValue}) or a full + * {@link SchemaIssue.Issue}; the result is wrapped in an {@link SchemaIssue.Pointer} * at the given `path`. * * @category models * @since 3.10.0 */ -export type FilterIssue = string | Issue.Issue | { +export type FilterIssue = string | SchemaIssue.Issue | { readonly path: ReadonlyArray - readonly issue: string | Issue.Issue + readonly issue: string | SchemaIssue.Issue } /** @@ -5871,20 +5910,20 @@ export type FilterIssue = string | Issue.Issue | { * * **Details** * - * Each shape is normalized into an {@link Issue.Issue} (or `undefined` for + * Each shape is normalized into an {@link SchemaIssue.Issue} (or `undefined` for * success) before being attached to the parse result: * * - `undefined`: success. The input satisfies the filter. * - `true`: success. Equivalent to `undefined`, useful when the predicate is * a plain boolean expression. - * - `false`: generic failure. Produces an {@link Issue.InvalidValue} wrapping + * - `false`: generic failure. Produces an {@link SchemaIssue.InvalidValue} wrapping * the input, with no custom message. * - {@link FilterIssue}: a single failure. See {@link FilterIssue} for the - * shapes (`string`, {@link Issue.Issue}, or `{ path, issue }`). + * shapes (`string`, {@link SchemaIssue.Issue}, or `{ path, issue }`). * - `ReadonlyArray`: several failures reported together. An * empty array is treated as success; a single-element array is equivalent * to returning that element directly; otherwise the entries are grouped - * into an {@link Issue.Composite}. + * into an {@link SchemaIssue.Composite}. * * @category models * @since 3.10.0 @@ -5896,17 +5935,17 @@ export type FilterOutput = | ReadonlyArray /** - * Groups multiple checks into a single {@link AST.FilterGroup}, applying + * Groups multiple checks into a single {@link SchemaAST.FilterGroup}, applying * optional shared annotations to the group as a whole. * * @category constructors * @since 4.0.0 */ export function makeFilterGroup( - checks: readonly [AST.Check, ...Array>], + checks: readonly [SchemaAST.Check, ...Array>], annotations: Annotations.Filter | undefined = undefined -): AST.FilterGroup { - return new AST.FilterGroup(checks, annotations) +): SchemaAST.FilterGroup { + return new SchemaAST.FilterGroup(checks, annotations) } const TRIMMED_PATTERN = "^\\S[\\s\\S]*\\S$|^\\S$|^$" @@ -5965,8 +6004,8 @@ export function isTrimmed(annotations?: Annotations.Filter) { * @category String checks * @since 4.0.0 */ -export const isPattern: (regExp: globalThis.RegExp, annotations?: Annotations.Filter) => AST.Filter = - AST.isPattern +export const isPattern: (regExp: globalThis.RegExp, annotations?: Annotations.Filter) => SchemaAST.Filter = + SchemaAST.isPattern /** * Validates that a string represents a finite number. @@ -5986,7 +6025,7 @@ export const isPattern: (regExp: globalThis.RegExp, annotations?: Annotations.Fi * @category String checks * @since 4.0.0 */ -export const isStringFinite: (annotations?: Annotations.Filter) => AST.Filter = AST.isStringFinite +export const isStringFinite: (annotations?: Annotations.Filter) => SchemaAST.Filter = SchemaAST.isStringFinite /** * Validates that a string is a signed base-10 integer literal for Effect's @@ -6005,7 +6044,7 @@ export const isStringFinite: (annotations?: Annotations.Filter) => AST.Filter AST.Filter = AST.isStringBigInt +export const isStringBigInt: (annotations?: Annotations.Filter) => SchemaAST.Filter = SchemaAST.isStringBigInt /** * Validates that a string has the `Symbol(description)` format used by Effect's @@ -6019,7 +6058,7 @@ export const isStringBigInt: (annotations?: Annotations.Filter) => AST.Filter AST.Filter = AST.isStringSymbol +export const isStringSymbol: (annotations?: Annotations.Filter) => SchemaAST.Filter = SchemaAST.isStringSymbol /** * Returns a RegExp for validating an RFC 4122 UUID. @@ -6876,7 +6915,7 @@ export function isInt(annotations?: Annotations.Filter) { * @since 4.0.0 */ export function isInt32(annotations?: Annotations.Filter) { - return new AST.FilterGroup( + return new SchemaAST.FilterGroup( [ isInt(annotations), isBetween({ minimum: -2147483648, maximum: 2147483647 }) @@ -6908,7 +6947,7 @@ export function isInt32(annotations?: Annotations.Filter) { * @since 4.0.0 */ export function isUint32(annotations?: Annotations.Filter) { - return new AST.FilterGroup( + return new SchemaAST.FilterGroup( [ isInt(), isBetween({ minimum: 0, maximum: 4294967295 }) @@ -7379,7 +7418,7 @@ export function isMinLength(minLength: number, annotations?: Annotations.Filter) _tag: "isMinLength", minLength }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, toArbitraryConstraint: { string: { minLength @@ -7446,7 +7485,7 @@ export function isMaxLength(maxLength: number, annotations?: Annotations.Filter) _tag: "isMaxLength", maxLength }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, toArbitraryConstraint: { string: { maxLength @@ -7494,7 +7533,7 @@ export function isLengthBetween(minimum: number, maximum: number, annotations?: minimum, maximum }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, toArbitraryConstraint: { string: { minLength: minimum, @@ -7540,7 +7579,7 @@ export function isMinSize(minSize: number, annotations?: Annotations.Filter) { _tag: "isMinSize", minSize }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, toArbitraryConstraint: { array: { minLength: minSize @@ -7581,7 +7620,7 @@ export function isMaxSize(maxSize: number, annotations?: Annotations.Filter) { _tag: "isMaxSize", maxSize }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, toArbitraryConstraint: { array: { maxLength: maxSize @@ -7626,7 +7665,7 @@ export function isSizeBetween(minimum: number, maximum: number, annotations?: An minimum, maximum }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, toArbitraryConstraint: { array: { minLength: minimum, @@ -7669,7 +7708,7 @@ export function isMinProperties(minProperties: number, annotations?: Annotations _tag: "isMinProperties", minProperties }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, toArbitraryConstraint: { array: { minLength: minProperties @@ -7710,7 +7749,7 @@ export function isMaxProperties(maxProperties: number, annotations?: Annotations _tag: "isMaxProperties", maxProperties }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, toArbitraryConstraint: { array: { maxLength: maxProperties @@ -7755,7 +7794,7 @@ export function isPropertiesLengthBetween(minimum: number, maximum: number, anno minimum, maximum }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, toArbitraryConstraint: { array: { minLength: minimum, @@ -7785,20 +7824,20 @@ export function isPropertiesLengthBetween(minimum: number, maximum: number, anno */ export function isPropertyNames(keySchema: Top, annotations?: Annotations.Filter) { const propertyNames = toEncoded(keySchema) - const parser = Parser._issue(propertyNames.ast) + const parser = SchemaParser._issue(propertyNames.ast) return makeFilter( (input, ast, options) => { const keys = Reflect.ownKeys(input) - const issues: Array = [] + const issues: Array = [] for (const key of keys) { const issue = parser(key, options) if (issue !== undefined) { - issues.push(new Issue.Pointer([key], issue)) + issues.push(new SchemaIssue.Pointer([key], issue)) if (options.errors === "first") break } } if (Arr.isArrayNonEmpty(issues)) { - return new Issue.Composite(ast, Option_.some(input), issues) + return new SchemaIssue.Composite(ast, Option_.some(input), issues) } return true }, @@ -7808,7 +7847,7 @@ export function isPropertyNames(keySchema: Top, annotations?: Annotations.Filter _tag: "isPropertyNames", propertyNames: propertyNames.ast }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, ...annotations } ) @@ -7954,14 +7993,15 @@ export function Option(value: A): Option { return Effect.succeedNone } return Effect.mapBothEager( - Parser.decodeUnknownEffect(value)(input.value, options), + SchemaParser.decodeUnknownEffect(value)(input.value, options), { onSuccess: Option_.some, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["value"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["value"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) }, { typeConstructor: { @@ -7979,7 +8019,7 @@ export function Option(value: A): Option { Struct({ _tag: Literal("Some"), value }), Struct({ _tag: Literal("None") }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => e._tag === "None" ? Option_.none() : Option_.some(e.value), encode: (o) => (Option_.isSome(o) ? { _tag: "Some", value: o.value } as const : { _tag: "None" } as const) }) @@ -8031,7 +8071,7 @@ export interface OptionFromNullOr extends decodeTo(schema: S): OptionFromNullOr { return NullOr(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromNullOr() + SchemaTransformation.optionFromNullOr() )) } @@ -8064,7 +8104,7 @@ export interface OptionFromUndefinedOr extends decodeTo(schema: S): OptionFromUndefinedOr { return UndefinedOr(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromUndefinedOr() + SchemaTransformation.optionFromUndefinedOr() )) } @@ -8102,7 +8142,7 @@ export function OptionFromNullishOr( ): OptionFromNullishOr { return NullishOr(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromNullishOr(options) + SchemaTransformation.optionFromNullishOr(options) )) } @@ -8135,7 +8175,7 @@ export interface OptionFromOptionalKey extends decodeTo(schema: S): OptionFromOptionalKey { return optionalKey(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromOptionalKey() + SchemaTransformation.optionFromOptionalKey() )) } @@ -8170,7 +8210,7 @@ export interface OptionFromOptional extends decodeTo(schema: S): OptionFromOptional { return optional(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromOptional() + SchemaTransformation.optionFromOptional() )) } @@ -8217,7 +8257,7 @@ export function OptionFromOptionalNullOr( : undefined as S["Type"] | null | undefined return optional(NullOr(schema)).pipe(decodeTo( Option(toType(schema)), - Transformation.transformOptional, S["Type"] | null | undefined>({ + SchemaTransformation.transformOptional, S["Type"] | null | undefined>({ decode: (oe) => oe.pipe(Option_.filter(Predicate.isNotNullish), Option_.some), encode: onNoneEncoding === "omit" ? Option_.flatten @@ -8278,18 +8318,20 @@ export function Result( [success, failure], ([success, failure]) => (input, ast, options) => { if (!Result_.isResult(input)) { - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } switch (input._tag) { case "Success": - return Effect.mapBothEager(Parser.decodeEffect(success)(input.success, options), { + return Effect.mapBothEager(SchemaParser.decodeEffect(success)(input.success, options), { onSuccess: Result_.succeed, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["success"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["success"], issue)]) }) case "Failure": - return Effect.mapBothEager(Parser.decodeEffect(failure)(input.failure, options), { + return Effect.mapBothEager(SchemaParser.decodeEffect(failure)(input.failure, options), { onSuccess: Result_.fail, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["failure"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["failure"], issue)]) }) } }, @@ -8309,7 +8351,7 @@ export function Result( Struct({ _tag: Literal("Success"), success }), Struct({ _tag: Literal("Failure"), failure }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e): Result_.Result => e._tag === "Success" ? Result_.succeed(e.success) : Result_.fail(e.failure), encode: (r) => @@ -8381,36 +8423,36 @@ export function Redacted(value: S, options?: { readonly disallowJsonEncode?: boolean | undefined }): Redacted { const decodeLabel = typeof options?.label === "string" - ? Parser.decodeUnknownEffect(Literal(options.label)) + ? SchemaParser.decodeUnknownEffect(Literal(options.label)) : undefined const schema = declareConstructor, Redacted_.Redacted>()( [value], ([value]) => (input, ast, poptions) => { if (Redacted_.isRedacted(input)) { - const label: Effect.Effect = decodeLabel !== undefined + const label: Effect.Effect = decodeLabel !== undefined ? Effect.mapErrorEager( decodeLabel(input.label, poptions), - (issue) => new Issue.Pointer(["label"], issue) + (issue) => new SchemaIssue.Pointer(["label"], issue) ) : Effect.void return Effect.flatMapEager( label, () => Effect.mapBothEager( - Parser.decodeUnknownEffect(value)(Redacted_.value(input), poptions), + SchemaParser.decodeUnknownEffect(value)(Redacted_.value(input), poptions), { onSuccess: () => input, onFailure: (/** ignore the actual issue because of security reasons */) => { const oinput = Option_.some(input) - return new Issue.Composite(ast, oinput, [ - new Issue.Pointer(["value"], new Issue.InvalidValue(oinput)) + return new SchemaIssue.Composite(ast, oinput, [ + new SchemaIssue.Pointer(["value"], new SchemaIssue.InvalidValue(oinput)) ]) } } ) ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) }, { typeConstructor: { @@ -8426,13 +8468,13 @@ export function Redacted(value: S, options?: { link>()( redact(value), { - decode: Getter.transform((e) => Redacted_.make(e, { label: options?.label })), + decode: SchemaGetter.transform((e) => Redacted_.make(e, { label: options?.label })), encode: options?.disallowJsonEncode ? - Getter.forbidden((oe) => + SchemaGetter.forbidden((oe) => "Cannot serialize Redacted" + (Option_.isSome(oe) && typeof oe.value.label === "string" ? ` with label: "${oe.value.label}"` : "") ) : - Getter.transform(Redacted_.value) + SchemaGetter.transform(Redacted_.value) } ), toArbitrary: ([value]) => () => value.map((a) => Redacted_.make(a, { label: options?.label })), @@ -8463,7 +8505,7 @@ export interface RedactedFromValue * @since 4.0.0 */ export function redact(schema: S): middlewareDecoding { - return schema.pipe(middlewareDecoding(Effect.mapErrorEager(Issue.redact))) + return schema.pipe(middlewareDecoding(Effect.mapErrorEager(SchemaIssue.redact))) } /** @@ -8485,13 +8527,13 @@ export function RedactedFromValue(value: S, options?: { disallowJsonEncode: options?.disallowEncode }), { - decode: Getter.transform((t) => Redacted_.make(t, { label: options?.label })), + decode: SchemaGetter.transform((t) => Redacted_.make(t, { label: options?.label })), encode: options?.disallowEncode ? - Getter.forbidden((oe) => + SchemaGetter.forbidden((oe) => "Cannot encode Redacted" + (Option_.isSome(oe) && typeof oe.value.label === "string" ? ` with label: "${oe.value.label}"` : "") ) : - Getter.transform(Redacted_.value) + SchemaGetter.transform(Redacted_.value) } ) ) @@ -8563,24 +8605,25 @@ export function CauseReason(error: E, defect: D): [error, defect], ([error, defect]) => (input, ast, options) => { if (!Cause_.isReason(input)) { - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } switch (input._tag) { case "Fail": return Effect.mapBothEager( - Parser.decodeUnknownEffect(error)(input.error, options), + SchemaParser.decodeUnknownEffect(error)(input.error, options), { onSuccess: Cause_.makeFailReason, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["error"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["error"], issue)]) } ) case "Die": return Effect.mapBothEager( - Parser.decodeUnknownEffect(defect)(input.defect, options), + SchemaParser.decodeUnknownEffect(defect)(input.defect, options), { onSuccess: Cause_.makeDieReason, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["defect"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["defect"], issue)]) } ) case "Interrupt": @@ -8604,7 +8647,7 @@ export function CauseReason(error: E, defect: D): Struct({ _tag: Literal("Die"), defect }), Struct({ _tag: Literal("Interrupt"), fiberId: UndefinedOr(Finite) }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => { switch (e._tag) { case "Fail": @@ -8729,11 +8772,12 @@ export function Cause(error: E, defect: D): Cause< const failures = ArraySchema(CauseReason(error, defect)) return (input, ast, options) => { if (!Cause_.isCause(input)) { - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } - return Effect.mapBothEager(Parser.decodeUnknownEffect(failures)(input.reasons, options), { + return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(failures)(input.reasons, options), { onSuccess: Cause_.fromReasons, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["failures"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["failures"], issue)]) }) } }, @@ -8750,7 +8794,7 @@ export function Cause(error: E, defect: D): Cause< toCodec: ([error, defect]) => link>()( ArraySchema(CauseReason(error, defect)), - Transformation.transform({ + SchemaTransformation.transform({ decode: Cause_.fromReasons, encode: ({ reasons: failures }) => failures }) @@ -8817,7 +8861,7 @@ export const Error: Error = instanceOf(globalThis.Error, { Type: `globalThis.Error` }, expected: "Error", - toCodecJson: () => link()(ErrorJsonEncoded, Transformation.errorFromErrorJsonEncoded()), + toCodecJson: () => link()(ErrorJsonEncoded, SchemaTransformation.errorFromErrorJsonEncoded()), toArbitrary: () => (fc) => fc.string().map((message) => new globalThis.Error(message)) }) @@ -8846,7 +8890,7 @@ export const ErrorWithStack: Error = instanceOf(globalThis.Error, { toCodecJson: () => link()( ErrorJsonEncoded, - Transformation.errorFromErrorJsonEncoded({ + SchemaTransformation.errorFromErrorJsonEncoded({ includeStack: true }) ), @@ -8877,9 +8921,9 @@ export interface Defect extends readonly "Rebuild": Defect } -const defectTransformation = new Transformation.Transformation( - Getter.passthrough(), - Getter.transform((u) => { +const defectTransformation = new SchemaTransformation.Transformation( + SchemaGetter.passthrough(), + SchemaGetter.transform((u) => { try { return JSON.parse(JSON.stringify(u)) } catch { @@ -8902,7 +8946,7 @@ const defectTransformation = new Transformation.Transformation( * @since 3.10.0 */ export const Defect: Defect = Union([ - ErrorJsonEncoded.pipe(decodeTo(Error, Transformation.errorFromErrorJsonEncoded())), + ErrorJsonEncoded.pipe(decodeTo(Error, SchemaTransformation.errorFromErrorJsonEncoded())), Any.pipe(decodeTo( Unknown.annotate({ toCodecJson: () => link()(Any, defectTransformation), @@ -8921,7 +8965,7 @@ export const Defect: Defect = Union([ export const DefectWithStack: Defect = Union([ ErrorJsonEncoded.pipe(decodeTo( ErrorWithStack, - Transformation.errorFromErrorJsonEncoded({ + SchemaTransformation.errorFromErrorJsonEncoded({ includeStack: true }) )), @@ -8991,25 +9035,25 @@ export function Exit(value: A, erro const cause = Cause(error, defect) return (input, ast, options) => { if (!Exit_.isExit(input)) { - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } switch (input._tag) { case "Success": return Effect.mapBothEager( - Parser.decodeUnknownEffect(value)(input.value, options), + SchemaParser.decodeUnknownEffect(value)(input.value, options), { onSuccess: Exit_.succeed, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["value"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["value"], issue)]) } ) case "Failure": return Effect.mapBothEager( - Parser.decodeUnknownEffect(cause)(input.cause, options), + SchemaParser.decodeUnknownEffect(cause)(input.cause, options), { onSuccess: Exit_.failCause, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["cause"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["cause"], issue)]) } ) } @@ -9031,7 +9075,7 @@ export function Exit(value: A, erro Struct({ _tag: Literal("Success"), value }), Struct({ _tag: Literal("Failure"), cause: Cause(error, defect) }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e): Exit_.Exit => e._tag === "Success" ? Exit_.succeed(e.value) : Exit_.failCause(e.cause), encode: (exit) => @@ -9121,15 +9165,15 @@ export function ReadonlyMap(key: Key, value: return (input, ast, options) => { if (input instanceof globalThis.Map) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(array)([...input], options), + SchemaParser.decodeUnknownEffect(array)([...input], options), { onSuccess: (array: ReadonlyArray) => new globalThis.Map(array), onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["entries"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["entries"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -9144,7 +9188,7 @@ export function ReadonlyMap(key: Key, value: toCodec: ([key, value]) => link>()( ArraySchema(Tuple([key, value])), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => new globalThis.Map(e), encode: (map) => [...map.entries()] }) @@ -9216,15 +9260,15 @@ export function HashMap(key: Key, value: Val return (input, ast, options) => { if (HashMap_.isHashMap(input)) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(entries)(HashMap_.toEntries(input), options), + SchemaParser.decodeUnknownEffect(entries)(HashMap_.toEntries(input), options), { onSuccess: HashMap_.fromIterable, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["entries"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["entries"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -9240,7 +9284,7 @@ export function HashMap(key: Key, value: Val toCodec: ([key, value]) => link>()( ArraySchema(Tuple([key, value])), - Transformation.transform({ + SchemaTransformation.transform({ decode: HashMap_.fromIterable, encode: HashMap_.toEntries }) @@ -9311,15 +9355,15 @@ export function ReadonlySet(value: Value): $ReadonlySet { if (input instanceof globalThis.Set) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(array)([...input], options), + SchemaParser.decodeUnknownEffect(array)([...input], options), { onSuccess: (array: ReadonlyArray) => new globalThis.Set(array), onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["values"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["values"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -9334,7 +9378,7 @@ export function ReadonlySet(value: Value): $ReadonlySet link>()( ArraySchema(value), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => new globalThis.Set(e), encode: (set) => [...set.values()] }) @@ -9405,15 +9449,15 @@ export function HashSet(value: Value): HashSet { return (input, ast, options) => { if (HashSet_.isHashSet(input)) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), + SchemaParser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), { onSuccess: HashSet_.fromIterable, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["values"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["values"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -9428,7 +9472,7 @@ export function HashSet(value: Value): HashSet { toCodec: ([value]) => link>()( ArraySchema(value), - Transformation.transform({ + SchemaTransformation.transform({ decode: HashSet_.fromIterable, encode: Arr.fromIterable }) @@ -9506,15 +9550,15 @@ export function Chunk(value: Value): Chunk { return (input, ast, options) => { if (Chunk_.isChunk(input)) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), + SchemaParser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), { onSuccess: Chunk_.fromIterable, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["values"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["values"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -9529,7 +9573,7 @@ export function Chunk(value: Value): Chunk { toCodec: ([value]) => link>()( ArraySchema(value), - Transformation.transform({ + SchemaTransformation.transform({ decode: Chunk_.fromIterable, encode: Arr.fromIterable }) @@ -9592,11 +9636,11 @@ export const RegExp: RegExp = instanceOf( source: String, flags: String }), - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode: (e) => Effect.try({ try: () => new globalThis.RegExp(e.source, e.flags), - catch: (e) => new Issue.InvalidValue(Option_.some(e), { message: globalThis.String(e) }) + catch: (e) => new SchemaIssue.InvalidValue(Option_.some(e), { message: globalThis.String(e) }) }), encode: (regExp) => Effect.succeed({ @@ -9669,7 +9713,7 @@ export const URL: URL = instanceOf( toCodecJson: () => link()( URLString, - Transformation.urlFromString + SchemaTransformation.urlFromString ), toArbitrary: () => (fc) => fc.webUrl().map((s) => new globalThis.URL(s)), toEquivalence: () => (a, b) => a.toString() === b.toString() @@ -9700,7 +9744,7 @@ export interface URLFromString extends decodeTo { * @category URL * @since 4.0.0 */ -export const URLFromString: URLFromString = URLString.pipe(decodeTo(URL, Transformation.urlFromString)) +export const URLFromString: URLFromString = URLString.pipe(decodeTo(URL, SchemaTransformation.urlFromString)) /** * Type-level representation of {@link Date}. @@ -9756,7 +9800,7 @@ export const Date: Date = instanceOf( toCodecJson: () => link()( DateString, - Transformation.dateFromString + SchemaTransformation.dateFromString ), toArbitrary: () => (fc, ctx) => fc.date(ctx?.constraints?.date) } @@ -9799,7 +9843,7 @@ export interface DateFromString extends decodeTo { * @category Date * @since 3.10.0 */ -export const DateFromString: DateFromString = DateString.pipe(decodeTo(Date, Transformation.dateFromString)) +export const DateFromString: DateFromString = DateString.pipe(decodeTo(Date, SchemaTransformation.dateFromString)) /** * Type-level representation of {@link DateValid}. @@ -9875,7 +9919,7 @@ export const Duration: Duration = declare( Struct({ _tag: Literal("Nanos"), value: BigInt }), Struct({ _tag: Literal("Millis"), value: Int }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => { switch (e._tag) { case "Infinity": @@ -9942,7 +9986,7 @@ export interface DurationFromString extends decodeTo { * @since 4.0.0 */ export const DurationFromString: DurationFromString = DurationString.pipe( - decodeTo(Duration, Transformation.durationFromString) + decodeTo(Duration, SchemaTransformation.durationFromString) ) /** @@ -9975,7 +10019,7 @@ const bigint0 = globalThis.BigInt(0) * @since 3.10.0 */ export const DurationFromNanos: DurationFromNanos = BigInt.check(isGreaterThanOrEqualToBigInt(bigint0)).pipe( - decodeTo(Duration, Transformation.durationFromNanos) + decodeTo(Duration, SchemaTransformation.durationFromNanos) ) /** @@ -10007,7 +10051,7 @@ export interface DurationFromMillis extends decodeTo { * @since 3.10.0 */ export const DurationFromMillis: DurationFromMillis = Number.check(isGreaterThanOrEqualTo(0)).pipe( - decodeTo(Duration, Transformation.durationFromMillis) + decodeTo(Duration, SchemaTransformation.durationFromMillis) ) /** @@ -10056,7 +10100,7 @@ export const BigDecimal: BigDecimal = declare( toCodecJson: () => link()( BigDecimalString, - Transformation.bigDecimalFromString + SchemaTransformation.bigDecimalFromString ), toArbitrary: () => (fc) => fc.tuple(fc.bigInt(), fc.integer({ min: 0, max: 20 })) @@ -10104,7 +10148,7 @@ export interface BigDecimalFromString extends decodeTo { * @since 4.0.0 */ export const BigDecimalFromString: BigDecimalFromString = BigDecimalString.pipe( - decodeTo(BigDecimal, Transformation.bigDecimalFromString) + decodeTo(BigDecimal, SchemaTransformation.bigDecimalFromString) ) /** @@ -10224,8 +10268,8 @@ export function fromJsonString(schema: S): fromJsonString { return String.annotate({ expected: "a string that will be decoded as JSON", contentMediaType: "application/json", - contentSchema: AST.toEncoded(schema.ast) - }).pipe(decodeTo(schema, Transformation.fromJsonString)) + contentSchema: SchemaAST.toEncoded(schema.ast) + }).pipe(decodeTo(schema, SchemaTransformation.fromJsonString)) } /** @@ -10266,12 +10310,12 @@ export const File: File = instanceOf(globalThis.File, { name: String, lastModified: Number }), - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode: (e) => Result_.match(Encoding.decodeBase64(e.data), { onFailure: (error) => Effect.fail( - new Issue.InvalidValue(Option_.some(e.data), { + new SchemaIssue.InvalidValue(Option_.some(e.data), { message: error.message }) ), @@ -10294,7 +10338,7 @@ export const File: File = instanceOf(globalThis.File, { } }, catch: (e) => - new Issue.InvalidValue(Option_.some(file), { + new SchemaIssue.InvalidValue(Option_.some(file), { message: globalThis.String(e) }) }) @@ -10343,7 +10387,7 @@ export const FormData: FormData = instanceOf(globalThis.FormData, { ]) ]) ), - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode: (e) => { const out = new globalThis.FormData() for (const [key, entry] of e) { @@ -10465,7 +10509,7 @@ export interface fromFormData extends decodeTo { * @since 4.0.0 */ export function fromFormData(schema: S): fromFormData { - return FormData.pipe(decodeTo(schema, Transformation.fromFormData)) + return FormData.pipe(decodeTo(schema, SchemaTransformation.fromFormData)) } /** @@ -10500,7 +10544,7 @@ export const URLSearchParams: URLSearchParams = instanceOf(globalThis.URLSearchP toCodecJson: () => link()( String.annotate({ expected: "a query string that will be decoded as URLSearchParams" }), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => new globalThis.URLSearchParams(e), encode: (params) => params.toString() }) @@ -10598,7 +10642,7 @@ export interface fromURLSearchParams extends decodeTo(schema: S): fromURLSearchParams { - return URLSearchParams.pipe(decodeTo(schema, Transformation.fromURLSearchParams)) + return URLSearchParams.pipe(decodeTo(schema, SchemaTransformation.fromURLSearchParams)) } /** @@ -10666,7 +10710,7 @@ export interface NumberFromString extends decodeTo { */ export const NumberFromString: NumberFromString = String.annotate({ expected: "a string that will be decoded as a number" -}).pipe(decodeTo(Number, Transformation.numberFromString)) +}).pipe(decodeTo(Number, SchemaTransformation.numberFromString)) /** * Type-level representation of {@link FiniteFromString}. @@ -10695,7 +10739,7 @@ export interface FiniteFromString extends decodeTo { */ export const FiniteFromString: FiniteFromString = String.annotate({ expected: "a string that will be decoded as a finite number" -}).pipe(decodeTo(Finite, Transformation.numberFromString)) +}).pipe(decodeTo(Finite, SchemaTransformation.numberFromString)) /** * Type-level representation of {@link BigIntFromString}. @@ -10735,8 +10779,8 @@ export interface BigIntFromString extends decodeTo { * @category BigInt * @since 4.0.0 */ -export const BigIntFromString: BigIntFromString = make(AST.bigIntString).pipe( - decodeTo(BigInt, Transformation.bigintFromString) +export const BigIntFromString: BigIntFromString = make(SchemaAST.bigIntString).pipe( + decodeTo(BigInt, SchemaTransformation.bigintFromString) ) /** @@ -10783,7 +10827,7 @@ export interface Trim extends decodeTo { */ export const Trim: Trim = String.annotate({ expected: "a string that will be decoded as a trimmed string" -}).pipe(decodeTo(Trimmed, Transformation.trim())) +}).pipe(decodeTo(Trimmed, SchemaTransformation.trim())) /** * Type-level representation of {@link StringFromBase64}. @@ -10812,7 +10856,7 @@ export interface StringFromBase64 extends decodeTo { export const StringFromBase64: StringFromBase64 = String.annotate({ expected: "a base64 encoded string that will be decoded as a UTF-8 string" }).pipe( - decodeTo(String, Transformation.stringFromBase64String) + decodeTo(String, SchemaTransformation.stringFromBase64String) ) /** @@ -10842,7 +10886,7 @@ export interface StringFromBase64Url extends decodeTo { export const StringFromBase64Url: StringFromBase64Url = String.annotate({ expected: "a base64 (URL) encoded string that will be decoded as a UTF-8 string" }).pipe( - decodeTo(String, Transformation.stringFromBase64UrlString) + decodeTo(String, SchemaTransformation.stringFromBase64UrlString) ) /** @@ -10872,7 +10916,7 @@ export interface StringFromHex extends decodeTo { export const StringFromHex: StringFromHex = String.annotate({ expected: "a hex encoded string that will be decoded as a UTF-8 string" }).pipe( - decodeTo(String, Transformation.stringFromHexString) + decodeTo(String, SchemaTransformation.stringFromHexString) ) /** @@ -10921,7 +10965,7 @@ export interface StringFromUriComponent extends decodeTo { export const StringFromUriComponent: StringFromUriComponent = String.annotate({ expected: "a URI component encoded string that will be decoded as a UTF-8 string" }).pipe( - decodeTo(String, Transformation.stringFromUriComponent) + decodeTo(String, SchemaTransformation.stringFromUriComponent) ) /** @@ -10983,7 +11027,7 @@ export interface BooleanFromBit extends decodeTo bit === 1, encode: (bool) => bool ? 1 : 0 }) @@ -11030,7 +11074,7 @@ export const Uint8Array: Uint8Array = instanceOf(globalThis.Uint8Array link>()( Base64String, - Transformation.uint8ArrayFromBase64String + SchemaTransformation.uint8ArrayFromBase64String ), toArbitrary: () => (fc) => fc.uint8Array() }) @@ -11061,7 +11105,7 @@ export interface Uint8ArrayFromBase64 extends decodeTo { * @since 3.10.0 */ export const Uint8ArrayFromBase64: Uint8ArrayFromBase64 = Base64String.pipe( - decodeTo(Uint8Array, Transformation.uint8ArrayFromBase64String) + decodeTo(Uint8Array, SchemaTransformation.uint8ArrayFromBase64String) ) /** @@ -11093,8 +11137,8 @@ export const Uint8ArrayFromBase64Url: Uint8ArrayFromBase64Url = String.annotate( expected: "a base64 (URL) encoded string that will be decoded as a Uint8Array" }).pipe( decodeTo(Uint8Array, { - decode: Getter.decodeBase64Url(), - encode: Getter.encodeBase64Url() + decode: SchemaGetter.decodeBase64Url(), + encode: SchemaGetter.encodeBase64Url() }) ) @@ -11127,8 +11171,8 @@ export const Uint8ArrayFromHex: Uint8ArrayFromHex = String.annotate({ expected: "a hex encoded string that will be decoded as a Uint8Array" }).pipe( decodeTo(Uint8Array, { - decode: Getter.decodeHex(), - encode: Getter.encodeHex() + decode: SchemaGetter.decodeHex(), + encode: SchemaGetter.encodeHex() }) ) @@ -11178,7 +11222,7 @@ export const DateTimeUtc: DateTimeUtc = declare( toCodecJson: () => link()( String, - Transformation.dateTimeUtcFromString + SchemaTransformation.dateTimeUtcFromString ), toArbitrary: () => (fc, ctx) => fc.date({ noInvalidDate: true, ...ctx?.constraints?.date }).map((date) => DateTime.fromDateUnsafe(date)), @@ -11223,8 +11267,8 @@ export interface DateTimeUtcFromDate extends decodeTo { */ export const DateTimeUtcFromDate: DateTimeUtcFromDate = DateValid.pipe( decodeTo(DateTimeUtc, { - decode: Getter.dateTimeUtcFromInput(), - encode: Getter.transform(DateTime.toDateUtc) + decode: SchemaGetter.dateTimeUtcFromInput(), + encode: SchemaGetter.transform(DateTime.toDateUtc) }) ) @@ -11260,7 +11304,7 @@ export const DateTimeUtcFromString: DateTimeUtcFromString = String.annotate({ }).pipe( decodeTo( DateTimeUtc, - Transformation.dateTimeUtcFromString + SchemaTransformation.dateTimeUtcFromString ) ) @@ -11290,8 +11334,8 @@ export interface DateTimeUtcFromMillis extends decodeTo */ export const DateTimeUtcFromMillis: DateTimeUtcFromMillis = Number.pipe( decodeTo(DateTimeUtc, { - decode: Getter.dateTimeUtcFromInput(), - encode: Getter.transform(DateTime.toEpochMillis) + decode: SchemaGetter.dateTimeUtcFromInput(), + encode: SchemaGetter.transform(DateTime.toEpochMillis) }) ) @@ -11332,7 +11376,7 @@ export const TimeZoneOffset: TimeZoneOffset = declare( toCodecJson: () => link()( Number, - Transformation.timeZoneOffsetFromNumber + SchemaTransformation.timeZoneOffsetFromNumber ), toArbitrary: () => (fc) => fc.integer({ min: -12 * 60 * 60 * 1000, max: 14 * 60 * 60 * 1000 }).map((n) => DateTime.zoneMakeOffset(n)), @@ -11380,7 +11424,7 @@ export const TimeZoneNamed: TimeZoneNamed = declare( toCodecJson: () => link()( TimeZoneNamedString, - Transformation.timeZoneNamedFromString + SchemaTransformation.timeZoneNamedFromString ), toArbitrary: () => (fc) => fc.constantFrom( @@ -11418,7 +11462,7 @@ export interface TimeZoneNamedFromString extends decodeTo * @since 4.0.0 */ export const TimeZoneNamedFromString: TimeZoneNamedFromString = TimeZoneNamedString.pipe( - decodeTo(TimeZoneNamed, Transformation.timeZoneNamedFromString) + decodeTo(TimeZoneNamed, SchemaTransformation.timeZoneNamedFromString) ) /** @@ -11463,7 +11507,7 @@ export const TimeZone: TimeZone = declare( toCodecJson: () => link()( TimeZoneString, - Transformation.timeZoneFromString + SchemaTransformation.timeZoneFromString ), toArbitrary: () => (fc) => fc.oneof( @@ -11504,7 +11548,7 @@ export interface TimeZoneFromString extends decodeTo { * @since 4.0.0 */ export const TimeZoneFromString: TimeZoneFromString = TimeZoneString.pipe( - decodeTo(TimeZone, Transformation.timeZoneFromString) + decodeTo(TimeZone, SchemaTransformation.timeZoneFromString) ) /** @@ -11551,7 +11595,7 @@ export const DateTimeZoned: DateTimeZoned = declare( toCodecJson: () => link()( DateTimeZonedString, - Transformation.dateTimeZonedFromString + SchemaTransformation.dateTimeZonedFromString ), toArbitrary: () => (fc, ctx) => fc.tuple( @@ -11593,7 +11637,7 @@ export interface DateTimeZonedFromString extends decodeTo * @since 4.0.0 */ export const DateTimeZonedFromString: DateTimeZonedFromString = DateTimeZonedString.pipe( - decodeTo(DateTimeZoned, Transformation.dateTimeZonedFromString) + decodeTo(DateTimeZoned, SchemaTransformation.dateTimeZonedFromString) ) // ----------------------------------------------------------------------------- @@ -11612,7 +11656,7 @@ export interface Class, S>, RequiredKeys extends never ? void | S["~type.make.in"] : S["~type.make.in"], S["Iso"], @@ -11704,32 +11748,32 @@ function makeClass< static readonly identifier = identifier static readonly fields = struct.fields - static get ast(): AST.Declaration { + static get ast(): SchemaAST.Declaration { return getClassSchema(this).ast } static pipe() { return Pipeable.pipeArguments(this, arguments) } - static rebuild(ast: AST.Declaration) { + static rebuild(ast: SchemaAST.Declaration) { return getClassSchema(this).rebuild(ast) } static make(input: S["~type.make.in"], options?: MakeOptions): Self { return new this(input, options) } static makeOption(input: S["~type.make.in"], options?: MakeOptions): Option_.Option { - return Parser.makeOption(getClassSchema(this) as any)(input ?? {}, options) as any + return SchemaParser.makeOption(getClassSchema(this) as any)(input ?? {}, options) as any } static makeEffect(input: S["~type.make.in"], options?: MakeOptions): Effect.Effect { return (getClassSchema(this) as any).makeEffect(input ?? {}, options) } static annotate(annotations: Annotations.Declaration) { - return this.rebuild(AST.annotate(this.ast, annotations)) + return this.rebuild(SchemaAST.annotate(this.ast, annotations)) } static annotateKey(annotations: Annotations.Key) { - return this.rebuild(AST.annotateKey(this.ast, annotations)) + return this.rebuild(SchemaAST.annotateKey(this.ast, annotations)) } - static check(...checks: readonly [AST.Check, ...Array>]) { - return this.rebuild(AST.appendChecks(this.ast, checks)) + static check(...checks: readonly [SchemaAST.Check, ...Array>]) { + return this.rebuild(SchemaAST.appendChecks(this.ast, checks)) } static extend( identifier: string @@ -11742,7 +11786,7 @@ function makeClass< return makeClass( this, identifier, - makeStruct(AST.struct(fields, struct.ast.checks, { identifier }), fields), + makeStruct(SchemaAST.struct(fields, struct.ast.checks, { identifier }), fields), annotations, proto ) @@ -11766,9 +11810,9 @@ function makeClass< } function getClassTransformation(self: new(...args: ReadonlyArray) => any) { - return new Transformation.Transformation( - Getter.transform((input) => new self(input)), - Getter.passthrough() + return new SchemaTransformation.Transformation( + SchemaGetter.transform((input) => new self(input)), + SchemaGetter.passthrough() ) } @@ -11788,22 +11832,22 @@ function getClassSchemaFactory( if (memo === undefined) { const transformation = getClassTransformation(self) const to = make>( - new AST.Declaration( + new SchemaAST.Declaration( [from.ast], () => (input, ast) => { return input instanceof self || Predicate.hasProperty(input, getClassTypeId(identifier)) ? Effect.succeed(input) : - Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) }, { identifier, - [AST.ClassTypeId]: ([from]: readonly [AST.AST]) => new AST.Link(from, transformation), - toCodec: ([from]: readonly [Codec]) => new AST.Link(from.ast, transformation), + [SchemaAST.ClassTypeId]: ([from]: readonly [SchemaAST.AST]) => new SchemaAST.Link(from, transformation), + toCodec: ([from]: readonly [Codec]) => new SchemaAST.Link(from.ast, transformation), toArbitrary: ([from]: readonly [FastCheck.Arbitrary]) => () => from.map((args) => new self(args)), toFormatter: ([from]: readonly [Formatter]) => (t: Self) => `${self.identifier}(${from(t)})`, - "~sentinels": AST.collectSentinels(from.ast), + "~sentinels": SchemaAST.collectSentinels(from.ast), ...annotations } ) @@ -12185,18 +12229,18 @@ export function overrideToFormatter(toFormatter: () => Formatter< */ export function toFormatter(schema: Schema, options?: { readonly onBefore?: - | ((ast: AST.AST, recur: (ast: AST.AST) => Formatter) => Formatter | undefined) + | ((ast: SchemaAST.AST, recur: (ast: SchemaAST.AST) => Formatter) => Formatter | undefined) | undefined }): Formatter { return recur(schema.ast) - function recur(ast: AST.AST): Formatter { + function recur(ast: SchemaAST.AST): Formatter { // --------------------------------------------- // handle annotation // --------------------------------------------- const annotation = InternalAnnotations.resolve(ast)?.["toFormatter"] if (typeof annotation === "function") { - return annotation(AST.isDeclaration(ast) ? ast.typeParameters.map(recur) : []) + return annotation(SchemaAST.isDeclaration(ast) ? ast.typeParameters.map(recur) : []) } // --------------------------------------------- // handle onBefore @@ -12213,7 +12257,7 @@ export function toFormatter(schema: Schema, options?: { return on(ast) } - function on(ast: AST.AST): Formatter { + function on(ast: SchemaAST.AST): Formatter { switch (ast._tag) { default: return format @@ -12232,7 +12276,7 @@ export function toFormatter(schema: Schema, options?: { // --------------------------------------------- for (; i < elements.length; i++) { if (t.length < i + 1) { - if (AST.isOptional(ast.elements[i])) { + if (SchemaAST.isOptional(ast.elements[i])) { continue } } else { @@ -12275,7 +12319,7 @@ export function toFormatter(schema: Schema, options?: { const ps = ast.propertySignatures[i] const name = ps.name visited.add(name) - if (AST.isOptional(ps.type) && !Object.hasOwn(t, name)) { + if (SchemaAST.isOptional(ps.type) && !Object.hasOwn(t, name)) { continue } out.push(`${formatPropertyKey(name)}: ${propertySignatures[i](t[name])}`) @@ -12284,7 +12328,7 @@ export function toFormatter(schema: Schema, options?: { // handle index signatures // --------------------------------------------- for (let i = 0; i < indexSignatures.length; i++) { - const keys = AST.getIndexSignatureKeys(t, ast.indexSignatures[i].parameter) + const keys = SchemaAST.getIndexSignatureKeys(t, ast.indexSignatures[i].parameter) for (const key of keys) { if (visited.has(key)) { continue @@ -12298,10 +12342,10 @@ export function toFormatter(schema: Schema, options?: { } } case "Union": { - const getCandidates = (t: any) => AST.getCandidates(t, ast.types) + const getCandidates = (t: any) => SchemaAST.getCandidates(t, ast.types) return (t) => { const candidates = getCandidates(t) - const refinements = candidates.map(Parser._is) + const refinements = candidates.map(SchemaParser._is) for (let i = 0; i < candidates.length; i++) { const is = refinements[i] if (is(t)) { @@ -12312,7 +12356,7 @@ export function toFormatter(schema: Schema, options?: { } } case "Suspend": { - const get = AST.memoizeThunk(() => recur(ast.thunk())) + const get = SchemaAST.memoizeThunk(() => recur(ast.thunk())) return (t) => get()(t) } } @@ -12493,28 +12537,28 @@ export function toCodecJson(schema: Codec): Codec { +const toCodecJsonTop = SchemaAST.toCodec((ast) => { const out = toCodecJsonBase(ast, toCodecJsonTop) - return out !== ast && AST.isOptional(ast) ? AST.optionalKeyLastLink(out) : out + return out !== ast && SchemaAST.isOptional(ast) ? SchemaAST.optionalKeyLastLink(out) : out }) -function toCodecJsonBase(ast: AST.AST, recur: (ast: AST.AST) => AST.AST): AST.AST { +function toCodecJsonBase(ast: SchemaAST.AST, recur: (ast: SchemaAST.AST) => SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { case "Declaration": { const getLink = ast.annotations?.toCodecJson ?? ast.annotations?.toCodec if (Predicate.isFunction(getLink)) { - const tps = AST.isDeclaration(ast) - ? ast.typeParameters.map((tp) => InternalSchema.make(AST.toEncoded(tp))) + const tps = SchemaAST.isDeclaration(ast) + ? ast.typeParameters.map((tp) => InternalSchema.make(SchemaAST.toEncoded(tp))) : [] const link = getLink(tps) const to = recur(link.to) - return AST.replaceEncoding(ast, to === link.to ? [link] : [new AST.Link(to, link.transformation)]) + return SchemaAST.replaceEncoding(ast, to === link.to ? [link] : [new SchemaAST.Link(to, link.transformation)]) } - return AST.replaceEncoding(ast, [AST.unknownToNull]) + return SchemaAST.replaceEncoding(ast, [SchemaAST.unknownToNull]) } case "Unknown": case "ObjectKeyword": - return AST.replaceEncoding(ast, [AST.unknownToJson]) + return SchemaAST.replaceEncoding(ast, [SchemaAST.unknownToJson]) case "Undefined": case "Void": case "Literal": @@ -12533,7 +12577,7 @@ function toCodecJsonBase(ast: AST.AST, recur: (ast: AST.AST) => AST.AST): AST.AS case "Union": { const sortedTypes = InternalSchema.jsonReorder(ast.types) if (sortedTypes !== ast.types) { - return new AST.Union( + return new SchemaAST.Union( sortedTypes, ast.mode, ast.annotations, @@ -12560,22 +12604,22 @@ function toCodecJsonBase(ast: AST.AST, recur: (ast: AST.AST) => AST.AST): AST.AS * @since 4.0.0 */ export function toCodecIso(schema: S): Codec { - return make(toCodecIsoTop(AST.toType(schema.ast))) + return make(toCodecIsoTop(SchemaAST.toType(schema.ast))) } -const toCodecIsoTop = memoize((ast: AST.AST): AST.AST => { +const toCodecIsoTop = memoize((ast: SchemaAST.AST): SchemaAST.AST => { const out = toCodecIsoBase(ast, toCodecIsoTop) - return out !== ast && AST.isOptional(ast) ? AST.optionalKeyLastLink(out) : out + return out !== ast && SchemaAST.isOptional(ast) ? SchemaAST.optionalKeyLastLink(out) : out }) -function toCodecIsoBase(ast: AST.AST, recur: (ast: AST.AST) => AST.AST): AST.AST { +function toCodecIsoBase(ast: SchemaAST.AST, recur: (ast: SchemaAST.AST) => SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { case "Declaration": { const getLink = ast.annotations?.toCodecIso ?? ast.annotations?.toCodec if (Predicate.isFunction(getLink)) { const link = getLink(ast.typeParameters.map((tp) => InternalSchema.make(tp))) const to = recur(link.to) - return AST.replaceEncoding(ast, to === link.to ? [link] : [new AST.Link(to, link.transformation)]) + return SchemaAST.replaceEncoding(ast, to === link.to ? [link] : [new SchemaAST.Link(to, link.transformation)]) } return ast } @@ -12755,7 +12799,7 @@ const xml = { } } -function getStringTreePriority(ast: AST.AST): number { +function getStringTreePriority(ast: SchemaAST.AST): number { switch (ast._tag) { case "Null": case "Boolean": @@ -12772,30 +12816,30 @@ function getStringTreePriority(ast: AST.AST): number { const treeReorder = InternalSchema.makeReorder(getStringTreePriority) function serializerTree( - ast: AST.AST, - recur: (ast: AST.AST) => AST.AST, - onMissingAnnotation: (ast: AST.AST) => AST.AST -): AST.AST { + ast: SchemaAST.AST, + recur: (ast: SchemaAST.AST) => SchemaAST.AST, + onMissingAnnotation: (ast: SchemaAST.AST) => SchemaAST.AST +): SchemaAST.AST { switch (ast._tag) { case "Declaration": { const getLink = ast.annotations?.toCodecJson ?? ast.annotations?.toCodec if (Predicate.isFunction(getLink)) { - const tps = AST.isDeclaration(ast) - ? ast.typeParameters.map((tp) => make(recur(AST.toEncoded(tp)))) + const tps = SchemaAST.isDeclaration(ast) + ? ast.typeParameters.map((tp) => make(recur(SchemaAST.toEncoded(tp)))) : [] const link = getLink(tps) const to = recur(link.to) - return AST.replaceEncoding(ast, to === link.to ? [link] : [new AST.Link(to, link.transformation)]) + return SchemaAST.replaceEncoding(ast, to === link.to ? [link] : [new SchemaAST.Link(to, link.transformation)]) } return onMissingAnnotation(ast) } case "Null": - return AST.replaceEncoding(ast, [nullToString]) + return SchemaAST.replaceEncoding(ast, [nullToString]) case "Boolean": - return AST.replaceEncoding(ast, [booleanToString]) + return SchemaAST.replaceEncoding(ast, [booleanToString]) case "Unknown": case "ObjectKeyword": - return AST.replaceEncoding(ast, [AST.unknownToStringTree]) + return SchemaAST.replaceEncoding(ast, [SchemaAST.unknownToStringTree]) case "Enum": case "Number": case "Literal": @@ -12812,7 +12856,7 @@ function serializerTree( case "Union": { const sortedTypes = treeReorder(ast.types) if (sortedTypes !== ast.types) { - return new AST.Union( + return new SchemaAST.Union( sortedTypes, ast.mode, ast.annotations, @@ -12831,75 +12875,75 @@ function serializerTree( return ast } -const nullToString = new AST.Link( - new AST.Literal("null"), - new Transformation.Transformation( - Getter.transform(() => null), - Getter.transform(() => "null") +const nullToString = new SchemaAST.Link( + new SchemaAST.Literal("null"), + new SchemaTransformation.Transformation( + SchemaGetter.transform(() => null), + SchemaGetter.transform(() => "null") ) ) -const booleanToString = new AST.Link( - new AST.Union([new AST.Literal("true"), new AST.Literal("false")], "anyOf"), - new Transformation.Transformation( - Getter.transform((s) => s === "true"), - Getter.String() +const booleanToString = new SchemaAST.Link( + new SchemaAST.Union([new SchemaAST.Literal("true"), new SchemaAST.Literal("false")], "anyOf"), + new SchemaTransformation.Transformation( + SchemaGetter.transform((s) => s === "true"), + SchemaGetter.String() ) ) -const serializerStringTree = AST.toCodec((ast) => { - const out = serializerTree(ast, serializerStringTree, (ast) => AST.replaceEncoding(ast, [unknownToUndefined])) - if (out !== ast && AST.isOptional(ast)) { - return AST.optionalKeyLastLink(out) +const serializerStringTree = SchemaAST.toCodec((ast) => { + const out = serializerTree(ast, serializerStringTree, (ast) => SchemaAST.replaceEncoding(ast, [unknownToUndefined])) + if (out !== ast && SchemaAST.isOptional(ast)) { + return SchemaAST.optionalKeyLastLink(out) } return out }) -const unknownToUndefined = new AST.Link( - AST.undefined, - new Transformation.Transformation( - Getter.passthrough(), - Getter.transform(() => undefined) +const unknownToUndefined = new SchemaAST.Link( + SchemaAST.undefined, + new SchemaTransformation.Transformation( + SchemaGetter.passthrough(), + SchemaGetter.transform(() => undefined) ) ) -const serializerStringTreeKeepDeclarations = AST.toCodec((ast) => { +const serializerStringTreeKeepDeclarations = SchemaAST.toCodec((ast) => { const out = serializerTree(ast, serializerStringTreeKeepDeclarations, identity) - if (out !== ast && AST.isOptional(ast)) { - return AST.optionalKeyLastLink(out) + if (out !== ast && SchemaAST.isOptional(ast)) { + return SchemaAST.optionalKeyLastLink(out) } return out }) const SERIALIZER_ENSURE_ARRAY = "~effect/Schema/SERIALIZER_ENSURE_ARRAY" -const toCodecEnsureArray = AST.toCodec((ast) => { - if (AST.isUnion(ast) && ast.annotations?.[SERIALIZER_ENSURE_ARRAY]) { +const toCodecEnsureArray = SchemaAST.toCodec((ast) => { + if (SchemaAST.isUnion(ast) && ast.annotations?.[SERIALIZER_ENSURE_ARRAY]) { return ast } const out = onSerializerEnsureArray(ast) - if (AST.isArrays(out)) { - const ensure = new AST.Union( + if (SchemaAST.isArrays(out)) { + const ensure = new SchemaAST.Union( [ out, - AST.decodeTo( - AST.string, + SchemaAST.decodeTo( + SchemaAST.string, out, - new Transformation.Transformation( - Getter.split(), - Getter.passthrough() + new SchemaTransformation.Transformation( + SchemaGetter.split(), + SchemaGetter.passthrough() ) ) ], "anyOf", { [SERIALIZER_ENSURE_ARRAY]: true } ) - return AST.isOptional(ast) ? AST.optionalKey(ensure) : ensure + return SchemaAST.isOptional(ast) ? SchemaAST.optionalKey(ensure) : ensure } return out }) -function onSerializerEnsureArray(ast: AST.AST): AST.AST { +function onSerializerEnsureArray(ast: SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { default: return ast @@ -12925,7 +12969,7 @@ function onSerializerEnsureArray(ast: AST.AST): AST.AST { */ export function toIso(schema: S): Optic_.Iso { const serializer = toCodecIso(schema) - return Optic_.makeIso(Parser.encodeSync(serializer), Parser.decodeSync(serializer)) + return Optic_.makeIso(SchemaParser.encodeSync(serializer), SchemaParser.decodeSync(serializer)) } /** @@ -12996,14 +13040,14 @@ export interface overrideToCodecIso extends export function overrideToCodecIso( to: Codec, transformation: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter } ) { return (schema: S): overrideToCodecIso => { return make( - AST.annotate(schema.ast, { - toCodecIso: () => new AST.Link(to.ast, Transformation.make(transformation)) + SchemaAST.annotate(schema.ast, { + toCodecIso: () => new SchemaAST.Link(to.ast, SchemaTransformation.make(transformation)) }), { schema } ) @@ -13024,8 +13068,8 @@ export function overrideToCodecIso( */ export function toDifferJsonPatch(schema: Codec): Differ { const serializer = toCodecJson(schema) - const get = Parser.encodeSync(serializer) - const set = Parser.decodeSync(serializer) + const get = SchemaParser.encodeSync(serializer) + const set = SchemaParser.decodeSync(serializer) return { empty: [], diff: (oldValue, newValue) => JsonPatch.get(get(oldValue), get(newValue)), @@ -13125,7 +13169,7 @@ export interface JsonObject { * @category schemas * @since 4.0.0 */ -export const Json: Codec = make(AST.Json) +export const Json: Codec = make(SchemaAST.Json) /** * Recursive TypeScript type for mutable JSON values: `null`, `number`, @@ -13161,7 +13205,7 @@ export interface MutableJsonObject { * @category schemas * @since 4.0.0 */ -export const MutableJson: Codec = make(AST.MutableJson) +export const MutableJson: Codec = make(SchemaAST.MutableJson) // ----------------------------------------------------------------------------- // Annotations @@ -13351,7 +13395,7 @@ export declare namespace Annotations { * filter/refinement instead. */ readonly identifier?: string | undefined - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined /** * Optional metadata used to identify or extend the filter with custom data. */ @@ -13407,13 +13451,13 @@ export declare namespace Annotations { extends Bottom { readonly toCodec?: - | ((typeParameters: TypeParameters.Encoded) => AST.Link) + | ((typeParameters: TypeParameters.Encoded) => SchemaAST.Link) | undefined readonly toCodecJson?: - | ((typeParameters: TypeParameters.Encoded) => AST.Link) + | ((typeParameters: TypeParameters.Encoded) => SchemaAST.Link) | undefined readonly toCodecIso?: - | ((typeParameters: TypeParameters.Type) => AST.Link) + | ((typeParameters: TypeParameters.Type) => SchemaAST.Link) | undefined readonly toArbitrary?: ToArbitrary.Declaration | undefined readonly toEquivalence?: ToEquivalence.Declaration | undefined @@ -13428,11 +13472,11 @@ export declare namespace Annotations { readonly importDeclaration?: string | undefined } | undefined /** - * Used to collect sentinels from a Declaration AST. + * Used to collect sentinels from a Declaration SchemaAST. * * @internal */ - readonly "~sentinels"?: ReadonlyArray | undefined + readonly "~sentinels"?: ReadonlyArray | undefined } /** @@ -13852,7 +13896,7 @@ export declare namespace Annotations { } readonly isPropertyNames: { readonly _tag: "isPropertyNames" - readonly propertyNames: AST.AST + readonly propertyNames: SchemaAST.AST } // Arrays Meta readonly isUnique: { diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaParser.ts index dbb48d2d0a..4f07bf9542 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaParser.ts @@ -233,8 +233,9 @@ export function asserts(schema: S, input: I): asserts i * * **When to use** * - * Use when you need to decode untyped boundary input while preserving decoding - * failures, effectful transformations, and service requirements in an `Effect`. + * Use when you need to decode untyped boundary input in an `Effect` whose + * failure channel is `SchemaIssue.Issue`, while preserving transformations + * and service requirements. * * **Details** * @@ -264,9 +265,9 @@ export function decodeUnknownEffect( * * **When to use** * - * Use when you already have input typed as the schema's `Encoded` type and want - * decoding to stay in `Effect`, including parse failures and required decoding - * services. + * Use when you already have input typed as the schema's `Encoded` type and + * need an `Effect` whose failure channel is `SchemaIssue.Issue`, while + * preserving decoding service requirements. * * **Details** * @@ -345,8 +346,8 @@ export function decodePromise>( * * **When to use** * - * Use when you need to decode unknown input synchronously while preserving the - * parser outcome as an `Exit` value. + * Use when you need to decode unknown input synchronously into an `Exit` whose + * failure contains `SchemaIssue.Issue`. * * **Details** * @@ -381,8 +382,8 @@ export function decodeUnknownExit>( * * **When to use** * - * Use when you need synchronous decoding of already typed `Encoded` input with - * failures returned as `Exit` values. + * Use when you need synchronous decoding of already typed `Encoded` input into + * an `Exit` whose failure contains `SchemaIssue.Issue`. * * **Details** * @@ -572,8 +573,9 @@ export const decodeSync: >( * * **When to use** * - * Use when you need to encode untyped boundary input while preserving encoding - * failures and service requirements in an `Effect`. + * Use when you need to encode untyped boundary input in an `Effect` whose + * failure channel is `SchemaIssue.Issue`, while preserving service + * requirements. * * **Details** * @@ -604,8 +606,8 @@ export function encodeUnknownEffect( * **When to use** * * Use when you need to encode values already typed as the schema's decoded - * `Type` while preserving service requirements and returning failures in an - * `Effect`. + * `Type` in an `Effect` whose failure channel is `SchemaIssue.Issue`, while + * preserving service requirements. * * **Details** * @@ -681,8 +683,8 @@ export const encodePromise: >( * * **When to use** * - * Use when you need synchronous encoding of unknown input with the encoded - * value or schema issue returned as an `Exit`. + * Use when you need synchronous encoding of unknown input into an `Exit` whose + * failure contains `SchemaIssue.Issue`. * * **Details** * @@ -708,8 +710,8 @@ export function encodeUnknownExit>( * * **When to use** * - * Use when you need synchronous encoding of already typed schema values with - * failures returned as `Exit` values. + * Use when you need synchronous encoding of already typed schema values into + * an `Exit` whose failure contains `SchemaIssue.Issue`. * * **Details** * diff --git a/packages/effect/typetest/Effect.tst.ts b/packages/effect/typetest/Effect.tst.ts index 64bda0bc50..915bf151ae 100644 --- a/packages/effect/typetest/Effect.tst.ts +++ b/packages/effect/typetest/Effect.tst.ts @@ -1,4 +1,4 @@ -/** @effect-diagnostics floatingEffect:skip-file */ +/** @effect-diagnostics floatingEffect:skip-file missingEffectError:skip-file */ import { type Cause, type Channel, From 1799500a183f1641ca58c5591fdb29140f762e5a Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 09:01:04 +0200 Subject: [PATCH 17/29] wip --- packages/effect/src/Brand.ts | 18 +- packages/effect/src/Config.ts | 28 +-- packages/effect/src/Optic.ts | 31 +-- packages/effect/src/SchemaAST.ts | 228 +++++++++--------- packages/effect/src/SchemaGetter.ts | 77 +++--- packages/effect/src/SchemaIssue.ts | 40 +-- packages/effect/src/SchemaParser.ts | 223 +++++++++-------- packages/effect/src/SchemaRepresentation.ts | 19 +- packages/effect/src/SchemaTransformation.ts | 152 ++++++------ packages/effect/src/SchemaUtils.ts | 4 +- .../effect/src/internal/schema/annotations.ts | 8 +- .../effect/src/internal/schema/arbitrary.ts | 32 +-- .../effect/src/internal/schema/equivalence.ts | 22 +- .../src/internal/schema/representation.ts | 46 ++-- packages/effect/src/internal/schema/schema.ts | 34 +-- packages/effect/src/testing/TestSchema.ts | 40 +-- .../unstable/ai/AnthropicStructuredOutput.ts | 82 ++++--- .../effect/src/unstable/ai/LanguageModel.ts | 4 +- packages/effect/src/unstable/ai/McpSchema.ts | 10 +- packages/effect/src/unstable/ai/McpServer.ts | 6 +- .../src/unstable/ai/OpenAiStructuredOutput.ts | 95 ++++---- packages/effect/src/unstable/ai/Prompt.ts | 6 +- packages/effect/src/unstable/ai/Tool.ts | 8 +- .../effect/src/unstable/cluster/Envelope.ts | 6 +- packages/effect/src/unstable/cluster/Reply.ts | 26 +- .../effect/src/unstable/cluster/ShardId.ts | 6 +- .../effect/src/unstable/cluster/Snowflake.ts | 4 +- .../cluster/internal/entityManager.ts | 4 +- .../effect/src/unstable/encoding/Msgpack.ts | 12 +- packages/effect/src/unstable/encoding/Sse.ts | 4 +- packages/effect/src/unstable/http/Cookies.ts | 8 +- packages/effect/src/unstable/http/Headers.ts | 4 +- packages/effect/src/unstable/http/HttpBody.ts | 4 +- .../effect/src/unstable/http/Multipart.ts | 6 +- .../effect/src/unstable/http/UrlParams.ts | 12 +- .../effect/src/unstable/httpapi/HttpApi.ts | 4 +- .../src/unstable/httpapi/HttpApiBuilder.ts | 24 +- .../src/unstable/httpapi/HttpApiClient.ts | 32 +-- .../src/unstable/httpapi/HttpApiSchema.ts | 30 +-- .../effect/src/unstable/httpapi/OpenApi.ts | 36 +-- packages/effect/src/unstable/rpc/RpcSchema.ts | 4 +- packages/effect/src/unstable/schema/Model.ts | 10 +- .../src/unstable/schema/VariantSchema.ts | 4 +- .../src/unstable/workers/Transferable.ts | 12 +- .../src/unstable/workflow/DurableDeferred.ts | 10 +- .../effect/src/unstable/workflow/Workflow.ts | 12 +- 46 files changed, 769 insertions(+), 718 deletions(-) diff --git a/packages/effect/src/Brand.ts b/packages/effect/src/Brand.ts index f7fdff5bfa..27afbcf951 100644 --- a/packages/effect/src/Brand.ts +++ b/packages/effect/src/Brand.ts @@ -55,8 +55,8 @@ import * as Arr from "./Array.ts" import * as Option from "./Option.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import * as AST from "./SchemaAST.ts" -import type * as Issue from "./SchemaIssue.ts" +import * as SchemaAST from "./SchemaAST.ts" +import type * as SchemaIssue from "./SchemaIssue.ts" import type * as Types from "./Types.ts" const TypeId = "~effect/Brand" @@ -128,7 +128,7 @@ export interface Constructor> { * * @internal */ - checks?: readonly [AST.Check>, ...Array>>] | undefined + checks?: readonly [SchemaAST.Check>, ...Array>>] | undefined } /** @@ -148,7 +148,7 @@ export interface Constructor> { * @since 4.0.0 */ export class BrandError { - constructor(issue: Issue.Issue) { + constructor(issue: SchemaIssue.Issue) { this.issue = issue } /** @@ -168,7 +168,7 @@ export class BrandError { * * @since 4.0.0 */ - readonly issue: Issue.Issue + readonly issue: SchemaIssue.Issue /** * Human-readable rendering of the validation issue. * @@ -293,7 +293,7 @@ export function nominal>(): Constructor { export function make>( filter: (unbranded: Brand.Unbranded) => Schema.FilterOutput ): Constructor { - return check(AST.makeFilter(filter)) + return check(SchemaAST.makeFilter(filter)) } /** @@ -317,12 +317,12 @@ export function make>( */ export function check>( ...checks: readonly [ - AST.Check>, - ...Array>> + SchemaAST.Check>, + ...Array>> ] ): Constructor { const result = (input: Brand.Unbranded): Result.Result => { - return Result.mapError(AST.runChecks(checks, input), (issue) => new BrandError(issue)) as any + return Result.mapError(SchemaAST.runChecks(checks, input), (issue) => new BrandError(issue)) as any } return Object.assign((input: Brand.Unbranded) => Result.getOrThrow(result(input)), { option: (input: Brand.Unbranded) => Option.getSuccess(result(input)), diff --git a/packages/effect/src/Config.ts b/packages/effect/src/Config.ts index 2385cde757..8d5d448d20 100644 --- a/packages/effect/src/Config.ts +++ b/packages/effect/src/Config.ts @@ -81,10 +81,10 @@ import * as Option from "./Option.ts" import * as Predicate from "./Predicate.ts" import * as Rec from "./Record.ts" import * as Schema from "./Schema.ts" -import * as AST from "./SchemaAST.ts" -import * as Issue from "./SchemaIssue.ts" -import * as Parser from "./SchemaParser.ts" -import * as Transformation from "./SchemaTransformation.ts" +import * as SchemaAST from "./SchemaAST.ts" +import * as SchemaIssue from "./SchemaIssue.ts" +import * as SchemaParser from "./SchemaParser.ts" +import * as SchemaTransformation from "./SchemaTransformation.ts" const TypeId = "~effect/Config" @@ -394,7 +394,7 @@ export function all> | Record Effect.Effect = Effect.fnUntraced( @@ -644,7 +644,7 @@ const recur: ( const stat = yield* provider.load(path) if (stat && stat._tag === "Record") { for (const is of ast.indexSignatures) { - const matches = Parser._is(is.parameter) + const matches = SchemaParser._is(is.parameter) for (const key of stat.keys) { if (!Object.hasOwn(out, key) && matches(key)) { const value = yield* recur(is.type, provider, [...path, key]) @@ -731,8 +731,8 @@ const recur: ( */ export function schema(codec: Schema.Codec, path?: string | ConfigProvider.Path): Config { const codecStringTree = Schema.toCodecStringTree(codec) - const decodeUnknownEffect = Parser.decodeUnknownEffect(codecStringTree) - const codecStringTreeEncoded = AST.toEncoded(codecStringTree.ast) + const decodeUnknownEffect = SchemaParser.decodeUnknownEffect(codecStringTree) + const codecStringTreeEncoded = SchemaAST.toEncoded(codecStringTree.ast) const defaultPath = typeof path === "string" ? [path] : path ?? [] return make((provider) => { const path = provider.prefix ? [...provider.prefix, ...defaultPath] : defaultPath @@ -740,7 +740,7 @@ export function schema(codec: Schema.Codec, path?: string | ConfigPr Effect.flatMapEager((tree) => decodeUnknownEffect(tree).pipe( Effect.mapErrorEager((issue) => - new Schema.SchemaError(path.length > 0 ? new Issue.Pointer(path, issue) : issue) + new Schema.SchemaError(path.length > 0 ? new SchemaIssue.Pointer(path, issue) : issue) ) ) ), @@ -776,7 +776,7 @@ export const FalseValues = Schema.Literals(["false", "no", "off", "0", "n"]) export const Boolean = Schema.Literals([...TrueValues.literals, ...FalseValues.literals]).pipe( Schema.decodeTo( Schema.Boolean, - Transformation.transform({ + SchemaTransformation.transform({ decode: (value) => value === "true" || value === "yes" || value === "on" || value === "1" || value === "y", encode: (value) => value ? "true" : "false" }) @@ -867,7 +867,7 @@ export const Record = (key: K const recordString = Schema.String.pipe( Schema.decodeTo( Schema.Record(Schema.String, Schema.String), - Transformation.splitKeyValue(options) + SchemaTransformation.splitKeyValue(options) ), Schema.decodeTo(record) ) @@ -1059,7 +1059,7 @@ export function int(name?: string) { * @category constructors * @since 2.0.0 */ -export function literal(literal: L, name?: string) { +export function literal(literal: L, name?: string) { return schema(Schema.Literal(literal), name) } @@ -1087,7 +1087,7 @@ export function literal(literal: L, name?: string) { * @category constructors * @since 4.0.0 */ -export function literals>(literals: L, name?: string) { +export function literals>(literals: L, name?: string) { return schema(Schema.Literals(literals), name) } diff --git a/packages/effect/src/Optic.ts b/packages/effect/src/Optic.ts index 7f7db5178e..5baac778db 100644 --- a/packages/effect/src/Optic.ts +++ b/packages/effect/src/Optic.ts @@ -100,8 +100,8 @@ import * as Option from "./Option.ts" import * as Predicate from "./Predicate.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import * as AST from "./SchemaAST.ts" -import type * as Issue from "./SchemaIssue.ts" +import * as SchemaAST from "./SchemaAST.ts" +import type * as SchemaIssue from "./SchemaIssue.ts" import * as Struct from "./Struct.ts" import type { IsUnion } from "./Types.ts" @@ -396,7 +396,7 @@ export function makePrism(getResult: (s: S) => Result.Result, s * @category constructors * @since 4.0.0 */ -export function fromChecks(...checks: readonly [AST.Check, ...Array>]): Prism { +export function fromChecks(...checks: readonly [SchemaAST.Check, ...Array>]): Prism { return make(new CheckNode(checks)) } @@ -480,9 +480,9 @@ class PathNode { class CheckNode { readonly _tag = "CheckNode" - readonly checks: readonly [AST.Check, ...Array>] + readonly checks: readonly [SchemaAST.Check, ...Array>] - constructor(checks: readonly [AST.Check, ...Array>]) { + constructor(checks: readonly [SchemaAST.Check, ...Array>]) { this.checks = checks } } @@ -733,8 +733,11 @@ export interface Optional { * * @see {@link fromChecks} — standalone prism from checks */ - check(this: Prism, ...checks: readonly [AST.Check, ...Array>]): Prism - check(this: Optional, ...checks: readonly [AST.Check, ...Array>]): Optional + check(this: Prism, ...checks: readonly [SchemaAST.Check, ...Array>]): Prism + check( + this: Optional, + ...checks: readonly [SchemaAST.Check, ...Array>] + ): Optional /** * Narrows the focus to a subtype `B` using a type guard. @@ -805,11 +808,11 @@ export interface Optional { * * @see `.refine()` — for arbitrary type guards */ - tag( + tag( this: Prism, tag: Tag ): Prism> - tag( + tag( this: Optional, tag: Tag ): Optional> @@ -1160,11 +1163,11 @@ class OptionalImpl implements Optional { ) ) } - check(...checks: readonly [AST.Check, ...Array>]): any { + check(...checks: readonly [SchemaAST.Check, ...Array>]): any { return make(compose(this.node, new CheckNode(checks))) } refine(refinement: (a: A) => a is B, annotations?: Schema.Annotations.Filter): any { - return make(compose(this.node, new CheckNode([AST.makeFilterByGuard(refinement, annotations)]))) + return make(compose(this.node, new CheckNode([SchemaAST.makeFilterByGuard(refinement, annotations)]))) } tag(tag: string): any { return make( @@ -1377,7 +1380,7 @@ const recur = memoize((node: Node): Op => { case "CheckNode": return { _tag: "PrismNode", - get: (s: any) => Result.mapError(AST.runChecks(node.checks, s), String), + get: (s: any) => Result.mapError(SchemaAST.runChecks(node.checks, s), String), set: identity } case "CompositionNode": { @@ -1776,6 +1779,6 @@ export function failure(): Prism, E> { function runRefinement( refinement: (e: E) => e is T, annotations?: Schema.Annotations.Filter -): (e: E) => Result.Result { - return (e) => AST.runChecks([AST.makeFilterByGuard(refinement, annotations)], e) as any +): (e: E) => Result.Result { + return (e) => SchemaAST.runChecks([SchemaAST.makeFilterByGuard(refinement, annotations)], e) as any } diff --git a/packages/effect/src/SchemaAST.ts b/packages/effect/src/SchemaAST.ts index 8ef8ebc248..23d37b3554 100644 --- a/packages/effect/src/SchemaAST.ts +++ b/packages/effect/src/SchemaAST.ts @@ -89,10 +89,10 @@ import * as Predicate from "./Predicate.ts" import * as RegEx from "./RegExp.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import * as Getter from "./SchemaGetter.ts" -import * as Issue from "./SchemaIssue.ts" -import type * as Parser from "./SchemaParser.ts" -import * as Transformation from "./SchemaTransformation.ts" +import * as SchemaGetter from "./SchemaGetter.ts" +import * as SchemaIssue from "./SchemaIssue.ts" +import type * as SchemaParser from "./SchemaParser.ts" +import * as SchemaTransformation from "./SchemaTransformation.ts" /** * Discriminated union of all AST node types. @@ -269,7 +269,7 @@ export const isAny = makeGuard("Any") * **When to use** * * Use to detect schema AST nodes that match any string value while inspecting or - * transforming an AST. + * transforming an SchemaAST. * * @see {@link String} for the AST node class narrowed by this guard * @see {@link string} for the singleton `String` AST instance @@ -368,7 +368,7 @@ export const isUniqueSymbol = makeGuard("UniqueSymbol") * **When to use** * * Use to identify the AST node for the TypeScript `object` keyword when - * inspecting or transforming a schema AST. + * inspecting or transforming a schema SchemaAST. * * @see {@link ObjectKeyword} for the AST node matched by this guard * @see {@link objectKeyword} for the singleton `ObjectKeyword` AST instance @@ -463,14 +463,14 @@ export const isSuspend = makeGuard("Suspend") export class Link { readonly to: AST readonly transformation: - | Transformation.Transformation - | Transformation.Middleware + | SchemaTransformation.Transformation + | SchemaTransformation.Middleware constructor( to: AST, transformation: - | Transformation.Transformation - | Transformation.Middleware + | SchemaTransformation.Transformation + | SchemaTransformation.Middleware ) { this.to = to this.transformation = transformation @@ -712,13 +712,13 @@ export class Declaration extends Base { readonly typeParameters: ReadonlyArray readonly run: ( typeParameters: ReadonlyArray - ) => (input: unknown, self: Declaration, options: ParseOptions) => Effect.Effect + ) => (input: unknown, self: Declaration, options: ParseOptions) => Effect.Effect constructor( typeParameters: ReadonlyArray, run: ( typeParameters: ReadonlyArray - ) => (input: unknown, self: Declaration, options: ParseOptions) => Effect.Effect, + ) => (input: unknown, self: Declaration, options: ParseOptions) => Effect.Effect, annotations?: Schema.Annotations.Annotations, checks?: Checks, encoding?: Encoding, @@ -729,7 +729,7 @@ export class Declaration extends Base { this.run = run } /** @internal */ - getParser(): Parser.Parser { + getParser(): SchemaParser.Parser { const run = this.run(this.typeParameters) return (oinput, options) => { if (Option.isNone(oinput)) return Effect.succeedNone @@ -821,9 +821,9 @@ export class Undefined extends Base { const undefinedToNull = new Link( null_, - new Transformation.Transformation( - Getter.transform(() => undefined), - Getter.transform(() => null) + new SchemaTransformation.Transformation( + SchemaGetter.transform(() => undefined), + SchemaGetter.transform(() => null) ) ) @@ -1088,9 +1088,9 @@ export class Enum extends Base { return replaceEncoding(this, [ new Link( new Union(Object.keys(coercions).map((k) => new Literal(k)), "anyOf"), - new Transformation.Transformation( - Getter.transform((s) => coercions[s]), - Getter.String() + new SchemaTransformation.Transformation( + SchemaGetter.transform((s) => coercions[s]), + SchemaGetter.String() ) ) ]) @@ -1167,12 +1167,12 @@ export class TemplateLiteral extends Base { this.encodedParts = encodedParts } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { const parser = recur(this.asTemplateLiteralParser()) return (oinput: Option.Option, options: ParseOptions) => Effect.mapBothEager(parser(oinput, options), { onSuccess: () => oinput, - onFailure: (issue) => new Issue.Composite(this, oinput, [issue]) + onFailure: (issue) => new SchemaIssue.Composite(this, oinput, [issue]) }) } /** @internal */ @@ -1186,17 +1186,17 @@ export class TemplateLiteral extends Base { return decodeTo( string, tuple, - new Transformation.Transformation( - Getter.transformOrFail((s: string) => { + new SchemaTransformation.Transformation( + SchemaGetter.transformOrFail((s: string) => { const match = regExp.exec(s) if (match) return Effect.succeed(match.slice(1, this.parts.length + 1)) return Effect.fail( - new Issue.InvalidValue(Option.some(s), { + new SchemaIssue.InvalidValue(Option.some(s), { message: `Expected a value matching ${regExp.source}, got ${format(s)}` }) ) }), - Getter.transform((parts) => parts.join("")) + SchemaGetter.transform((parts) => parts.join("")) ) ) } @@ -1316,9 +1316,9 @@ function literalToString(ast: Literal): Literal { return replaceEncoding(ast, [ new Link( new Literal(literalAsString), - new Transformation.Transformation( - Getter.transform(() => ast.literal), - Getter.transform(() => literalAsString) + new SchemaTransformation.Transformation( + SchemaGetter.transform(() => ast.literal), + SchemaGetter.transform(() => literalAsString) ) ) ]) @@ -1639,7 +1639,7 @@ export class Arrays extends Base { } } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { // oxlint-disable-next-line @typescript-eslint/no-this-alias const ast = this const elements = ast.elements.map((ast) => ({ ast, parser: recur(ast) })) @@ -1649,7 +1649,10 @@ export class Arrays extends Base { const [head, ...tail] = rest const tailLen = tail.length - function getParser(tailThreshold: number, index: number): { readonly ast: AST; readonly parser: Parser.Parser } { + function getParser( + tailThreshold: number, + index: number + ): { readonly ast: AST; readonly parser: SchemaParser.Parser } { if (index < elementLen) { return elements[index] } else if (index >= tailThreshold) { @@ -1666,7 +1669,7 @@ export class Arrays extends Base { // If the input is not an array, return early with an error if (!Array.isArray(input)) { - return yield* Effect.fail(new Issue.InvalidType(ast, oinput)) + return yield* Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } const len = input.length @@ -1677,7 +1680,7 @@ export class Arrays extends Base { len, tailThreshold: resolveTailThreshold(len, elementLen, tailLen), output: new globalThis.Array(len), - issues: undefined as Arr.NonEmptyArray | undefined, + issues: undefined as Arr.NonEmptyArray | undefined, options } const concurrency = resolveConcurrency(options?.concurrency) @@ -1692,17 +1695,17 @@ export class Arrays extends Base { // --------------------------------------------- if (ast.rest.length === 0 && len > elementLen) { for (let i = elementLen; i <= len - 1; i++) { - const issue = new Issue.Pointer([i], new Issue.UnexpectedKey(ast, input[i])) + const issue = new SchemaIssue.Pointer([i], new SchemaIssue.UnexpectedKey(ast, input[i])) if (options.errors === "all") { if (state.issues) state.issues.push(issue) else state.issues = [issue] } else { - return yield* Effect.fail(new Issue.Composite(ast, oinput, [issue])) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, [issue])) } } } if (state.issues) { - return yield* Effect.fail(new Issue.Composite(ast, oinput, state.issues)) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, state.issues)) } return Option.some(state.output) }) @@ -1724,11 +1727,14 @@ const parseArray = iterateEager<{ readonly ast: AST readonly oinput: Option.Option readonly len: number - readonly getParser: (tailThreshold: number, index: number) => { readonly ast: AST; readonly parser: Parser.Parser } + readonly getParser: ( + tailThreshold: number, + index: number + ) => { readonly ast: AST; readonly parser: SchemaParser.Parser } readonly tailThreshold: number readonly options: ParseOptions readonly output: Array - issues: Array | undefined + issues: Array | undefined }, unknown>()({ onItem(s, item, i) { const value = i < s.len ? Option.some(item) : Option.none() @@ -1742,12 +1748,12 @@ const parseArray = iterateEager<{ } else { const p = s.getParser(s.tailThreshold, i) if (isOptional(p.ast)) return - const issue = new Issue.Pointer([i], new Issue.MissingKey(p.ast.context?.annotations)) + const issue = new SchemaIssue.Pointer([i], new SchemaIssue.MissingKey(p.ast.context?.annotations)) if (s.options.errors === "all") { if (s.issues) s.issues.push(issue) else s.issues = [issue] } else { - return Exit.fail(new Issue.Composite(s.ast, s.oinput, [issue])) + return Exit.fail(new SchemaIssue.Composite(s.ast, s.oinput, [issue])) } } } @@ -1770,22 +1776,22 @@ const wrapPropertyKeyIssue = ( s: { readonly oinput: Option.Option readonly options: ParseOptions - issues: Array | undefined + issues: Array | undefined }, ast: AST, key: PropertyKey, - exit: Exit.Failure + exit: Exit.Failure ) => { const issueResult = Cause.findError(exit.cause) if (Result.isFailure(issueResult)) { return exit } - const issue = new Issue.Pointer([key], issueResult.success) + const issue = new SchemaIssue.Pointer([key], issueResult.success) if (s.options.errors === "all") { if (s.issues) s.issues.push(issue) else s.issues = [issue] } else { - return Exit.fail(new Issue.Composite(ast, s.oinput, [issue])) + return Exit.fail(new SchemaIssue.Composite(ast, s.oinput, [issue])) } } @@ -1888,7 +1894,7 @@ export class KeyValueCombiner { * * - `parameter` — the key type AST (e.g. {@link String} for `string` keys, * {@link TemplateLiteral} for patterned keys). - * - `type` — the value type AST. + * - `type` — the value type SchemaAST. * - `merge` — optional {@link KeyValueCombiner} for handling duplicate keys. * * **Gotchas** @@ -1984,14 +1990,14 @@ export class Objects extends Base { } } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { // oxlint-disable-next-line @typescript-eslint/no-this-alias const ast = this const expectedKeys: Array = [] const expectedKeysSet = new Set() const properties: Array<{ readonly ps: PropertySignature | IndexSignature - readonly parser: Parser.Parser + readonly parser: SchemaParser.Parser readonly name: PropertyKey readonly type: AST }> = [] @@ -2019,7 +2025,7 @@ export class Objects extends Base { readonly input: Record readonly options: ParseOptions readonly out: Record - issues: Array | undefined + issues: Array | undefined }, [key: PropertyKey, is: IndexSignature]>()({ onItem: Effect.fnUntracedEager(function*( s, @@ -2029,7 +2035,7 @@ export class Objects extends Base { const effKey = parserKey(Option.some(key), s.options) const exitKey = (effectIsExit(effKey) ? effKey : yield* Effect.exit(effKey)) as Exit.Exit< Option.Option, - Issue.Issue + SchemaIssue.Issue > if (exitKey._tag === "Failure") { const eff = wrapPropertyKeyIssue(s, ast, key, exitKey) @@ -2056,7 +2062,7 @@ export class Objects extends Base { } } }), - step: (_s, _, exit: Exit.Exit) => exit._tag === "Failure" ? exit : undefined + step: (_s, _, exit: Exit.Exit) => exit._tag === "Failure" ? exit : undefined }) : undefined @@ -2068,7 +2074,7 @@ export class Objects extends Base { // If the input is not a record, return early with an error if (!(typeof input === "object" && input !== null && !Array.isArray(input))) { - return yield* Effect.fail(new Issue.InvalidType(ast, oinput)) + return yield* Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } const out: Record = {} @@ -2077,7 +2083,7 @@ export class Objects extends Base { oinput, input, out, - issues: undefined as Arr.NonEmptyArray | undefined, + issues: undefined as Arr.NonEmptyArray | undefined, options } const errorsAllOption = options.errors === "all" @@ -2095,7 +2101,7 @@ export class Objects extends Base { if (!expectedKeysSet.has(key)) { // key is unexpected if (onExcessPropertyError) { - const issue = new Issue.Pointer([key], new Issue.UnexpectedKey(ast, input[key])) + const issue = new SchemaIssue.Pointer([key], new SchemaIssue.UnexpectedKey(ast, input[key])) if (errorsAllOption) { if (state.issues) { state.issues.push(issue) @@ -2104,7 +2110,7 @@ export class Objects extends Base { } continue } else { - return yield* Effect.fail(new Issue.Composite(ast, oinput, [issue])) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, [issue])) } } else { // preserve key @@ -2140,7 +2146,7 @@ export class Objects extends Base { } if (state.issues) { - return yield* Effect.fail(new Issue.Composite(ast, oinput, state.issues)) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, state.issues)) } if (options.propertyOrder === "original") { // preserve input keys order @@ -2195,7 +2201,7 @@ export class Objects extends Base { type ParsedProperty = { readonly ps: PropertySignature | IndexSignature - readonly parser: Parser.Parser + readonly parser: SchemaParser.Parser readonly name: PropertyKey readonly type: AST } @@ -2206,7 +2212,7 @@ const parseProperties = iterateEager<{ readonly input: Record readonly options: ParseOptions readonly out: Record - issues: Array | undefined + issues: Array | undefined }, ParsedProperty>()({ onItem( s: { @@ -2214,7 +2220,7 @@ const parseProperties = iterateEager<{ readonly input: Record readonly options: ParseOptions readonly out: Record - issues: Array | undefined + issues: Array | undefined }, p ) { @@ -2229,14 +2235,14 @@ const parseProperties = iterateEager<{ } else if (exit.value._tag === "Some") { internalRecord.set(s.out, p.name, exit.value.value) } else if (!isOptional(p.type)) { - const issue = new Issue.Pointer([p.name], new Issue.MissingKey(p.type.context?.annotations)) + const issue = new SchemaIssue.Pointer([p.name], new SchemaIssue.MissingKey(p.type.context?.annotations)) if (s.options.errors === "all") { if (s.issues) s.issues.push(issue) else s.issues = [issue] return } else { return Exit.fail( - new Issue.Composite(s.ast, s.oinput, [issue]) + new SchemaIssue.Composite(s.ast, s.oinput, [issue]) ) } } @@ -2546,7 +2552,7 @@ export class Union extends Base { this.mode = mode } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { // oxlint-disable-next-line @typescript-eslint/no-this-alias const ast = this @@ -2564,16 +2570,20 @@ export class Union extends Base { input, out: undefined, successes: [], - issues: undefined as Arr.NonEmptyArray | undefined, + issues: undefined as Arr.NonEmptyArray | undefined, options } const concurrency = resolveConcurrency(options?.concurrency) const eff = parseUnion(state, candidates, concurrency) if (!eff) { - return state.out ? Effect.succeed(state.out) : Effect.fail(new Issue.AnyOf(ast, input, state.issues ?? [])) + return state.out + ? Effect.succeed(state.out) + : Effect.fail(new SchemaIssue.AnyOf(ast, input, state.issues ?? [])) } return Effect.flatMap(eff, (_) => { - return state.out ? Effect.succeed(state.out) : Effect.fail(new Issue.AnyOf(ast, input, state.issues ?? [])) + return state.out + ? Effect.succeed(state.out) + : Effect.fail(new SchemaIssue.AnyOf(ast, input, state.issues ?? [])) }) } } @@ -2624,14 +2634,14 @@ export class Union extends Base { } const parseUnion = iterateEager<{ - readonly recur: (ast: AST) => Parser.Parser + readonly recur: (ast: AST) => SchemaParser.Parser readonly ast: Union readonly oinput: Option.Option readonly input: unknown readonly options: ParseOptions out: Option.Option | undefined successes: Array - issues: Array | undefined + issues: Array | undefined }, AST>()({ onItem(s, ast) { const parser = s.recur(ast) @@ -2648,7 +2658,7 @@ const parseUnion = iterateEager<{ } else { if (s.out && s.ast.mode === "oneOf") { s.successes.push(candidate) - return Exit.fail(new Issue.OneOf(s.ast, s.input, s.successes)) + return Exit.fail(new SchemaIssue.OneOf(s.ast, s.input, s.successes)) } s.out = exit.value s.successes.push(candidate) @@ -2667,9 +2677,9 @@ const nonFiniteLiterals = new Union([ const numberToJson = new Link( new Union([number, nonFiniteLiterals], "anyOf"), - new Transformation.Transformation( - Getter.Number(), - Getter.transform((n) => globalThis.Number.isFinite(n) ? n : globalThis.String(n)) + new SchemaTransformation.Transformation( + SchemaGetter.Number(), + SchemaGetter.transform((n) => globalThis.Number.isFinite(n) ? n : globalThis.String(n)) ) ) @@ -2741,7 +2751,7 @@ export class Suspend extends Base { this.thunk = memoizeThunk(thunk) } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { return recur(this.thunk()) } /** @internal */ @@ -2781,7 +2791,7 @@ export class Suspend extends Base { */ export class Filter extends Pipeable.Class { readonly _tag = "Filter" - readonly run: (input: E, self: AST, options: ParseOptions) => Issue.Issue | undefined + readonly run: (input: E, self: AST, options: ParseOptions) => SchemaIssue.Issue | undefined readonly annotations: Schema.Annotations.Filter | undefined /** * Whether the parsing process should be aborted after this check has failed. @@ -2789,7 +2799,7 @@ export class Filter extends Pipeable.Class { readonly aborted: boolean constructor( - run: (input: E, self: AST, options: ParseOptions) => Issue.Issue | undefined, + run: (input: E, self: AST, options: ParseOptions) => SchemaIssue.Issue | undefined, annotations: Schema.Annotations.Filter | undefined = undefined, /** * Whether the parsing process should be aborted after this check has failed. @@ -2871,7 +2881,7 @@ export function makeFilter( aborted: boolean = false ): Filter { return new Filter( - (input, ast, options) => Issue.make(input, ast, filter(input, ast, options)), + (input, ast, options) => SchemaIssue.make(input, ast, filter(input, ast, options)), annotations, aborted ) @@ -2883,7 +2893,7 @@ export function makeFilterByGuard( annotations?: Schema.Annotations.Filter ): Filter { return new Filter( - (input: E) => is(input) ? undefined : new Issue.InvalidValue(Option.some(input)), + (input: E) => is(input) ? undefined : new SchemaIssue.InvalidValue(Option.some(input)), annotations, true // after a guard, we always want to abort ) @@ -3016,7 +3026,7 @@ export function applyToLastLink(f: (ast: AST) => AST) { /** @internal */ export function middlewareDecoding( ast: AST, - middleware: Transformation.Middleware + middleware: SchemaTransformation.Middleware ): AST { return appendTransformation(ast, middleware, toType(ast)) } @@ -3024,7 +3034,7 @@ export function middlewareDecoding( /** @internal */ export function middlewareEncoding( ast: AST, - middleware: Transformation.Middleware + middleware: SchemaTransformation.Middleware ): AST { return appendTransformation(toEncoded(ast), middleware, ast) } @@ -3032,8 +3042,8 @@ export function middlewareEncoding( function appendTransformation( from: AST, transformation: - | Transformation.Transformation - | Transformation.Middleware, + | SchemaTransformation.Transformation + | SchemaTransformation.Middleware, to: A ): A { const link = new Link(from, transformation) @@ -3121,11 +3131,11 @@ export function mutableKey(ast: A): A { /** @internal */ export function withConstructorDefault( ast: A, - defaultValue: Effect.Effect + defaultValue: Effect.Effect ): A { - const transformation = new Transformation.Transformation( - Getter.withDefault(defaultValue), - Getter.passthrough() + const transformation = new SchemaTransformation.Transformation( + SchemaGetter.withDefault(defaultValue), + SchemaGetter.passthrough() ) const encoding: Encoding = [new Link(unknown, transformation)] const context = ast.context ? @@ -3155,7 +3165,7 @@ export function withConstructorDefault( export function decodeTo( from: AST, to: A, - transformation: Transformation.Transformation + transformation: SchemaTransformation.Transformation ): A { return appendTransformation(from, transformation, to) } @@ -3322,7 +3332,7 @@ function flipEncoding(ast: AST, encoding: Encoding): AST { * * After flipping, what was decoding becomes encoding and vice versa. This is * the core operation behind `Schema.encode` — encoding a value is decoding - * with a flipped AST. + * with a flipped SchemaAST. * * - Memoized: same input reference → same output reference. * - Recursively walks composite nodes. @@ -3394,7 +3404,7 @@ function handleTemplateLiteralASTPartParens(part: TemplateLiteralPart, s: string function fromConst( ast: AST, value: T -): Parser.Parser { +): SchemaParser.Parser { const succeed = Effect.succeedSome(value) return (oinput) => { if (oinput._tag === "None") { @@ -3402,21 +3412,21 @@ function fromConst( } return oinput.value === value ? succeed - : Effect.fail(new Issue.InvalidType(ast, oinput)) + : Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } } function fromRefinement( ast: AST, refinement: (input: unknown) => input is T -): Parser.Parser { +): SchemaParser.Parser { return (oinput) => { if (oinput._tag === "None") { return Effect.succeedNone } return refinement(oinput.value) ? Effect.succeed(oinput) - : Effect.fail(new Issue.InvalidType(ast, oinput)) + : Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } } @@ -3490,12 +3500,12 @@ const finiteString = appendChecks(string, [isStringFinite()]) const finiteToString = new Link( finiteString, - Transformation.numberFromString + SchemaTransformation.numberFromString ) const numberToString = new Link( new Union([finiteString, nonFiniteLiterals], "anyOf"), - Transformation.numberFromString + SchemaTransformation.numberFromString ) /** @@ -3527,7 +3537,7 @@ export const bigIntString = appendChecks(string, [isStringBigInt({ const bigIntToString = new Link( bigIntString, - Transformation.bigintFromString + SchemaTransformation.bigintFromString ) const REGEXP_PATTERN = "Symbol\\((.*)\\)" @@ -3542,15 +3552,15 @@ export const symbolString = appendChecks(string, [isStringSymbol()]) */ const symbolToString = new Link( symbolString, - new Transformation.Transformation( - Getter.transform((description) => globalThis.Symbol.for(isStringSymbolRegExp.exec(description)![1])), - Getter.transformOrFail((sym: symbol) => { + new SchemaTransformation.Transformation( + SchemaGetter.transform((description) => globalThis.Symbol.for(isStringSymbolRegExp.exec(description)![1])), + SchemaGetter.transformOrFail((sym: symbol) => { const key = globalThis.Symbol.keyFor(sym) if (key !== undefined) { return Effect.succeed(globalThis.String(sym)) } return Effect.fail( - new Issue.Forbidden(Option.some(sym), { message: "cannot serialize to string, Symbol is not registered" }) + new SchemaIssue.Forbidden(Option.some(sym), { message: "cannot serialize to string, Symbol is not registered" }) ) }) ) @@ -3575,7 +3585,7 @@ export function isStringSymbol(annotations?: Schema.Annotations.Filter) { export function collectIssues( checks: ReadonlyArray>, value: T, - issues: Array, + issues: Array, ast: AST, options: ParseOptions ) { @@ -3586,7 +3596,7 @@ export function collectIssues( } else { const issue = check.run(value, ast, options) if (issue) { - issues.push(new Issue.Filter(value, check, issue)) + issues.push(new SchemaIssue.Filter(value, check, issue)) if (check.aborted || options?.errors !== "all") { return } @@ -3599,11 +3609,11 @@ export function collectIssues( export function runChecks( checks: readonly [Check, ...Array>], s: T -): Result.Result { - const issues: Array = [] +): Result.Result { + const issues: Array = [] collectIssues(checks, s, issues, unknown, { errors: "all" }) if (Arr.isArrayNonEmpty(issues)) { - const issue = new Issue.Composite(unknown, Option.some(s), issues) + const issue = new SchemaIssue.Composite(unknown, Option.some(s), issues) return Result.fail(issue) } return Result.succeed(s) @@ -3750,7 +3760,7 @@ export const Json = new Declaration( () => (input, ast) => isJson(input) ? Effect.succeed(input) : - Effect.fail(new Issue.InvalidType(ast, Option.some(input))), + Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(input))), { typeConstructor: { _tag: "effect/Json" @@ -3760,7 +3770,7 @@ export const Json = new Declaration( Type: `Schema.Json` }, expected: "JSON value", - toCodecJson: () => new Link(unknown, Transformation.passthrough()) + toCodecJson: () => new Link(unknown, SchemaTransformation.passthrough()) } ) @@ -3778,16 +3788,16 @@ export const MutableJson = annotate(Json, { /** @internal */ export const unknownToNull = new Link( null_, - new Transformation.Transformation( - Getter.passthrough(), - Getter.transform(() => null) + new SchemaTransformation.Transformation( + SchemaGetter.passthrough(), + SchemaGetter.transform(() => null) ) ) /** @internal */ export const unknownToJson = new Link( Json, - Transformation.passthrough() + SchemaTransformation.passthrough() ) /** @@ -3824,15 +3834,15 @@ const StringTree = new Declaration( () => (input, ast) => isStringTree(input) ? Effect.succeed(input) : - Effect.fail(new Issue.InvalidType(ast, Option.some(input))), + Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(input))), { expected: "StringTree", - toCodecStringTree: () => new Link(unknown, Transformation.passthrough()) + toCodecStringTree: () => new Link(unknown, SchemaTransformation.passthrough()) } ) /** @internal */ export const unknownToStringTree = new Link( StringTree, - Transformation.passthrough() + SchemaTransformation.passthrough() ) diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index c18ef46bcc..415b9ca4b5 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -93,8 +93,8 @@ import * as Pipeable from "./Pipeable.ts" import * as Predicate from "./Predicate.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import type * as AST from "./SchemaAST.ts" -import * as Issue from "./SchemaIssue.ts" +import type * as SchemaAST from "./SchemaAST.ts" +import * as SchemaIssue from "./SchemaIssue.ts" import * as Str from "./String.ts" /** @@ -137,14 +137,14 @@ import * as Str from "./String.ts" export class Getter extends Pipeable.Class { readonly run: ( input: Option.Option, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, R> + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, R> constructor( run: ( input: Option.Option, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, R> + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, R> ) { super() this.run = run @@ -224,7 +224,7 @@ export function succeed(t: T): Getter { * @category constructors * @since 4.0.0 */ -export function fail(f: (oe: Option.Option) => Issue.Issue): Getter { +export function fail(f: (oe: Option.Option) => SchemaIssue.Issue): Getter { return new Getter((oe) => Effect.fail(f(oe))) } @@ -238,7 +238,7 @@ export function fail(f: (oe: Option.Option) => Issue.Issue): Getter` input for context. * * **Example** (Forbidding a decode direction) @@ -257,7 +257,7 @@ export function fail(f: (oe: Option.Option) => Issue.Issue): Getter(message: (oe: Option.Option) => string): Getter { - return fail((oe) => new Issue.Forbidden(oe, { message: message(oe) })) + return fail((oe) => new SchemaIssue.Forbidden(oe, { message: message(oe) })) } const passthrough_ = new Getter(Effect.succeed) @@ -404,7 +404,7 @@ export function passthroughSubtype(): Getter { * @since 4.0.0 */ export function onNone( - f: (options: AST.ParseOptions) => Effect.Effect, Issue.Issue, R> + f: (options: SchemaAST.ParseOptions) => Effect.Effect, SchemaIssue.Issue, R> ): Getter { return new Getter((ot, options) => Option.isNone(ot) ? f(options) : Effect.succeed(ot)) } @@ -419,7 +419,7 @@ export function onNone( * * **Details** * - * - When input is `None`, fails with `Issue.MissingKey`. + * - When input is `None`, fails with `SchemaIssue.MissingKey`. * - When input is `Some`, passes it through unchanged. * - Optional `annotations` customize the error message for the missing key. * @@ -438,7 +438,7 @@ export function onNone( * @since 4.0.0 */ export function required(annotations?: Schema.Annotations.Key): Getter { - return onNone(() => Effect.fail(new Issue.MissingKey(annotations))) + return onNone(() => Effect.fail(new SchemaIssue.MissingKey(annotations))) } /** @@ -473,7 +473,7 @@ export function required(annotations?: Schema.Annotations.Ke * @since 4.0.0 */ export function onSome( - f: (e: E, options: AST.ParseOptions) => Effect.Effect, Issue.Issue, R> + f: (e: E, options: SchemaAST.ParseOptions) => Effect.Effect, SchemaIssue.Issue, R> ): Getter { return new Getter((oe, options) => Option.isNone(oe) ? Effect.succeedNone : f(oe.value, options)) } @@ -494,7 +494,7 @@ export function onSome( * - `false` or a `string` — value is invalid, fails with an `Issue`. * - An `Issue` object — fails with that issue directly. * - `{ path, issue }` — fails with a nested path issue (`issue` may be a - * message string or a full {@link Issue.Issue}). + * message string or a full {@link SchemaIssue.Issue}). * - Does not transform the value — input and output types are the same. * * **Example** (Effectful validation) @@ -514,7 +514,7 @@ export function onSome( * @since 4.0.0 */ export function checkEffect( - f: (input: T, options: AST.ParseOptions) => Effect.Effect< + f: (input: T, options: SchemaAST.ParseOptions) => Effect.Effect< undefined | boolean | Schema.FilterIssue, never, R @@ -522,7 +522,7 @@ export function checkEffect( ): Getter { return onSome((t, options) => { return f(t, options).pipe(Effect.flatMapEager((out) => { - const issue = Issue.makeSingle(t, out) + const issue = SchemaIssue.makeSingle(t, out) return issue ? Effect.fail(issue) : Effect.succeed(Option.some(t)) @@ -605,7 +605,7 @@ export function transform(f: (e: E) => T): Getter { * @since 4.0.0 */ export function transformOrFail( - f: (e: E, options: AST.ParseOptions) => Effect.Effect + f: (e: E, options: SchemaAST.ParseOptions) => Effect.Effect ): Getter { return onSome((e, options) => f(e, options).pipe(Effect.mapEager(Option.some))) } @@ -703,7 +703,7 @@ export function omit(): Getter { * @since 4.0.0 */ export function withDefault( - defaultValue: Effect.Effect + defaultValue: Effect.Effect ): Getter { return new Getter((o) => { const filtered = Option.filter(o, Predicate.isNotUndefined) @@ -1036,7 +1036,7 @@ type ParseJsonOptions = { * - Skips `None` inputs. * - Without `reviver`: returns `Schema.MutableJson` (typed JSON). * - With `reviver`: returns `unknown` (reviver may produce arbitrary values). - * - On parse failure, fails with `Issue.InvalidValue` containing the error message. + * - On parse failure, fails with `SchemaIssue.InvalidValue` containing the error message. * * **Example** (Parse JSON) * @@ -1058,7 +1058,7 @@ export function parseJson(options?: ParseJsonOptions | undefin return onSome((input) => Effect.try({ try: () => Option.some(JSON.parse(input, options?.reviver)), - catch: (e) => new Issue.InvalidValue(Option.some(input), { message: globalThis.String(e) }) + catch: (e) => new SchemaIssue.InvalidValue(Option.some(input), { message: globalThis.String(e) }) }) ) } @@ -1079,7 +1079,7 @@ type StringifyJsonOptions = { * * - Skips `None` inputs. * - On thrown stringify failures, such as circular references, fails with - * `Issue.InvalidValue`. + * `SchemaIssue.InvalidValue`. * - Supports optional `replacer` and `space` options, matching * `JSON.stringify`. * - If `JSON.stringify` returns `undefined`, such as for `undefined`, @@ -1104,7 +1104,7 @@ export function stringifyJson(options?: StringifyJsonOptions): Getter Effect.try({ try: () => Option.some(JSON.stringify(input, options?.replacer, options?.space)), - catch: (e) => new Issue.InvalidValue(Option.some(input), { message: globalThis.String(e) }) + catch: (e) => new SchemaIssue.InvalidValue(Option.some(input), { message: globalThis.String(e) }) }) ) } @@ -1311,7 +1311,7 @@ export function encodeHex(): Getter { * * **Details** * - * - Fails with `Issue.InvalidValue` if the input is not valid Base64. + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64. * * **Example** (Decode Base64 to bytes) * @@ -1332,7 +1332,7 @@ export function decodeBase64(): Getter { return transformOrFail((input) => Effect.mapErrorEager( Effect.fromResult(Encoding.decodeBase64(input)), - (e) => new Issue.InvalidValue(Option.some(input), { message: e.message }) + (e) => new SchemaIssue.InvalidValue(Option.some(input), { message: e.message }) ) ) } @@ -1342,7 +1342,7 @@ export function decodeBase64(): Getter { * * **Details** * - * - Fails with `Issue.InvalidValue` if the input is not valid Base64. + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64. * * **Example** (Decode Base64 to string) * @@ -1362,7 +1362,7 @@ export function decodeBase64(): Getter { export function decodeBase64String(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeBase64String(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) @@ -1373,7 +1373,7 @@ export function decodeBase64String(): Getter { * * **Details** * - * - Fails with `Issue.InvalidValue` if the input is not valid Base64Url. + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64Url. * * **Example** (Decode Base64Url to bytes) * @@ -1393,7 +1393,7 @@ export function decodeBase64String(): Getter { export function decodeBase64Url(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeBase64Url(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) @@ -1404,7 +1404,7 @@ export function decodeBase64Url(): Getter { * * **Details** * - * - Fails with `Issue.InvalidValue` if the input is not valid Base64Url. + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64Url. * * **Example** (Decode Base64Url to string) * @@ -1424,7 +1424,7 @@ export function decodeBase64Url(): Getter { export function decodeBase64UrlString(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeBase64UrlString(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) @@ -1435,7 +1435,7 @@ export function decodeBase64UrlString(): Getter { * * **Details** * - * - Fails with `Issue.InvalidValue` if the input is not valid hex. + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid hex. * * **Example** (Decode hex to bytes) * @@ -1455,7 +1455,7 @@ export function decodeBase64UrlString(): Getter { export function decodeHex(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeHex(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) @@ -1466,7 +1466,7 @@ export function decodeHex(): Getter { * * **Details** * - * - Fails with `Issue.InvalidValue` if the input is not valid hex. + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid hex. * * **Example** (Decode hex to string) * @@ -1486,7 +1486,7 @@ export function decodeHex(): Getter { export function decodeHexString(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeHexString(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) @@ -1523,7 +1523,7 @@ export function encodeUriComponent(): Getter { * * **Details** * - * - Fails with `Issue.InvalidValue` if the input contains malformed percent-encoding sequences. + * - Fails with `SchemaIssue.InvalidValue` if the input contains malformed percent-encoding sequences. * * **Example** (Decode a URI component) * @@ -1545,7 +1545,7 @@ export function decodeUriComponent(): Getter { return Effect.succeed(globalThis.decodeURIComponent(input)) } catch (e) { return Effect.fail( - new Issue.InvalidValue(Option.some(input), { + new SchemaIssue.InvalidValue(Option.some(input), { message: e instanceof URIError ? e.message : "Invalid URI component" }) ) @@ -1566,7 +1566,7 @@ export function decodeUriComponent(): Getter { * instant objects, zoned instant objects, JavaScript `Date` instances, epoch * milliseconds, and date strings. * - Converts successfully parsed values to UTC. - * - Fails with `Issue.InvalidValue` if the input cannot be parsed as a valid + * - Fails with `SchemaIssue.InvalidValue` if the input cannot be parsed as a valid * `DateTime`. * * **Example** (Parse DateTime) @@ -1586,7 +1586,8 @@ export function decodeUriComponent(): Getter { export function dateTimeUtcFromInput(): Getter { return transformOrFail((input) => { return Option.match(DateTime.make(input), { - onNone: () => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: "Invalid DateTime input" })), + onNone: () => + Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: "Invalid DateTime input" })), onSome: (dt) => Effect.succeed(DateTime.toUtc(dt)) }) }) diff --git a/packages/effect/src/SchemaIssue.ts b/packages/effect/src/SchemaIssue.ts index ad089ca0b4..47c5ca2a0b 100644 --- a/packages/effect/src/SchemaIssue.ts +++ b/packages/effect/src/SchemaIssue.ts @@ -86,7 +86,7 @@ import * as Option from "./Option.ts" import { hasProperty } from "./Predicate.ts" import * as Redacted from "./Redacted.ts" import type * as Schema from "./Schema.ts" -import type * as AST from "./SchemaAST.ts" +import type * as SchemaAST from "./SchemaAST.ts" const TypeId = "~effect/SchemaIssue/Issue" @@ -233,7 +233,7 @@ export class Filter extends Base { /** * The filter that failed. */ - readonly filter: AST.Filter + readonly filter: SchemaAST.Filter /** * The issue that occurred. */ @@ -247,7 +247,7 @@ export class Filter extends Base { /** * The filter that failed. */ - filter: AST.Filter, + filter: SchemaAST.Filter, /** * The issue that occurred. */ @@ -286,7 +286,7 @@ export class Encoding extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.AST + readonly ast: SchemaAST.AST /** * The input value that caused the issue. */ @@ -300,7 +300,7 @@ export class Encoding extends Base { /** * The schema that caused the issue. */ - ast: AST.AST, + ast: SchemaAST.AST, /** * The input value that caused the issue. */ @@ -428,7 +428,7 @@ export class UnexpectedKey extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.AST + readonly ast: SchemaAST.AST /** * The input value that caused the issue. */ @@ -438,7 +438,7 @@ export class UnexpectedKey extends Base { /** * The schema that caused the issue. */ - ast: AST.AST, + ast: SchemaAST.AST, /** * The input value that caused the issue. */ @@ -476,7 +476,7 @@ export class Composite extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.AST + readonly ast: SchemaAST.AST /** * The input value that caused the issue. */ @@ -490,7 +490,7 @@ export class Composite extends Base { /** * The schema that caused the issue. */ - ast: AST.AST, + ast: SchemaAST.AST, /** * The input value that caused the issue. */ @@ -548,7 +548,7 @@ export class InvalidType extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.AST + readonly ast: SchemaAST.AST /** * The input value that caused the issue. */ @@ -558,7 +558,7 @@ export class InvalidType extends Base { /** * The schema that caused the issue. */ - ast: AST.AST, + ast: SchemaAST.AST, /** * The input value that caused the issue. */ @@ -720,7 +720,7 @@ export class AnyOf extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.Union + readonly ast: SchemaAST.Union /** * The input value that caused the issue. */ @@ -734,7 +734,7 @@ export class AnyOf extends Base { /** * The schema that caused the issue. */ - ast: AST.Union, + ast: SchemaAST.Union, /** * The input value that caused the issue. */ @@ -778,7 +778,7 @@ export class OneOf extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.Union + readonly ast: SchemaAST.Union /** * The input value that caused the issue. */ @@ -786,13 +786,13 @@ export class OneOf extends Base { /** * The schemas that were successful. */ - readonly successes: ReadonlyArray + readonly successes: ReadonlyArray constructor( /** * The schema that caused the issue. */ - ast: AST.Union, + ast: SchemaAST.Union, /** * The input value that caused the issue. */ @@ -800,7 +800,7 @@ export class OneOf extends Base { /** * The schemas that were successful. */ - successes: ReadonlyArray + successes: ReadonlyArray ) { super() this.ast = ast @@ -887,7 +887,7 @@ export function makeSingle(input: unknown, out: undefined | boolean | Schema.Fil } /** @internal */ -export function make(input: unknown, ast: AST.AST, out: Schema.FilterOutput): Issue | undefined { +export function make(input: unknown, ast: SchemaAST.AST, out: Schema.FilterOutput): Issue | undefined { if (Array.isArray(out)) { if (Arr.isReadonlyArrayNonEmpty(out)) { if (out.length === 1) { @@ -1121,7 +1121,7 @@ function toDefaultIssues( } } -function formatCheck(check: AST.Check): string { +function formatCheck(check: SchemaAST.Check): string { const expected = check.annotations?.expected if (typeof expected === "string") return expected @@ -1144,7 +1144,7 @@ function formatCheck(check: AST.Check): string { * * **Details** * - * This is the default formatter used by `Issue.toString()`. + * This is the default formatter used by `SchemaIssue.toString()`. * * - Flattens the issue tree into `{ message, path }` entries using * {@link defaultLeafHook} and {@link defaultCheckHook}. diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaParser.ts index 4f07bf9542..f3db904e5a 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaParser.ts @@ -53,17 +53,17 @@ import * as Option from "./Option.ts" import * as Predicate from "./Predicate.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import * as AST from "./SchemaAST.ts" -import * as Issue from "./SchemaIssue.ts" +import * as SchemaAST from "./SchemaAST.ts" +import * as SchemaIssue from "./SchemaIssue.ts" -const recurDefaults = memoize((ast: AST.AST): AST.AST => { +const recurDefaults = memoize((ast: SchemaAST.AST): SchemaAST.AST => { switch (ast._tag) { case "Declaration": { - const getLink = ast.annotations?.[AST.ClassTypeId] + const getLink = ast.annotations?.[SchemaAST.ClassTypeId] if (Predicate.isFunction(getLink)) { const link = getLink(ast.typeParameters) const to = recurDefaults(link.to) - return AST.replaceEncoding(ast, to === link.to ? [link] : [new AST.Link(to, link.transformation)]) + return SchemaAST.replaceEncoding(ast, to === link.to ? [link] : [new SchemaAST.Link(to, link.transformation)]) } return ast } @@ -72,7 +72,7 @@ const recurDefaults = memoize((ast: AST.AST): AST.AST => { return ast.recur((ast) => { const defaultValue = ast.context?.defaultValue if (defaultValue) { - return AST.replaceEncoding(recurDefaults(ast), defaultValue) + return SchemaAST.replaceEncoding(recurDefaults(ast), defaultValue) } return recurDefaults(ast) }) @@ -101,9 +101,9 @@ const recurDefaults = memoize((ast: AST.AST): AST.AST => { * @since 4.0.0 */ export function makeEffect(schema: S) { - const ast = recurDefaults(AST.toType(schema.ast)) + const ast = recurDefaults(SchemaAST.toType(schema.ast)) const parser = run(ast) - return (input: S["~type.make.in"], options?: Schema.MakeOptions): Effect.Effect => { + return (input: S["~type.make.in"], options?: Schema.MakeOptions): Effect.Effect => { return parser( input, options?.disableChecks @@ -182,17 +182,17 @@ export function is(schema: Schema.Schema): (input: I) => input is I & T } /** @internal */ -export function _is(ast: AST.AST) { - const parser = asExit(run(AST.toType(ast))) +export function _is(ast: SchemaAST.AST) { + const parser = asExit(run(SchemaAST.toType(ast))) return (input: I): input is I & T => { - return Exit.isSuccess(parser(input, AST.defaultParseOptions)) + return Exit.isSuccess(parser(input, SchemaAST.defaultParseOptions)) } } /** @internal */ -export function _issue(ast: AST.AST) { +export function _issue(ast: SchemaAST.AST) { const parser = run(ast) - return (input: unknown, options: AST.ParseOptions): Issue.Issue | undefined => { + return (input: unknown, options: SchemaAST.ParseOptions): SchemaIssue.Issue | undefined => { return Effect.runSync(Effect.matchEager(parser(input, options), { onSuccess: () => undefined, onFailure: identity @@ -217,8 +217,8 @@ export function _issue(ast: AST.AST) { * @since 4.0.0 */ export function asserts(schema: S, input: I): asserts input is I & S["Type"] { - const parser = asExit(run(AST.toType(schema.ast))) - const exit = parser(input, AST.defaultParseOptions) + const parser = asExit(run(SchemaAST.toType(schema.ast))) + const exit = parser(input, SchemaAST.defaultParseOptions) if (Exit.isFailure(exit)) { const issue = Cause.findError(exit.cause) if (Result.isFailure(issue)) { @@ -251,8 +251,11 @@ export function asserts(schema: S, input: I): asserts i */ export function decodeUnknownEffect( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Effect.Effect { + options?: SchemaAST.ParseOptions +): ( + input: unknown, + options?: SchemaAST.ParseOptions +) => Effect.Effect { const parser = run(schema.ast) return options === undefined ? parser @@ -283,9 +286,11 @@ export function decodeUnknownEffect( */ export const decodeEffect: ( schema: S, - options?: AST.ParseOptions -) => (input: S["Encoded"], options?: AST.ParseOptions) => Effect.Effect = - decodeUnknownEffect + options?: SchemaAST.ParseOptions +) => ( + input: S["Encoded"], + options?: SchemaAST.ParseOptions +) => Effect.Effect = decodeUnknownEffect /** * Creates a Promise-based decoder for `unknown` input. @@ -308,8 +313,8 @@ export const decodeEffect: ( */ export function decodeUnknownPromise>( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Promise { + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Promise { return asPromise(decodeUnknownEffect(schema, options)) } @@ -335,8 +340,8 @@ export function decodeUnknownPromise>( */ export function decodePromise>( schema: S, - options?: AST.ParseOptions -): (input: S["Encoded"], options?: AST.ParseOptions) => Promise { + options?: SchemaAST.ParseOptions +): (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Promise { return asPromise(decodeEffect(schema, options)) } @@ -371,8 +376,8 @@ export function decodePromise>( */ export function decodeUnknownExit>( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Exit.Exit { + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Exit.Exit { return asExit(decodeUnknownEffect(schema, options)) } @@ -398,8 +403,9 @@ export function decodeUnknownExit>( */ export const decodeExit: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Encoded"], options?: AST.ParseOptions) => Exit.Exit = decodeUnknownExit + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Exit.Exit = + decodeUnknownExit /** * Creates a decoder for `unknown` input that returns an `Option` safely. @@ -423,8 +429,8 @@ export const decodeExit: >( */ export function decodeUnknownOption>( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Option.Option { + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Option.Option { return asOption(decodeUnknownEffect(schema, options)) } @@ -450,8 +456,8 @@ export function decodeUnknownOption>( */ export const decodeOption: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Encoded"], options?: AST.ParseOptions) => Option.Option = decodeUnknownOption + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Option.Option = decodeUnknownOption /** * Creates a decoder for `unknown` input that reports failure safely as a @@ -480,8 +486,8 @@ export const decodeOption: >( */ export function decodeUnknownResult>( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Result.Result { + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Result.Result { return asResult(decodeUnknownEffect(schema, options)) } @@ -512,8 +518,9 @@ export function decodeUnknownResult>( */ export const decodeResult: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Encoded"], options?: AST.ParseOptions) => Result.Result = decodeUnknownResult + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Result.Result = + decodeUnknownResult /** * Creates a synchronous decoder for `unknown` input. @@ -537,8 +544,8 @@ export const decodeResult: >( */ export function decodeUnknownSync>( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => S["Type"] { + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => S["Type"] { return asSync(decodeUnknownEffect(schema, options)) } @@ -565,8 +572,8 @@ export function decodeUnknownSync>( */ export const decodeSync: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Encoded"], options?: AST.ParseOptions) => S["Type"] = decodeUnknownSync + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => S["Type"] = decodeUnknownSync /** * Creates an effectful encoder for `unknown` input. @@ -591,9 +598,12 @@ export const decodeSync: >( */ export function encodeUnknownEffect( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Effect.Effect { - const parser = run(AST.flip(schema.ast)) + options?: SchemaAST.ParseOptions +): ( + input: unknown, + options?: SchemaAST.ParseOptions +) => Effect.Effect { + const parser = run(SchemaAST.flip(schema.ast)) return options === undefined ? parser : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions)) @@ -622,9 +632,11 @@ export function encodeUnknownEffect( */ export const encodeEffect: ( schema: S, - options?: AST.ParseOptions -) => (input: S["Type"], options?: AST.ParseOptions) => Effect.Effect = - encodeUnknownEffect + options?: SchemaAST.ParseOptions +) => ( + input: S["Type"], + options?: SchemaAST.ParseOptions +) => Effect.Effect = encodeUnknownEffect /** * Creates a Promise-based encoder for `unknown` input. @@ -647,8 +659,8 @@ export const encodeEffect: ( */ export const encodeUnknownPromise = >( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Promise => + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Promise => asPromise(encodeUnknownEffect(schema, options)) /** @@ -674,8 +686,8 @@ export const encodeUnknownPromise = >( */ export const encodePromise: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Type"], options?: AST.ParseOptions) => Promise = encodeUnknownPromise + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Promise = encodeUnknownPromise /** * Creates a synchronous encoder for `unknown` input that reports failure safely @@ -699,8 +711,8 @@ export const encodePromise: >( */ export function encodeUnknownExit>( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Exit.Exit { + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Exit.Exit { return asExit(encodeUnknownEffect(schema, options)) } @@ -726,8 +738,9 @@ export function encodeUnknownExit>( */ export const encodeExit: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Type"], options?: AST.ParseOptions) => Exit.Exit = encodeUnknownExit + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Exit.Exit = + encodeUnknownExit /** * Creates an encoder for `unknown` input that returns an `Option` safely. @@ -750,8 +763,8 @@ export const encodeExit: >( */ export function encodeUnknownOption>( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Option.Option { + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Option.Option { return asOption(encodeUnknownEffect(schema, options)) } @@ -777,8 +790,8 @@ export function encodeUnknownOption>( */ export const encodeOption: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Type"], options?: AST.ParseOptions) => Option.Option = encodeUnknownOption + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Option.Option = encodeUnknownOption /** * Creates an encoder for `unknown` input that reports failure safely as a @@ -803,8 +816,8 @@ export const encodeOption: >( */ export function encodeUnknownResult>( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => Result.Result { + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Result.Result { return asResult(encodeUnknownEffect(schema, options)) } @@ -831,8 +844,9 @@ export function encodeUnknownResult>( */ export const encodeResult: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Type"], options?: AST.ParseOptions) => Result.Result = encodeUnknownResult + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Result.Result = + encodeUnknownResult /** * Creates a synchronous encoder for `unknown` input. @@ -855,8 +869,8 @@ export const encodeResult: >( */ export function encodeUnknownSync>( schema: S, - options?: AST.ParseOptions -): (input: unknown, options?: AST.ParseOptions) => S["Encoded"] { + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => S["Encoded"] { return asSync(encodeUnknownEffect(schema, options)) } @@ -884,51 +898,51 @@ export function encodeUnknownSync>( */ export const encodeSync: >( schema: S, - options?: AST.ParseOptions -) => (input: S["Type"], options?: AST.ParseOptions) => S["Encoded"] = encodeUnknownSync + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => S["Encoded"] = encodeUnknownSync const mergeParseOptions = ( - options: AST.ParseOptions, - overrideOptions: AST.ParseOptions | undefined -): AST.ParseOptions => overrideOptions === undefined ? options : { ...options, ...overrideOptions } + options: SchemaAST.ParseOptions, + overrideOptions: SchemaAST.ParseOptions | undefined +): SchemaAST.ParseOptions => overrideOptions === undefined ? options : { ...options, ...overrideOptions } /** @internal */ -export function run(ast: AST.AST) { +export function run(ast: SchemaAST.AST) { const parser = recur(ast) - return (input: unknown, options?: AST.ParseOptions): Effect.Effect => - Effect.flatMapEager(parser(Option.some(input), options ?? AST.defaultParseOptions), (oa) => { + return (input: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => + Effect.flatMapEager(parser(Option.some(input), options ?? SchemaAST.defaultParseOptions), (oa) => { if (oa._tag === "None") { - return Effect.fail(new Issue.InvalidValue(oa)) + return Effect.fail(new SchemaIssue.InvalidValue(oa)) } return Effect.succeed(oa.value as T) }) } function asPromise( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => Promise { - return (input: E, options?: AST.ParseOptions) => Effect.runPromise(parser(input, options)) + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => Promise { + return (input: E, options?: SchemaAST.ParseOptions) => Effect.runPromise(parser(input, options)) } function asExit( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => Exit.Exit { - return (input: E, options?: AST.ParseOptions) => Effect.runSyncExit(parser(input, options) as any) + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => Exit.Exit { + return (input: E, options?: SchemaAST.ParseOptions) => Effect.runSyncExit(parser(input, options) as any) } /** @internal */ export function asOption( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => Option.Option { + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => Option.Option { const parserExit = asExit(parser) - return (input: E, options?: AST.ParseOptions) => Exit.getSuccess(parserExit(input, options)) + return (input: E, options?: SchemaAST.ParseOptions) => Exit.getSuccess(parserExit(input, options)) } function asResult( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => Result.Result { + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => Result.Result { const parserExit = asExit(parser) - return (input: E, options?: AST.ParseOptions) => { + return (input: E, options?: SchemaAST.ParseOptions) => { const exit = parserExit(input, options) if (Exit.isSuccess(exit)) { return Result.succeed(exit.value) @@ -942,9 +956,9 @@ function asResult( } function asSync( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => T { - return (input: E, options?: AST.ParseOptions) => + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => T { + return (input: E, options?: SchemaAST.ParseOptions) => Effect.runSync( Effect.mapErrorEager( parser(input, options), @@ -955,11 +969,14 @@ function asSync( /** @internal */ export interface Parser { - (input: Option.Option, options: AST.ParseOptions): Effect.Effect, Issue.Issue, any> + ( + input: Option.Option, + options: SchemaAST.ParseOptions + ): Effect.Effect, SchemaIssue.Issue, any> } const recur = memoize( - (ast: AST.AST): Parser => { + (ast: SchemaAST.AST): Parser => { let parser: Parser const astOptions = InternalAnnotations.resolve(ast)?.["parseOptions"] if (!ast.context && !ast.encoding && !ast.checks) { @@ -971,14 +988,14 @@ const recur = memoize( return parser(ou, options) } } - const isStructural = AST.isArrays(ast) || AST.isObjects(ast) || - (AST.isDeclaration(ast) && ast.typeParameters.length > 0) + const isStructural = SchemaAST.isArrays(ast) || SchemaAST.isObjects(ast) || + (SchemaAST.isDeclaration(ast) && ast.typeParameters.length > 0) return (ou, options) => { if (astOptions) { options = { ...options, ...astOptions } } const encoding = ast.encoding - let srou: Effect.Effect, Issue.Issue, unknown> | undefined + let srou: Effect.Effect, SchemaIssue.Issue, unknown> | undefined if (encoding) { const links = encoding const len = links.length @@ -994,7 +1011,7 @@ const recur = memoize( srou = link.transformation.decode(srou, options) } } - srou = Effect.mapErrorEager(srou!, (issue) => new Issue.Encoding(ast, ou, issue)) + srou = Effect.mapErrorEager(srou!, (issue) => new SchemaIssue.Encoding(ast, ou, issue)) } parser ??= ast.getParser(recur) @@ -1004,18 +1021,18 @@ const recur = memoize( const checks = ast.checks if (options?.errors === "all" && isStructural && Option.isSome(ou)) { sroa = Effect.catchEager(sroa, (issue) => { - const issues: Array = [] - AST.collectIssues( - checks.filter((check) => check.annotations?.[AST.STRUCTURAL_ANNOTATION_KEY]), + const issues: Array = [] + SchemaAST.collectIssues( + checks.filter((check) => check.annotations?.[SchemaAST.STRUCTURAL_ANNOTATION_KEY]), ou.value, issues, ast, options ) - const out: Issue.Issue = Arr.isArrayNonEmpty(issues) + const out: SchemaIssue.Issue = Arr.isArrayNonEmpty(issues) ? issue._tag === "Composite" && issue.ast === ast - ? new Issue.Composite(ast, issue.actual, [...issue.issues, ...issues]) - : new Issue.Composite(ast, ou, [issue, ...issues]) + ? new SchemaIssue.Composite(ast, issue.actual, [...issue.issues, ...issues]) + : new SchemaIssue.Composite(ast, ou, [issue, ...issues]) : issue return Effect.fail(out) }) @@ -1023,12 +1040,12 @@ const recur = memoize( sroa = Effect.flatMapEager(sroa, (oa) => { if (Option.isSome(oa)) { const value = oa.value - const issues: Array = [] + const issues: Array = [] - AST.collectIssues(checks, value, issues, ast, options) + SchemaAST.collectIssues(checks, value, issues, ast, options) if (Arr.isArrayNonEmpty(issues)) { - return Effect.fail(new Issue.Composite(ast, oa, issues)) + return Effect.fail(new SchemaIssue.Composite(ast, oa, issues)) } } return Effect.succeed(oa) diff --git a/packages/effect/src/SchemaRepresentation.ts b/packages/effect/src/SchemaRepresentation.ts index 1a784e8174..1201178ef0 100644 --- a/packages/effect/src/SchemaRepresentation.ts +++ b/packages/effect/src/SchemaRepresentation.ts @@ -96,8 +96,8 @@ import * as Option from "./Option.ts" import * as Predicate from "./Predicate.ts" import * as Rec from "./Record.ts" import * as Schema from "./Schema.ts" -import type * as AST from "./SchemaAST.ts" -import * as Getter from "./SchemaGetter.ts" +import type * as SchemaAST from "./SchemaAST.ts" +import * as SchemaGetter from "./SchemaGetter.ts" // ----------------------------------------------------------------------------- // specification @@ -863,8 +863,8 @@ const isPrimitiveTree = Schema.is($PrimitiveTree) */ export const $Annotations = Schema.Record(Schema.String, Schema.Unknown).pipe( Schema.encodeTo(Schema.Record(Schema.String, $PrimitiveTree), { - decode: Getter.passthrough(), - encode: Getter.transformOptional(Option.flatMap((r) => { + decode: SchemaGetter.passthrough(), + encode: SchemaGetter.transformOptional(Option.flatMap((r) => { const out: Record = {} for (const [k, v] of Object.entries(r)) { if (!toJsonAnnotationsBlacklist.has(k) && isPrimitiveTree(v)) { @@ -1694,7 +1694,7 @@ export const $MultiDocument = Schema.Struct({ * @category constructors * @since 4.0.0 */ -export const fromAST: (ast: AST.AST) => Document = InternalRepresentation.fromAST +export const fromAST: (ast: SchemaAST.AST) => Document = InternalRepresentation.fromAST /** * Converts one or more Schema ASTs into a {@link MultiDocument}. @@ -1713,7 +1713,8 @@ export const fromAST: (ast: AST.AST) => Document = InternalRepresentation.fromAS * @category constructors * @since 4.0.0 */ -export const fromASTs: (asts: readonly [AST.AST, ...Array]) => MultiDocument = InternalRepresentation.fromASTs +export const fromASTs: (asts: readonly [SchemaAST.AST, ...Array]) => MultiDocument = + InternalRepresentation.fromASTs /** * Schema that decodes a {@link Document} from JSON and encodes it back. @@ -2108,7 +2109,7 @@ export function toSchema(document: Document, } } - function toSchemaCheck(check: Check): AST.Check { + function toSchemaCheck(check: Check): SchemaAST.Check { switch (check._tag) { case "Filter": return toSchemaFilter(check) @@ -2118,7 +2119,7 @@ export function toSchema(document: Document, } } - function toSchemaFilter(filter: Filter): AST.Check { + function toSchemaFilter(filter: Filter): SchemaAST.Check { const a = filter.annotations switch (filter.meta._tag) { // String Meta @@ -3709,7 +3710,7 @@ function collectAnnotations( return Rec.isEmptyRecord(as) ? undefined : as } -function isLiteralValue(value: unknown): value is AST.LiteralValue { +function isLiteralValue(value: unknown): value is SchemaAST.LiteralValue { return typeof value === "string" || typeof value === "number" || typeof value === "boolean" } diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index e4a624a0dc..1b8331f612 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -92,9 +92,9 @@ import * as Effect from "./Effect.ts" import { formatDate } from "./Formatter.ts" import * as Option from "./Option.ts" import * as Predicate from "./Predicate.ts" -import type * as AST from "./SchemaAST.ts" -import * as Getter from "./SchemaGetter.ts" -import * as Issue from "./SchemaIssue.ts" +import type * as SchemaAST from "./SchemaAST.ts" +import * as SchemaGetter from "./SchemaGetter.ts" +import * as SchemaIssue from "./SchemaIssue.ts" /** * Middleware that wraps the entire parsing `Effect` pipeline for both @@ -141,23 +141,23 @@ import * as Issue from "./SchemaIssue.ts" export class Middleware { readonly _tag = "Middleware" readonly decode: ( - effect: Effect.Effect, Issue.Issue, RDE>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, RDT> + effect: Effect.Effect, SchemaIssue.Issue, RDE>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, RDT> readonly encode: ( - effect: Effect.Effect, Issue.Issue, RET>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, REE> + effect: Effect.Effect, SchemaIssue.Issue, RET>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, REE> constructor( decode: ( - effect: Effect.Effect, Issue.Issue, RDE>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, RDT>, + effect: Effect.Effect, SchemaIssue.Issue, RDE>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, RDT>, encode: ( - effect: Effect.Effect, Issue.Issue, RET>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, REE> + effect: Effect.Effect, SchemaIssue.Issue, RET>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, REE> ) { this.decode = decode this.encode = encode @@ -213,12 +213,12 @@ const TypeId = "~effect/SchemaTransformation/Transformation" export class Transformation { readonly [TypeId] = TypeId readonly _tag = "Transformation" - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter constructor( - decode: Getter.Getter, - encode: Getter.Getter + decode: SchemaGetter.Getter, + encode: SchemaGetter.Getter ) { this.decode = decode this.encode = encode @@ -300,8 +300,8 @@ export function isTransformation(u: unknown): u is Transformation(options: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter }): Transformation => { if (isTransformation(options)) { return options as any @@ -353,12 +353,12 @@ export const make = (options: { * @since 3.10.0 */ export function transformOrFail(options: { - readonly decode: (e: E, options: AST.ParseOptions) => Effect.Effect - readonly encode: (t: T, options: AST.ParseOptions) => Effect.Effect + readonly decode: (e: E, options: SchemaAST.ParseOptions) => Effect.Effect + readonly encode: (t: T, options: SchemaAST.ParseOptions) => Effect.Effect }): Transformation { return new Transformation( - Getter.transformOrFail(options.decode), - Getter.transformOrFail(options.encode) + SchemaGetter.transformOrFail(options.decode), + SchemaGetter.transformOrFail(options.encode) ) } @@ -405,8 +405,8 @@ export function transform(options: { readonly encode: (input: T) => E }): Transformation { return new Transformation( - Getter.transform(options.decode), - Getter.transform(options.encode) + SchemaGetter.transform(options.decode), + SchemaGetter.transform(options.encode) ) } @@ -456,8 +456,8 @@ export function transformOptional(options: { readonly encode: (input: Option.Option) => Option.Option }): Transformation { return new Transformation( - Getter.transformOptional(options.decode), - Getter.transformOptional(options.encode) + SchemaGetter.transformOptional(options.decode), + SchemaGetter.transformOptional(options.encode) ) } @@ -494,8 +494,8 @@ export function transformOptional(options: { */ export function trim(): Transformation { return new Transformation( - Getter.trim(), - Getter.passthrough() + SchemaGetter.trim(), + SchemaGetter.passthrough() ) } @@ -531,8 +531,8 @@ export function trim(): Transformation { */ export function snakeToCamel(): Transformation { return new Transformation( - Getter.snakeToCamel(), - Getter.camelToSnake() + SchemaGetter.snakeToCamel(), + SchemaGetter.camelToSnake() ) } @@ -568,8 +568,8 @@ export function snakeToCamel(): Transformation { */ export function toLowerCase(): Transformation { return new Transformation( - Getter.toLowerCase(), - Getter.passthrough() + SchemaGetter.toLowerCase(), + SchemaGetter.passthrough() ) } @@ -605,8 +605,8 @@ export function toLowerCase(): Transformation { */ export function toUpperCase(): Transformation { return new Transformation( - Getter.toUpperCase(), - Getter.passthrough() + SchemaGetter.toUpperCase(), + SchemaGetter.passthrough() ) } @@ -641,8 +641,8 @@ export function toUpperCase(): Transformation { */ export function capitalize(): Transformation { return new Transformation( - Getter.capitalize(), - Getter.passthrough() + SchemaGetter.capitalize(), + SchemaGetter.passthrough() ) } @@ -677,8 +677,8 @@ export function capitalize(): Transformation { */ export function uncapitalize(): Transformation { return new Transformation( - Getter.uncapitalize(), - Getter.passthrough() + SchemaGetter.uncapitalize(), + SchemaGetter.passthrough() ) } @@ -722,14 +722,14 @@ export function splitKeyValue(options?: { readonly keyValueSeparator?: string | undefined }): Transformation, string> { return new Transformation( - Getter.splitKeyValue(options), - Getter.joinKeyValue(options) + SchemaGetter.splitKeyValue(options), + SchemaGetter.joinKeyValue(options) ) } const passthrough_ = new Transformation( - Getter.passthrough(), - Getter.passthrough() + SchemaGetter.passthrough(), + SchemaGetter.passthrough() ) /** @@ -870,8 +870,8 @@ export function passthroughSubtype(): Transformation { * @since 4.0.0 */ export const numberFromString = new Transformation( - Getter.Number(), - Getter.String() + SchemaGetter.Number(), + SchemaGetter.String() ) /** @@ -905,8 +905,8 @@ export const numberFromString = new Transformation( * @since 4.0.0 */ export const bigintFromString = new Transformation( - Getter.BigInt(), - Getter.String() + SchemaGetter.BigInt(), + SchemaGetter.String() ) /** @@ -939,8 +939,8 @@ export const bigintFromString = new Transformation( * @since 4.0.0 */ export const dateFromString: Transformation = new Transformation( - Getter.Date(), - Getter.transform(formatDate) + SchemaGetter.Date(), + SchemaGetter.transform(formatDate) ) /** @@ -980,7 +980,8 @@ export const durationFromString: Transformation = tra >({ decode: (s) => Option.match(Duration.fromInput(s as Duration.Input), { - onNone: () => Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid Duration string: ${s}` })), + onNone: () => + Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid Duration string: ${s}` })), onSome: Effect.succeed }), encode: (duration) => Effect.succeed(globalThis.String(duration)) @@ -1021,7 +1022,7 @@ export const durationFromNanos: Transformation = tran Option.match(Duration.toNanos(a), { onNone: () => Effect.fail( - new Issue.InvalidValue(Option.some(a), { message: `Unable to encode ${a} into a bigint` }) + new SchemaIssue.InvalidValue(Option.some(a), { message: `Unable to encode ${a} into a bigint` }) ), onSome: (nanos) => Effect.succeed(nanos) }) @@ -1339,7 +1340,7 @@ export const urlFromString: Transformation = transformOrFail Effect.try({ try: () => new URL(s), - catch: () => new Issue.InvalidValue(Option.some(s), { message: `Invalid URL string: ${s}` }) + catch: () => new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid URL string: ${s}` }) }), encode: (url) => Effect.succeed(url.href) }) @@ -1368,7 +1369,7 @@ export const bigDecimalFromString: Transformation decode: (s) => { const result = BigDecimal.fromString(s) return Option.isNone(result) - ? Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid BigDecimal string: ${s}` })) + ? Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid BigDecimal string: ${s}` })) : Effect.succeed(result.value) }, encode: (bd) => Effect.succeed(BigDecimal.format(bd)) @@ -1405,8 +1406,8 @@ export const bigDecimalFromString: Transformation * @since 4.0.0 */ export const uint8ArrayFromBase64String: Transformation, string> = new Transformation( - Getter.decodeBase64(), - Getter.encodeBase64() + SchemaGetter.decodeBase64(), + SchemaGetter.encodeBase64() ) /** @@ -1439,8 +1440,8 @@ export const uint8ArrayFromBase64String: Transformation = new Transformation( - Getter.decodeBase64String(), - Getter.encodeBase64() + SchemaGetter.decodeBase64String(), + SchemaGetter.encodeBase64() ) /** @@ -1472,8 +1473,8 @@ export const stringFromBase64String: Transformation = new Transf * @since 4.0.0 */ export const stringFromBase64UrlString: Transformation = new Transformation( - Getter.decodeBase64UrlString(), - Getter.encodeBase64Url() + SchemaGetter.decodeBase64UrlString(), + SchemaGetter.encodeBase64Url() ) /** @@ -1505,8 +1506,8 @@ export const stringFromBase64UrlString: Transformation = new Tra * @since 4.0.0 */ export const stringFromHexString: Transformation = new Transformation( - Getter.decodeHexString(), - Getter.encodeHex() + SchemaGetter.decodeHexString(), + SchemaGetter.encodeHex() ) /** @@ -1542,8 +1543,8 @@ export const stringFromHexString: Transformation = new Transform * @since 4.0.0 */ export const stringFromUriComponent: Transformation = new Transformation( - Getter.decodeUriComponent(), - Getter.encodeUriComponent() + SchemaGetter.decodeUriComponent(), + SchemaGetter.encodeUriComponent() ) /** @@ -1577,8 +1578,8 @@ export const stringFromUriComponent: Transformation = new Transf * @since 4.0.0 */ export const fromJsonString = new Transformation( - Getter.parseJson(), - Getter.stringifyJson() + SchemaGetter.parseJson(), + SchemaGetter.stringifyJson() ) /** @@ -1613,8 +1614,8 @@ export const fromJsonString = new Transformation( * @since 4.0.0 */ export const fromFormData = new Transformation( - Getter.decodeFormData(), - Getter.encodeFormData() + SchemaGetter.decodeFormData(), + SchemaGetter.encodeFormData() ) /** @@ -1649,8 +1650,8 @@ export const fromFormData = new Transformation( * @since 4.0.0 */ export const fromURLSearchParams = new Transformation( - Getter.decodeURLSearchParams(), - Getter.encodeURLSearchParams() + SchemaGetter.decodeURLSearchParams(), + SchemaGetter.encodeURLSearchParams() ) /** @@ -1706,7 +1707,8 @@ export const timeZoneNamedFromString: Transformation({ decode: (s) => { return Option.match(DateTime.zoneMakeNamed(s), { - onNone: () => Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid IANA time zone: ${s}` })), + onNone: () => + Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid IANA time zone: ${s}` })), onSome: Effect.succeed }) }, @@ -1740,7 +1742,7 @@ export const timeZoneFromString: Transformation = tra >({ decode: (s) => { return Option.match(DateTime.zoneFromString(s), { - onNone: () => Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid time zone: ${s}` })), + onNone: () => Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid time zone: ${s}` })), onSome: Effect.succeed }) }, @@ -1775,7 +1777,7 @@ export const dateTimeUtcFromString: Transformation = trans decode: (s) => { return Option.match(DateTime.make(s), { onNone: () => - Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid UTC DateTime string: ${s}` })), + Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid UTC DateTime string: ${s}` })), onSome: (result) => Effect.succeed(DateTime.toUtc(result)) }) }, @@ -1809,7 +1811,7 @@ export const dateTimeZonedFromString: Transformation = t decode: (s) => { return Option.match(DateTime.makeZonedFromString(s), { onNone: () => - Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid Zoned DateTime string: ${s}` })), + Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid Zoned DateTime string: ${s}` })), onSome: Effect.succeed }) }, diff --git a/packages/effect/src/SchemaUtils.ts b/packages/effect/src/SchemaUtils.ts index 5540fac3d0..dbb332fb54 100644 --- a/packages/effect/src/SchemaUtils.ts +++ b/packages/effect/src/SchemaUtils.ts @@ -37,7 +37,7 @@ */ import { identity } from "./Function.ts" import * as Schema from "./Schema.ts" -import * as Transformation from "./SchemaTransformation.ts" +import * as SchemaTransformation from "./SchemaTransformation.ts" /** * Builds an experimental schema for instances of a native class using a struct @@ -68,7 +68,7 @@ export function getNativeClassSchema any, S exten readonly annotations?: Schema.Annotations.Declaration> } ): Schema.decodeTo, S["Iso"]>, S> { - const transformation = Transformation.transform, S["Type"]>({ + const transformation = SchemaTransformation.transform, S["Type"]>({ decode: (props) => new constructor(props), encode: identity }) diff --git a/packages/effect/src/internal/schema/annotations.ts b/packages/effect/src/internal/schema/annotations.ts index a147066fe3..174494ae60 100644 --- a/packages/effect/src/internal/schema/annotations.ts +++ b/packages/effect/src/internal/schema/annotations.ts @@ -1,15 +1,15 @@ import { memoize } from "../../Function.ts" import type * as Schema from "../../Schema.ts" -import type * as AST from "../../SchemaAST.ts" +import type * as SchemaAST from "../../SchemaAST.ts" /** @internal */ -export function resolve(ast: AST.AST): Schema.Annotations.Annotations | undefined { +export function resolve(ast: SchemaAST.AST): Schema.Annotations.Annotations | undefined { return ast.checks ? ast.checks[ast.checks.length - 1].annotations : ast.annotations } /** @internal */ export function resolveAt(key: string) { - return (ast: AST.AST): A | undefined => resolve(ast)?.[key] as A | undefined + return (ast: SchemaAST.AST): A | undefined => resolve(ast)?.[key] as A | undefined } /** @internal */ @@ -25,7 +25,7 @@ export const resolveDescription = resolveAt("description") export const resolveBrands = resolveAt>("brands") /** @internal */ -export const getExpected = memoize((ast: AST.AST): string => { +export const getExpected = memoize((ast: SchemaAST.AST): string => { const identifier = resolveIdentifier(ast) if (typeof identifier === "string") return identifier return ast.getExpected(getExpected) diff --git a/packages/effect/src/internal/schema/arbitrary.ts b/packages/effect/src/internal/schema/arbitrary.ts index eaf8759404..23ff933a29 100644 --- a/packages/effect/src/internal/schema/arbitrary.ts +++ b/packages/effect/src/internal/schema/arbitrary.ts @@ -6,17 +6,17 @@ import * as Number from "../../Number.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import type * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import * as Struct from "../../Struct.ts" import type * as FastCheck from "../../testing/FastCheck.ts" import * as UndefinedOr from "../../UndefinedOr.ts" import { errorWithPath } from "../errors.ts" import * as InternalAnnotations from "./annotations.ts" -const arbitraryMemoMap = new WeakMap>() +const arbitraryMemoMap = new WeakMap>() -function applyChecks(ast: AST.AST, filters: Array>, arbitrary: FastCheck.Arbitrary) { - return filters.map((filter) => (a: any) => filter.run(a, ast, AST.defaultParseOptions) === undefined).reduce( +function applyChecks(ast: SchemaAST.AST, filters: Array>, arbitrary: FastCheck.Arbitrary) { + return filters.map((filter) => (a: any) => filter.run(a, ast, SchemaAST.defaultParseOptions) === undefined).reduce( (acc, filter) => acc.filter(filter), arbitrary ) @@ -99,7 +99,7 @@ function isConstraintKey(key: string): key is keyof Schema.Annotations.ToArbitra /** @internal */ export function constraintContext( - filters: Array> + filters: Array> ): (ctx: Schema.Annotations.ToArbitrary.Context) => Schema.Annotations.ToArbitrary.Context { const annotations = filters.map((filter) => filter.annotations?.toArbitraryConstraint).filter( Predicate.isNotUndefined @@ -140,7 +140,7 @@ interface LazyArbitraryWithContext { } /** @internal */ -export function getFilters(checks: AST.Checks | undefined): Array> { +export function getFilters(checks: SchemaAST.Checks | undefined): Array> { if (checks) { return checks.flatMap((check) => { switch (check._tag) { @@ -155,11 +155,11 @@ export function getFilters(checks: AST.Checks | undefined): Array => { +export const memoized = memoize((ast: SchemaAST.AST): LazyArbitraryWithContext => { return recur(ast, []) }) -function recur(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWithContext { +function recur(ast: SchemaAST.AST, path: ReadonlyArray): LazyArbitraryWithContext { // --------------------------------------------- // handle Override annotation // --------------------------------------------- @@ -167,7 +167,7 @@ function recur(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWit | Schema.Annotations.ToArbitrary.Declaration> | undefined if (annotation) { - const typeParameters = AST.isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path)) : [] + const typeParameters = SchemaAST.isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path)) : [] const filters = getFilters(ast.checks) const f = constraintContext(filters) return (fc, ctx) => @@ -180,13 +180,13 @@ function recur(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWit if (ast.checks) { const filters = getFilters(ast.checks) const f = constraintContext(filters) - const lawc = recur(AST.replaceChecks(ast, undefined), path) + const lawc = recur(SchemaAST.replaceChecks(ast, undefined), path) return (fc, ctx) => applyChecks(ast, filters, lawc(fc, f(ctx))) } return base(ast, path) } -function base(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWithContext { +function base(ast: SchemaAST.AST, path: ReadonlyArray): LazyArbitraryWithContext { switch (ast._tag) { case "Never": case "Declaration": @@ -229,9 +229,9 @@ function base(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWith case "ObjectKeyword": return (fc) => fc.oneof(fc.object(), fc.array(fc.anything())) case "Enum": - return recur(AST.enumsToLiterals(ast), path) + return recur(SchemaAST.enumsToLiterals(ast), path) case "TemplateLiteral": - return (fc) => fc.stringMatching(AST.getTemplateLiteralRegExp(ast)) + return (fc) => fc.stringMatching(SchemaAST.getTemplateLiteralRegExp(ast)) case "Arrays": return (fc, ctx) => { const reset = resetContext(ctx) @@ -240,7 +240,7 @@ function base(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWith // --------------------------------------------- const elements: Array>> = ast.elements.map((e, i) => { const out = recur(e, [...path, i])(fc, reset) - if (!AST.isOptional(e)) { + if (!SchemaAST.isOptional(e)) { return out.map(Option.some) } return out.chain((a) => fc.boolean().map((b) => b ? Option.some(a) : Option.none())) @@ -285,7 +285,7 @@ function base(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWith const requiredKeys: Array = [] for (const ps of ast.propertySignatures) { const name = ps.name - if (!AST.isOptional(ps.type)) { + if (!SchemaAST.isOptional(ps.type)) { requiredKeys.push(name) } pss[name] = recur(ps.type, [...path, name])(fc, reset) @@ -315,7 +315,7 @@ function base(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWith if (memo) return memo - const get = AST.memoizeThunk(() => recur(ast.thunk(), path)) + const get = SchemaAST.memoizeThunk(() => recur(ast.thunk(), path)) const out: LazyArbitraryWithContext = (fc, ctx) => fc.constant(null).chain(() => get()(fc, { ...ctx, isSuspend: true })) diff --git a/packages/effect/src/internal/schema/equivalence.ts b/packages/effect/src/internal/schema/equivalence.ts index c60f775fdd..c6b88f05d5 100644 --- a/packages/effect/src/internal/schema/equivalence.ts +++ b/packages/effect/src/internal/schema/equivalence.ts @@ -3,17 +3,17 @@ import * as Equivalence from "../../Equivalence.ts" import { memoize } from "../../Function.ts" import * as Predicate from "../../Predicate.ts" import type * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Parser from "../../SchemaParser.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaParser from "../../SchemaParser.ts" import { errorWithPath } from "../errors.ts" import * as InternalAnnotations from "./annotations.ts" /** @internal */ -export const toEquivalence = memoize((ast: AST.AST): Equivalence.Equivalence => { +export const toEquivalence = memoize((ast: SchemaAST.AST): Equivalence.Equivalence => { return recur(ast, []) }) -function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equivalence { +function recur(ast: SchemaAST.AST, path: ReadonlyArray): Equivalence.Equivalence { // --------------------------------------------- // handle annotations // --------------------------------------------- @@ -21,7 +21,7 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi | Schema.Annotations.ToEquivalence.Declaration> | undefined if (annotation) { - return annotation(AST.isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path)) : []) + return annotation(SchemaAST.isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path)) : []) } switch (ast._tag) { case "Never": @@ -105,7 +105,7 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi const name = ps.name const aHas = Object.hasOwn(a, name) const bHas = Object.hasOwn(b, name) - if (AST.isOptional(ps.type)) { + if (SchemaAST.isOptional(ps.type)) { if (aHas !== bHas) { return false } @@ -119,8 +119,8 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi // --------------------------------------------- for (let i = 0; i < indexSignatures.length; i++) { const is = ast.indexSignatures[i] - const aKeys = AST.getIndexSignatureKeys(a, is.parameter) - const bKeys = AST.getIndexSignatureKeys(b, is.parameter) + const aKeys = SchemaAST.getIndexSignatureKeys(a, is.parameter) + const bKeys = SchemaAST.getIndexSignatureKeys(b, is.parameter) if (aKeys.length !== bKeys.length) return false @@ -136,8 +136,8 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi } case "Union": return Equivalence.make((a, b) => { - const candidates = AST.getCandidates(a, ast.types) - const types = candidates.map(Parser._is) + const candidates = SchemaAST.getCandidates(a, ast.types) + const types = candidates.map(SchemaParser._is) for (let i = 0; i < candidates.length; i++) { const is = types[i] if (is(a) && is(b)) { @@ -147,7 +147,7 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi return false }) case "Suspend": { - const get = AST.memoizeThunk(() => recur(ast.thunk(), path)) + const get = SchemaAST.memoizeThunk(() => recur(ast.thunk(), path)) return Equivalence.make((a, b) => get()(a, b)) } } diff --git a/packages/effect/src/internal/schema/representation.ts b/packages/effect/src/internal/schema/representation.ts index 6c7523a091..9b8f47c7c5 100644 --- a/packages/effect/src/internal/schema/representation.ts +++ b/packages/effect/src/internal/schema/representation.ts @@ -7,24 +7,24 @@ import * as Predicate from "../../Predicate.ts" import * as Rec from "../../Record.ts" import * as RegEx from "../../RegExp.ts" import type * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import type * as SchemaRepresentation from "../../SchemaRepresentation.ts" import * as InternalAnnotations from "./annotations.ts" import * as InternalSchema from "./schema.ts" /** @internal */ -export function fromAST(ast: AST.AST): SchemaRepresentation.Document { +export function fromAST(ast: SchemaAST.AST): SchemaRepresentation.Document { const { references, representations: schemas } = fromASTs([ast]) return { representation: schemas[0], references } } /** @internal */ -export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRepresentation.MultiDocument { +export function fromASTs(asts: readonly [SchemaAST.AST, ...Array]): SchemaRepresentation.MultiDocument { const references: Record = {} - const referenceMap = new Map() + const referenceMap = new Map() const uniqueReferences = new Set() - const visiting = new Set() + const visiting = new Set() const schemas = Arr.map(asts, (ast) => recur(ast)) @@ -45,13 +45,13 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep return candidate } - function recur(ast: AST.AST, prefix?: string): SchemaRepresentation.Representation { + function recur(ast: SchemaAST.AST, prefix?: string): SchemaRepresentation.Representation { const found = referenceMap.get(ast) if (found !== undefined) { return { _tag: "Reference", $ref: found } } - const last = AST.getLastEncoding(ast) + const last = SchemaAST.getLastEncoding(ast) const identifier = InternalAnnotations.resolveIdentifier(ast) ?? prefix if (ast !== last) { @@ -95,17 +95,17 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep return out } - function getEncodedSchema(last: AST.Declaration): AST.AST { + function getEncodedSchema(last: SchemaAST.Declaration): SchemaAST.AST { const getLink = last.annotations?.toCodecJson ?? last.annotations?.toCodec if (Predicate.isFunction(getLink)) { - const tps = last.typeParameters.map((tp) => InternalSchema.make(AST.toEncoded(tp))) + const tps = last.typeParameters.map((tp) => InternalSchema.make(SchemaAST.toEncoded(tp))) const link = getLink(tps) - return AST.replaceEncoding(last, [link]) + return SchemaAST.replaceEncoding(last, [link]) } - return AST.null + return SchemaAST.null } - function on(last: AST.AST): SchemaRepresentation.Representation { + function on(last: SchemaAST.AST): SchemaRepresentation.Representation { const annotations = fromASTAnnotations(last.annotations) switch (last._tag) { case "Declaration": { @@ -135,7 +135,7 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep _tag: last._tag, checks: fromASTChecks(last.checks), ...annotations, - ...(typeof contentMediaType === "string" && AST.isAST(contentSchema) + ...(typeof contentMediaType === "string" && SchemaAST.isAST(contentSchema) ? { contentSchema: recur(contentSchema) } : undefined) } @@ -180,9 +180,9 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep return { _tag: last._tag, elements: last.elements.map((e) => { - const last = AST.getLastEncoding(e) + const last = SchemaAST.getLastEncoding(e) return { - isOptional: AST.isOptional(last), + isOptional: SchemaAST.isOptional(last), type: recur(e), ...fromASTAnnotations(last.context?.annotations) } @@ -195,12 +195,12 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep return { _tag: last._tag, propertySignatures: last.propertySignatures.map((ps) => { - const last = AST.getLastEncoding(ps.type) + const last = SchemaAST.getLastEncoding(ps.type) return { name: ps.name, type: recur(ps.type), - isOptional: AST.isOptional(last), - isMutable: AST.isMutable(last), + isOptional: SchemaAST.isOptional(last), + isMutable: SchemaAST.isMutable(last), ...fromASTAnnotations(last.context?.annotations) } }), @@ -232,12 +232,12 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep } function fromASTChecks( - checks: readonly [AST.Check, ...Array>] | undefined + checks: readonly [SchemaAST.Check, ...Array>] | undefined ): Array> { if (!checks) return [] return checks.map(getCheck).filter((c) => c !== undefined) - function getCheck(c: AST.Check): SchemaRepresentation.Check | undefined { + function getCheck(c: SchemaAST.Check): SchemaRepresentation.Check | undefined { switch (c._tag) { case "Filter": { const meta = c.annotations?.meta @@ -283,7 +283,7 @@ export const fromASTBlacklist: Set = new Set([ "toCodec", "toCodecJson", "toCodecIso", - AST.ClassTypeId + SchemaAST.ClassTypeId ]) const standardJsonSchemaAnnotationKeys: ReadonlySet = new Set([ @@ -784,9 +784,9 @@ function getPartPattern(part: SchemaRepresentation.Representation): string { case "Literal": return RegEx.escape(globalThis.String(part.literal)) case "String": - return AST.STRING_PATTERN + return SchemaAST.STRING_PATTERN case "Number": - return AST.FINITE_PATTERN + return SchemaAST.FINITE_PATTERN case "TemplateLiteral": return part.parts.map(getPartPattern).join("") case "Union": diff --git a/packages/effect/src/internal/schema/schema.ts b/packages/effect/src/internal/schema/schema.ts index 40debae4ca..c7cf93e2f9 100644 --- a/packages/effect/src/internal/schema/schema.ts +++ b/packages/effect/src/internal/schema/schema.ts @@ -2,9 +2,9 @@ import * as Effect from "../../Effect.ts" import { flow } from "../../Function.ts" import * as Pipeable from "../../Pipeable.ts" import type * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import type { Issue } from "../../SchemaIssue.ts" -import * as Parser from "../../SchemaParser.ts" +import * as SchemaParser from "../../SchemaParser.ts" /** @internal */ export const TypeId = "~effect/Schema/Schema" @@ -15,13 +15,13 @@ const SchemaProto = { return Pipeable.pipeArguments(this, arguments) }, annotate(this: Schema.Top, annotations: Schema.Annotations.Annotations) { - return this.rebuild(AST.annotate(this.ast, annotations)) + return this.rebuild(SchemaAST.annotate(this.ast, annotations)) }, annotateKey(this: Schema.Top, annotations: Schema.Annotations.Key) { - return this.rebuild(AST.annotateKey(this.ast, annotations)) + return this.rebuild(SchemaAST.annotateKey(this.ast, annotations)) }, - check(this: Schema.Top, ...checks: readonly [AST.Check, ...Array>]) { - return this.rebuild(AST.appendChecks(this.ast, checks)) + check(this: Schema.Top, ...checks: readonly [SchemaAST.Check, ...Array>]) { + return this.rebuild(SchemaAST.appendChecks(this.ast, checks)) } } @@ -32,10 +32,10 @@ export function make(ast: S["ast"], options?: object): S { Object.assign(self, options) } self.ast = ast - self.rebuild = (ast: AST.AST) => make(ast, options) - self.makeEffect = flow(Parser.makeEffect(self), Effect.mapErrorEager((issue) => new SchemaError(issue))) - self.make = Parser.make(self) - self.makeOption = Parser.makeOption(self) + self.rebuild = (ast: SchemaAST.AST) => make(ast, options) + self.makeEffect = flow(SchemaParser.makeEffect(self), Effect.mapErrorEager((issue) => new SchemaError(issue))) + self.make = SchemaParser.make(self) + self.makeOption = SchemaParser.makeOption(self) return self } @@ -62,7 +62,7 @@ export class SchemaError { /** @internal */ export const jsonReorder = makeReorder(getJsonPriority) -function getJsonPriority(ast: AST.AST): number { +function getJsonPriority(ast: SchemaAST.AST): number { switch (ast._tag) { case "BigInt": case "Symbol": @@ -74,18 +74,18 @@ function getJsonPriority(ast: AST.AST): number { } /** @internal */ -export function makeReorder(getPriority: (ast: AST.AST) => number) { - return (types: ReadonlyArray): ReadonlyArray => { +export function makeReorder(getPriority: (ast: SchemaAST.AST) => number) { + return (types: ReadonlyArray): ReadonlyArray => { // Create a map of original indices for O(1) lookup - const indexMap = new Map() + const indexMap = new Map() for (let i = 0; i < types.length; i++) { - indexMap.set(AST.toEncoded(types[i]), i) + indexMap.set(SchemaAST.toEncoded(types[i]), i) } // Create a sorted copy of the types array const sortedTypes = [...types].sort((a, b) => { - a = AST.toEncoded(a) - b = AST.toEncoded(b) + a = SchemaAST.toEncoded(a) + b = SchemaAST.toEncoded(b) const pa = getPriority(a) const pb = getPriority(b) if (pa !== pb) return pa - pb diff --git a/packages/effect/src/testing/TestSchema.ts b/packages/effect/src/testing/TestSchema.ts index 19d351b08b..bb2d9a4ba3 100644 --- a/packages/effect/src/testing/TestSchema.ts +++ b/packages/effect/src/testing/TestSchema.ts @@ -72,9 +72,9 @@ import * as Effect from "../Effect.ts" import * as Record from "../Record.ts" import * as Result from "../Result.ts" import * as Schema from "../Schema.ts" -import * as AST from "../SchemaAST.ts" -import type * as Issue from "../SchemaIssue.ts" -import * as Parser from "../SchemaParser.ts" +import * as SchemaAST from "../SchemaAST.ts" +import type * as SchemaIssue from "../SchemaIssue.ts" +import * as SchemaParser from "../SchemaParser.ts" import * as FastCheck from "../testing/FastCheck.ts" /** @@ -132,12 +132,12 @@ export class Asserts { static ast = { fields: { equals: (a: Schema.Struct.Fields, b: Schema.Struct.Fields) => { - assert.deepStrictEqual(Record.map(a, AST.getAST), Record.map(b, AST.getAST)) + assert.deepStrictEqual(Record.map(a, SchemaAST.getAST), Record.map(b, SchemaAST.getAST)) } }, elements: { equals: (a: Schema.Tuple.Elements, b: Schema.Tuple.Elements) => { - assert.deepStrictEqual(a.map(AST.getAST), b.map(AST.getAST)) + assert.deepStrictEqual(a.map(SchemaAST.getAST), b.map(SchemaAST.getAST)) } } } as const @@ -173,7 +173,7 @@ export class Asserts { * @see {@link encoding} for assertions against encoded output */ make(options?: Schema.MakeOptions) { - const makeEffect = Parser.makeEffect(this.schema) + const makeEffect = SchemaParser.makeEffect(this.schema) async function succeed(input: S["Type"]): Promise async function succeed(input: S["~type.make.in"], expected: S["Type"]): Promise async function succeed(input: S["~type.make.in"], expected?: S["Type"]) { @@ -226,8 +226,8 @@ export class Asserts { verifyLosslessTransformation>(this: Asserts, options?: { readonly params?: FastCheck.Parameters<[S["Type"]]> }) { - const decodeUnknownEffect = Parser.decodeUnknownEffect(this.schema) - const encodeEffect = Parser.encodeEffect(this.schema) + const decodeUnknownEffect = SchemaParser.decodeUnknownEffect(this.schema) + const encodeEffect = SchemaParser.encodeEffect(this.schema) const arbitrary = Schema.toArbitrary(this.schema) return FastCheck.assert( FastCheck.asyncProperty(arbitrary, async (t) => { @@ -270,7 +270,7 @@ export class Asserts { * @see {@link encoding} for assertions in the opposite direction */ decoding(options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined }) { return new Decoding(this.schema, options) } @@ -300,7 +300,7 @@ export class Asserts { * @see {@link decoding} for assertions in the opposite direction */ encoding(options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined }) { return new Encoding(this.schema, options) } @@ -374,16 +374,16 @@ export class Decoding { readonly schema: S readonly decodeUnknownEffect: ( input: unknown, - options?: AST.ParseOptions - ) => Effect.Effect + options?: SchemaAST.ParseOptions + ) => Effect.Effect readonly options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined } | undefined constructor(schema: S, options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined }) { this.schema = schema - this.decodeUnknownEffect = Parser.decodeUnknownEffect(schema) + this.decodeUnknownEffect = SchemaParser.decodeUnknownEffect(schema) this.options = options } /** @@ -514,16 +514,16 @@ export class Encoding { readonly schema: S readonly encodeUnknownEffect: ( input: unknown, - options?: AST.ParseOptions - ) => Effect.Effect + options?: SchemaAST.ParseOptions + ) => Effect.Effect readonly options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined } | undefined constructor(schema: S, options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined }) { this.schema = schema - this.encodeUnknownEffect = Parser.encodeUnknownEffect(schema) + this.encodeUnknownEffect = SchemaParser.encodeUnknownEffect(schema) this.options = options } /** diff --git a/packages/effect/src/unstable/ai/AnthropicStructuredOutput.ts b/packages/effect/src/unstable/ai/AnthropicStructuredOutput.ts index 59c85c6a8c..6d0558be26 100644 --- a/packages/effect/src/unstable/ai/AnthropicStructuredOutput.ts +++ b/packages/effect/src/unstable/ai/AnthropicStructuredOutput.ts @@ -41,8 +41,8 @@ import * as JsonSchema from "../../JsonSchema.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as LanguageModel from "./LanguageModel.ts" import * as OpenAiStructuredOutput from "./OpenAiStructuredOutput.ts" import * as Tool from "./Tool.ts" @@ -88,8 +88,10 @@ export function toCodecAnthropic( readonly jsonSchema: JsonSchema.JsonSchema } { const to = schema.ast - const from = recur(AST.toEncoded(to)) - const codec = from === to ? schema : Schema.make(AST.decodeTo(from, to, Transformation.passthrough())) + const from = recur(SchemaAST.toEncoded(to)) + const codec = from === to + ? schema + : Schema.make(SchemaAST.decodeTo(from, to, SchemaTransformation.passthrough())) const document = JsonSchema.resolveTopLevel$ref(Schema.toJsonSchemaDocument(codec)) const jsonSchema = { ...document.schema } if (Object.keys(document.definitions).length > 0) { @@ -98,7 +100,7 @@ export function toCodecAnthropic( return { codec, jsonSchema } } -function recur(ast: AST.AST): AST.AST { +function recur(ast: SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { case "Declaration": case "Void": @@ -126,14 +128,14 @@ function recur(ast: AST.AST): AST.AST { case "String": { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.String(annotations, filters) + return new SchemaAST.String(annotations, filters) } return ast } case "Number": { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.Number(annotations, filters) + return new SchemaAST.Number(annotations, filters) } return ast } @@ -144,7 +146,7 @@ function recur(ast: AST.AST): AST.AST { if (typeof literal === "string" || typeof literal === "number" || typeof literal === "boolean") { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.Literal(ast.literal, annotations, filters) + return new SchemaAST.Literal(ast.literal, annotations, filters) } return ast } @@ -156,12 +158,12 @@ function recur(ast: AST.AST): AST.AST { } case "Union": { if (ast.mode === "oneOf") { - return new AST.Union(ast.types, "anyOf", ast.annotations, ast.checks) + return new SchemaAST.Union(ast.types, "anyOf", ast.annotations, ast.checks) } - const types = AST.mapOrSame(ast.types, recur) + const types = SchemaAST.mapOrSame(ast.types, recur) const { annotations, filters } = get(ast) if (types !== ast.types || annotations !== undefined || filters !== undefined) { - return new AST.Union(types, "anyOf", annotations, filters) + return new SchemaAST.Union(types, "anyOf", annotations, filters) } return ast } @@ -181,15 +183,17 @@ function recur(ast: AST.AST): AST.AST { annotations.description = TUPLE_DESCRIPTION } const propertySignatures = ast.elements.map((e, i) => { - return new AST.PropertySignature(String(i), e) + return new SchemaAST.PropertySignature(String(i), e) }) if (ast.rest.length === 1) { - propertySignatures.push(new AST.PropertySignature(REST_PROPERTY_NAME, new AST.Arrays(false, [], ast.rest))) + propertySignatures.push( + new SchemaAST.PropertySignature(REST_PROPERTY_NAME, new SchemaAST.Arrays(false, [], ast.rest)) + ) } - return AST.decodeTo( - recur(new AST.Objects(propertySignatures, [], annotations, filters)), + return SchemaAST.decodeTo( + recur(new SchemaAST.Objects(propertySignatures, [], annotations, filters)), ast, - Transformation.transform({ + SchemaTransformation.transform({ decode: (o) => { let t: Array = [] for (let i = 0; i < ast.elements.length; i++) { @@ -218,9 +222,9 @@ function recur(ast: AST.AST): AST.AST { }) ) } else { - const rest = AST.mapOrSame(ast.rest, recur) + const rest = SchemaAST.mapOrSame(ast.rest, recur) if (rest !== ast.rest || annotations !== undefined || filters !== undefined) { - return new AST.Arrays(false, [], rest, annotations, filters) + return new SchemaAST.Arrays(false, [], rest, annotations, filters) } return ast } @@ -228,7 +232,7 @@ function recur(ast: AST.AST): AST.AST { case "Objects": { let { annotations, filters } = get(ast) if (ast.indexSignatures.length === 0) { - const propertySignatures = AST.mapOrSame(ast.propertySignatures, (ps) => { + const propertySignatures = SchemaAST.mapOrSame(ast.propertySignatures, (ps) => { if (typeof ps.name !== "string") { throw new Error( `${errorPrefix}: Property names must be strings (got ${typeof ps.name})` @@ -236,11 +240,11 @@ function recur(ast: AST.AST): AST.AST { } let type = recur(ps.type) // opttional properties are not supported by Anthropic, so we translate them to nullable unions - if (AST.isOptional(ps.type)) { - type = AST.decodeTo( - new AST.Union([type, AST.null], "anyOf"), - AST.optionalKey(type), - Transformation.transformOptional({ + if (SchemaAST.isOptional(ps.type)) { + type = SchemaAST.decodeTo( + new SchemaAST.Union([type, SchemaAST.null], "anyOf"), + SchemaAST.optionalKey(type), + SchemaTransformation.transformOptional({ decode: Option.filter(Predicate.isNotNull), encode: Option.orElseSome(() => null) }) @@ -249,12 +253,12 @@ function recur(ast: AST.AST): AST.AST { if (type === ps.type) { return ps } - return new AST.PropertySignature(ps.name, type) + return new SchemaAST.PropertySignature(ps.name, type) }) if ( propertySignatures !== ast.propertySignatures || annotations !== undefined || filters !== undefined ) { - return new AST.Objects(propertySignatures, [], annotations, filters) + return new SchemaAST.Objects(propertySignatures, [], annotations, filters) } } else if (ast.indexSignatures.length === 1 && ast.propertySignatures.length === 0) { const is = ast.indexSignatures[0] @@ -268,10 +272,12 @@ function recur(ast: AST.AST): AST.AST { annotations ??= {} annotations.description = RECORD_DESCRIPTION } - return AST.decodeTo( - recur(new AST.Arrays(false, [], [new AST.Arrays(false, [is.parameter, is.type], [])], annotations)), + return SchemaAST.decodeTo( + recur( + new SchemaAST.Arrays(false, [], [new SchemaAST.Arrays(false, [is.parameter, is.type], [])], annotations) + ), ast, - Transformation.transform({ + SchemaTransformation.transform({ decode: Object.fromEntries, encode: Object.entries }) @@ -288,7 +294,7 @@ function recur(ast: AST.AST): AST.AST { const errorPrefix = "AnthropicStructuredOutput" -function unsupportedAst(ast: AST.AST, details?: string): never { +function unsupportedAst(ast: SchemaAST.AST, details?: string): never { const base = `Unsupported AST ${ast._tag}` const full = `${errorPrefix}: ${base}` throw new Error(details !== undefined ? `${full} (${details})` : full) @@ -308,14 +314,14 @@ type Annotation = type Filter = | Annotation - | { readonly _tag: "filter"; readonly filter: AST.Filter } + | { readonly _tag: "filter"; readonly filter: SchemaAST.Filter } -const get = (ast: AST.AST): { +const get = (ast: SchemaAST.AST): { annotations: Record | undefined - filters: [AST.Check, ...AST.Check[]] | undefined + filters: [SchemaAST.Check, ...SchemaAST.Check[]] | undefined } => { const annotations: Record = {} - const filters: Array> = [] + const filters: Array> = [] const checks = getChecks(ast) if (checks.length > 0) { for (const check of checks) { @@ -345,7 +351,7 @@ const get = (ast: AST.AST): { } } -const getChecks = (ast: AST.AST): Array => [ +const getChecks = (ast: SchemaAST.AST): Array => [ ...(ast.checks !== undefined ? getFilters(ast.checks) : []), ...getAnnotations(ast.annotations) ] @@ -372,7 +378,7 @@ const getAnnotations = (annotations: Schema.Annotations.Filter | undefined): Arr return out } -function getFilter(filter: AST.Filter): Array { +function getFilter(filter: SchemaAST.Filter): Array { let out: Array = [] const annotations = getAnnotations(filter.annotations) const meta = filter.annotations?.meta @@ -396,7 +402,7 @@ function getFilter(filter: AST.Filter): Array { return out } -function resetFilter(filter: AST.Filter): AST.Filter { +function resetFilter(filter: SchemaAST.Filter): SchemaAST.Filter { return filter.annotate({ description: undefined, expected: undefined, @@ -405,7 +411,7 @@ function resetFilter(filter: AST.Filter): AST.Filter { }) } -function getFilters(checks: readonly [AST.Check, ...AST.Check[]]): Array { +function getFilters(checks: readonly [SchemaAST.Check, ...SchemaAST.Check[]]): Array { return checks.flatMap((check) => { switch (check._tag) { case "Filter": diff --git a/packages/effect/src/unstable/ai/LanguageModel.ts b/packages/effect/src/unstable/ai/LanguageModel.ts index 55c54a347a..981590fc92 100644 --- a/packages/effect/src/unstable/ai/LanguageModel.ts +++ b/packages/effect/src/unstable/ai/LanguageModel.ts @@ -61,7 +61,7 @@ import * as Predicate from "../../Predicate.ts" import * as Queue from "../../Queue.ts" import { CurrentConcurrency } from "../../References.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import * as Sink from "../../Sink.ts" import * as Stream from "../../Stream.ts" import type { Span } from "../../Tracer.ts" @@ -2209,7 +2209,7 @@ export const getObjectName = ( if ("identifier" in schema && typeof schema.identifier === "string") { return schema.identifier } - const identifier = AST.resolveIdentifier(schema.ast) + const identifier = SchemaAST.resolveIdentifier(schema.ast) if (typeof identifier === "string") { return identifier } diff --git a/packages/effect/src/unstable/ai/McpSchema.ts b/packages/effect/src/unstable/ai/McpSchema.ts index a435b5a683..16dd05b5ef 100644 --- a/packages/effect/src/unstable/ai/McpSchema.ts +++ b/packages/effect/src/unstable/ai/McpSchema.ts @@ -35,7 +35,7 @@ import { constFalse, constTrue } from "../../Function.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as Getter from "../../SchemaGetter.ts" +import * as SchemaGetter from "../../SchemaGetter.ts" import type * as Scope from "../../Scope.ts" import * as Rpc from "../rpc/Rpc.ts" import type * as RpcClient from "../rpc/RpcClient.ts" @@ -77,8 +77,8 @@ export const optionalWithDefault = >({ - decode: Getter.withDefault(effect), - encode: Getter.passthrough() + decode: SchemaGetter.withDefault(effect), + encode: SchemaGetter.passthrough() }), Schema.withConstructorDefault< Schema.decodeTo>, Schema.optionalKey> @@ -100,8 +100,8 @@ export const optionalWithDefault = (schema: S): Schema.decodeTo, Schema.optionalKey> => Schema.optionalKey(schema).pipe( Schema.decodeTo(Schema.optional(schema), { - decode: Getter.passthrough() as any, - encode: Getter.transformOptional(Option.flatMap(Option.fromUndefinedOr)) + decode: SchemaGetter.passthrough() as any, + encode: SchemaGetter.transformOptional(Option.flatMap(Option.fromUndefinedOr)) }) ) diff --git a/packages/effect/src/unstable/ai/McpServer.ts b/packages/effect/src/unstable/ai/McpServer.ts index 36aa1af158..bac04e72ce 100644 --- a/packages/effect/src/unstable/ai/McpServer.ts +++ b/packages/effect/src/unstable/ai/McpServer.ts @@ -36,7 +36,7 @@ import * as Queue from "../../Queue.ts" import * as RcMap from "../../RcMap.ts" import { CurrentLogLevel } from "../../References.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import * as Sink from "../../Sink.ts" import type { Stdio } from "../../Stdio.ts" import * as Stream from "../../Stream.ts" @@ -1071,8 +1071,8 @@ export const registerPrompt = < for (const [name, prop] of Object.entries(props)) { args.push({ name, - description: AST.resolveDescription(prop.ast), - required: !AST.isOptional(prop.ast) + description: SchemaAST.resolveDescription(prop.ast), + required: !SchemaAST.isOptional(prop.ast) }) } const prompt = new Prompt({ diff --git a/packages/effect/src/unstable/ai/OpenAiStructuredOutput.ts b/packages/effect/src/unstable/ai/OpenAiStructuredOutput.ts index a9b169be7b..6dead3e08b 100644 --- a/packages/effect/src/unstable/ai/OpenAiStructuredOutput.ts +++ b/packages/effect/src/unstable/ai/OpenAiStructuredOutput.ts @@ -56,8 +56,8 @@ import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Rec from "../../Record.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Tool from "./Tool.ts" /** @@ -95,8 +95,10 @@ export function toCodecOpenAI( jsonSchema: JsonSchema.JsonSchema } { const to = schema.ast - const from = recurOpenAI(AST.toEncoded(to)) - const codec = from === to ? schema : Schema.make(AST.decodeTo(from, to, Transformation.passthrough())) + const from = recurOpenAI(SchemaAST.toEncoded(to)) + const codec = from === to + ? schema + : Schema.make(SchemaAST.decodeTo(from, to, SchemaTransformation.passthrough())) const document = JsonSchema.resolveTopLevel$ref(Schema.toJsonSchemaDocument(codec)) const jsonSchema = rewriteOpenAI(document.schema) if (Object.keys(document.definitions).length > 0) { @@ -136,7 +138,7 @@ function rewriteOpenAI(schema: JsonSchema.JsonSchema): JsonSchema.JsonSchema { return out } -function recurOpenAI(ast: AST.AST): AST.AST { +function recurOpenAI(ast: SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { case "Declaration": case "Void": @@ -163,14 +165,14 @@ function recurOpenAI(ast: AST.AST): AST.AST { case "String": { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.String(annotations, filters) + return new SchemaAST.String(annotations, filters) } return ast } case "Number": { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.Number(annotations, filters) + return new SchemaAST.Number(annotations, filters) } return ast } @@ -181,7 +183,7 @@ function recurOpenAI(ast: AST.AST): AST.AST { if (typeof literal === "string" || typeof literal === "number" || typeof literal === "boolean") { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.Literal(ast.literal, annotations, filters) + return new SchemaAST.Literal(ast.literal, annotations, filters) } return ast } @@ -193,12 +195,12 @@ function recurOpenAI(ast: AST.AST): AST.AST { } case "Union": { if (ast.mode === "oneOf") { - return new AST.Union(ast.types, "anyOf", ast.annotations, ast.checks) + return new SchemaAST.Union(ast.types, "anyOf", ast.annotations, ast.checks) } - const types = AST.mapOrSame(ast.types, recurOpenAI) + const types = SchemaAST.mapOrSame(ast.types, recurOpenAI) const { annotations, filters } = get(ast) if (types !== ast.types || annotations !== undefined || filters !== undefined) { - return new AST.Union(types, "anyOf", annotations, filters) + return new SchemaAST.Union(types, "anyOf", annotations, filters) } return ast } @@ -218,15 +220,17 @@ function recurOpenAI(ast: AST.AST): AST.AST { annotations.description = TUPLE_DESCRIPTION } const propertySignatures = ast.elements.map((e, i) => { - return new AST.PropertySignature(String(i), e) + return new SchemaAST.PropertySignature(String(i), e) }) if (ast.rest.length === 1) { - propertySignatures.push(new AST.PropertySignature(REST_PROPERTY_NAME, new AST.Arrays(false, [], ast.rest))) + propertySignatures.push( + new SchemaAST.PropertySignature(REST_PROPERTY_NAME, new SchemaAST.Arrays(false, [], ast.rest)) + ) } - return AST.decodeTo( - recurOpenAI(new AST.Objects(propertySignatures, [], annotations, filters)), + return SchemaAST.decodeTo( + recurOpenAI(new SchemaAST.Objects(propertySignatures, [], annotations, filters)), ast, - Transformation.transform({ + SchemaTransformation.transform({ decode: (o) => { let t: Array = [] for (let i = 0; i < ast.elements.length; i++) { @@ -255,9 +259,9 @@ function recurOpenAI(ast: AST.AST): AST.AST { }) ) } else { - const rest = AST.mapOrSame(ast.rest, recurOpenAI) + const rest = SchemaAST.mapOrSame(ast.rest, recurOpenAI) if (rest !== ast.rest || annotations !== undefined || filters !== undefined) { - return new AST.Arrays(false, [], rest, annotations, filters) + return new SchemaAST.Arrays(false, [], rest, annotations, filters) } return ast } @@ -265,7 +269,7 @@ function recurOpenAI(ast: AST.AST): AST.AST { case "Objects": { let { annotations, filters } = get(ast) if (ast.indexSignatures.length === 0) { - const propertySignatures = AST.mapOrSame(ast.propertySignatures, (ps) => { + const propertySignatures = SchemaAST.mapOrSame(ast.propertySignatures, (ps) => { if (typeof ps.name !== "string") { throw new Error( `${errorPrefix}: Property names must be strings (got ${typeof ps.name})` @@ -273,11 +277,11 @@ function recurOpenAI(ast: AST.AST): AST.AST { } let type = recurOpenAI(ps.type) // optional properties are not supported by OpenAI, so we translate them to nullable unions - if (AST.isOptional(ps.type)) { - type = AST.decodeTo( - new AST.Union([type, AST.null], "anyOf"), - AST.optionalKey(type), - Transformation.transformOptional({ + if (SchemaAST.isOptional(ps.type)) { + type = SchemaAST.decodeTo( + new SchemaAST.Union([type, SchemaAST.null], "anyOf"), + SchemaAST.optionalKey(type), + SchemaTransformation.transformOptional({ decode: Option.filter(Predicate.isNotNull), encode: Option.orElseSome(() => null) }) @@ -286,12 +290,12 @@ function recurOpenAI(ast: AST.AST): AST.AST { if (type === ps.type) { return ps } - return new AST.PropertySignature(ps.name, type) + return new SchemaAST.PropertySignature(ps.name, type) }) if ( propertySignatures !== ast.propertySignatures || annotations !== undefined || filters !== undefined ) { - return new AST.Objects(propertySignatures, [], annotations, filters) + return new SchemaAST.Objects(propertySignatures, [], annotations, filters) } } else if (ast.indexSignatures.length === 1 && ast.propertySignatures.length === 0) { const is = ast.indexSignatures[0] @@ -305,10 +309,12 @@ function recurOpenAI(ast: AST.AST): AST.AST { annotations ??= {} annotations.description = RECORD_DESCRIPTION } - return AST.decodeTo( - recurOpenAI(new AST.Arrays(false, [], [new AST.Arrays(false, [is.parameter, is.type], [])], annotations)), + return SchemaAST.decodeTo( + recurOpenAI( + new SchemaAST.Arrays(false, [], [new SchemaAST.Arrays(false, [is.parameter, is.type], [])], annotations) + ), ast, - Transformation.transform({ + SchemaTransformation.transform({ decode: Object.fromEntries, encode: Object.entries }) @@ -324,18 +330,18 @@ function recurOpenAI(ast: AST.AST): AST.AST { const cached = cache.get(ast) if (cached) return cached const { annotations, filters } = get(ast) - const out = new AST.Suspend(() => recurOpenAI(ast.thunk()), annotations, filters) + const out = new SchemaAST.Suspend(() => recurOpenAI(ast.thunk()), annotations, filters) cache.set(ast, out) return out } } } -const cache = new Map() +const cache = new Map() const errorPrefix = "OpenAiStructuredOutput" -function unsupportedAst(ast: AST.AST, details?: string): never { +function unsupportedAst(ast: SchemaAST.AST, details?: string): never { const base = `Unsupported AST ${ast._tag}` const full = `${errorPrefix}: ${base}` throw new Error(details !== undefined ? `${full} (${details})` : full) @@ -355,17 +361,17 @@ type Annotation = type Filter = | Annotation - | { readonly _tag: "filter"; readonly filter: AST.Filter } + | { readonly _tag: "filter"; readonly filter: SchemaAST.Filter } | { readonly _tag: "regex"; readonly source: string } -const get = (ast: AST.AST): { +const get = (ast: SchemaAST.AST): { annotations: Record | undefined - filters: [AST.Check, ...AST.Check[]] | undefined + filters: [SchemaAST.Check, ...SchemaAST.Check[]] | undefined } => { const annotations: Record = {} - const filters: Array> = [] + const filters: Array> = [] const regexSources: Array = [] - const checks = getChecks(ast, AST.isArrays(ast)) + const checks = getChecks(ast, SchemaAST.isArrays(ast)) if (checks.length > 0) { for (const check of checks) { switch (check._tag) { @@ -394,10 +400,10 @@ const get = (ast: AST.AST): { } // OpenAI does not support allOf, so we merge multiple regex patterns into a single isPattern filter if (regexSources.length === 1) { - filters.push(AST.isPattern(new RegExp(regexSources[0]))) + filters.push(SchemaAST.isPattern(new RegExp(regexSources[0]))) } else if (regexSources.length > 1) { const combined = regexSources.map((s) => `(?=[\\s\\S]*?(?:${s}))`).join("") - filters.push(AST.isPattern(new RegExp(`^${combined}`))) + filters.push(SchemaAST.isPattern(new RegExp(`^${combined}`))) } return { annotations: Object.keys(annotations).length > 0 ? annotations : undefined, @@ -405,7 +411,7 @@ const get = (ast: AST.AST): { } } -const getChecks = (ast: AST.AST, isArray: boolean): Array => [ +const getChecks = (ast: SchemaAST.AST, isArray: boolean): Array => [ ...(ast.checks !== undefined ? getFilters(ast.checks, isArray) : []), ...getAnnotations(ast.annotations) ] @@ -432,7 +438,7 @@ const getAnnotations = (annotations: Schema.Annotations.Filter | undefined): Arr return out } -function getFilter(filter: AST.Filter, isArray: boolean): Array { +function getFilter(filter: SchemaAST.Filter, isArray: boolean): Array { let out: Array = [] const annotations = getAnnotations(filter.annotations) const meta = filter.annotations?.meta @@ -471,7 +477,7 @@ function getFilter(filter: AST.Filter, isArray: boolean): Array { return out } -function resetFilter(filter: AST.Filter): AST.Filter { +function resetFilter(filter: SchemaAST.Filter): SchemaAST.Filter { return filter.annotate({ description: undefined, expected: undefined, @@ -480,7 +486,10 @@ function resetFilter(filter: AST.Filter): AST.Filter { }) } -function getFilters(checks: readonly [AST.Check, ...AST.Check[]], isArray: boolean): Array { +function getFilters( + checks: readonly [SchemaAST.Check, ...SchemaAST.Check[]], + isArray: boolean +): Array { return checks.flatMap((check) => { switch (check._tag) { case "Filter": diff --git a/packages/effect/src/unstable/ai/Prompt.ts b/packages/effect/src/unstable/ai/Prompt.ts index 1b1fdcc5a5..85e675ca8c 100644 --- a/packages/effect/src/unstable/ai/Prompt.ts +++ b/packages/effect/src/unstable/ai/Prompt.ts @@ -61,7 +61,7 @@ import { type Pipeable, pipeArguments } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" import * as SchemaIssue from "../../SchemaIssue.ts" -import * as Parser from "../../SchemaParser.ts" +import * as SchemaParser from "../../SchemaParser.ts" import * as SchemaTransformation from "../../SchemaTransformation.ts" import type * as Response from "./Response.ts" @@ -1783,7 +1783,7 @@ export const Prompt: Schema.Codec = Schema.Struct({ SchemaTransformation.transformOrFail({ decode: (input) => Effect.mapBothEager( - Parser.decodeEffect(Schema.Array(Message))(input.content), + SchemaParser.decodeEffect(Schema.Array(Message))(input.content), { onSuccess: makePrompt, onFailure: () => @@ -1792,7 +1792,7 @@ export const Prompt: Schema.Codec = Schema.Struct({ ), encode: (prompt) => Effect.mapBothEager( - Parser.encodeEffect(Schema.Array(Message))(prompt.content), + SchemaParser.encodeEffect(Schema.Array(Message))(prompt.content), { onSuccess: (messages) => ({ content: messages }), onFailure: () => diff --git a/packages/effect/src/unstable/ai/Tool.ts b/packages/effect/src/unstable/ai/Tool.ts index ded2f171d4..42c5b7865a 100644 --- a/packages/effect/src/unstable/ai/Tool.ts +++ b/packages/effect/src/unstable/ai/Tool.ts @@ -63,7 +63,7 @@ import type * as JsonSchema from "../../JsonSchema.ts" import { pipeArguments } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import type * as Struct from "../../Struct.ts" import type * as Types from "../../Types.ts" import type * as AiError from "./AiError.ts" @@ -1640,7 +1640,7 @@ export const getDescription = (tool: Tool): string | undefined return tool.description } if (Schema.isSchema(tool.parametersSchema)) { - return AST.resolveDescription(tool.parametersSchema.ast) + return SchemaAST.resolveDescription(tool.parametersSchema.ast) } return undefined } @@ -2043,6 +2043,6 @@ export interface EmptyParams extends Schema.$Record export const EmptyParams: EmptyParams = Schema.Record(Schema.String, Schema.Never) /** @internal */ -export function isEmptyParamsRecord(indexSignature: AST.IndexSignature): boolean { - return indexSignature.parameter === AST.string && AST.isNever(indexSignature.type) +export function isEmptyParamsRecord(indexSignature: SchemaAST.IndexSignature): boolean { + return indexSignature.parameter === SchemaAST.string && SchemaAST.isNever(indexSignature.type) } diff --git a/packages/effect/src/unstable/cluster/Envelope.ts b/packages/effect/src/unstable/cluster/Envelope.ts index 71f9a57abd..184b7de5ed 100644 --- a/packages/effect/src/unstable/cluster/Envelope.ts +++ b/packages/effect/src/unstable/cluster/Envelope.ts @@ -28,7 +28,7 @@ import * as Predicate from "../../Predicate.ts" import * as PrimaryKey from "../../PrimaryKey.ts" import type { ReadonlyRecord } from "../../Record.ts" import * as Schema from "../../Schema.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Headers from "../http/Headers.ts" import type * as Rpc from "../rpc/Rpc.ts" import { EntityAddress } from "./EntityAddress.ts" @@ -406,10 +406,10 @@ export const Request = Schema.declare( * @category serialization * @since 4.0.0 */ -export const RequestTransform: Transformation.Transformation< +export const RequestTransform: SchemaTransformation.Transformation< Request.Any, any -> = Transformation.transform({ +> = SchemaTransformation.transform({ decode: (u: any) => makeRequest(u), encode: (u) => u as any }) diff --git a/packages/effect/src/unstable/cluster/Reply.ts b/packages/effect/src/unstable/cluster/Reply.ts index 604aac6359..9b5f255017 100644 --- a/packages/effect/src/unstable/cluster/Reply.ts +++ b/packages/effect/src/unstable/cluster/Reply.ts @@ -30,9 +30,9 @@ import * as Exit from "../../Exit.ts" import * as Option from "../../Option.ts" import { hasProperty } from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Parser from "../../SchemaParser.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaParser from "../../SchemaParser.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Rpc from "../rpc/Rpc.ts" import type * as RpcMessage from "../rpc/RpcMessage.ts" import type * as RpcSchema from "../rpc/RpcSchema.ts" @@ -221,7 +221,7 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ * * @since 4.0.0 */ - static readonly transform: Transformation.Transformation = Transformation.transform({ + static readonly transform: SchemaTransformation.Transformation = SchemaTransformation.transform({ decode: (a: any) => new Chunk(a), encode: (a) => a as any }) @@ -254,10 +254,11 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ [success], ([success]) => (input, ast, options) => { if (!isReply(input) || input._tag !== "Chunk") { - return Effect.fail(new Issue.InvalidType(ast, Option.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(input))) } - return Effect.mapBothEager(Parser.decodeEffect(Schema.NonEmptyArray(success))(input.values, options), { - onFailure: (issue) => new Issue.Composite(ast, Option.some(input), [new Issue.Pointer(["values"], issue)]), + return Effect.mapBothEager(SchemaParser.decodeEffect(Schema.NonEmptyArray(success))(input.values, options), { + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option.some(input), [new SchemaIssue.Pointer(["values"], issue)]), onSuccess: (values) => new Chunk({ ...input, values } as any) }) }, @@ -272,7 +273,7 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ sequence: Schema.Number, values: Schema.NonEmptyArray(success) }), - Transformation.transform({ + SchemaTransformation.transform({ decode: (encoded) => new Chunk(encoded), encode: (result) => ({ ...result }) }) @@ -359,10 +360,11 @@ export class WithExit extends Data.TaggedClass("WithExit")<{ [exitSchema], ([exit]) => (input, ast, options) => { if (!isReply(input) || input._tag !== "WithExit") { - return Effect.fail(new Issue.InvalidType(ast, Option.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(input))) } - return Effect.mapBothEager(Parser.decodeEffect(exit)(input.exit, options), { - onFailure: (issue) => new Issue.Composite(ast, Option.some(input), [new Issue.Pointer(["exit"], issue)]), + return Effect.mapBothEager(SchemaParser.decodeEffect(exit)(input.exit, options), { + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option.some(input), [new SchemaIssue.Pointer(["exit"], issue)]), onSuccess: (exit) => new WithExit({ ...input, exit: exit as any }) }) }, @@ -376,7 +378,7 @@ export class WithExit extends Data.TaggedClass("WithExit")<{ id: SnowflakeFromBigInt, exit }), - Transformation.transform({ + SchemaTransformation.transform({ decode: (encoded) => new WithExit(encoded as any), encode: (result) => ({ ...result }) }) diff --git a/packages/effect/src/unstable/cluster/ShardId.ts b/packages/effect/src/unstable/cluster/ShardId.ts index dc19cb2e51..dc9b6a0a61 100644 --- a/packages/effect/src/unstable/cluster/ShardId.ts +++ b/packages/effect/src/unstable/cluster/ShardId.ts @@ -29,7 +29,7 @@ import * as Hash from "../../Hash.ts" import { hasProperty } from "../../Predicate.ts" import * as PrimaryKey from "../../PrimaryKey.ts" import * as S from "../../Schema.ts" -import * as Getter from "../../SchemaGetter.ts" +import * as SchemaGetter from "../../SchemaGetter.ts" const TypeId = "~effect/cluster/ShardId" @@ -69,8 +69,8 @@ export const ShardId = S.declare(isShardId, { id: S.Number }), { - decode: Getter.transform(({ group, id }) => make(group, id)), - encode: Getter.passthrough() + decode: SchemaGetter.transform(({ group, id }) => make(group, id)), + encode: SchemaGetter.passthrough() } ) }) diff --git a/packages/effect/src/unstable/cluster/Snowflake.ts b/packages/effect/src/unstable/cluster/Snowflake.ts index fc2e2b8a06..a31a2f4b25 100644 --- a/packages/effect/src/unstable/cluster/Snowflake.ts +++ b/packages/effect/src/unstable/cluster/Snowflake.ts @@ -27,7 +27,7 @@ import * as Effect from "../../Effect.ts" import { identity } from "../../Function.ts" import * as Layer from "../../Layer.ts" import * as Schema from "../../Schema.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import type { MachineId } from "./MachineId.ts" /** @@ -129,7 +129,7 @@ export interface SnowflakeFromString extends Schema.decodeTo( if (!rpc) { return Effect.fail( new Schema.SchemaError( - new Issue.InvalidValue(Option.some(message), { + new SchemaIssue.InvalidValue(Option.some(message), { message: `Unknown tag ${message.envelope.tag} for entity type ${entity.type}` }) ) diff --git a/packages/effect/src/unstable/encoding/Msgpack.ts b/packages/effect/src/unstable/encoding/Msgpack.ts index d7f021e1bd..46f4461b30 100644 --- a/packages/effect/src/unstable/encoding/Msgpack.ts +++ b/packages/effect/src/unstable/encoding/Msgpack.ts @@ -44,8 +44,8 @@ import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import type * as Pull from "../../Pull.ts" import * as Schema from "../../Schema.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" const MsgPackErrorTypeId = "~effect/encoding/MsgPack/MsgPackError" @@ -361,16 +361,16 @@ export interface schema extends Schema.decodeTo -> = Transformation.transformOrFail({ +> = SchemaTransformation.transformOrFail({ decode(e, _options) { try { return Effect.succeed(Msgpackr.decode(e)) } catch (cause) { return Effect.fail( - new Issue.InvalidValue(Option.some(e), { + new SchemaIssue.InvalidValue(Option.some(e), { message: Predicate.hasProperty(cause, "message") ? String(cause.message) : String(cause) }) ) @@ -381,7 +381,7 @@ export const transformation: Transformation.Transformation< return Effect.succeed(Msgpackr.encode(t) as Uint8Array) } catch (cause) { return Effect.fail( - new Issue.InvalidValue(Option.some(t), { + new SchemaIssue.InvalidValue(Option.some(t), { message: Predicate.hasProperty(cause, "message") ? String(cause.message) : String(cause) }) ) diff --git a/packages/effect/src/unstable/encoding/Sse.ts b/packages/effect/src/unstable/encoding/Sse.ts index ee89b66cbb..85a35a580e 100644 --- a/packages/effect/src/unstable/encoding/Sse.ts +++ b/packages/effect/src/unstable/encoding/Sse.ts @@ -51,7 +51,7 @@ import { hasProperty } from "../../Predicate.ts" import * as Pull from "../../Pull.ts" import * as Result from "../../Result.ts" import * as Schema from "../../Schema.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" /** * Creates a channel that parses Server-Sent Events text chunks into `Event` values. @@ -494,7 +494,7 @@ export const Event: Schema.Struct<{ * @category models * @since 4.0.0 */ -export const transformEvent = Transformation.transform<{ +export const transformEvent = SchemaTransformation.transform<{ readonly id?: string | undefined readonly event: string readonly data: string diff --git a/packages/effect/src/unstable/http/Cookies.ts b/packages/effect/src/unstable/http/Cookies.ts index 3957bb5df0..f835b8e5ba 100644 --- a/packages/effect/src/unstable/http/Cookies.ts +++ b/packages/effect/src/unstable/http/Cookies.ts @@ -71,7 +71,7 @@ import * as Predicate from "../../Predicate.ts" import * as Record from "../../Record.ts" import * as Result from "../../Result.ts" import * as Schema from "../../Schema.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import type * as Types from "../../Types.ts" const TypeId = "~effect/http/Cookies" @@ -130,7 +130,7 @@ export const CookiesSchema: CookiesSchema = Schema.declare( toCodecJson: () => Schema.link()( Schema.Array(Schema.String), - Transformation.transform({ + SchemaTransformation.transform({ decode: (input) => fromSetCookie(input), encode: (cookies) => toSetCookieHeaders(cookies) }) @@ -138,7 +138,7 @@ export const CookiesSchema: CookiesSchema = Schema.declare( toCodecIso: () => Schema.link()( Schema.Record(Schema.String, CookieSchema), - Transformation.transform({ + SchemaTransformation.transform({ decode: (input) => fromReadonlyRecord(input), encode: (cookies) => cookies.cookies }) @@ -932,7 +932,7 @@ export const toRecord = (self: Cookies): Record => { export const schemaRecord = CookiesSchema.pipe( Schema.decodeTo( Schema.Record(Schema.String, Schema.String), - Transformation.transform({ + SchemaTransformation.transform({ decode: toRecord, encode: (self) => fromIterable(Object.entries(self).map(([name, value]) => makeCookieUnsafe(name, value))) }) diff --git a/packages/effect/src/unstable/http/Headers.ts b/packages/effect/src/unstable/http/Headers.ts index 52365a2687..dc8565b144 100644 --- a/packages/effect/src/unstable/http/Headers.ts +++ b/packages/effect/src/unstable/http/Headers.ts @@ -66,7 +66,7 @@ import * as Record from "../../Record.ts" import * as Redactable from "../../Redactable.ts" import * as Redacted from "../../Redacted.ts" import * as Schema from "../../Schema.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import type { Mutable } from "../../Types.ts" /** @@ -189,7 +189,7 @@ export const HeadersSchema: HeadersSchema = Schema.declare( toCodec: () => Schema.link()( Schema.Record(Schema.String, Schema.String), - Transformation.transform({ + SchemaTransformation.transform({ decode: (input) => fromInput(input), encode: (headers) => ({ ...headers }) }) diff --git a/packages/effect/src/unstable/http/HttpBody.ts b/packages/effect/src/unstable/http/HttpBody.ts index df7340c1a4..af1b46e720 100644 --- a/packages/effect/src/unstable/http/HttpBody.ts +++ b/packages/effect/src/unstable/http/HttpBody.ts @@ -65,7 +65,7 @@ import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" import type { ParseOptions } from "../../SchemaAST.ts" import type { Issue } from "../../SchemaIssue.ts" -import * as Parser from "../../SchemaParser.ts" +import * as SchemaParser from "../../SchemaParser.ts" import type * as Stream_ from "../../Stream.ts" import * as UrlParams from "./UrlParams.ts" @@ -365,7 +365,7 @@ export const jsonSchema = ( schema: S, options?: ParseOptions | undefined ) => { - const encode = Parser.encodeUnknownEffect(Schema.toCodecJson(schema)) + const encode = SchemaParser.encodeUnknownEffect(Schema.toCodecJson(schema)) return (body: S["Type"], contentType?: string): Effect.Effect => encode(body, options).pipe( Effect.mapError((issue) => new HttpBodyError({ reason: { _tag: "SchemaError", issue }, cause: issue })), diff --git a/packages/effect/src/unstable/http/Multipart.ts b/packages/effect/src/unstable/http/Multipart.ts index d3563f1d66..069c978f39 100644 --- a/packages/effect/src/unstable/http/Multipart.ts +++ b/packages/effect/src/unstable/http/Multipart.ts @@ -55,7 +55,7 @@ import * as Predicate from "../../Predicate.ts" import * as Pull from "../../Pull.ts" import * as Schema from "../../Schema.ts" import type { ParseOptions } from "../../SchemaAST.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import type * as Scope from "../../Scope.ts" import * as Stream from "../../Stream.ts" import * as UndefinedOr from "../../UndefinedOr.ts" @@ -306,7 +306,7 @@ export const PersistedFileSchema: PersistedFileSchema = Schema.declare( contentType: Schema.String.annotate({ contentEncoding: "binary" }), path: Schema.String }), - Transformation.transform({ + SchemaTransformation.transform({ decode: ({ contentType, key, name, path }) => new PersistedFileImpl(key, name, contentType, path), encode: (file) => ({ key: file.key, @@ -344,7 +344,7 @@ export const SingleFileSchema: Schema.decodeTo file, encode: (file) => [file] }) diff --git a/packages/effect/src/unstable/http/UrlParams.ts b/packages/effect/src/unstable/http/UrlParams.ts index 8490684fd5..0f77661a6f 100644 --- a/packages/effect/src/unstable/http/UrlParams.ts +++ b/packages/effect/src/unstable/http/UrlParams.ts @@ -51,8 +51,8 @@ import { hasProperty } from "../../Predicate.ts" import type { ReadonlyRecord } from "../../Record.ts" import * as Result from "../../Result.ts" import * as Schema from "../../Schema.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Tuple from "../../Tuple.ts" const TypeId = "~effect/http/UrlParams" @@ -276,7 +276,7 @@ export const UrlParamsSchema: UrlParamsSchema = Schema.declare( toCodec: () => Schema.link()( Schema.Array(Schema.Tuple([Schema.String, Schema.String])), - Transformation.transform({ + SchemaTransformation.transform({ decode: make, encode: (self) => self.params }) @@ -624,10 +624,10 @@ export const schemaJsonField = (field: string): schemaJsonField => UrlParamsSchema.pipe( Schema.decodeTo( Schema.UnknownFromJsonString, - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode: (params) => Option.match(getFirst(params, field), { - onNone: () => Effect.fail(new Issue.Pointer([field], new Issue.MissingKey(undefined))), + onNone: () => Effect.fail(new SchemaIssue.Pointer([field], new SchemaIssue.MissingKey(undefined))), onSome: Effect.succeed }), encode: (value) => Effect.succeed(make([[field, value]])) @@ -688,7 +688,7 @@ export const schemaRecord: schemaRecord = UrlParamsSchema.pipe( Schema.String, Schema.Union([Schema.String, Schema.NonEmptyArray(Schema.String)]) ), - Transformation.transform({ + SchemaTransformation.transform({ decode: toReadonlyRecord, encode: fromInput }) diff --git a/packages/effect/src/unstable/httpapi/HttpApi.ts b/packages/effect/src/unstable/httpapi/HttpApi.ts index d3c66239d3..224666911a 100644 --- a/packages/effect/src/unstable/httpapi/HttpApi.ts +++ b/packages/effect/src/unstable/httpapi/HttpApi.ts @@ -54,7 +54,7 @@ import { type Pipeable, pipeArguments } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Record from "../../Record.ts" import type * as Schema from "../../Schema.ts" -import type * as AST from "../../SchemaAST.ts" +import type * as SchemaAST from "../../SchemaAST.ts" import type { Mutable } from "../../Types.ts" import type { PathInput } from "../http/HttpRouter.ts" import * as HttpApiEndpoint from "./HttpApiEndpoint.ts" @@ -322,7 +322,7 @@ export const reflect = ( const extractResponseContent = ( schemas: Array, - getStatus: (ast: AST.AST) => number + getStatus: (ast: SchemaAST.AST) => number ): ReadonlyMap]> => { const map = new Map]>() diff --git a/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts b/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts index 67ed47e3a8..9f26bc28ef 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts @@ -56,9 +56,9 @@ import { type Pipeable, pipeArguments } from "../../Pipeable.ts" import * as Redacted from "../../Redacted.ts" import * as Result from "../../Result.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Scope from "../../Scope.ts" import * as Stream from "../../Stream.ts" import type { Covariant, NoInfer } from "../../Types.ts" @@ -596,7 +596,7 @@ function buildPayloadDecoders( result.set(contentType, { _tag: encoding._tag, decode, - nullOnEmpty: schemas.some((s) => AST.isNull(AST.toEncoded(s.ast))) + nullOnEmpty: schemas.some((s) => SchemaAST.isNull(SchemaAST.toEncoded(s.ast))) }) } }) @@ -828,8 +828,8 @@ function makeErrorSchema(endpoint: HttpApiEndpoint.AnyWithProps): Schema.Encoder return schemas.length === 1 ? schemas[0] : Schema.Union(schemas) } -function toResponseSchema(getStatus: (ast: AST.AST) => number) { - const cache = new WeakMap() +function toResponseSchema(getStatus: (ast: SchemaAST.AST) => number) { + const cache = new WeakMap() return (schema: Schema.Top): Schema.Encoder => { const cached = cache.get(schema.ast) @@ -845,9 +845,9 @@ function toResponseSchema(getStatus: (ast: AST.AST) => number) { } function getResponseTransformation( - getStatus: (ast: AST.AST) => number, + getStatus: (ast: SchemaAST.AST) => number, schema: Schema.Top -): Transformation.Transformation { +): SchemaTransformation.Transformation { const ast = schema.ast const encode = getResponseEncode( getStatus(ast), @@ -855,8 +855,8 @@ function getResponseTransformation( HttpApiSchema.isNoContent(ast) ) - return Transformation.transformOrFail({ - decode: (res) => Effect.fail(new Issue.Forbidden(Option.some(res), { message: "Encode only schema" })), + return SchemaTransformation.transformOrFail({ + decode: (res) => Effect.fail(new SchemaIssue.Forbidden(Option.some(res), { message: "Encode only schema" })), encode }) } @@ -865,7 +865,7 @@ function getResponseEncode( status: number, encoding: HttpApiSchema.ResponseEncoding, isNoContent: boolean -): (e: E) => Effect.Effect { +): (e: E) => Effect.Effect { switch (encoding._tag) { case "Json": { return ((e) => { @@ -876,7 +876,7 @@ function getResponseEncode( const s = JSON.stringify(e) return Effect.succeed(Response.text(s, { status, contentType: encoding.contentType })) } catch (error) { - return Effect.fail(new Issue.InvalidValue(Option.some(e), { message: globalThis.String(error) })) + return Effect.fail(new SchemaIssue.InvalidValue(Option.some(e), { message: globalThis.String(error) })) } }) } diff --git a/packages/effect/src/unstable/httpapi/HttpApiClient.ts b/packages/effect/src/unstable/httpapi/HttpApiClient.ts index f038843ea8..479a132382 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiClient.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiClient.ts @@ -42,9 +42,9 @@ import { identity } from "../../Function.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import type { Simplify } from "../../Types.ts" import * as UndefinedOr from "../../UndefinedOr.ts" import * as HttpBody from "../http/HttpBody.ts" @@ -679,7 +679,7 @@ const ArrayBuffer = Schema.instanceOf(globalThis.ArrayBuffer, { const Uint8ArrayFromArrayBuffer = ArrayBuffer.pipe( Schema.decodeTo( Schema.Uint8Array as Schema.instanceOf>, - Transformation.transform({ + SchemaTransformation.transform({ decode(fromA) { return new Uint8Array(fromA) }, @@ -696,7 +696,7 @@ const Uint8ArrayFromArrayBuffer = ArrayBuffer.pipe( const StringFromArrayBuffer = ArrayBuffer.pipe( Schema.decodeTo( Schema.String, - Transformation.transform({ + SchemaTransformation.transform({ decode(fromA) { return new TextDecoder().decode(fromA) }, @@ -716,7 +716,7 @@ const UnknownFromArrayBuffer = StringFromArrayBuffer.pipe(Schema.decodeTo( // Handle No Content Schema.Literal("").pipe(Schema.decodeTo( Schema.Undefined, - Transformation.transform({ + SchemaTransformation.transform({ decode: () => undefined, encode: () => "" }) @@ -733,11 +733,11 @@ function toCodecArrayBuffer(schemas: readonly [Schema.Top, ...Array] switch (encoding._tag) { case "Json": { // handle json codecs that transform void schemas to null - const encodedIsNull = AST.isNull(AST.toEncoded(schema.ast)) + const encodedIsNull = SchemaAST.isNull(SchemaAST.toEncoded(schema.ast)) return UnknownFromArrayBuffer.pipe(Schema.decodeTo( schema, encodedIsNull ? - Transformation.transform({ + SchemaTransformation.transform({ decode: (a) => a === undefined ? null : a, encode: (a) => a === null ? undefined : a }) as any : @@ -776,7 +776,7 @@ function getEncodePayloadSchema( return Schema.Union(schemas.map((s) => getEncodePayloadSchemaFromBody(s, method))) } -const bodyFromPayloadCache = new WeakMap() +const bodyFromPayloadCache = new WeakMap() function getEncodePayloadSchemaFromBody( schema: Schema.Top, @@ -790,40 +790,40 @@ function getEncodePayloadSchemaFromBody( const encoding = HttpApiSchema.getPayloadEncoding(ast, method) const out = $HttpBody.pipe(Schema.decodeTo( schema, - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode(httpBody) { - return Effect.fail(new Issue.Forbidden(Option.some(httpBody), { message: "Encode only schema" })) + return Effect.fail(new SchemaIssue.Forbidden(Option.some(httpBody), { message: "Encode only schema" })) }, encode(t) { switch (encoding._tag) { case "Multipart": - return Effect.fail(new Issue.Forbidden(Option.some(t), { message: "Payload must be a FormData" })) + return Effect.fail(new SchemaIssue.Forbidden(Option.some(t), { message: "Payload must be a FormData" })) case "Json": { try { const body = JSON.stringify(t) return Effect.succeed(HttpBody.text(body, encoding.contentType)) } catch (error) { - return Effect.fail(new Issue.InvalidValue(Option.some(t), { message: globalThis.String(error) })) + return Effect.fail(new SchemaIssue.InvalidValue(Option.some(t), { message: globalThis.String(error) })) } } case "Text": { if (typeof t !== "string") { return Effect.fail( - new Issue.InvalidValue(Option.some(t), { message: "Expected a string" }) + new SchemaIssue.InvalidValue(Option.some(t), { message: "Expected a string" }) ) } return Effect.succeed(HttpBody.text(t, encoding.contentType)) } case "FormUrlEncoded": { if (!Predicate.isObject(t)) { - return Effect.fail(new Issue.InvalidValue(Option.some(t), { message: "Expected a record" })) + return Effect.fail(new SchemaIssue.InvalidValue(Option.some(t), { message: "Expected a record" })) } return Effect.succeed(HttpBody.urlParams(UrlParams.fromInput(t as any))) } case "Uint8Array": { if (!(t instanceof Uint8Array)) { return Effect.fail( - new Issue.InvalidValue(Option.some(t), { message: "Expected a Uint8Array" }) + new SchemaIssue.InvalidValue(Option.some(t), { message: "Expected a Uint8Array" }) ) } return Effect.succeed(HttpBody.uint8Array(t, encoding.contentType)) diff --git a/packages/effect/src/unstable/httpapi/HttpApiSchema.ts b/packages/effect/src/unstable/httpapi/HttpApiSchema.ts index e272c85d3c..b8010a7b02 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiSchema.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiSchema.ts @@ -43,8 +43,8 @@ */ import { constVoid, type LazyArg } from "../../Function.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import { hasBody, type HttpMethod } from "../http/HttpMethod.ts" import type * as Multipart_ from "../http/Multipart.ts" @@ -274,7 +274,7 @@ export function asNoContent(options: { return Schema.Void.pipe( Schema.decodeTo( Schema.toType(self), - Transformation.transform({ + SchemaTransformation.transform({ decode: options.decode, encode: constVoid }) @@ -472,18 +472,18 @@ export function asUint8Array(options?: { * @category predicates * @since 4.0.0 */ -export const isNoContent = (ast: AST.AST): boolean => { - if (AST.isVoid(ast)) return true - const encoded = AST.toEncoded(ast) - if (AST.isVoid(encoded)) return true +export const isNoContent = (ast: SchemaAST.AST): boolean => { + if (SchemaAST.isVoid(ast)) return true + const encoded = SchemaAST.toEncoded(ast) + if (SchemaAST.isVoid(encoded)) return true const target = ast.encoding?.[0].to if (target === undefined) return false - return AST.isVoid(target) + return SchemaAST.isVoid(target) } -const resolveHttpApiEncoding = AST.resolveAt("~httpApiEncoding") +const resolveHttpApiEncoding = SchemaAST.resolveAt("~httpApiEncoding") -const resolveHttpApiStatus = AST.resolveAt("httpApiStatus") +const resolveHttpApiStatus = SchemaAST.resolveAt("httpApiStatus") const defaultJsonEncoding: Encoding = { _tag: "Json", @@ -494,19 +494,19 @@ const defaultUrlEncodedEncoding: Encoding = { contentType: "application/x-www-form-urlencoded" } -function getEncoding(ast: AST.AST): Encoding { +function getEncoding(ast: SchemaAST.AST): Encoding { return resolveHttpApiEncoding(ast) ?? defaultJsonEncoding } /** @internal */ -export function getPayloadEncoding(ast: AST.AST, method: HttpMethod): PayloadEncoding { +export function getPayloadEncoding(ast: SchemaAST.AST, method: HttpMethod): PayloadEncoding { const encoding = resolveHttpApiEncoding(ast) if (encoding) return encoding return hasBody(method) ? defaultJsonEncoding : defaultUrlEncodedEncoding } /** @internal */ -export function getResponseEncoding(ast: AST.AST): ResponseEncoding { +export function getResponseEncoding(ast: SchemaAST.AST): ResponseEncoding { const out = getEncoding(ast) if (out._tag === "Multipart") { throw new Error("Multipart is not supported in response") @@ -515,11 +515,11 @@ export function getResponseEncoding(ast: AST.AST): ResponseEncoding { } /** @internal */ -export function getStatusSuccess(self: AST.AST): number { +export function getStatusSuccess(self: SchemaAST.AST): number { return resolveHttpApiStatus(self) ?? 200 } /** @internal */ -export function getStatusError(self: AST.AST): number { +export function getStatusError(self: SchemaAST.AST): number { return resolveHttpApiStatus(self) ?? 500 } diff --git a/packages/effect/src/unstable/httpapi/OpenApi.ts b/packages/effect/src/unstable/httpapi/OpenApi.ts index 7e826db892..8e208e90da 100644 --- a/packages/effect/src/unstable/httpapi/OpenApi.ts +++ b/packages/effect/src/unstable/httpapi/OpenApi.ts @@ -51,7 +51,7 @@ import { escapeToken } from "../../JsonPointer.ts" import * as JsonSchema from "../../JsonSchema.ts" import * as Option from "../../Option.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import * as SchemaRepresentation from "../../SchemaRepresentation.ts" import * as HttpMethod from "../http/HttpMethod.ts" import * as HttpApi from "./HttpApi.ts" @@ -305,11 +305,11 @@ export function fromApi( const pathOps: Array< { readonly _tag: "schema" - readonly ast: AST.AST + readonly ast: SchemaAST.AST readonly path: ReadonlyArray } | { readonly _tag: "parameter" - readonly ast: AST.AST + readonly ast: SchemaAST.AST readonly path: ReadonlyArray } > = [] @@ -383,8 +383,8 @@ export function fromApi( const filtered = schemas.filter((s) => !HttpApiSchema.isNoContent(s.ast)) if (filtered.length === 0) return hasContent = true - const asts = filtered.map(AST.getAST) - const ast = asts.length === 1 ? asts[0] : new AST.Union(asts, "anyOf") + const asts = filtered.map(SchemaAST.getAST) + const ast = asts.length === 1 ? asts[0] : new SchemaAST.Union(asts, "anyOf") pathOps.push({ _tag: "schema", ast: toEncodingAST(ast, encoding._tag), @@ -409,8 +409,8 @@ export function fromApi( if (content !== undefined) { content.forEach((map, encoding) => { map.forEach((schemas, contentType) => { - const asts = Array.from(schemas, AST.getAST) - const ast = asts.length === 1 ? asts[0] : new AST.Union(asts, "anyOf") + const asts = Array.from(schemas, SchemaAST.getAST) + const ast = asts.length === 1 ? asts[0] : new SchemaAST.Union(asts, "anyOf") pathOps.push({ _tag: "schema", @@ -429,14 +429,14 @@ export function fromApi( function processParameters(schema: Schema.Top | undefined, i: OpenAPISpecParameter["in"]) { if (schema) { - const ast = AST.getLastEncoding(schema.ast) - if (AST.isObjects(ast)) { + const ast = SchemaAST.getLastEncoding(schema.ast) + if (SchemaAST.isObjects(ast)) { for (const ps of ast.propertySignatures) { op.parameters.push({ name: String(ps.name), in: i, schema: {}, - required: i === "path" || !AST.isOptional(ps.type) + required: i === "path" || !SchemaAST.isOptional(ps.type) }) pathOps.push({ _tag: "parameter", @@ -528,7 +528,7 @@ export function fromApi( processAnnotation(api.annotations, HttpApi.AdditionalSchemas, (componentSchemas) => { componentSchemas.forEach((componentSchema) => { - const identifier = AST.resolveIdentifier(componentSchema.ast) + const identifier = SchemaAST.resolveIdentifier(componentSchema.ast) if (identifier !== undefined) { if (identifier in spec.components.schemas) { throw new globalThis.Error(`Duplicate component schema identifier: ${identifier}`) @@ -603,8 +603,8 @@ type ResponseBodies = Map< function extractResponseBodies( schemas: Array, - getStatus: (ast: AST.AST) => number, - getDescription: (ast: AST.AST) => string | undefined + getStatus: (ast: SchemaAST.AST) => number, + getDescription: (ast: SchemaAST.AST) => string | undefined ): ResponseBodies { const map = new Map @@ -671,8 +671,8 @@ function extractResponseBodies( } } -function resolveDescriptionOrIdentifier(ast: AST.AST): string | undefined { - return AST.resolveDescription(ast) ?? AST.resolveIdentifier(ast) +function resolveDescriptionOrIdentifier(ast: SchemaAST.AST): string | undefined { + return SchemaAST.resolveDescription(ast) ?? SchemaAST.resolveIdentifier(ast) } type Content = Map< @@ -687,7 +687,7 @@ const Uint8ArrayEncoding = Schema.String.annotate({ format: "binary" }) -function toEncodingAST(ast: AST.AST, _tag: HttpApiSchema.Encoding["_tag"]): AST.AST { +function toEncodingAST(ast: SchemaAST.AST, _tag: HttpApiSchema.Encoding["_tag"]): SchemaAST.AST { switch (_tag) { case "Uint8Array": return Uint8ArrayEncoding.ast @@ -701,9 +701,9 @@ function toEncodingAST(ast: AST.AST, _tag: HttpApiSchema.Encoding["_tag"]): AST. } } -function persistedFileToBinaryEncoding(ast: AST.AST): AST.AST { +function persistedFileToBinaryEncoding(ast: SchemaAST.AST): SchemaAST.AST { if ( - AST.isDeclaration(ast) && + SchemaAST.isDeclaration(ast) && ((ast.annotations as (Schema.Annotations.Declaration | undefined))?.typeConstructor?._tag === "effect/http/PersistedFile") ) { diff --git a/packages/effect/src/unstable/rpc/RpcSchema.ts b/packages/effect/src/unstable/rpc/RpcSchema.ts index 2a0aa7ff75..193c2270b1 100644 --- a/packages/effect/src/unstable/rpc/RpcSchema.ts +++ b/packages/effect/src/unstable/rpc/RpcSchema.ts @@ -39,7 +39,7 @@ import { constUndefined } from "../../Function.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import type * as AST from "../../SchemaAST.ts" +import type * as SchemaAST from "../../SchemaAST.ts" import * as Stream_ from "../../Stream.ts" const StreamSchemaTypeId = "~effect/rpc/RpcSchema/StreamSchema" @@ -81,7 +81,7 @@ export interface Stream extends Stream_.Stream, A["DecodingServices"] | E["DecodingServices"], A["EncodingServices"] | E["EncodingServices"], - AST.Declaration, + SchemaAST.Declaration, Stream > { diff --git a/packages/effect/src/unstable/schema/Model.ts b/packages/effect/src/unstable/schema/Model.ts index 4f9093e5d2..b71ae18b6f 100644 --- a/packages/effect/src/unstable/schema/Model.ts +++ b/packages/effect/src/unstable/schema/Model.ts @@ -26,8 +26,8 @@ import * as Effect from "../../Effect.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as Getter from "../../SchemaGetter.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaGetter from "../../SchemaGetter.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as VariantSchema from "./VariantSchema.ts" const { @@ -304,7 +304,7 @@ export const optionalOption = (schema: S): optionalOption< Schema.optionalKey(Schema.NullOr(schema)).pipe( Schema.decodeTo( Schema.Option(Schema.toType(schema)), - Transformation.transformOptional, S["Type"] | null>({ + SchemaTransformation.transformOptional, S["Type"] | null>({ decode: (oe) => oe.pipe(Option.filter(Predicate.isNotNull), Option.some), encode: Option.flatten }) as any @@ -415,8 +415,8 @@ export interface Date extends Schema.decodeTo, S */ export const Date: Date = Schema.String.pipe( Schema.decodeTo(Schema.DateTimeUtc, { - decode: Getter.dateTimeUtcFromInput().map(DateTime.removeTime), - encode: Getter.transform(DateTime.formatIsoDate) + decode: SchemaGetter.dateTimeUtcFromInput().map(DateTime.removeTime), + encode: SchemaGetter.transform(DateTime.formatIsoDate) }) ) diff --git a/packages/effect/src/unstable/schema/VariantSchema.ts b/packages/effect/src/unstable/schema/VariantSchema.ts index d9e42163d8..02cf722e3f 100644 --- a/packages/effect/src/unstable/schema/VariantSchema.ts +++ b/packages/effect/src/unstable/schema/VariantSchema.ts @@ -26,7 +26,7 @@ import { dual } from "../../Function.ts" import { type Pipeable, pipeArguments } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import type * as AST from "../../SchemaAST.ts" +import type * as SchemaAST from "../../SchemaAST.ts" import * as Struct_ from "../../Struct.ts" /** @@ -279,7 +279,7 @@ export interface Class< S["Encoded"], S["DecodingServices"], S["EncodingServices"], - AST.Declaration, + SchemaAST.Declaration, Schema.decodeTo, S>, S["~type.make.in"], S["Iso"], diff --git a/packages/effect/src/unstable/workers/Transferable.ts b/packages/effect/src/unstable/workers/Transferable.ts index b8ca78b3d7..24d99361ca 100644 --- a/packages/effect/src/unstable/workers/Transferable.ts +++ b/packages/effect/src/unstable/workers/Transferable.ts @@ -35,7 +35,7 @@ import * as Context from "../../Context.ts" import * as Effect from "../../Effect.ts" import { dual } from "../../Function.ts" import * as Schema from "../../Schema.ts" -import * as Getter from "../../SchemaGetter.ts" +import * as SchemaGetter from "../../SchemaGetter.ts" /** * Service for collecting `Transferable` objects while encoding worker messages @@ -118,8 +118,8 @@ export const addAll = ( */ export const getterAddAll = ( f: (_: A) => Iterable -): Getter.Getter => - Getter.transformOrFail((e: A) => +): SchemaGetter.Getter => + SchemaGetter.transformOrFail((e: A) => Effect.contextWith((services) => { const collector = Context.getOrUndefined(services, Collector) if (!collector) return Effect.succeed(e) @@ -167,15 +167,15 @@ export const schema: { toCodecJson: () => passthroughLink }).pipe( Schema.decode({ - decode: Getter.passthrough(), + decode: SchemaGetter.passthrough(), encode: getterAddAll(f) }) ) ) const passthroughLink = Schema.link()(Schema.Any, { - decode: Getter.passthrough(), - encode: Getter.passthrough() + decode: SchemaGetter.passthrough(), + encode: SchemaGetter.passthrough() }) /** diff --git a/packages/effect/src/unstable/workflow/DurableDeferred.ts b/packages/effect/src/unstable/workflow/DurableDeferred.ts index 8690175833..511367d3fb 100644 --- a/packages/effect/src/unstable/workflow/DurableDeferred.ts +++ b/packages/effect/src/unstable/workflow/DurableDeferred.ts @@ -33,7 +33,7 @@ import * as Filter from "../../Filter.ts" import { dual } from "../../Function.ts" import * as Option from "../../Option.ts" import * as Schema from "../../Schema.ts" -import * as Getter from "../../SchemaGetter.ts" +import * as SchemaGetter from "../../SchemaGetter.ts" import type * as Activity from "./Activity.ts" import * as Workflow from "./Workflow.ts" import type { WorkflowEngine, WorkflowInstance } from "./WorkflowEngine.ts" @@ -370,12 +370,12 @@ export class TokenParsed extends Schema.Class( Schema.Tuple([Schema.String, Schema.String, Schema.String]) ), { - decode: Getter.decodeBase64UrlString(), - encode: Getter.encodeBase64Url() + decode: SchemaGetter.decodeBase64UrlString(), + encode: SchemaGetter.encodeBase64Url() } ), Schema.decodeTo(TokenParsed, { - decode: Getter.transform( + decode: SchemaGetter.transform( ([workflowName, executionId, deferredName]) => new TokenParsed({ workflowName, @@ -383,7 +383,7 @@ export class TokenParsed extends Schema.Class( deferredName }) ), - encode: Getter.transform( + encode: SchemaGetter.transform( (parsed) => [ parsed.workflowName, diff --git a/packages/effect/src/unstable/workflow/Workflow.ts b/packages/effect/src/unstable/workflow/Workflow.ts index a152095eae..fce27804f7 100644 --- a/packages/effect/src/unstable/workflow/Workflow.ts +++ b/packages/effect/src/unstable/workflow/Workflow.ts @@ -36,8 +36,8 @@ import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import type * as Schedule from "../../Schedule.ts" import * as Schema from "../../Schema.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Parser from "../../SchemaParser.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaParser from "../../SchemaParser.ts" import * as Tranformation from "../../SchemaTransformation.ts" import * as Scope from "../../Scope.ts" import type { ExitEncoded } from "../rpc/RpcMessage.ts" @@ -539,15 +539,15 @@ export class Complete extends Data.TaggedClass("Complete")<{ [Schema.Exit(options.success, options.error, Schema.Defect)], ([exit]) => (input, ast, options) => { if (!(isResult(input) && input._tag === "Complete")) { - return Effect.fail(new Issue.InvalidType(ast, Option.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(input))) } return Effect.mapBothEager( - Parser.decodeEffect(exit)(input.exit, options), + SchemaParser.decodeEffect(exit)(input.exit, options), { onSuccess: (exit) => new Complete({ exit }), onFailure: (issue) => - new Issue.Composite(ast, Option.some(input), [ - new Issue.Pointer(["exit"], issue) + new SchemaIssue.Composite(ast, Option.some(input), [ + new SchemaIssue.Pointer(["exit"], issue) ]) } ) From 72a9bc9aad500afed5b0b6bc97bfddbd0ed92f8c Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 09:47:31 +0200 Subject: [PATCH 18/29] Align Schema adapter failures: `Schema` result, promise, and sync adapters now surface `SchemaError`, while `SchemaParser` result, promise, and sync adapters expose `SchemaIssue.Issue`. Mark `SchemaParser` option adapters as internal because their error details are discarded --- .changeset/schema-parser-adapter-errors.md | 5 + packages/effect/src/Schema.ts | 198 +++++++++++++++------ packages/effect/src/SchemaParser.ts | 124 +++---------- packages/effect/test/schema/Schema.test.ts | 75 +++++++- packages/effect/typetest/schema/api.tst.ts | 22 ++- 5 files changed, 259 insertions(+), 165 deletions(-) create mode 100644 .changeset/schema-parser-adapter-errors.md diff --git a/.changeset/schema-parser-adapter-errors.md b/.changeset/schema-parser-adapter-errors.md new file mode 100644 index 0000000000..17aeb89892 --- /dev/null +++ b/.changeset/schema-parser-adapter-errors.md @@ -0,0 +1,5 @@ +--- +"effect": patch +--- + +Align Schema adapter failures: `Schema` result, promise, and sync adapters now surface `SchemaError`, while `SchemaParser` result, promise, and sync adapters expose `SchemaIssue.Issue`. Mark `SchemaParser` option adapters as internal because their error details are discarded. diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index a003b05549..c0873a2dd7 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -1351,7 +1351,8 @@ export const decodeExit: >( * **Details** * * Prefer this over {@link decodeUnknownExit} or {@link decodeUnknownEffect} - * when you don't need error details. For typed input use {@link decodeOption}. + * when you don't need error details. For input already typed as the schema's + * `Encoded` type use {@link decodeOption}. * Options may be provided either when creating the decoder or when applying it; * application options override creation options. * @@ -1367,7 +1368,8 @@ export const decodeUnknownOption = SchemaParser.decodeUnknownOption * * **When to use** * - * Use when typed input should be decoded and only success or failure matters. + * Use when you already have input typed as the schema's `Encoded` type and + * only need to know whether decoding succeeded. * * **Details** * @@ -1382,33 +1384,41 @@ export const decodeOption = SchemaParser.decodeOption /** * Decodes an `unknown` input against a schema, returning a `Result` that - * succeeds with the decoded value or fails with a schema issue. + * succeeds with the decoded value or fails with a {@link SchemaError}. * * **When to use** * * Use when you do not know the input type statically and want decoding to - * return a `Result` with structured issue data. + * return a `Result` with `SchemaError` failure data. * * **Details** * - * For typed input use {@link decodeResult}. + * For input already typed as the schema's `Encoded` type use + * {@link decodeResult}. * Options may be provided either when creating the decoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.decodeUnknownResult} for the adapter that fails with `SchemaIssue.Issue` directly + * * @category decoding * @since 4.0.0 */ -export const decodeUnknownResult = SchemaParser.decodeUnknownResult +export function decodeUnknownResult>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.decodeUnknownResult(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Result_.Result => { + return Result_.mapError(parser(input, options), (issue) => new SchemaError(issue)) + } +} /** * Decodes a typed input (the schema's `Encoded` type) against a schema, * returning a `Result` that succeeds with the decoded value or fails with a - * schema issue. + * {@link SchemaError}. * * **When to use** * - * Use when typed input should be decoded into a `Result` with structured issue - * data. + * Use when you already have input typed as the schema's `Encoded` type and + * want decoding to return a `Result` with `SchemaError` failure data. * * **Details** * @@ -1416,38 +1426,55 @@ export const decodeUnknownResult = SchemaParser.decodeUnknownResult * Options may be provided either when creating the decoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.decodeResult} for the adapter that fails with `SchemaIssue.Issue` directly + * * @category decoding * @since 4.0.0 */ -export const decodeResult = SchemaParser.decodeResult +export const decodeResult: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Result_.Result = + decodeUnknownResult /** * Decodes an `unknown` input against a schema, returning a `Promise` that - * resolves with the decoded value or rejects with a schema issue. + * resolves with the decoded value or rejects with a {@link SchemaError}. * * **When to use** * - * Use when you need to decode unknown input in Promise-based APIs. + * Use when you need decoding of unknown input to return a JavaScript `Promise` + * that rejects with `SchemaError`. * * **Details** * - * For typed input use {@link decodePromise}. + * For input already typed as the schema's `Encoded` type use + * {@link decodePromise}. * Options may be provided either when creating the decoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.decodeUnknownPromise} for the adapter that rejects with `SchemaIssue.Issue` directly + * * @category decoding * @since 3.10.0 */ -export const decodeUnknownPromise = SchemaParser.decodeUnknownPromise +export function decodeUnknownPromise>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = decodeUnknownEffect(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Promise => { + return Effect.runPromise(parser(input, options)) + } +} /** * Decodes a typed input (the schema's `Encoded` type) against a schema, * returning a `Promise` that resolves with the decoded value or rejects with a - * schema issue. + * {@link SchemaError}. * * **When to use** * - * Use when you need to decode typed encoded input in Promise-based APIs. + * Use when you already have input typed as the schema's `Encoded` type and + * need decoding to return a JavaScript `Promise` that rejects with + * `SchemaError`. * * **Details** * @@ -1455,23 +1482,28 @@ export const decodeUnknownPromise = SchemaParser.decodeUnknownPromise * Options may be provided either when creating the decoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.decodePromise} for the adapter that rejects with `SchemaIssue.Issue` directly + * * @category decoding * @since 3.10.0 */ -export const decodePromise = SchemaParser.decodePromise +export const decodePromise: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Promise = decodeUnknownPromise /** * Decodes an `unknown` input against a schema synchronously, returning the - * decoded value or throwing an `Error` whose cause contains the schema issue. + * decoded value or throwing a {@link SchemaError}. * * **When to use** * * Use when you need to validate unknown data at a synchronous boundary and want - * schema mismatches to throw. + * schema mismatches to throw `SchemaError`. * * **Details** * - * For typed input use `decodeSync`. + * For input already typed as the schema's `Encoded` type use `decodeSync`. * Only service-free schemas can be decoded synchronously. For non-throwing * alternatives see `decodeUnknownOption`, `decodeUnknownExit`, or * `decodeUnknownEffect`. Options may be provided either when creating the @@ -1488,26 +1520,32 @@ export const decodePromise = SchemaParser.decodePromise * // Output: 42 * * Schema.decodeUnknownSync(NumberFromString)("not a number") - * // throws Error: NumberFromString + * // throws SchemaError: NumberFromString * // └─ Encoded side transformation failure * // └─ NumberFromString * // └─ Expected a numeric string, actual "not a number" * ``` * + * @see {@link SchemaParser.decodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue` + * * @category decoding * @since 4.0.0 */ -export const decodeUnknownSync = SchemaParser.decodeUnknownSync +export function decodeUnknownSync>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = decodeUnknownEffect(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): S["Type"] => { + return Effect.runSync(parser(input, options) as Effect.Effect) + } +} /** * Decodes a typed input (the schema's `Encoded` type) against a schema - * synchronously, returning the decoded value or throwing an `Error` whose cause - * contains the schema issue. + * synchronously, returning the decoded value or throwing a {@link SchemaError}. * * **When to use** * - * Use when typed input should be decoded synchronously and schema mismatches - * should throw. + * Use when you already have input typed as the schema's `Encoded` type and + * want schema mismatches to throw `SchemaError` synchronously. * * **Details** * @@ -1516,10 +1554,15 @@ export const decodeUnknownSync = SchemaParser.decodeUnknownSync * provided either when creating the decoder or when applying it; application * options override creation options. * + * @see {@link SchemaParser.decodeSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue` + * * @category decoding * @since 4.0.0 */ -export const decodeSync = SchemaParser.decodeSync +export const decodeSync: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => S["Type"] = decodeUnknownSync /** * Encodes an `unknown` input against a schema, returning an `Effect` that @@ -1532,7 +1575,7 @@ export const decodeSync = SchemaParser.decodeSync * * **Details** * - * Prefer {@link encodeEffect} when the input is already typed as the schema's + * Prefer {@link encodeEffect} when the value is already typed as the schema's * `Type`. * Options may be provided either when creating the encoder or when applying it; * application options override creation options. @@ -1605,7 +1648,7 @@ export const encodeEffect: ( * **Details** * * Only usable with schemas that have no `EncodingServices` requirement. Prefer - * {@link encodeExit} when the input is already typed as the schema's `Type`. + * {@link encodeExit} when the value is already typed as the schema's `Type`. * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * @@ -1660,7 +1703,8 @@ export const encodeExit: >( * **Details** * * Prefer this over {@link encodeUnknownExit} or {@link encodeUnknownEffect} - * when you don't need error details. For typed input use {@link encodeOption}. + * when you don't need error details. For values already typed as the schema's + * `Type` use {@link encodeOption}. * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * @@ -1676,7 +1720,8 @@ export const encodeUnknownOption = SchemaParser.encodeUnknownOption * * **When to use** * - * Use when typed input should be encoded and only success or failure matters. + * Use when you already have a value typed as the schema's `Type` and only need + * to know whether encoding succeeded. * * **Details** * @@ -1691,32 +1736,40 @@ export const encodeOption = SchemaParser.encodeOption /** * Encodes an `unknown` input against a schema, returning a `Result` that - * succeeds with the encoded value or fails with a schema issue. + * succeeds with the encoded value or fails with a {@link SchemaError}. * * **When to use** * * Use when you do not know the input type statically and want encoding to - * return a `Result` with structured issue data. + * return a `Result` with `SchemaError` failure data. * * **Details** * - * For typed input use {@link encodeResult}. + * For values already typed as the schema's `Type` use {@link encodeResult}. * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.encodeUnknownResult} for the adapter that fails with `SchemaIssue.Issue` directly + * * @category encoding * @since 4.0.0 */ -export const encodeUnknownResult = SchemaParser.encodeUnknownResult +export function encodeUnknownResult>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.encodeUnknownResult(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Result_.Result => { + return Result_.mapError(parser(input, options), (issue) => new SchemaError(issue)) + } +} /** * Encodes a typed input (the schema's `Type`) against a schema, returning a - * `Result` that succeeds with the encoded value or fails with a schema issue. + * `Result` that succeeds with the encoded value or fails with a + * {@link SchemaError}. * * **When to use** * - * Use when typed input should be encoded into a `Result` with structured issue - * data. + * Use when you already have a value typed as the schema's `Type` and want + * encoding to return a `Result` with `SchemaError` failure data. * * **Details** * @@ -1724,37 +1777,53 @@ export const encodeUnknownResult = SchemaParser.encodeUnknownResult * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.encodeResult} for the adapter that fails with `SchemaIssue.Issue` directly + * * @category encoding * @since 4.0.0 */ -export const encodeResult = SchemaParser.encodeResult +export const encodeResult: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Result_.Result = + encodeUnknownResult /** * Encodes an `unknown` input against a schema, returning a `Promise` that - * resolves with the encoded value or rejects with a schema issue. + * resolves with the encoded value or rejects with a {@link SchemaError}. * * **When to use** * - * Use when you need to encode unknown input in Promise-based APIs. + * Use when you need encoding of unknown input to return a JavaScript `Promise` + * that rejects with `SchemaError`. * * **Details** * - * For typed input use {@link encodePromise}. + * For values already typed as the schema's `Type` use {@link encodePromise}. * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.encodeUnknownPromise} for the adapter that rejects with `SchemaIssue.Issue` directly + * * @category encoding * @since 3.10.0 */ -export const encodeUnknownPromise = SchemaParser.encodeUnknownPromise +export function encodeUnknownPromise>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = encodeUnknownEffect(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Promise => { + return Effect.runPromise(parser(input, options)) + } +} /** * Encodes a typed input (the schema's `Type`) against a schema, returning a - * `Promise` that resolves with the encoded value or rejects with a schema issue. + * `Promise` that resolves with the encoded value or rejects with a + * {@link SchemaError}. * * **When to use** * - * Use when you need to encode typed schema values in Promise-based APIs. + * Use when you already have a value typed as the schema's `Type` and need + * encoding to return a JavaScript `Promise` that rejects with `SchemaError`. * * **Details** * @@ -1762,41 +1831,53 @@ export const encodeUnknownPromise = SchemaParser.encodeUnknownPromise * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.encodePromise} for the adapter that rejects with `SchemaIssue.Issue` directly + * * @category encoding * @since 3.10.0 */ -export const encodePromise = SchemaParser.encodePromise +export const encodePromise: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Promise = encodeUnknownPromise /** - * Encodes an `unknown` input against a schema synchronously, throwing an `Error` - * whose cause contains the schema issue on failure. + * Encodes an `unknown` input against a schema synchronously, throwing a + * {@link SchemaError} on failure. * * **When to use** * * Use when you need to serialize unknown data at a synchronous boundary and - * want schema mismatches to throw. + * want schema mismatches to throw `SchemaError`. * * **Details** * * For non-throwing alternatives see {@link encodeUnknownOption}, - * {@link encodeUnknownExit}, or {@link encodeUnknownEffect}. For typed input - * use {@link encodeSync}. + * {@link encodeUnknownExit}, or {@link encodeUnknownEffect}. For values + * already typed as the schema's `Type` use {@link encodeSync}. * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.encodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue` + * * @category encoding * @since 4.0.0 */ -export const encodeUnknownSync = SchemaParser.encodeUnknownSync +export function encodeUnknownSync>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = encodeUnknownEffect(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): S["Encoded"] => { + return Effect.runSync(parser(input, options) as Effect.Effect) + } +} /** * Encodes a typed input (the schema's `Type`) against a schema synchronously, - * throwing an `Error` whose cause contains the schema issue on failure. + * throwing a {@link SchemaError} on failure. * * **When to use** * - * Use when typed input should be encoded synchronously and schema mismatches - * should throw. + * Use when you already have a value typed as the schema's `Type` and want + * schema mismatches to throw `SchemaError` synchronously. * * **Details** * @@ -1804,10 +1885,15 @@ export const encodeUnknownSync = SchemaParser.encodeUnknownSync * Options may be provided either when creating the encoder or when applying it; * application options override creation options. * + * @see {@link SchemaParser.encodeSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue` + * * @category encoding * @since 4.0.0 */ -export const encodeSync = SchemaParser.encodeSync +export const encodeSync: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => S["Encoded"] = encodeUnknownSync /** * Creates a schema from an AST (Abstract Syntax Tree) node. diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaParser.ts index f3db904e5a..26777dcdd6 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaParser.ts @@ -297,8 +297,8 @@ export const decodeEffect: ( * * **When to use** * - * Use when decoding untyped input with a service-free schema at a JavaScript - * `Promise` boundary. + * Use when you need to decode untyped input with a service-free schema and + * return a JavaScript `Promise` that rejects with `SchemaIssue.Issue`. * * **Details** * @@ -325,14 +325,14 @@ export function decodeUnknownPromise>( * **When to use** * * Use when you already have input typed as the schema's `Encoded` type and need - * a native `Promise` boundary. + * decoding to return a JavaScript `Promise` that rejects with `SchemaIssue.Issue`. * * **Details** * * The returned function resolves with the decoded `Type` on success and rejects * with a `SchemaIssue.Issue` on decoding failure. * - * @see {@link decodeUnknownPromise} for untyped input at a `Promise` boundary + * @see {@link decodeUnknownPromise} for untyped input returning a JavaScript `Promise` * @see {@link decodeEffect} for preserving decoding services and failures in `Effect` * * @category decoding @@ -367,7 +367,6 @@ export function decodePromise>( * * @see {@link decodeExit} for input already typed as the schema's `Encoded` type * @see {@link decodeUnknownEffect} for preserving decoding services and failures in `Effect` - * @see {@link decodeUnknownOption} for discarding issue details * @see {@link decodeUnknownResult} for returning schema issues as data * @see {@link decodeUnknownSync} for throwing on decoding failure * @@ -407,26 +406,7 @@ export const decodeExit: >( ) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Exit.Exit = decodeUnknownExit -/** - * Creates a decoder for `unknown` input that returns an `Option` safely. - * - * **When to use** - * - * Use when decoding unknown input and you want a synchronous `Option` result - * that keeps the decoded value on success but discards issue details on - * failure. - * - * **Details** - * - * The returned function produces `Option.some` with the decoded `Type` on success - * or `Option.none` on failure, discarding issue details. - * - * @see {@link decodeOption} for input already typed as the schema's `Encoded` type - * @see {@link decodeUnknownResult} for retaining schema issues as data - * - * @category decoding - * @since 3.10.0 - */ +/** @internal */ export function decodeUnknownOption>( schema: S, options?: SchemaAST.ParseOptions @@ -434,26 +414,7 @@ export function decodeUnknownOption>( return asOption(decodeUnknownEffect(schema, options)) } -/** - * Creates a decoder safely for input already typed as the schema's `Encoded` type, - * returning an `Option`. - * - * **When to use** - * - * Use when you already have input typed as the schema's `Encoded` type and only - * need to know whether decoding succeeds. - * - * **Details** - * - * The returned function produces `Option.some` with the decoded `Type` on success - * or `Option.none` on failure, discarding issue details. - * - * @see {@link decodeUnknownOption} for untyped input with the same yes/no result shape - * @see {@link decodeResult} for retaining schema issues as data - * - * @category decoding - * @since 3.10.0 - */ +/** @internal */ export const decodeOption: >( schema: S, options?: SchemaAST.ParseOptions @@ -465,8 +426,8 @@ export const decodeOption: >( * * **When to use** * - * Use when decoding untyped boundary input and you want schema issues returned - * as data in a `Result`. + * Use when decoding untyped boundary input and you want `SchemaIssue.Issue` + * failures returned as data in a `Result`. * * **Details** * @@ -498,7 +459,7 @@ export function decodeUnknownResult>( * **When to use** * * Use when you already have input typed as the schema's `Encoded` type and want - * schema decoding failures represented as `Result.fail`. + * schema decoding failures represented as `Result.fail` with `SchemaIssue.Issue`. * * **Details** * @@ -528,7 +489,7 @@ export const decodeResult: >( * **When to use** * * Use to decode untrusted or dynamically typed input at a synchronous boundary - * where invalid data should be reported by throwing. + * where invalid data should throw an `Error` whose cause is `SchemaIssue.Issue`. * * **Details** * @@ -556,7 +517,7 @@ export function decodeUnknownSync>( * **When to use** * * Use to decode values already typed as the schema's `Encoded` input when - * decoding failure should be reported by throwing an `Error`. + * decoding failure should throw an `Error` whose cause is `SchemaIssue.Issue`. * * **Details** * @@ -643,8 +604,9 @@ export const encodeEffect: ( * * **When to use** * - * Use to encode untrusted or dynamically typed values at a `Promise` boundary - * when the schema has no encoding service requirements. + * Use when you need to encode untrusted or dynamically typed values with a + * service-free schema and return a JavaScript `Promise` that rejects with + * `SchemaIssue.Issue`. * * **Details** * @@ -669,9 +631,9 @@ export const encodeUnknownPromise = >( * * **When to use** * - * Use when you need a `Promise`-returning encoder for values already typed as - * the schema's decoded `Type`, such as at a JavaScript `Promise` interop - * boundary. + * Use when you already have values typed as the schema's decoded `Type` and + * need encoding to return a JavaScript `Promise` that rejects with + * `SchemaIssue.Issue`. * * **Details** * @@ -742,25 +704,7 @@ export const encodeExit: >( ) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Exit.Exit = encodeUnknownExit -/** - * Creates an encoder for `unknown` input that returns an `Option` safely. - * - * **When to use** - * - * Use when encoding untyped input and you want a synchronous `Option` result - * that keeps the encoded value on success but discards issue details on failure. - * - * **Details** - * - * The returned function produces `Option.some` with the schema's `Encoded` value - * on success or `Option.none` on failure, discarding issue details. - * - * @see {@link encodeOption} for input already typed as the schema's decoded `Type` - * @see {@link encodeUnknownResult} for retaining schema issues as data - * - * @category encoding - * @since 3.10.0 - */ +/** @internal */ export function encodeUnknownOption>( schema: S, options?: SchemaAST.ParseOptions @@ -768,26 +712,7 @@ export function encodeUnknownOption>( return asOption(encodeUnknownEffect(schema, options)) } -/** - * Creates an encoder safely for input already typed as the schema's decoded `Type`, - * returning an `Option`. - * - * **When to use** - * - * Use when encoding values that are already typed as the schema's decoded - * `Type` and an `Option` result is the desired success/failure boundary. - * - * **Details** - * - * The returned function produces `Option.some` with the schema's `Encoded` value - * on success or `Option.none` on failure, discarding issue details. - * - * @see {@link encodeUnknownOption} for untyped input with the same yes/no result shape - * @see {@link encodeResult} for retaining schema issues as data - * - * @category encoding - * @since 3.10.0 - */ +/** @internal */ export const encodeOption: >( schema: S, options?: SchemaAST.ParseOptions @@ -800,7 +725,8 @@ export const encodeOption: >( * **When to use** * * Use when encoding values from an unknown or dynamically typed boundary - * synchronously, and you want schema issues returned as `Result` data. + * synchronously, and you want `SchemaIssue.Issue` failures returned as `Result` + * data. * * **Details** * @@ -828,8 +754,7 @@ export function encodeUnknownResult>( * **When to use** * * Use when you already have input typed as the schema's decoded `Type` and want - * encoding failures returned as a `Result` instead of thrown or run in - * `Effect`. + * encoding failures returned as `Result.fail` with `SchemaIssue.Issue`. * * **Details** * @@ -854,7 +779,7 @@ export const encodeResult: >( * **When to use** * * Use when you need to encode values from untyped input in synchronous code and - * want encoding failures to throw. + * want encoding failures to throw an `Error` whose cause is `SchemaIssue.Issue`. * * **Details** * @@ -881,7 +806,7 @@ export function encodeUnknownSync>( * **When to use** * * Use to encode already typed schema values synchronously when encoding failure - * should be reported by throwing an `Error`. + * should throw an `Error` whose cause is `SchemaIssue.Issue`. * * **Details** * @@ -889,7 +814,6 @@ export function encodeUnknownSync>( * an `Error` with the `SchemaIssue.Issue` in its `cause` on encoding failure. * * @see {@link encodeUnknownSync} for unknown input with the same throwing boundary - * @see {@link encodeOption} for discarding failure details * @see {@link encodeResult} for returning schema issues as data * @see {@link encodeEffect} for effectful encoding that preserves service requirements * diff --git a/packages/effect/test/schema/Schema.test.ts b/packages/effect/test/schema/Schema.test.ts index dbb58a5e70..8abc821d03 100644 --- a/packages/effect/test/schema/Schema.test.ts +++ b/packages/effect/test/schema/Schema.test.ts @@ -6756,18 +6756,34 @@ Expected a value with a size of at most 2, got Map([["a",1],["b",NaN],["c",3]])` const schema = Schema.FiniteFromString const decodeUnknownPromise = Schema.decodeUnknownPromise(schema) const encodeUnknownPromise = Schema.encodeUnknownPromise(schema) + const decodeUnknownPromiseIssue = SchemaParser.decodeUnknownPromise(schema) + const encodeUnknownPromiseIssue = SchemaParser.encodeUnknownPromise(schema) - const r1 = await decodeUnknownPromise("1").then(Result.succeed, (e) => Result.fail(e.toString())) + const r1 = await decodeUnknownPromise("1").then(Result.succeed, Result.fail) deepStrictEqual(r1, Result.succeed(1)) - const r2 = await decodeUnknownPromise(null).then(Result.succeed, (e) => Result.fail(e.toString())) - deepStrictEqual(r2, Result.fail("Expected string, got null")) + const r2 = await decodeUnknownPromise(null).then(Result.succeed, Result.fail) + assertTrue(Result.isFailure(r2)) + assertTrue(Schema.isSchemaError(r2.failure)) + strictEqual(r2.failure.message, "Expected string, got null") - const r3 = await encodeUnknownPromise(1).then(Result.succeed, (e) => Result.fail(e.toString())) + const r3 = await encodeUnknownPromise(1).then(Result.succeed, Result.fail) deepStrictEqual(r3, Result.succeed("1")) - const r4 = await encodeUnknownPromise(null).then(Result.succeed, (e) => Result.fail(e.toString())) - deepStrictEqual(r4, Result.fail("Expected number, got null")) + const r4 = await encodeUnknownPromise(null).then(Result.succeed, Result.fail) + assertTrue(Result.isFailure(r4)) + assertTrue(Schema.isSchemaError(r4.failure)) + strictEqual(r4.failure.message, "Expected number, got null") + + const r5 = await decodeUnknownPromiseIssue(null).then(Result.succeed, Result.fail) + assertTrue(Result.isFailure(r5)) + assertTrue(SchemaIssue.isIssue(r5.failure)) + strictEqual(r5.failure.toString(), "Expected string, got null") + + const r6 = await encodeUnknownPromiseIssue(null).then(Result.succeed, Result.fail) + assertTrue(Result.isFailure(r6)) + assertTrue(SchemaIssue.isIssue(r6.failure)) + strictEqual(r6.failure.toString(), "Expected number, got null") }) }) @@ -6783,7 +6799,8 @@ Expected a value with a size of at most 2, got Map([["a",1],["b",NaN],["c",3]])` const r2 = decodeUnknownResult(null) assertTrue(Result.isFailure(r2)) - strictEqual(r2.failure.toString(), "Expected string, got null") + assertTrue(Schema.isSchemaError(r2.failure)) + strictEqual(r2.failure.message, "Expected string, got null") const r3 = encodeUnknownResult(1) assertTrue(Result.isSuccess(r3)) @@ -6791,7 +6808,49 @@ Expected a value with a size of at most 2, got Map([["a",1],["b",NaN],["c",3]])` const r4 = encodeUnknownResult(null) assertTrue(Result.isFailure(r4)) - strictEqual(r4.failure.toString(), "Expected number, got null") + assertTrue(Schema.isSchemaError(r4.failure)) + strictEqual(r4.failure.message, "Expected number, got null") + + const r5 = SchemaParser.decodeUnknownResult(schema)(null) + assertTrue(Result.isFailure(r5)) + assertTrue(SchemaIssue.isIssue(r5.failure)) + strictEqual(r5.failure.toString(), "Expected string, got null") + + const r6 = SchemaParser.encodeUnknownResult(schema)(null) + assertTrue(Result.isFailure(r6)) + assertTrue(SchemaIssue.isIssue(r6.failure)) + strictEqual(r6.failure.toString(), "Expected number, got null") + }) + }) + + describe("decodeUnknownSync / encodeUnknownSync", () => { + it("FiniteFromString", () => { + const schema = Schema.FiniteFromString + + strictEqual(Schema.decodeUnknownSync(schema)("1"), 1) + strictEqual(Schema.encodeUnknownSync(schema)(1), "1") + + throws(() => Schema.decodeUnknownSync(schema)(null), (e) => { + assertTrue(Schema.isSchemaError(e)) + strictEqual(e.message, "Expected string, got null") + }) + + throws(() => Schema.encodeUnknownSync(schema)(null), (e) => { + assertTrue(Schema.isSchemaError(e)) + strictEqual(e.message, "Expected number, got null") + }) + + throws(() => SchemaParser.decodeUnknownSync(schema)(null), (e) => { + ok(e instanceof Error) + assertTrue(SchemaIssue.isIssue(e.cause)) + strictEqual(e.cause.toString(), "Expected string, got null") + }) + + throws(() => SchemaParser.encodeUnknownSync(schema)(null), (e) => { + ok(e instanceof Error) + assertTrue(SchemaIssue.isIssue(e.cause)) + strictEqual(e.cause.toString(), "Expected number, got null") + }) }) }) diff --git a/packages/effect/typetest/schema/api.tst.ts b/packages/effect/typetest/schema/api.tst.ts index 680150c5e2..f215f2a0f8 100644 --- a/packages/effect/typetest/schema/api.tst.ts +++ b/packages/effect/typetest/schema/api.tst.ts @@ -1,5 +1,5 @@ import { hole, Schema } from "effect" -import type { Effect, Exit, Option } from "effect" +import type { Effect, Exit, Option, Result } from "effect" import { describe, expect, it } from "tstyche" describe("decoding / encoding API", () => { @@ -173,6 +173,16 @@ describe("decoding / encoding API", () => { })("a")({ a: "1" }) expect(decodeExit).type.toBe>() + const decodeUnknownResult = ((key: K) => { + return Schema.decodeUnknownResult(schemas[key]) + })("a")({ a: "1" }) + expect(decodeUnknownResult).type.toBe>() + + const decodeResult = ((key: K) => { + return Schema.decodeResult(schemas[key]) + })("a")({ a: "1" }) + expect(decodeResult).type.toBe>() + const decodeUnknownOption = ((key: K) => { return Schema.decodeUnknownOption(schemas[key]) })("a")({ a: "1" }) @@ -223,6 +233,16 @@ describe("decoding / encoding API", () => { })("a")({ a: 1 }) expect(encodeExit).type.toBe>() + const encodeUnknownResult = ((key: K) => { + return Schema.encodeUnknownResult(schemas[key]) + })("a")({ a: 1 }) + expect(encodeUnknownResult).type.toBe>() + + const encodeResult = ((key: K) => { + return Schema.encodeResult(schemas[key]) + })("a")({ a: 1 }) + expect(encodeResult).type.toBe>() + const encodeUnknownOption = ((key: K) => { return Schema.encodeUnknownOption(schemas[key]) })("a")({ a: 1 }) From 1a9d2e985447b5cffc468e70526ae8cb3d9e63e8 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 15:16:18 +0200 Subject: [PATCH 19/29] wip --- packages/ai/openai-compat/src/OpenAiClient.ts | 4 +- packages/ai/openai/src/OpenAiClient.ts | 4 +- .../ai/openrouter/src/OpenRouterClient.ts | 4 +- packages/effect/src/Array.ts | 3 +- packages/effect/src/BigDecimal.ts | 12 +- packages/effect/src/BigInt.ts | 2 +- packages/effect/src/Cause.ts | 16 +- packages/effect/src/Config.ts | 2 +- packages/effect/src/ConfigProvider.ts | 18 +-- packages/effect/src/Console.ts | 4 +- packages/effect/src/Context.ts | 10 +- packages/effect/src/Effect.ts | 4 +- packages/effect/src/Exit.ts | 17 +- packages/effect/src/Fiber.ts | 4 +- packages/effect/src/Filter.ts | 4 +- packages/effect/src/HashRing.ts | 2 +- packages/effect/src/JsonSchema.ts | 30 ++-- packages/effect/src/Layer.ts | 8 +- packages/effect/src/Number.ts | 2 +- packages/effect/src/Option.ts | 9 +- packages/effect/src/Predicate.ts | 3 +- packages/effect/src/PubSub.ts | 6 +- packages/effect/src/Result.ts | 12 +- packages/effect/src/Schema.ts | 4 +- packages/effect/src/SchemaAST.ts | 6 +- packages/effect/src/SchemaGetter.ts | 108 +++++++------ packages/effect/src/SchemaRepresentation.ts | 40 ++--- packages/effect/src/SchemaTransformation.ts | 147 ++++++++++-------- packages/effect/src/ScopedRef.ts | 9 +- packages/effect/src/Sink.ts | 4 +- packages/effect/src/Stream.ts | 6 +- packages/effect/src/Unify.ts | 4 +- packages/effect/src/unstable/ai/AiError.ts | 3 +- packages/effect/src/unstable/cli/Param.ts | 4 +- .../eventlog/EventLogServerUnencrypted.ts | 7 +- .../src/unstable/httpapi/HttpApiMiddleware.ts | 6 +- packages/opentelemetry/src/Resource.ts | 2 +- packages/opentelemetry/src/WebSdk.ts | 6 +- 38 files changed, 301 insertions(+), 235 deletions(-) diff --git a/packages/ai/openai-compat/src/OpenAiClient.ts b/packages/ai/openai-compat/src/OpenAiClient.ts index 8d17b84a85..2333cf3891 100644 --- a/packages/ai/openai-compat/src/OpenAiClient.ts +++ b/packages/ai/openai-compat/src/OpenAiClient.ts @@ -305,8 +305,8 @@ export const layer = (options: Options): Layer.Layer(): Reducer.Reducer> { * * **When to use** * - * Use when you only need the number of elements that satisfy a predicate. + * Use when you need to count how many elements of an iterable satisfy a + * predicate. * * **Details** * diff --git a/packages/effect/src/BigDecimal.ts b/packages/effect/src/BigDecimal.ts index 8664985d21..3498cabbe9 100644 --- a/packages/effect/src/BigDecimal.ts +++ b/packages/effect/src/BigDecimal.ts @@ -658,8 +658,8 @@ export const divide: { * * **When to use** * - * Use when you need the decimal quotient and the divisor is known to be - * non-zero, so division by zero should be a thrown exception. + * Use when you need to divide `BigDecimal` values where the divisor is known + * to be non-zero, so division by zero should be a thrown exception. * * **Details** * @@ -1170,8 +1170,8 @@ export const remainder: { * * **When to use** * - * Use when you need the decimal remainder and the divisor is known to be - * non-zero, so division by zero should be a thrown exception. + * Use when you need to compute a `BigDecimal` remainder where the divisor is + * known to be non-zero, so division by zero should be a thrown exception. * * **Gotchas** * @@ -1606,8 +1606,8 @@ export const toExponential = (n: BigDecimal): string => { * * **When to use** * - * Use when you need a JavaScript number at an interop boundary and can tolerate - * precision loss. + * Use when you need a JavaScript number at an interop boundary where precision + * loss is acceptable. * * **Gotchas** * diff --git a/packages/effect/src/BigInt.ts b/packages/effect/src/BigInt.ts index 2f9406bc86..664a081373 100644 --- a/packages/effect/src/BigInt.ts +++ b/packages/effect/src/BigInt.ts @@ -254,7 +254,7 @@ export const divide: { * * **When to use** * - * Use to divide `bigint` values when the divisor is known to be non-zero and + * Use to divide `bigint` values where the divisor is known to be non-zero and * division by zero should be a thrown exception. * * **Details** diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index b3675cf08a..fe98dbf4f0 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -854,7 +854,8 @@ export const hasFails: (self: Cause) => boolean = effect.hasFails * * **When to use** * - * Use when you need the full `Fail` reason, including annotations. + * Use when you need the full `Fail` reason from a `Cause`, including + * annotations. * * **Example** (extracting the first Fail reason) * @@ -883,7 +884,8 @@ export const findFail: (self: Cause) => Result.Result, Cause(self: Cause) => boolean = effect.hasDies * * **When to use** * - * Use when you need the full `Die` reason, including annotations. + * Use when you need the full `Die` reason from a `Cause`, including + * annotations. * * **Example** (extracting the first Die reason) * @@ -992,7 +995,8 @@ export const findDie: (self: Cause) => Result.Result> = effe * * **When to use** * - * Use when you only need the unwrapped defect value. + * Use when you need the first defect value from a `Cause` as a `Result`, + * without the full `Die` reason. * * **Example** (extracting the first defect) * @@ -1041,8 +1045,8 @@ export const hasInterrupts: (self: Cause) => boolean = effect.hasInterrupt * * **When to use** * - * Use when you need the fiber ID and annotations from the first interruption - * reason. + * Use when you need the first `Interrupt` reason from a `Cause`, including the + * fiber ID and annotations. * * **Example** (extracting the first interrupt) * diff --git a/packages/effect/src/Config.ts b/packages/effect/src/Config.ts index 8d5d448d20..9202eebb59 100644 --- a/packages/effect/src/Config.ts +++ b/packages/effect/src/Config.ts @@ -194,7 +194,7 @@ const Proto = { * **When to use** * * Use to build a custom config that cannot be expressed with {@link schema} or - * convenience constructors, or to compose configs programmatically. + * convenience constructors, or compose configs programmatically. * * **Details** * diff --git a/packages/effect/src/ConfigProvider.ts b/packages/effect/src/ConfigProvider.ts index 5751f22aff..7aa37b225b 100644 --- a/packages/effect/src/ConfigProvider.ts +++ b/packages/effect/src/ConfigProvider.ts @@ -367,7 +367,7 @@ export interface ConfigProvider extends Pipeable { * **When to use** * * Use to override the active raw configuration provider for an entire program, - * or to retrieve the current provider inside an Effect. + * or retrieve the current provider inside an Effect. * * **Example** (Providing a custom provider) * @@ -470,8 +470,8 @@ export function make( * * **When to use** * - * Use to layer multiple config sources, such as env vars plus a defaults - * file, or to provide partial overrides on top of a base config. + * Use to layer multiple config sources, such as env vars plus a defaults file, + * or provide partial overrides on top of a base config. * * **Details** * @@ -597,7 +597,7 @@ export const constantCase: (self: ConfigProvider) => ConfigProvider = mapInput(( * **When to use** * * Use to namespace config under a prefix like `"app"` or `"database"`, or - * to reuse the same provider shape for multiple sub-configs. + * reuse the same provider shape for multiple sub-configs. * * **Details** * @@ -685,9 +685,9 @@ export const layer = ( * * **When to use** * - * Use to add defaults that should only apply when the primary provider - * has no value for a path, or to override specific keys while keeping the rest - * from the existing provider by setting `asPrimary: true`. + * Use to add defaults that should only apply when the primary provider has no + * value for a path, or override specific keys while keeping the rest from the + * existing provider by setting `asPrimary: true`. * * **Details** * @@ -821,8 +821,8 @@ function describeUnknown(u: unknown): Node | undefined { * * **When to use** * - * Use to read configuration from `process.env`, which is the default when - * no provider is explicitly set, or to pass a custom env record for testing or + * Use to read configuration from `process.env`, which is the default when no + * provider is explicitly set, or pass a custom env record for testing or * non-Node runtimes. * * **Details** diff --git a/packages/effect/src/Console.ts b/packages/effect/src/Console.ts index aa44e6c757..c14f65aa19 100644 --- a/packages/effect/src/Console.ts +++ b/packages/effect/src/Console.ts @@ -113,8 +113,8 @@ export interface Console { * * **When to use** * - * Use when an Effect program needs the current console service as a context - * reference, such as when providing or overriding a console implementation. + * Use when you need to access, provide, or override the current console service + * through Effect context. * * **Details** * diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index 0f98d3b6e4..9076e0ff75 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -193,7 +193,8 @@ export declare namespace ServiceClass { * * **When to use** * - * Use when you need a dependency to be provided by the surrounding context. + * Use when you need to define a context service key for a dependency that must + * be provided by the surrounding context. * * **Details** * @@ -798,7 +799,8 @@ export const addOrOmit: { * * **When to use** * - * Use when you want a fallback value for a missing regular service. + * Use when you need a fallback for a missing `Context.Service` key while still + * resolving `Context.Reference` defaults. * * **Details** * @@ -1329,8 +1331,8 @@ const withMapUnsafe = (self: Context, f: (map: Map(self: Effect) => Effect = in * * **When to use** * - * Use to handle the failure value as a success, or to move the success value - * into the failure channel. + * Use to handle the failure value as a success, or move the success value into + * the failure channel. * * **Details** * diff --git a/packages/effect/src/Exit.ts b/packages/effect/src/Exit.ts index effe3dcfb1..74d05d31a4 100644 --- a/packages/effect/src/Exit.ts +++ b/packages/effect/src/Exit.ts @@ -729,8 +729,8 @@ export const filterCause: (self: Exit) => Result.Result(input: Exit) => Result.Result * * **When to use** * - * Use when composing Exit checks with `Filter` or other `Result`-based - * filtering APIs and you only need the first defect in the Cause. + * Use when you need the first defect from an `Exit` as a `Result` for + * `Filter` or other `Result`-based filtering APIs. * * **Details** * @@ -1051,7 +1051,8 @@ export const asVoidAll: >>( * * **When to use** * - * Use when you want to optionally extract the value without pattern matching + * Use when you need the success value from an `Exit` as an `Option` instead of + * pattern matching. * * **Details** * @@ -1079,7 +1080,8 @@ export const getSuccess: (self: Exit) => Option = effect.exitGetS * * **When to use** * - * Use when you want to optionally inspect the failure cause + * Use when you need the failure `Cause` from an `Exit` as an `Option` instead + * of pattern matching. * * **Details** * @@ -1107,7 +1109,8 @@ export const getCause: (self: Exit) => Option> = effe * * **When to use** * - * Use when you want to optionally extract a typed error without dealing with the full Cause + * Use when you need the first typed error from an `Exit` as an `Option`, + * ignoring successes and non-typed failures. * * **Details** * diff --git a/packages/effect/src/Fiber.ts b/packages/effect/src/Fiber.ts index bc68325837..8d3b93fe3c 100644 --- a/packages/effect/src/Fiber.ts +++ b/packages/effect/src/Fiber.ts @@ -291,8 +291,8 @@ export const awaitAll: >( * * **When to use** * - * Use when the forked fiber is part of the current workflow and - * its failure should fail the current Effect. + * Use when you need a forked fiber's failure to fail the current Effect because + * that fiber is part of the current workflow. * * **Gotchas** * diff --git a/packages/effect/src/Filter.ts b/packages/effect/src/Filter.ts index 0ce4873c5f..ab644f1965 100644 --- a/packages/effect/src/Filter.ts +++ b/packages/effect/src/Filter.ts @@ -811,8 +811,8 @@ export const composePassthrough: { * * **When to use** * - * Use when adapting a `Filter` to `Option`-based code and you only need the - * passed value, with filtered-out inputs represented as `None`. + * Use when adapting a `Filter` to `Option`-based code where passed values + * become `Some` and filtered-out inputs become `None`. * * @see {@link toResult} for keeping the filter failure value * @see {@link toPredicate} for plain boolean pass/fail checks diff --git a/packages/effect/src/HashRing.ts b/packages/effect/src/HashRing.ts index e027ff1eaa..ca1065238d 100644 --- a/packages/effect/src/HashRing.ts +++ b/packages/effect/src/HashRing.ts @@ -235,7 +235,7 @@ function addNodesToRing(self: HashRing, keys * **When to use** * * Use to register one node in a `HashRing` so lookups and shard assignments can - * return it, or to update that node's weight. + * return it, or update that node's weight. * * **Details** * diff --git a/packages/effect/src/JsonSchema.ts b/packages/effect/src/JsonSchema.ts index da3d748ef2..6935154223 100644 --- a/packages/effect/src/JsonSchema.ts +++ b/packages/effect/src/JsonSchema.ts @@ -259,8 +259,8 @@ export const META_SCHEMA_URI_DRAFT_07 = "http://json-schema.org/draft-07/schema" * * **When to use** * - * Use to populate the `$schema` field when emitting a JSON Schema document that - * should declare JSON Schema Draft 2020-12. + * Use when you need to populate the `$schema` field while emitting a JSON + * Schema document that should declare JSON Schema Draft 2020-12. * * **Details** * @@ -283,8 +283,8 @@ const RE_COMPONENTS_SCHEMAS = /^#\/components\/schemas(?=\/|$)/ * * **When to use** * - * Use when you have a JSON Schema that follows Draft-07 conventions and - * need the canonical Draft-2020-12 document representation. + * Use when you have a raw JSON Schema object that follows Draft-07 conventions + * and need the canonical Draft-2020-12 document representation. * * **Details** * @@ -436,7 +436,7 @@ export function fromSchemaDraft07(js: JsonSchema): Document<"draft-2020-12"> { * * **When to use** * - * Use when you already have a schema in Draft-2020-12 format. + * Use when you already have a raw JSON Schema object in Draft-2020-12 format. * * **Details** * @@ -478,7 +478,8 @@ export function fromSchemaDraft2020_12(js: JsonSchema): Document<"draft-2020-12" * * **When to use** * - * Use when you need to consume schemas from an OpenAPI 3.1 specification. + * Use when you need to consume raw JSON Schema objects from an OpenAPI 3.1 + * specification. * * **Details** * @@ -517,7 +518,8 @@ export function fromSchemaOpenApi3_1(js: JsonSchema): Document<"draft-2020-12"> * * **When to use** * - * Use when you need to consume schemas from an OpenAPI 3.0 specification. + * Use when you need to consume raw JSON Schema objects from an OpenAPI 3.0 + * specification. * * **Details** * @@ -556,7 +558,8 @@ export function fromSchemaOpenApi3_0(schema: JsonSchema): Document<"draft-2020-1 * * **When to use** * - * Use when you need to output a schema in Draft-07 format. + * Use when you need to output a canonical JSON Schema document in Draft-07 + * format. * * **Details** * @@ -706,7 +709,8 @@ function toSchemaDraft07(schema: JsonSchema): JsonSchema { * * **When to use** * - * Use when generating an OpenAPI 3.1 specification from internal schemas. + * Use when you need to emit an OpenAPI 3.1 multi-document from canonical JSON + * Schema documents. * * **Details** * @@ -930,8 +934,8 @@ function widen_type(node: Record): Record { * * **When to use** * - * Use when you need to dereference a `$ref` pointer to get the actual - * schema it points to. + * Use when you need to dereference a `$ref` pointer to get the JSON Schema + * object it points to. * * **Details** * @@ -979,8 +983,8 @@ export function resolve$ref($ref: string, definitions: Definitions): JsonSchema * * **When to use** * - * Use to dereference a top-level `$ref` before inspecting the root - * schema's properties directly. + * Use when you need to dereference a top-level `$ref` before inspecting the + * root JSON Schema object's properties directly. * * **Details** * diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index 7ea156b04a..3010b41314 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -891,8 +891,8 @@ export const empty: Layer = succeedContext(Context.empty()) * * **When to use** * - * Use when the service can be created synchronously but should be deferred until the - * layer is built. + * Use when you need to provide one service whose value is created + * synchronously, but creation should be deferred until the layer is built. * * **Details** * @@ -971,8 +971,8 @@ export const syncContext = (evaluate: LazyArg>): Layer * * **When to use** * - * Use when constructing the service requires effects, dependencies, or scoped resource - * acquisition. + * Use when you need to construct a service with an Effect, dependencies, or + * scoped resource acquisition. * * **Details** * diff --git a/packages/effect/src/Number.ts b/packages/effect/src/Number.ts index 36881b8aaa..cc0067909a 100644 --- a/packages/effect/src/Number.ts +++ b/packages/effect/src/Number.ts @@ -231,7 +231,7 @@ export const divide: { * * **When to use** * - * Use to divide `number` values when the divisor is known to be non-zero and + * Use to divide `number` values where the divisor is known to be non-zero and * division by zero should be a thrown exception. * * **Example** (Dividing numbers unsafely) diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index 75dab42b35..b2f9ecf220 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -323,7 +323,7 @@ export const none = (): Option => option.none * * **When to use** * - * Use to wrap a known-present value as `Option` + * Use to wrap a known present value as `Option` * - Returning a successful result from a partial function * * **Details** @@ -614,7 +614,8 @@ export const getSuccess: (self: Result) => Option = result.getSuc * * **When to use** * - * Use when you only need the failure value from a `Result`. + * Use when you need to discard a `Result` success and keep only the failure + * value as an `Option`. * * **Details** * @@ -1007,7 +1008,7 @@ export const liftNullishOr = , B>( * * **When to use** * - * Use when you need to pass missing optional values to APIs that expect `null`. + * Use when you need to pass absent `Option` values to APIs that expect `null`. * * **Details** * @@ -1039,7 +1040,7 @@ export const getOrNull: (self: Option) => A | null = getOrElse(constNull) * * **When to use** * - * Use when you need to pass missing optional values to APIs that expect + * Use when you need to pass absent `Option` values to APIs that expect * `undefined`. * * **Details** diff --git a/packages/effect/src/Predicate.ts b/packages/effect/src/Predicate.ts index 3aea5e4960..06ab9d9e70 100644 --- a/packages/effect/src/Predicate.ts +++ b/packages/effect/src/Predicate.ts @@ -1376,7 +1376,8 @@ export function isPromise(input: unknown): input is Promise { * * **When to use** * - * Use when you only need `then` to interop with promise-like values. + * Use when you need to recognize promise-like values by a callable `then` + * method. * * **Details** * diff --git a/packages/effect/src/PubSub.ts b/packages/effect/src/PubSub.ts index d6482f6e21..56eb408c4f 100644 --- a/packages/effect/src/PubSub.ts +++ b/packages/effect/src/PubSub.ts @@ -968,8 +968,8 @@ export const publish: { * * **When to use** * - * Use when you need a non-blocking synchronous publish attempt and can handle - * `false` when the message cannot be accepted immediately. + * Use when you need a non-blocking synchronous publish attempt where `false` + * is an acceptable result when the message cannot be accepted immediately. * * **Details** * @@ -1477,7 +1477,7 @@ export const remaining = (self: Subscription): Effect.Effect => * **When to use** * * Use when you need a synchronous check of messages currently available in a - * subscription and can handle `Option.none()` when it is shut down. + * subscription where `Option.none()` represents a shut-down subscription. * * **Example** (Checking remaining messages synchronously) * diff --git a/packages/effect/src/Result.ts b/packages/effect/src/Result.ts index a4c865805c..e275becf56 100644 --- a/packages/effect/src/Result.ts +++ b/packages/effect/src/Result.ts @@ -682,7 +682,8 @@ export const isSuccess: (self: Result) => self is Success = re * * **When to use** * - * Use to extract only the success value and discard failure information. + * Use when you need to extract the success value as an `Option` and discard + * failure information. * * **Details** * @@ -714,7 +715,8 @@ export const getSuccess: (self: Result) => Option = result.getSuc * * **When to use** * - * Use to extract only the failure value and discard successful values. + * Use when you need to extract the failure value as an `Option` and discard + * successful values. * * **Details** * @@ -1163,7 +1165,8 @@ export const getOrElse: { * * **When to use** * - * Use with APIs that represent absence as `null`. + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `null`. * * **Details** * @@ -1195,7 +1198,8 @@ export const getOrNull: (self: Result) => A | null = getOrElse(const * * **When to use** * - * Use with APIs that represent absence as `undefined`. + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `undefined`. * * **Details** * diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index c0873a2dd7..74f685ce7e 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -3121,8 +3121,8 @@ interface fieldsAssign extends Lambda { * * **When to use** * - * Use to add the same fields to an existing struct or to every struct member of - * a union. + * Use to add the same fields to an existing struct or every struct member of a + * union. * * **Details** * diff --git a/packages/effect/src/SchemaAST.ts b/packages/effect/src/SchemaAST.ts index 23d37b3554..637151e0b0 100644 --- a/packages/effect/src/SchemaAST.ts +++ b/packages/effect/src/SchemaAST.ts @@ -268,8 +268,8 @@ export const isAny = makeGuard("Any") * * **When to use** * - * Use to detect schema AST nodes that match any string value while inspecting or - * transforming an SchemaAST. + * Use to detect schema AST nodes that match any string value while inspecting + * or transforming a Schema AST. * * @see {@link String} for the AST node class narrowed by this guard * @see {@link string} for the singleton `String` AST instance @@ -368,7 +368,7 @@ export const isUniqueSymbol = makeGuard("UniqueSymbol") * **When to use** * * Use to identify the AST node for the TypeScript `object` keyword when - * inspecting or transforming a schema SchemaAST. + * inspecting or transforming a Schema AST. * * @see {@link ObjectKeyword} for the AST node matched by this guard * @see {@link objectKeyword} for the singleton `ObjectKeyword` AST instance diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index 415b9ca4b5..cbfff8c2fb 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -102,8 +102,8 @@ import * as Str from "./String.ts" * * **When to use** * - * Use when you need to build and compose custom schema transformations for - * `Schema.decodeTo` or `Schema.decode`. + * Use when you need a schema getter to build and compose custom transformations + * for `Schema.decodeTo` or `Schema.decode`. * * **Details** * @@ -168,7 +168,8 @@ export class Getter extends Pipeable.Class { * * **When to use** * - * Use when a schema field should always decode to a fixed value. + * Use when you need a schema getter that always decodes a field to a fixed + * value. * - You need a placeholder getter that produces a known default. * * **Details** @@ -200,7 +201,7 @@ export function succeed(t: T): Getter { * * **When to use** * - * Use when a transformation should unconditionally reject input. + * Use when you need a schema getter that unconditionally rejects input. * - Building custom validation getters that produce specific error types. * * **Details** @@ -233,7 +234,8 @@ export function fail(f: (oe: Option.Option) => SchemaIssue.Issue): Gett * * **When to use** * - * Use when a field or direction (encode/decode) should be disallowed entirely. + * Use when you need a schema getter to disallow a field or direction + * (encode/decode) entirely. * - You want a clear "forbidden" error message in schema validation output. * * **Details** @@ -271,8 +273,8 @@ function isPassthrough(getter: Getter): getter is typeof passt * * **When to use** * - * Use when you need one side of a `decodeTo` pair, either encode or decode, to - * pass values through unchanged. + * Use when you need a schema getter for one side of a `decodeTo` pair, either + * encode or decode, to pass values through unchanged. * * **Details** * @@ -313,8 +315,8 @@ export function passthrough(): Getter { * * **When to use** * - * Use when you need an identity getter whose decoded/output type is narrower - * than the encoded/input type. + * Use when you need a schema getter that passes values through when the + * decoded/output type is narrower than the encoded/input type. * * **Details** * @@ -345,8 +347,8 @@ export function passthroughSupertype(): Getter { * * **When to use** * - * Use when you need type-safe passthrough without `{ strict: false }` for an - * encoded type that narrows the decoded type. + * Use when you need a schema getter that passes values through without + * `{ strict: false }` for an encoded type that narrows the decoded type. * * **Details** * @@ -377,7 +379,8 @@ export function passthroughSubtype(): Getter { * * **When to use** * - * Use when you need to provide a fallback or computed value for missing struct keys. + * Use when you need a schema getter to provide a fallback or computed value for + * missing struct keys. * - Building custom "default value" logic more complex than {@link withDefault}. * * **Details** @@ -414,8 +417,8 @@ export function onNone( * * **When to use** * - * Use when you need a struct field to be present in the encoded input and want - * schema validation to report a missing key error. + * Use when you need a schema getter to require a struct field in the encoded + * input and report a missing key error when it is absent. * * **Details** * @@ -446,7 +449,8 @@ export function required(annotations?: Schema.Annotations.Ke * * **When to use** * - * Use when you need to transform or validate only when a value is present. + * Use when you need a schema getter to transform or validate only when a field + * value is present. * - Missing keys should remain absent in the output. * * **Details** @@ -483,7 +487,8 @@ export function onSome( * * **When to use** * - * Use when you need to validate a decoded value (e.g. check a constraint or call an external service). + * Use when you need a schema getter to validate a decoded value (e.g. check a + * constraint or call an external service). * - The validation may be asynchronous or require Effect services. * * **Details** @@ -535,7 +540,8 @@ export function checkEffect( * * **When to use** * - * Use when you have a pure, infallible transformation between types. + * Use when you need a schema getter for a pure, infallible transformation + * between types. * - Building encode/decode pairs for `Schema.decodeTo`. * * **Details** @@ -574,8 +580,8 @@ export function transform(f: (e: E) => T): Getter { * * **When to use** * - * Use when you need a transformation that may fail, require Effect services, - * or run asynchronously. + * Use when you need a schema getter for a transformation that may fail, require + * Effect services, or run asynchronously. * * **Details** * @@ -615,7 +621,7 @@ export function transformOrFail( * * **When to use** * - * Use when you need to handle both `Some` and `None` cases. + * Use when you need a schema getter to handle both `Some` and `None` cases. * - You want to turn a present value into absent, or vice versa. * * **Details** @@ -648,7 +654,8 @@ export function transformOptional(f: (oe: Option.Option) => Option.Opti * * **When to use** * - * Use when a field should be excluded during decoding or encoding. + * Use when you need a schema getter to exclude a field during decoding or + * encoding. * * **Details** * @@ -678,8 +685,8 @@ export function omit(): Getter { * * **When to use** * - * Use when you need a fallback for a field that may be `undefined` in the - * encoded input. + * Use when you need a schema getter to provide a fallback for a field that may + * be `undefined` in the encoded input. * * **Details** * @@ -716,7 +723,8 @@ export function withDefault( * * **When to use** * - * Use when you need a string representation of an arbitrary encoded value. + * Use when you need a schema getter to coerce a present encoded value to a + * string with `String()`. * * **Details** * @@ -746,7 +754,8 @@ export function String(): Getter { * * **When to use** * - * Use when you need numeric coercion of an encoded value. + * Use when you need a schema getter to coerce a present encoded value to a + * number with `Number()`. * * **Details** * @@ -776,7 +785,8 @@ export function Number(): Getter { * * **When to use** * - * Use when you need boolean coercion (truthiness check) of an encoded value. + * Use when you need a schema getter to coerce a present encoded value to a + * boolean with `Boolean()`. * * **Details** * @@ -804,7 +814,8 @@ export function Boolean(): Getter { * * **When to use** * - * Use when you need to convert strings, numbers, or booleans to `bigint`. + * Use when you need a schema getter to convert a present string, number, or + * boolean value to `bigint`. * * **Details** * @@ -832,8 +843,8 @@ export function BigInt(): Getter(options?: { * * **When to use** * - * Use when you need to serialize a decoded record as a delimited key-value - * string. + * Use when you need a schema getter to serialize a present decoded record as a + * delimited key-value string. * * **Details** * @@ -1198,8 +1211,8 @@ export function joinKeyValue>(options?: { * * **When to use** * - * Use when you need to split an encoded string containing a delimited list, - * such as CSV values. + * Use when you need a schema getter to split a present encoded string + * containing a delimited list, such as CSV values. * * **Details** * @@ -1558,7 +1571,8 @@ export function decodeUriComponent(): Getter { * * **When to use** * - * Use when you need to decode an encoded date/time value to a `DateTime.Utc`. + * Use when you need a schema getter to decode a present encoded date/time value + * to a `DateTime.Utc`. * * **Details** * @@ -1598,7 +1612,8 @@ export function dateTimeUtcFromInput(): Gette * * **When to use** * - * Use to parse `FormData` from HTTP requests into structured objects. + * Use when you need a schema getter to parse `FormData` from HTTP requests into + * structured objects. * * **Details** * @@ -1635,7 +1650,8 @@ const collectFormDataEntries = collectBracketPathEntries((value): value is strin * * **When to use** * - * Use to serialize structured data to `FormData` for HTTP requests. + * Use when you need a schema getter to serialize structured data to `FormData` + * for HTTP requests. * * **Details** * @@ -1677,7 +1693,8 @@ export function encodeFormData(): Getter { * * **When to use** * - * Use to parse query parameters from URLs into structured objects. + * Use when you need a schema getter to parse query parameters from URLs into + * structured objects. * * **Details** * @@ -1712,7 +1729,8 @@ const collectURLSearchParamsEntries = collectBracketPathEntries(Predicate.isStri * * **When to use** * - * Use to serialize structured data to query parameters for URLs. + * Use when you need a schema getter to serialize structured data to query + * parameters for URLs. * * **Details** * @@ -1768,7 +1786,8 @@ function bracketPathToTokens(bracketPath: string): Array { * * **When to use** * - * Use to parse FormData or URLSearchParams entries into structured objects. + * Use when you need a schema getter to parse FormData or URLSearchParams + * entries into structured objects. * - You have flat key-value pairs with bracket-path keys that need nesting. * * **Details** @@ -1862,7 +1881,8 @@ export function makeTreeRecord( * * **When to use** * - * Use to serialize structured objects to flat key-value entries. + * Use when you need a schema getter to serialize structured objects to flat + * key-value entries. * - Building custom `FormData` or `URLSearchParams` encoders. * * **Details** diff --git a/packages/effect/src/SchemaRepresentation.ts b/packages/effect/src/SchemaRepresentation.ts index 1201178ef0..c46bfd2357 100644 --- a/packages/effect/src/SchemaRepresentation.ts +++ b/packages/effect/src/SchemaRepresentation.ts @@ -1667,7 +1667,8 @@ export const $MultiDocument = Schema.Struct({ * * **When to use** * - * Use when you have a single schema and need its representation. + * Use when you have a single Schema AST and need a schema representation + * document. * * **Details** * @@ -1701,7 +1702,8 @@ export const fromAST: (ast: SchemaAST.AST) => Document = InternalRepresentation. * * **When to use** * - * Use when you have multiple schemas that may share references. + * Use when you have multiple Schema ASTs and need one schema representation + * `MultiDocument` with shared references. * * **Details** * @@ -1721,8 +1723,8 @@ export const fromASTs: (asts: readonly [SchemaAST.AST, ...Array]) * * **When to use** * - * Use with `Schema.decodeUnknownSync` or `Schema.encodeSync` to serialize - * and deserialize documents. + * Use when you need a JSON codec for schema representation documents with + * `Schema.decodeUnknownSync` or `Schema.encodeSync`. * * **Example** (Round-tripping a Document through JSON) * @@ -1759,8 +1761,8 @@ export const MultiDocumentFromJson: Schema.Codec = S * * **When to use** * - * Use when you need to pass a single `Document` where an API expects a - * `MultiDocument`. + * Use when you need to pass a single schema representation `Document` where an + * API expects a `MultiDocument`. * * @see {@link Document} * @see {@link MultiDocument} @@ -1802,8 +1804,8 @@ export type Reviver = (declaration: Declaration, recur: (representation: Repr * * **When to use** * - * Use when passing this as `options.reviver` to {@link toSchema} to reconstruct - * schemas that use these types. + * Use when you need the default `options.reviver` for {@link toSchema} to + * reconstruct runtime schemas for built-in Effect declarations. * * **Details** * @@ -1890,8 +1892,8 @@ export const toSchemaDefaultReviver: Reviver = (s, recur) => { * * **When to use** * - * Use when you have a serialized or computed representation and need a - * working Schema for decoding/encoding. + * Use when you have a serialized or computed schema representation document and + * need a runtime Schema for decoding/encoding. * * **Details** * @@ -2236,8 +2238,8 @@ export function toSchema(document: Document, * * **When to use** * - * Use to produce a standard JSON Schema from an Effect Schema - * representation. + * Use when you need to produce a standard JSON Schema document from a schema + * representation `Document`. * * **Example** (Generating JSON Schema) * @@ -2268,7 +2270,8 @@ export const toJsonSchemaDocument: ( * * **When to use** * - * Use when you have multiple schemas sharing references. + * Use when you already have a schema representation `MultiDocument` and need a + * Draft 2020-12 JSON Schema multi-document. * * @see {@link MultiDocument} * @see {@link toJsonSchemaDocument} @@ -2374,8 +2377,8 @@ export type CodeDocument = { * * **When to use** * - * Use to produce source code for Schema definitions, such as in codegen - * tools. + * Use when you need to produce source code for Effect Schema definitions from a + * schema representation `MultiDocument`. * * **Details** * @@ -3010,8 +3013,8 @@ function toRuntimeRegExp(regExp: RegExp): string { * * **When to use** * - * Use to import external JSON Schemas into the Effect representation - * system. + * Use when you need to import a Draft 2020-12 JSON Schema document into the + * Effect schema representation system. * * **Details** * @@ -3050,7 +3053,8 @@ export function fromJsonSchemaDocument(document: JsonSchema.Document<"draft-2020 * * **When to use** * - * Use to import multiple JSON Schemas sharing definitions. + * Use when you need to import a Draft 2020-12 JSON Schema multi-document whose + * schemas share definitions. * * **Details** * diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index 1b8331f612..e8fcb1949d 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -102,7 +102,8 @@ import * as SchemaIssue from "./SchemaIssue.ts" * * **When to use** * - * Use when you need to catch or recover from parsing errors (e.g. `Schema.catchDecoding`). + * Use when you need a schema middleware to catch or recover from parsing + * errors (e.g. `Schema.catchDecoding`). * - You need to run side effects around the parsing pipeline. * - You need access to the full `Effect` rather than a single decoded value. * @@ -175,7 +176,8 @@ const TypeId = "~effect/SchemaTransformation/Transformation" * * **When to use** * - * Use when you need to define how a schema converts between two representations. + * Use when you need a schema transformation that defines how a schema converts + * between two representations. * - You want to compose multiple transformations into a pipeline. * - You want to flip a transformation to swap decode/encode. * @@ -239,7 +241,8 @@ export class Transformation { * * **When to use** * - * Use to check whether a value is already a Transformation before wrapping it. + * Use to check whether a value is already a schema transformation before + * wrapping it. * * **Details** * @@ -274,7 +277,8 @@ export function isTransformation(u: unknown): u is Transformation(options: { * * **When to use** * - * Use when you need an infallible conversion that does not require Effect - * services. + * Use when you need an infallible schema transformation that does not require + * Effect services. * * **Details** * @@ -416,7 +420,8 @@ export function transform(options: { * * **When to use** * - * Use when you need to produce or consume `Option.None` to represent absent keys. + * Use when you need a schema transformation to produce or consume `Option.None` + * for absent keys. * - You are working with optional struct fields. * * **Details** @@ -467,7 +472,8 @@ export function transformOptional(options: { * * **When to use** * - * Use to normalize user input by stripping leading/trailing whitespace. + * Use when you need a schema transformation to normalize user input by + * stripping leading/trailing whitespace. * * **Details** * @@ -505,7 +511,8 @@ export function trim(): Transformation { * * **When to use** * - * Use to convert API field names between snake_case and camelCase conventions. + * Use when you need a schema transformation to convert API field names between + * snake_case and camelCase conventions. * * **Details** * @@ -542,7 +549,8 @@ export function snakeToCamel(): Transformation { * * **When to use** * - * Use to normalize strings to lowercase (e.g. email addresses). + * Use when you need a schema transformation to normalize strings to lowercase + * (e.g. email addresses). * * **Details** * @@ -579,7 +587,8 @@ export function toLowerCase(): Transformation { * * **When to use** * - * Use to normalize strings to uppercase (e.g. country codes). + * Use when you need a schema transformation to normalize strings to uppercase + * (e.g. country codes). * * **Details** * @@ -616,7 +625,8 @@ export function toUpperCase(): Transformation { * * **When to use** * - * Use to normalize display names or titles. + * Use when you need a schema transformation to normalize display names or + * titles. * * **Details** * @@ -652,7 +662,8 @@ export function capitalize(): Transformation { * * **When to use** * - * Use to normalize identifiers or field names. + * Use when you need a schema transformation to normalize identifiers or field + * names. * * **Details** * @@ -688,7 +699,8 @@ export function uncapitalize(): Transformation { * * **When to use** * - * Use to parse query-string-like or config-file-like strings into records. + * Use when you need a schema transformation to parse query-string-like or + * config-file-like strings into records. * * **Details** * @@ -738,9 +750,8 @@ const passthrough_ = new Transformation( * * **When to use** * - * Use when you need to connect two schemas that share the same type with no - * conversion, such as when `Schema.decodeTo` requires a transformation but no - * actual conversion is needed. + * Use when you need a schema transformation to connect two schemas that share + * the same type with no actual conversion. * * **Details** * @@ -778,8 +789,8 @@ export function passthrough(): Transformation { * * **When to use** * - * Use when you need a no-op transformation whose decoded side is narrower than - * the encoded side. + * Use when you need a no-op schema transformation whose decoded side is + * narrower than the encoded side. * * **Details** * @@ -811,8 +822,8 @@ export function passthroughSupertype(): Transformation { * * **When to use** * - * Use when you need a no-op transformation whose encoded side is more specific - * than its decoded side. + * Use when you need a no-op schema transformation whose encoded side is more + * specific than its decoded side. * * **Details** * @@ -844,7 +855,8 @@ export function passthroughSubtype(): Transformation { * * **When to use** * - * Use to parse numeric strings from APIs, form data, or URL parameters. + * Use when you need a schema transformation to parse numeric strings from APIs, + * form data, or URL parameters. * * **Details** * @@ -880,7 +892,8 @@ export const numberFromString = new Transformation( * * **When to use** * - * Use to parse large integer strings (e.g. database IDs, blockchain values). + * Use when you need a schema transformation to parse large integer strings + * (e.g. database IDs, blockchain values). * * **Details** * @@ -914,7 +927,8 @@ export const bigintFromString = new Transformation( * * **When to use** * - * Use to parse ISO 8601 date strings from APIs or user input. + * Use when you need a schema transformation to parse ISO 8601 date strings from + * APIs or user input. * * **Details** * @@ -949,7 +963,8 @@ export const dateFromString: Transformation = new Trans * * **When to use** * - * Use to parse human-readable duration strings from APIs, config, or user input. + * Use when you need a schema transformation to parse human-readable duration + * strings from APIs, config, or user input. * * **Details** * @@ -993,7 +1008,8 @@ export const durationFromString: Transformation = tra * * **When to use** * - * Use when working with nanosecond-precision timestamps or intervals. + * Use when you need a schema transformation for nanosecond-precision timestamps + * or intervals. * * **Details** * @@ -1034,8 +1050,8 @@ export const durationFromNanos: Transformation = tran * * **When to use** * - * Use when you need to decode timeouts, delays, elapsed intervals, or other - * duration values stored as millisecond counts. + * Use when you need a schema transformation to decode timeouts, delays, elapsed + * intervals, or other duration values stored as millisecond counts. * * **Details** * @@ -1099,7 +1115,8 @@ export const errorFromErrorJsonEncoded = (options?: { * * **When to use** * - * Use to convert nullable API fields to `Option`. + * Use when you need a schema transformation to convert nullable API fields to + * `Option`. * * **Details** * @@ -1138,7 +1155,8 @@ export function optionFromNullOr(): Transformation, T | null * * **When to use** * - * Use to convert undefined-or API fields to `Option`. + * Use when you need a schema transformation to convert API fields that use + * `undefined` for absence to `Option`. * * **Details** * @@ -1179,8 +1197,8 @@ export function optionFromUndefinedOr(): Transformation, T | * * **When to use** * - * Use to convert nullish API fields to `Option` when both `null` and - * `undefined` represent absence. + * Use when you need a schema transformation to convert nullish API fields to + * `Option` when both `null` and `undefined` represent absence. * * **Details** * @@ -1225,8 +1243,8 @@ export function optionFromNullishOr( * * **When to use** * - * Use to convert optional struct keys (declared with `Schema.optionalKey`) to - * `Option` values. + * Use when you need a schema transformation to convert optional struct keys + * (declared with `Schema.optionalKey`) to `Option` values. * * **Details** * @@ -1269,7 +1287,8 @@ export function optionFromOptionalKey(): Transformation, T> * * **When to use** * - * Use to convert optional (possibly `undefined`) values to `Option`. + * Use when you need a schema transformation to convert optional (possibly + * `undefined`) values to `Option`. * * **Details** * @@ -1312,7 +1331,8 @@ export function optionFromOptional(): Transformation, T | un * * **When to use** * - * Use to parse URL strings from user input or API responses. + * Use when you need a schema transformation to parse URL strings from user + * input or API responses. * * **Details** * @@ -1351,7 +1371,8 @@ export const urlFromString: Transformation = transformOrFail * * **When to use** * - * Use when handling binary data transmitted as Base64 strings (e.g. file uploads, - * API payloads). + * Use when you need a schema transformation for binary data transmitted as + * Base64 strings (e.g. file uploads, API payloads). * * **Details** * @@ -1416,7 +1437,8 @@ export const uint8ArrayFromBase64String: Transformation = new Transf * * **When to use** * - * Use when handling text data transmitted as Base64 URL-safe strings. + * Use when you need a schema transformation for text data transmitted as Base64 + * URL-safe strings. * * **Details** * @@ -1482,7 +1505,8 @@ export const stringFromBase64UrlString: Transformation = new Tra * * **When to use** * - * Use when handling text data transmitted as hexadecimal strings. + * Use when you need a schema transformation for text data transmitted as + * hexadecimal strings. * * **Details** * @@ -1516,9 +1540,9 @@ export const stringFromHexString: Transformation = new Transform * * **When to use** * - * Use when you need to store structured data in URL query parameters or - * fragments, such as composing with `Schema.parseJson` to round-trip JSON - * through a URL. + * Use when you need a schema transformation to store structured data in URL + * query parameters or fragments, such as composing with `Schema.parseJson` to + * round-trip JSON through a URL. * * **Details** * @@ -1553,8 +1577,9 @@ export const stringFromUriComponent: Transformation = new Transf * * **When to use** * - * Use when you need to decode JSON stored or transmitted as a string, usually - * before composing with another schema that validates the parsed structure. + * Use when you need a schema transformation to decode JSON stored or + * transmitted as a string, usually before composing with another schema that + * validates the parsed structure. * * **Details** * @@ -1588,8 +1613,8 @@ export const fromJsonString = new Transformation( * * **When to use** * - * Use when form or multipart payloads contain keys such as `user[name]` or `items[0]` that - * should become nested data. + * Use when you need a schema transformation for form or multipart payloads + * whose keys, such as `user[name]` or `items[0]`, should become nested data. * * **Details** * @@ -1624,8 +1649,8 @@ export const fromFormData = new Transformation( * * **When to use** * - * Use when query strings contain keys such as `filter[name]` or `items[0]` that should - * become nested data. + * Use when you need a schema transformation for query strings whose keys, such + * as `filter[name]` or `items[0]`, should become nested data. * * **Details** * @@ -1660,8 +1685,8 @@ export const fromURLSearchParams = new Transformation( * * **When to use** * - * Use to represent fixed-offset time zones with numeric millisecond offsets in - * schema transformations or JSON codecs. + * Use when you need a schema transformation to represent fixed-offset time + * zones with numeric millisecond offsets. * * **Details** * @@ -1688,8 +1713,8 @@ export const timeZoneOffsetFromNumber: Transformation = tra * * **When to use** * - * Use to decode date-time strings when the schema value should be a normalized - * `DateTime.Utc` and encode back as a UTC ISO string. + * Use when you need a schema transformation to decode date-time strings to a + * normalized `DateTime.Utc` and encode back as a UTC ISO string. * * **Details** * @@ -1790,8 +1815,8 @@ export const dateTimeUtcFromString: Transformation = trans * * **When to use** * - * Use to define a schema transformation for ISO zoned date-time strings that - * decode to `DateTime.Zoned` and encode with `DateTime.formatIsoZoned`. + * Use when you need a schema transformation for ISO zoned date-time strings + * that decode to `DateTime.Zoned` and encode with `DateTime.formatIsoZoned`. * * **Details** * diff --git a/packages/effect/src/ScopedRef.ts b/packages/effect/src/ScopedRef.ts index 1b5ed40012..b81cd219d8 100644 --- a/packages/effect/src/ScopedRef.ts +++ b/packages/effect/src/ScopedRef.ts @@ -164,14 +164,13 @@ export const make = (evaluate: LazyArg): Effect.Effect, never }) /** - * Sets the value of this reference to the specified resourcefully-created - * value, releasing any resources associated with the old value. + * Sets the value of this reference to a newly acquired scoped value, releasing + * any resources associated with the old value. * * **When to use** * - * Use to replace the current value of an existing `ScopedRef` with a - * resourcefully acquired value while releasing resources for the previous - * value. + * Use to replace the current value of an existing `ScopedRef` with a newly + * acquired scoped value while releasing resources for the previous value. * * **Details** * diff --git a/packages/effect/src/Sink.ts b/packages/effect/src/Sink.ts index 4cb0328706..902a0f4a1c 100644 --- a/packages/effect/src/Sink.ts +++ b/packages/effect/src/Sink.ts @@ -448,8 +448,8 @@ export declare namespace make { * * **When to use** * - * Use when you need an effect to provide both the result value and optional - * leftovers. + * Use when you need to create a sink from an effect that returns both the sink + * result value and optional leftovers. * * @category constructors * @since 4.0.0 diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 2601b87899..2417ba3a93 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -475,8 +475,8 @@ export const service = (service: Context.Key): Stream = * * **When to use** * - * Use to emit an optional dependency as a stream element without requiring that - * dependency to be present. + * Use when you need a stream that emits an optional service from the context + * without requiring that service to be present. * * **Example** (Accessing an optional service as a stream) * @@ -811,7 +811,7 @@ export const toChannel = ( * **When to use** * * Use when you need callback-based code to emit stream values by offering to a - * `Queue`, or to signal stream completion through the `Queue` module APIs. + * `Queue`, or signal stream completion through the `Queue` module APIs. * * By default it uses an "unbounded" buffer size. * You can customize the buffer size and strategy by passing an object as the diff --git a/packages/effect/src/Unify.ts b/packages/effect/src/Unify.ts index aad6549de2..745eedae27 100644 --- a/packages/effect/src/Unify.ts +++ b/packages/effect/src/Unify.ts @@ -79,8 +79,8 @@ export type unifySymbol = typeof unifySymbol * * **When to use** * - * Use with `unifySymbol` to expose the source type that unification should read - * from a protocol-enabled data type. + * Use when you need a type-level protocol key that exposes the source type + * read by `Unify` from a protocol-enabled data type. * * **Details** * diff --git a/packages/effect/src/unstable/ai/AiError.ts b/packages/effect/src/unstable/ai/AiError.ts index e6ba66a459..db06ba3072 100644 --- a/packages/effect/src/unstable/ai/AiError.ts +++ b/packages/effect/src/unstable/ai/AiError.ts @@ -1497,7 +1497,8 @@ const TypeId = "~effect/unstable/ai/AiError/AiError" as const * * **When to use** * - * Use with `Effect.catchReason` for ergonomic error handling. + * Use when you need AI errors that can be handled by semantic reason with + * `Effect.catchReason`. * * **Details** * diff --git a/packages/effect/src/unstable/cli/Param.ts b/packages/effect/src/unstable/cli/Param.ts index 1dfcc0566a..1963ac0b0d 100644 --- a/packages/effect/src/unstable/cli/Param.ts +++ b/packages/effect/src/unstable/cli/Param.ts @@ -1054,8 +1054,8 @@ export const withDescription: { * * **When to use** * - * Use when experimental, internal, or deprecated flags that should be - * accepted but not advertised. + * Use when experimental, internal, or deprecated flags should be accepted but + * not advertised. * * **Example** (Hiding a flag from help) * diff --git a/packages/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts b/packages/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts index 4829ae737b..f130398537 100644 --- a/packages/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts +++ b/packages/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts @@ -805,10 +805,9 @@ export const layerServer: Layer.Layer< * * **When to use** * - * Use when you need a complete unencrypted event-log RPC endpoint for a trusted - * deployment, local development, tests, or a server-side event source, and you - * can provide storage, store mapping, authorization, an RPC protocol, and the - * event-group handler layer. + * Use when you need the full unencrypted event-log RPC server layer with + * storage, authorization, RPC protocol, and event-group handler dependencies + * supplied externally. * * **Details** * diff --git a/packages/effect/src/unstable/httpapi/HttpApiMiddleware.ts b/packages/effect/src/unstable/httpapi/HttpApiMiddleware.ts index 4399b22bb2..d52c562d9f 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiMiddleware.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiMiddleware.ts @@ -348,9 +348,9 @@ export type ServiceClass< * * **When to use** * - * Use when you need the optional configuration to declare required services, - * provided services, typed error schemas, security schemes, client errors, and - * whether generated clients must provide a matching client middleware. + * Use when you need an HTTP API middleware service whose configuration declares + * required services, provided services, typed error schemas, security schemes, + * client errors, or a matching client middleware requirement. * * @category schemas * @since 4.0.0 diff --git a/packages/opentelemetry/src/Resource.ts b/packages/opentelemetry/src/Resource.ts index 8f5a8caf89..93e7da3b33 100644 --- a/packages/opentelemetry/src/Resource.ts +++ b/packages/opentelemetry/src/Resource.ts @@ -78,7 +78,7 @@ export const layer = (config: { * **When to use** * * Use to turn explicit service metadata into a raw OpenTelemetry attribute map - * for lower-level resource construction or for merging with environment-derived + * for lower-level resource construction or merging with environment-derived * attributes via `layerFromEnv`. * * **Details** diff --git a/packages/opentelemetry/src/WebSdk.ts b/packages/opentelemetry/src/WebSdk.ts index bae4b1ad94..f8e51703f9 100644 --- a/packages/opentelemetry/src/WebSdk.ts +++ b/packages/opentelemetry/src/WebSdk.ts @@ -99,10 +99,8 @@ export const layerTracerProvider = ( * * **When to use** * - * Use to install browser OpenTelemetry support for an Effect application when - * service metadata is provided in code and tracing, metrics, or logging should - * be enabled from supplied span processors, metric readers, or log record - * processors. + * Use to install browser OpenTelemetry support when service metadata is + * configured in code and telemetry processors or readers are supplied directly. * * **Details** * From 59de20961168fa27c3a990f67319c60c0a29b74d Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 15:38:31 +0200 Subject: [PATCH 20/29] wip --- .../anthropic/src/AnthropicLanguageModel.ts | 9 +- .../ai/openai-compat/src/OpenAiTelemetry.ts | 6 +- packages/ai/openai/src/OpenAiClient.ts | 6 +- packages/ai/openai/src/OpenAiTelemetry.ts | 6 +- packages/effect/src/Array.ts | 4 +- packages/effect/src/BigInt.ts | 6 +- packages/effect/src/Boolean.ts | 4 +- packages/effect/src/Equal.ts | 33 ++-- packages/effect/src/Equivalence.ts | 59 ++++---- packages/effect/src/Exit.ts | 50 +++--- packages/effect/src/Formatter.ts | 22 ++- packages/effect/src/Newtype.ts | 4 +- packages/effect/src/Optic.ts | 11 +- packages/effect/src/Schema.ts | 125 ++++++--------- packages/effect/src/SchemaGetter.ts | 66 ++++---- packages/effect/src/SchemaTransformation.ts | 143 +++++++++--------- packages/effect/src/ScopedRef.ts | 5 +- .../unstable/ai/AnthropicStructuredOutput.ts | 33 ++-- .../src/unstable/ai/OpenAiStructuredOutput.ts | 38 ++--- 19 files changed, 287 insertions(+), 343 deletions(-) diff --git a/packages/ai/anthropic/src/AnthropicLanguageModel.ts b/packages/ai/anthropic/src/AnthropicLanguageModel.ts index c00037eecf..b1beedb687 100644 --- a/packages/ai/anthropic/src/AnthropicLanguageModel.ts +++ b/packages/ai/anthropic/src/AnthropicLanguageModel.ts @@ -81,13 +81,14 @@ export type Model = typeof Generated.Model.Type * * **When to use** * - * Use when you need to provide or override Anthropic model configuration on a - * per-request basis via `Context.Service`. + * Use when you need scoped Anthropic model request defaults or per-operation + * overrides from Effect context. * * **Details** * - * This service can be used to provide default configuration values or to - * override configuration on a per-request basis. + * The service stores request fields that are merged into Anthropic Messages API + * requests. Scoped configuration overrides defaults supplied to `model`, + * `make`, or `layer`. * * @category configuration * @since 4.0.0 diff --git a/packages/ai/openai-compat/src/OpenAiTelemetry.ts b/packages/ai/openai-compat/src/OpenAiTelemetry.ts index b2adce1ab7..ac6e7bb822 100644 --- a/packages/ai/openai-compat/src/OpenAiTelemetry.ts +++ b/packages/ai/openai-compat/src/OpenAiTelemetry.ts @@ -60,7 +60,7 @@ export type OpenAiTelemetryAttributes = Simplify< /** * All telemetry attributes which are part of the GenAI specification, - * including the OpenAi-specific attributes. + * including the OpenAI-specific attributes. * * @category models * @since 4.0.0 @@ -154,7 +154,7 @@ const addOpenAiResponseAttributes = Telemetry.addSpanAttributes("gen_ai.openai.r > /** - * Applies the specified OpenAi GenAI telemetry attributes to the provided + * Applies the specified OpenAI GenAI telemetry attributes to the provided * `Span`. * * **When to use** @@ -170,7 +170,7 @@ const addOpenAiResponseAttributes = Telemetry.addSpanAttributes("gen_ai.openai.r * * **Gotchas** * - * This method will mutate the `Span` **in-place**. + * Mutates the supplied `Span` in place. * * @category tracing * @since 4.0.0 diff --git a/packages/ai/openai/src/OpenAiClient.ts b/packages/ai/openai/src/OpenAiClient.ts index a87e98916a..372e1f2e28 100644 --- a/packages/ai/openai/src/OpenAiClient.ts +++ b/packages/ai/openai/src/OpenAiClient.ts @@ -703,7 +703,8 @@ const decodeEvent = Schema.decodeUnknownSync(Schema.fromJsonString(AllEvents)) * - `NodeSocket.layerWebSocketConstructorWS` * - `BunSocket.layerWebSocketConstructor` * - * This is because it needs to use non-standard options for setting the Authorization header. + * These constructor layers support the non-standard options needed to set the + * Authorization header. * * @see {@link layerWebSocketMode} for providing WebSocket mode through a layer * @see {@link OpenAiSocket} for direct access to the WebSocket-backed streaming service @@ -740,7 +741,8 @@ export const withWebSocketMode = ( * - `NodeSocket.layerWebSocketConstructorWS` * - `BunSocket.layerWebSocketConstructor` * - * This is because it needs to use non-standard options for setting the Authorization header. + * These constructor layers support the non-standard options needed to set the + * Authorization header. * * @see {@link withWebSocketMode} for enabling WebSocket mode around a single effect * diff --git a/packages/ai/openai/src/OpenAiTelemetry.ts b/packages/ai/openai/src/OpenAiTelemetry.ts index 18da1d53cd..6c60b37721 100644 --- a/packages/ai/openai/src/OpenAiTelemetry.ts +++ b/packages/ai/openai/src/OpenAiTelemetry.ts @@ -51,7 +51,7 @@ export type OpenAiTelemetryAttributes = Simplify< /** * All telemetry attributes which are part of the GenAI specification, - * including the OpenAi-specific attributes. + * including the OpenAI-specific attributes. * * @category models * @since 4.0.0 @@ -145,7 +145,7 @@ const addOpenAiResponseAttributes = Telemetry.addSpanAttributes("gen_ai.openai.r > /** - * Applies the specified OpenAi GenAI telemetry attributes to the provided + * Applies the specified OpenAI GenAI telemetry attributes to the provided * `Span`. * * **When to use** @@ -155,7 +155,7 @@ const addOpenAiResponseAttributes = Telemetry.addSpanAttributes("gen_ai.openai.r * * **Gotchas** * - * This method will mutate the `Span` **in-place**. + * Mutates the supplied `Span` in place. * * @see {@link OpenAiTelemetryAttributeOptions} for the accepted telemetry attributes * @see {@link Telemetry.addGenAIAnnotations} for the provider-neutral annotation helper diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 642460fc30..63756953fa 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -2267,7 +2267,7 @@ export const sortBy = >( * * **Details** * - * - Returns `NonEmptyArray` when both inputs are non-empty. + * Returns `NonEmptyArray` when both inputs are non-empty. * * **Example** (Zipping two arrays) * @@ -3928,7 +3928,7 @@ export const separate: >>( * * **Details** * - * - The function receives `(accumulator, element, index)`. + * The function receives `(accumulator, element, index)`. * * **Example** (Summing an array) * diff --git a/packages/effect/src/BigInt.ts b/packages/effect/src/BigInt.ts index 664a081373..1fbec2b043 100644 --- a/packages/effect/src/BigInt.ts +++ b/packages/effect/src/BigInt.ts @@ -526,9 +526,9 @@ export const between: { * * **Details** * - * - If the `bigint` is less than the `minimum` value, the function returns the `minimum` value. - * - If the `bigint` is greater than the `maximum` value, the function returns the `maximum` value. - * - Otherwise, it returns the original `bigint`. + * If the `bigint` is less than the minimum, the function returns the minimum. + * If the `bigint` is greater than the maximum, the function returns the + * maximum. Otherwise, it returns the original `bigint`. * * **Example** (Clamping a bigint to bounds) * diff --git a/packages/effect/src/Boolean.ts b/packages/effect/src/Boolean.ts index f2eca12dc8..cadd0de3f0 100644 --- a/packages/effect/src/Boolean.ts +++ b/packages/effect/src/Boolean.ts @@ -257,7 +257,7 @@ export const and: { } = dual(2, (self: boolean, that: boolean): boolean => self && that) /** - * Combines two boolean using NAND: `!(self && that)`. + * Combines two booleans using NAND: `!(self && that)`. * * **When to use** * @@ -284,7 +284,7 @@ export const nand: { } = dual(2, (self: boolean, that: boolean): boolean => !(self && that)) /** - * Combines two boolean using OR: `self || that`. + * Combines two booleans using OR: `self || that`. * * **When to use** * diff --git a/packages/effect/src/Equal.ts b/packages/effect/src/Equal.ts index 69e25ed9fa..e541661131 100644 --- a/packages/effect/src/Equal.ts +++ b/packages/effect/src/Equal.ts @@ -176,25 +176,20 @@ export interface Equal extends Hash.Hash { * * **Details** * - * - Returns a `boolean`; never throws. - * - Primitives: compared by value. `NaN` equals `NaN`. - * - Objects implementing {@link Equal}: delegates to their - * `[Equal.symbol]` method. If only one operand implements `Equal`, the - * result is `false`. - * - Dates: compared by ISO string representation. - * - RegExps: compared by string representation. - * - Arrays: element-by-element recursive comparison (order matters). - * - Maps / Sets: structural comparison of entries (order-independent). - * - Plain objects: all own and inherited enumerable keys are compared - * recursively. - * - Functions without an `Equal` implementation are compared by reference. - * - Circular references are handled; two structures that are circular at the - * same depth are considered equal. - * - Hash values are checked first as a fast-path rejection. - * - Supports dual (data-last) usage: call with one argument to get a curried - * predicate. - * - Useful in data-level assertions or conditional logic where structural - * comparison is needed. + * Returns a `boolean` and never throws. Primitives are compared by value, and + * `NaN` equals `NaN`. Objects implementing `Equal` delegate to their + * `[Equal.symbol]` method; if only one operand implements `Equal`, the result + * is `false`. + * + * Dates compare by ISO string, RegExps compare by string representation, + * arrays compare element-by-element, Maps and Sets compare entries + * order-independently, and plain objects compare enumerable keys recursively. + * Functions without an `Equal` implementation compare by reference. Circular + * references are handled when both structures are circular at the same depth. + * + * Hash values are checked first as a fast-path rejection. The function also + * supports dual data-last usage: call it with one argument to get a curried + * predicate. * * **Gotchas** * diff --git a/packages/effect/src/Equivalence.ts b/packages/effect/src/Equivalence.ts index 01f998d5dc..92d93dde6d 100644 --- a/packages/effect/src/Equivalence.ts +++ b/packages/effect/src/Equivalence.ts @@ -147,9 +147,10 @@ export interface EquivalenceTypeLambda extends TypeLambda { * * **Details** * - * - First checks reference equality (`===`) for performance; if values are identical, returns `true` without calling the function - * - Falls back to the provided equivalence function if values are not the same reference - * - The provided function must satisfy reflexive, symmetric, and transitive properties + * The returned equivalence first checks reference equality (`===`) for + * performance. If the values are not the same reference, it falls back to the + * provided equivalence function, which must satisfy reflexive, symmetric, and + * transitive properties. * * **Example** (Case-insensitive string equivalence) * @@ -198,11 +199,10 @@ const isStrictEquivalent = (x: unknown, y: unknown) => x === y * * **Details** * - * - Uses JavaScript's strict equality operator (`===`) - * - For primitives: compares values directly - * - For objects: compares by reference, so only the same object instance is equivalent - * - Can be used as a building block for more complex equivalences via - * {@link mapInput} or {@link combine} + * Uses JavaScript's strict equality operator (`===`). Primitives compare by + * value. Objects compare by reference, so only the same object instance is + * equivalent. Use this as a building block for more complex equivalences via + * `mapInput` or `combine`. * * **Gotchas** * @@ -340,9 +340,10 @@ export const BigInt: Equivalence = isStrictEquivalent * * **Details** * - * - Returns `true` only if both equivalences return `true` - * - Short-circuits: if the first equivalence returns `false`, the second is not called - * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * Returns `true` only if both equivalences return `true`. The comparison + * short-circuits when the first equivalence returns `false`. The result is also + * an equivalence that satisfies reflexive, symmetric, and transitive + * properties. * * **Example** (Combining name and age equivalences) * @@ -393,10 +394,11 @@ export const combine: { * * **Details** * - * - Returns `true` only if all equivalences in the collection return `true` - * - Short-circuits: stops at the first equivalence that returns `false` - * - Empty collections return an equivalence that always returns `true` - * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * Returns `true` only if all equivalences in the collection return `true`. The + * comparison stops at the first equivalence that returns `false`. Empty + * collections return an equivalence that always returns `true`. The result is + * also an equivalence that satisfies reflexive, symmetric, and transitive + * properties. * * **Example** (Combining multiple field equivalences) * @@ -535,10 +537,11 @@ export const mapInput: { * * **Details** * - * - Requires tuples to have the same length; different lengths are never equivalent - * - Applies each equivalence to the corresponding element position - * - Returns `true` only if all elements are equivalent according to their respective equivalences - * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * Tuples must have the same length; different lengths are never equivalent. + * Each equivalence is applied to the corresponding element position. The result + * returns `true` only if all elements are equivalent according to their + * respective equivalences, and it also satisfies reflexive, symmetric, and + * transitive properties. * * **Example** (Homogeneous tuple equivalence) * @@ -674,11 +677,11 @@ export { * * **Details** * - * - Compares only the properties specified in the struct definition - * - Properties not in the struct are ignored - * - Returns `true` only if all specified properties are equivalent according to their equivalences - * - Supports both string and symbol keys via `Reflect.ownKeys` - * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * Compares only the properties specified in the struct definition; other + * properties are ignored. String and symbol keys are supported via + * `Reflect.ownKeys`. The result returns `true` only if all specified properties + * are equivalent according to their equivalences, and it also satisfies + * reflexive, symmetric, and transitive properties. * * **Example** (Struct with different equivalences per field) * @@ -822,10 +825,10 @@ export function Record(value: Equivalence): Equivalence Exit = core.exitDie * * **When to use** * - * Use to signal that a fiber was interrupted + * Use to signal that a fiber was interrupted. * * **Details** * - * - Optionally pass a fiber ID to identify which fiber was interrupted - * - * Returns a `Failure` with an `Interrupt` cause. + * Optionally pass a fiber ID to identify which fiber was interrupted. Returns + * a `Failure` with an `Interrupt` cause. * * **Example** (Creating an interruption Exit) * @@ -481,14 +480,12 @@ export const isFailure: (self: Exit) => self is Failure = effe * * **When to use** * - * Use to distinguish typed failures from defects or interruptions + * Use to distinguish typed failures from defects or interruptions. * * **Details** * - * - Returns `false` for successful exits - * - * Only checks for `Fail` reasons in the Cause. A Cause with only `Die` or - * `Interrupt` reasons returns `false`. + * Returns `false` for successful exits. Only checks for `Fail` reasons in the + * Cause. A Cause with only `Die` or `Interrupt` reasons returns `false`. * * **Example** (Checking for typed errors) * @@ -513,14 +510,12 @@ export const hasFails: (self: Exit) => self is Failure = effec * * **When to use** * - * Use to check for unexpected errors + * Use to check for unexpected errors. * * **Details** * - * - Returns `false` for successful exits - * - * Only checks for `Die` reasons in the Cause. A Cause with only `Fail` or - * `Interrupt` reasons returns `false`. + * Returns `false` for successful exits. Only checks for `Die` reasons in the + * Cause. A Cause with only `Fail` or `Interrupt` reasons returns `false`. * * **Example** (Checking for defects) * @@ -545,14 +540,12 @@ export const hasDies: (self: Exit) => self is Failure = effect * * **When to use** * - * Use to check if a fiber was interrupted + * Use to check if a fiber was interrupted. * * **Details** * - * - Returns `false` for successful exits - * - * Only checks for `Interrupt` reasons in the Cause. A Cause with only `Fail` - * or `Die` reasons returns `false`. + * Returns `false` for successful exits. Only checks for `Interrupt` reasons in + * the Cause. A Cause with only `Fail` or `Die` reasons returns `false`. * * **Example** (Checking for interruptions) * @@ -809,14 +802,13 @@ export const findDefect: (input: Exit) => Result.Result extends Lens, Prism {} * * **When to use** * - * Use when you have two pure functions that form a lossless round-trip between `S` - * and `A`. + * Use when you have two pure conversion functions that preserve all information + * between `S` and `A`. * * **Details** * - * - The returned optic can be composed with any other optic. + * The returned optic can be composed with any other optic. * * **Example** (wrapping/unwrapping a branded type) * @@ -192,9 +192,8 @@ export function makeIso(get: (s: S) => A, set: (a: A) => S): Iso { * * **When to use** * - * Use when you always have a value to read (the part exists unconditionally). - * - You need the original `S` to produce the updated whole (unlike - * {@link Iso}). + * Use when you always have a value to read and need the original `S` to produce + * the updated whole, unlike `Iso`. * * **Details** * diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 74f685ce7e..c33c666aaf 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -4954,23 +4954,21 @@ export interface compose extends decodeTo extends decodeTo extends decodeTo` value. + * Decodes a required value that may be `undefined` to a required `Option` + * value. * * **Details** * - * Decoding: - * - `undefined` is decoded as `None` - * - other values are decoded as `Some` - * - * Encoding: - * - `None` is encoded as `undefined` - * - `Some` is encoded as the value + * Decoding maps `undefined` to `None` and all other values to `Some`. Encoding + * maps `None` to `undefined` and maps `Some` to its value. * * @category Option * @since 3.10.0 @@ -8209,13 +8196,10 @@ export interface OptionFromNullishOr extends decodeTo extends decodeTo extends decodeTo` + * Decodes an optional or `undefined` value `A` to a required `Option` * value. * * **Details** * - * Decoding: - * - a missing key is decoded as `None` - * - a present key with an `undefined` value is decoded as `None` - * - all other values are decoded as `Some` - * - * Encoding: - * - `None` is encoded as missing key - * - `Some` is encoded as the value + * Decoding maps a missing key or a present `undefined` value to `None`, and + * maps all other values to `Some`. Encoding maps `None` to a missing key and + * maps `Some` to its value. * * @category Option * @since 4.0.0 @@ -8316,17 +8290,10 @@ export interface OptionFromOptionalNullOr extends decodeTo( } /** - * Creates a new `ScopedRef` from an effect that resourcefully produces a - * value. + * Creates a new `ScopedRef` from an effect that acquires the initial value. * * **When to use** * @@ -150,7 +149,7 @@ export const get = (self: ScopedRef): Effect.Effect => Effect.sync(() = * `fromAcquire` so acquisition and finalization are tracked. * * @see {@link fromAcquire} for creating a `ScopedRef` from an effect that acquires the initial value - * @see {@link set} for replacing the current value with a resourcefully acquired value + * @see {@link set} for replacing the current value with a newly acquired value * * @category constructors * @since 2.0.0 diff --git a/packages/effect/src/unstable/ai/AnthropicStructuredOutput.ts b/packages/effect/src/unstable/ai/AnthropicStructuredOutput.ts index 6d0558be26..e5d834697d 100644 --- a/packages/effect/src/unstable/ai/AnthropicStructuredOutput.ts +++ b/packages/effect/src/unstable/ai/AnthropicStructuredOutput.ts @@ -48,32 +48,29 @@ import * as OpenAiStructuredOutput from "./OpenAiStructuredOutput.ts" import * as Tool from "./Tool.ts" /** - * Transforms a `Schema.Codec` into a form compatible with Anthropic's structured output constraints. + * Converts a `Schema.Codec` to Anthropic structured-output JSON Schema and a + * matching codec for model output. * * **When to use** * - * Use to adapt an `Effect` `Schema.Codec` for Anthropic structured output by - * returning an Anthropic-compatible JSON Schema together with a codec that - * preserves the decoded value type. + * Use when you send Effect Schema-backed structured output requests to + * Anthropic and need provider-compatible JSON Schema without losing the decoded + * application type. * * **Details** * - * The transformation walks the schema AST and rewrites constructs that Anthropic does not support natively: + * Returns the JSON Schema to include in the request and the codec to use when + * decoding the model response. If the input schema already fits Anthropic's + * supported JSON Schema subset, the original codec is returned unchanged. * - * - **Tuples** are converted to objects with numeric string keys (e.g. - * `"0"`, `"1"`) since Anthropic does not support tuple schemas. Rest - * elements are placed under a `"__rest__"` key. - * - **Optional properties** are replaced with `T | null` unions, because - * Anthropic requires all properties to be present. - * - **Records** (index signatures) are converted to arrays of `[key, value]` - * pairs. - * - **`oneOf` unions** are rewritten as `anyOf` unions. - * - **Filters and annotations** are preserved where compatible (e.g. - * `description`, supported `format` values like `"date-time"`, `"email"`, - * `"uuid"`, etc.), and stripped otherwise. + * **Gotchas** * - * If the schema is already compatible, the original codec is returned - * unchanged. + * - Some schemas use a provider-safe encoded shape: tuples become objects with + * numeric string keys, records become arrays of `[key, value]` pairs, and + * optional properties become required nullable properties. + * - `oneOf` unions are emitted as `anyOf` unions. + * - Unsupported schema kinds throw during conversion instead of producing a + * lossy schema. * * @see {@link LanguageModel.CodecTransformer} for the structured-output transformer contract * @see {@link OpenAiStructuredOutput.toCodecOpenAI} for the OpenAI-specific transformer diff --git a/packages/effect/src/unstable/ai/OpenAiStructuredOutput.ts b/packages/effect/src/unstable/ai/OpenAiStructuredOutput.ts index 6dead3e08b..afc0c92bb7 100644 --- a/packages/effect/src/unstable/ai/OpenAiStructuredOutput.ts +++ b/packages/effect/src/unstable/ai/OpenAiStructuredOutput.ts @@ -61,29 +61,31 @@ import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Tool from "./Tool.ts" /** - * Transforms a `Schema.Codec` into a form compatible with OpenAI's structured output constraints. + * Converts a `Schema.Codec` to OpenAI structured-output JSON Schema and a + * matching codec for model output. + * + * **When to use** + * + * Use when you send Effect Schema-backed structured output requests to OpenAI + * and need provider-compatible JSON Schema without losing the decoded + * application type. * * **Details** * - * The transformation walks the schema AST and rewrites constructs that - * OpenAI does not support natively: + * Returns the JSON Schema to include in the request and the codec to use when + * decoding the model response. If the input schema already fits OpenAI's + * supported JSON Schema subset, the original codec is returned unchanged. * - * - **Tuples** are converted to objects with numeric string keys (e.g. - * `"0"`, `"1"`) since OpenAI does not support tuple schemas. Rest - * elements are placed under a `"__rest__"` key. - * - **Optional properties** are replaced with `T | null` unions, because - * OpenAI requires all properties to be present. - * - **Records** (index signatures) are converted to arrays of `[key, value]` - * pairs. - * - **`oneOf` unions** are rewritten as `anyOf` unions. - * - **Regex patterns** from multiple filters are merged into a single - * `pattern` using lookaheads, since OpenAI does not support `allOf`. - * - **Filters and annotations** are preserved where compatible (e.g. - * `description`, supported `format` values like `"date-time"`, `"email"`, - * `"uuid"`, etc.), and stripped otherwise. + * **Gotchas** * - * If the schema is already compatible, the original codec is returned - * unchanged. + * - Some schemas use a provider-safe encoded shape: tuples become objects with + * numeric string keys, records become arrays of `[key, value]` pairs, and + * optional properties become required nullable properties. + * - `oneOf` unions are emitted as `anyOf` unions. + * - Regex patterns from multiple filters are merged into one `pattern` because + * OpenAI structured output does not support `allOf`. + * - Unsupported schema kinds throw during conversion instead of producing a + * lossy schema. * * @category Codec Transformation * @since 4.0.0 From cbc47e4be8df55e7c636f3640296d062acfff0e8 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 15:54:01 +0200 Subject: [PATCH 21/29] wip --- packages/effect/src/Array.ts | 234 ++++++++++------------ packages/effect/src/Duration.ts | 16 +- packages/effect/src/Effect.ts | 86 ++++---- packages/effect/src/Exit.ts | 48 ++--- packages/effect/src/Iterable.ts | 7 +- packages/effect/src/Logger.ts | 9 +- packages/effect/src/Metric.ts | 83 ++++---- packages/effect/src/Order.ts | 152 +++++++------- packages/effect/src/Predicate.ts | 231 +++++++++++---------- packages/effect/src/SchemaGetter.ts | 16 +- packages/effect/src/UndefinedOr.ts | 10 +- packages/effect/src/unstable/cli/Param.ts | 4 +- 12 files changed, 421 insertions(+), 475 deletions(-) diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 63756953fa..2dd5277d14 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -198,8 +198,8 @@ export type NonEmptyArray = [A, ...Array] * * **Details** * - * - The element type is inferred as the union of all arguments. - * - Always returns a `NonEmptyArray` since at least one argument is required. + * The element type is inferred as the union of all arguments. Because at least + * one argument is required, this always returns a `NonEmptyArray`. * * **Example** (Creating an array from values) * @@ -357,10 +357,9 @@ export const replicate: { * * **Details** * - * - If the input is already an array, returns it **by reference** (no copy). - * - Otherwise, creates a new array from the iterable. - * - Use {@link copy} if you need a fresh array even when the input is already - * an array. + * If the input is already an array, this returns it by reference without + * copying. Otherwise, it creates a new array from the iterable. Use `copy` if + * you need a fresh array even when the input is already an array. * * **Example** (Converting a Set to an array) * @@ -390,9 +389,9 @@ export const fromIterable = (collection: Iterable): Array => * * **Details** * - * - If the input is already an array, returns it by reference. - * - If the input is a single value, wraps it in a one-element array. - * - Useful for APIs that accept `A | Array`. + * If the input is already an array, this returns it by reference. If the input + * is a single value, this wraps it in a one-element array. This is useful for + * APIs that accept `A | Array`. * * **Example** (Normalizing input) * @@ -421,8 +420,8 @@ export const ensure = (self: ReadonlyArray | A): Array => Array.isArray * * **Details** * - * - Key order follows `Object.entries` semantics. - * - Returns an empty array for an empty record. + * Key order follows `Object.entries` semantics. Empty records produce an empty + * array. * * **Example** (Record to entries) * @@ -637,7 +636,7 @@ export const matchRight: { * * **Details** * - * - Always returns a non-empty array. + * Always returns a non-empty array. * * **Example** (Prepending an element) * @@ -668,7 +667,7 @@ export const prepend: { * * **Details** * - * - If either input is non-empty, the result is a `NonEmptyArray`. + * If either input is non-empty, the result is a `NonEmptyArray`. * * **Example** (Prepending multiple elements) * @@ -707,7 +706,7 @@ export const prependAll: { * * **Details** * - * - Always returns a non-empty array. + * Always returns a non-empty array. * * **Example** (Appending an element) * @@ -739,7 +738,7 @@ export const append: { * * **Details** * - * - If either input is non-empty, the result is a `NonEmptyArray`. + * If either input is non-empty, the result is a `NonEmptyArray`. * * **Example** (Concatenating arrays) * @@ -777,9 +776,9 @@ export const appendAll: { * * **Details** * - * - The output length is `input.length + 1` (starts with the initial value). - * - Always returns a `NonEmptyArray` because the initial value is included. - * - Use {@link reduce} if you only need the final accumulated value. + * The output length is `input.length + 1` because it starts with the initial + * value. The result is always a `NonEmptyArray`. Use `reduce` if you only need + * the final accumulated value. * * **Example** (Running totals) * @@ -819,8 +818,8 @@ export const scan: { * * **Details** * - * - The output length is `input.length + 1` (ends with the initial value). - * - Always returns a `NonEmptyArray`. + * The output length is `input.length + 1` because it ends with the initial + * value. The result is always a `NonEmptyArray`. * * **Example** (Reverse running totals) * @@ -859,8 +858,8 @@ export const scanRight: { * * **Details** * - * - Acts as a type guard narrowing the input to `Array`. - * - Delegates to `globalThis.Array.isArray`. + * Acts as a type guard narrowing the input to `Array` and delegates to + * `globalThis.Array.isArray`. * * **Example** (Type-guarding an unknown value) * @@ -1003,8 +1002,7 @@ const clamp = (i: number, as: ReadonlyArray): number => Math.floor(Math.mi * * **Details** * - * - The index is floored to an integer. - * - Never throws. + * The index is floored to an integer. This never throws. * * **Example** (Safe index access) * @@ -1040,8 +1038,8 @@ export const get: { * * **Details** * - * - Throws an `Error` with the message `"Index out of bounds: "`. - * - Prefer {@link get} for safe access. + * Throws an `Error` with the message `"Index out of bounds: "`. Prefer + * `get` for safe access. * * **Example** (Unsafe index access) * @@ -1078,8 +1076,7 @@ export const getUnsafe: { * * **Details** * - * - Returns a tuple `[head, tail]`. - * - Requires a `NonEmptyReadonlyArray`. + * Returns a tuple `[head, tail]` and requires a `NonEmptyReadonlyArray`. * * **Example** (Destructuring head and tail) * @@ -1112,8 +1109,7 @@ export const unprepend = ( * * **Details** * - * - Returns a tuple `[init, last]`. - * - Requires a `NonEmptyReadonlyArray`. + * Returns a tuple `[init, last]` and requires a `NonEmptyReadonlyArray`. * * **Example** (Destructuring init and last) * @@ -1243,8 +1239,7 @@ export const lastNonEmpty = (self: NonEmptyReadonlyArray): A => self[self. * * **Details** * - * - Allocates a new array via `slice(1)`. - * - Returns `Option.none()` for empty inputs. + * Allocates a new array via `slice(1)`. Empty inputs return `Option.none()`. * * **Example** (Getting the tail) * @@ -1298,8 +1293,8 @@ export const tailNonEmpty = (self: NonEmptyReadonlyArray): Array => sel * * **Details** * - * - Allocates a new array via `slice(0, -1)`. - * - Returns `Option.none()` for empty inputs. + * Allocates a new array via `slice(0, -1)`. Empty inputs return + * `Option.none()`. * * **Example** (Getting init) * @@ -1353,8 +1348,7 @@ export const initNonEmpty = (self: NonEmptyReadonlyArray): Array => sel * * **Details** * - * - `n` is clamped to `[0, length]`. - * - Returns an empty array when `n <= 0`. + * `n` is clamped to `[0, length]`. Returns an empty array when `n <= 0`. * * **Example** (Taking from the start) * @@ -1388,8 +1382,7 @@ export const take: { * * **Details** * - * - `n` is clamped to `[0, length]`. - * - Returns an empty array when `n <= 0`. + * `n` is clamped to `[0, length]`. Returns an empty array when `n <= 0`. * * **Example** (Taking from the end) * @@ -1425,8 +1418,8 @@ export const takeRight: { * * **Details** * - * - Supports refinements for type narrowing. - * - The predicate receives `(element, index)`. + * Supports refinements for type narrowing. The predicate receives + * `(element, index)`. * * **Example** (Taking while condition holds) * @@ -1472,8 +1465,8 @@ export const takeWhile: { * * **Details** * - * - The filter receives `(element, index)`. - * - Stops at the first filter failure. + * The filter receives `(element, index)` and processing stops at the first + * filter failure. * * @see {@link takeWhile} for taking a prefix based on a boolean predicate * @@ -1519,9 +1512,9 @@ const spanIndex = (self: Iterable, predicate: (a: A, i: number) => boolean * * **Details** * - * - Equivalent to `[takeWhile(pred), dropWhile(pred)]` but more efficient - * (single pass). - * - Supports refinements for type narrowing of the prefix. + * Equivalent to `[takeWhile(pred), dropWhile(pred)]`, but more efficient + * because it runs in a single pass. Supports refinements for type narrowing of + * the prefix. * * **Example** (Splitting at predicate boundary) * @@ -1566,8 +1559,8 @@ export const span: { * * **Details** * - * - `n` is clamped to `[0, length]`. - * - Returns a copy of the full array when `n <= 0`. + * `n` is clamped to `[0, length]`. When `n <= 0`, this returns a copy of the + * full array. * * **Example** (Dropping from the start) * @@ -1675,8 +1668,8 @@ export const dropWhile: { * * **Details** * - * - The filter receives `(element, index)`. - * - Returns the remaining original elements after the first filter failure. + * The filter receives `(element, index)`. The result contains the remaining + * original elements after the first filter failure. * * @see {@link dropWhile} for dropping a prefix with a simple boolean predicate * @see {@link takeWhileFilter} for keeping only the matching prefix @@ -1785,9 +1778,9 @@ export const findLastIndex: { * * **Details** * - * - Accepts a predicate `(a, i) => boolean`, a refinement, or a function - * `(a, i) => Option` for simultaneous find-and-transform. - * - Returns `Option.none()` if no element matches. + * Accepts a predicate `(a, i) => boolean`, a refinement, or a function + * `(a, i) => Option` for simultaneous find-and-transform. If no element + * matches, this returns `Option.none()`. * * **Example** (Finding the first match) * @@ -1882,8 +1875,8 @@ export const findFirstWithIndex: { * * **Details** * - * - Searches from the end of the array. - * - Returns `Option.none()` if no element matches. + * Searches from the end of the array. If no element matches, this returns + * `Option.none()`. * * **Example** (Finding the last match) * @@ -1940,7 +1933,7 @@ export const findLast: { * * **Details** * - * - Valid indices: `0` to `length` (inclusive — inserting at `length` appends). + * Valid indices are `0` to `length`, inclusive. Inserting at `length` appends. * * **Example** (Inserting at an index) * @@ -1978,7 +1971,7 @@ export const insertAt: { * * **Details** * - * - Returns `Option.none()` when the index is out of bounds. + * Returns `Option.none()` when the index is out of bounds. * * **Example** (Replacing an element) * @@ -2019,7 +2012,7 @@ export const replace: { * * **Details** * - * - Returns `Option.none()` when the index is out of bounds. + * Returns `Option.none()` when the index is out of bounds. * * **Example** (Modifying an element) * @@ -2102,7 +2095,7 @@ export const remove: { * * **Details** * - * - Preserves `NonEmptyArray` in the return type. + * Preserves `NonEmptyArray` in the return type. * * **Example** (Reversing an array) * @@ -2129,9 +2122,8 @@ export const reverse = >( * * **Details** * - * - Preserves `NonEmptyArray` in the return type. - * - Use {@link sortWith} to sort by a derived key, or {@link sortBy} for - * multi-key sorting. + * Preserves `NonEmptyArray` in the return type. Use `sortWith` to sort by a + * derived key, or `sortBy` for multi-key sorting. * * **Example** (Sorting numbers) * @@ -2170,7 +2162,7 @@ export const sort: { * * **Details** * - * - Equivalent to `sort(Order.mapInput(order, f))` but more convenient. + * Equivalent to `sort(Order.mapInput(order, f))`, but more convenient. * * **Example** (Sorting strings by length) * @@ -2211,8 +2203,8 @@ export const sortWith: { * * **Details** * - * - Data-last only (returns a function). - * - Preserves `NonEmptyArray` in the return type. + * This is data-last only and returns a function. The return type preserves + * `NonEmptyArray`. * * **Example** (Multi-key sorting) * @@ -2372,8 +2364,8 @@ export const unzip: >( * * **Details** * - * - Preserves `NonEmptyArray` in the return type. - * - An empty input produces an empty result. + * The return type preserves `NonEmptyArray`. Empty inputs produce an empty + * result. * * **Example** (Interspersing a separator) * @@ -2531,9 +2523,9 @@ export const setLastNonEmpty: { * * **Details** * - * - `n` is rounded to the nearest integer before rotating. - * - Preserves `NonEmptyArray` in the return type. - * - Returns a copy for empty arrays or when the normalized rotation is `0`. + * `n` is rounded to the nearest integer before rotating. The return type + * preserves `NonEmptyArray`. Empty arrays, or rotations normalized to `0`, + * return a copy. * * **Example** (Rotating elements) * @@ -2644,10 +2636,8 @@ export const contains: { * * **Details** * - * - The function receives a `NonEmptyReadonlyArray` and returns - * `[value, rest]`. - * - Continues until the remaining array is empty. - * - Useful for custom splitting/grouping logic. + * The function receives a `NonEmptyReadonlyArray` and returns `[value, rest]`. + * Processing continues until the remaining array is empty. * * **Example** (Chopping an array) * @@ -2707,8 +2697,8 @@ export const chop: { * * **Details** * - * - `n` can be `0` (all elements in the second array). - * - `n` is floored to an integer. + * `n` can be `0`, in which case all elements are placed in the second array. + * The index is floored to an integer. * * **Example** (Splitting at an index) * @@ -2776,8 +2766,7 @@ export const splitAtNonEmpty: { * * **Details** * - * - Uses `chunksOf(ceil(length / n))` internally. - * - The last chunk may be shorter. + * Uses `chunksOf(ceil(length / n))` internally. The last chunk may be shorter. * * **Example** (Splitting into groups) * @@ -2844,8 +2833,8 @@ export const splitWhere: { * * **Details** * - * - Preserves `NonEmptyArray` in the return type. - * - Useful when you need a distinct reference (e.g. before mutating). + * The return type preserves `NonEmptyArray`. Use this when you need a distinct + * reference, for example before mutating the returned array. * * **Example** (Copying an array) * @@ -2878,7 +2867,7 @@ export const copy: { * * **Details** * - * - Returns an empty array when `n <= 0`. + * Returns an empty array when `n <= 0`. * * **Example** (Padding an array) * @@ -2923,9 +2912,8 @@ export const pad: { * * **Details** * - * - `chunksOf(n)([])` is `[]`, not `[[]]`. - * - Each chunk is a `NonEmptyArray`. - * - Preserves `NonEmptyArray` in the outer return type. + * `chunksOf(n)([])` is `[]`, not `[[]]`. Each chunk is a `NonEmptyArray`, and + * the outer return type preserves `NonEmptyArray`. * * **Example** (Chunking an array) * @@ -2966,8 +2954,8 @@ export const chunksOf: { * * **Details** * - * - Returns an empty array if `n <= 0` or the array has fewer than `n` elements. - * - Each window is a tuple of exactly `n` elements. + * Returns an empty array if `n <= 0` or the array has fewer than `n` elements. + * Each window is a tuple of exactly `n` elements. * * **Example** (Sliding windows) * @@ -3007,8 +2995,8 @@ export const window: { * * **Details** * - * - Only groups **adjacent** elements — non-adjacent duplicates stay separate. - * - Requires a `NonEmptyReadonlyArray`. + * Only adjacent elements are grouped. Non-adjacent duplicates stay separate. + * Requires a `NonEmptyReadonlyArray`. * * **Example** (Grouping consecutive equal elements) * @@ -3057,7 +3045,7 @@ export const groupWith: { * * **Details** * - * - Only groups **adjacent** elements. + * Only adjacent elements are grouped. * * **Example** (Grouping adjacent equal elements) * @@ -3087,9 +3075,8 @@ export const group: (self: NonEmptyReadonlyArray) => NonEmptyArray>>( * * **Details** * - * - The filter receives `(element, index)`. - * - Failures are discarded. + * The filter receives `(element, index)`. Failures are discarded. * * **Example** (Filter and transform) * @@ -3785,8 +3771,8 @@ export const filterMap: { * * **Details** * - * - The predicate receives `(element, index)`. - * - Supports refinements for type narrowing. + * The predicate receives `(element, index)`. Refinements are supported for type + * narrowing. * * **Example** (Filtering even numbers) * @@ -3831,8 +3817,7 @@ export const filter: { * * **Details** * - * - Returns `[excluded, satisfying]`. - * - The filter receives `(element, index)`. + * Returns `[excluded, satisfying]`. The filter receives `(element, index)`. * * **Example** (Partitioning with a filter) * @@ -3890,8 +3875,8 @@ export const partition: { * * **Details** * - * - Returns `[failures, successes]`. - * - Equivalent to `partition(identity)`. + * Returns `[failures, successes]`. This is equivalent to + * `partition(identity)`. * * **Example** (Separating Results) * @@ -3962,7 +3947,7 @@ export const reduce: { * * **Details** * - * - The function receives `(accumulator, element, index)`. + * The function receives `(accumulator, element, index)`. * * **Example** (Right-to-left fold) * @@ -4236,7 +4221,7 @@ export const some: { * * **Details** * - * - For index `i`, the function receives `self.slice(i)`. + * For index `i`, the function receives `self.slice(i)`. * * **Example** (Suffix lengths) * @@ -4496,7 +4481,7 @@ export const dedupe = >( * * **Details** * - * - Non-adjacent duplicates are preserved. + * Non-adjacent duplicates are preserved. * * **Example** (Deduplicating adjacent elements) * @@ -4583,10 +4568,10 @@ export const join: { * * **Details** * - * - Combines `map` and `reduce` in a single pass. - * - The callback receives the current state, element, and index, and returns `[nextState, mappedValue]`. - * - Returns `[finalState, mappedArray]`. - * - Dual: can be used in both data-first and data-last style. + * Combines `map` and `reduce` in a single pass. The callback receives the + * current state, element, and index, and returns `[nextState, mappedValue]`. + * The result is `[finalState, mappedArray]`. This can be used in both + * data-first and data-last style. * * **Example** (Running sum alongside mapped values) * @@ -4639,9 +4624,9 @@ export const mapAccum: { * * **Details** * - * - Produces every combination of an element from `self` with an element from `that`. - * - Result length is `self.length * that.length`. - * - Order: iterates `that` for each element of `self`. + * Produces every combination of an element from `self` with an element from + * `that`, so the result length is `self.length * that.length`. Iteration visits + * every element of `that` for each element of `self`. * * **Example** (Combining numbers and letters) * @@ -4675,8 +4660,8 @@ export const cartesianWith: { * * **Details** * - * - Produces every `[a, b]` combination of an element from `self` with an element from `that`. - * - Result length is `self.length * that.length`. + * Produces every `[a, b]` combination of an element from `self` with an element + * from `that`, so the result length is `self.length * that.length`. * * **Example** (All pairs of two arrays) * @@ -4752,9 +4737,9 @@ export const Do: ReadonlyArray<{}> = of({}) * * **Details** * - * - Each `bind` call adds a named property to the accumulated object. - * - The callback receives the current scope and must return an array. - * - Equivalent to `flatMap` + merging the new value into the scope object. + * Each `bind` call adds a named property to the accumulated object. The + * callback receives the current scope and must return an array. This is + * equivalent to `flatMap` plus merging the new value into the scope object. * * **Example** (Binding two arrays) * @@ -4801,8 +4786,8 @@ export const bind: { * * **Details** * - * - Equivalent to `Array.map(self, (a) => ({ [tag]: a }))`. - * - Alternative to starting with `Do` + `bind`; useful when you already have an array. + * Equivalent to `Array.map(self, (a) => ({ [tag]: a }))`. This is an + * alternative to starting with `Do` plus `bind` when you already have an array. * * **Example** (Naming an existing array) * @@ -4845,8 +4830,9 @@ export { * * **Details** * - * - Unlike {@link bind}, the callback returns a single value (not an array), so no cartesian product occurs. - * - Useful for derived or intermediate values that depend on previously bound variables. + * Unlike `bind`, the callback returns a single value instead of an array, so + * no cartesian product occurs. Use this for derived or intermediate values + * that depend on previously bound variables. * * **Example** (Adding a computed value) * @@ -4907,8 +4893,8 @@ export function makeReducerConcat(): Reducer.Reducer> { * * **Details** * - * - The predicate receives both the element and its index. - * - Returns `0` for an empty iterable. + * The predicate receives both the element and its index. Empty iterables return + * `0`. * * **Example** (Counting even numbers) * diff --git a/packages/effect/src/Duration.ts b/packages/effect/src/Duration.ts index 8e92175e51..4a15e5ca3c 100644 --- a/packages/effect/src/Duration.ts +++ b/packages/effect/src/Duration.ts @@ -1443,16 +1443,12 @@ export const times: { * * **Details** * - * Infinity subtraction follows these rules: - * - * - infinity - infinity = 0 - * - infinity - negativeInfinity = infinity - * - infinity - finite = infinity - * - negativeInfinity - negativeInfinity = 0 - * - negativeInfinity - infinity = negativeInfinity - * - negativeInfinity - finite = negativeInfinity - * - finite - infinity = negativeInfinity - * - finite - negativeInfinity = infinity + * Infinity subtraction follows signed-infinity arithmetic. Subtracting the + * same infinity from itself returns zero. Positive infinity minus negative + * infinity or any finite duration remains positive infinity. Negative infinity + * minus positive infinity or any finite duration remains negative infinity. + * Finite durations minus positive infinity produce negative infinity, and + * finite durations minus negative infinity produce positive infinity. * * **Example** (Subtracting durations) * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index e9f9d32da1..62d4ae70b9 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -598,10 +598,8 @@ export const all: < * * **Details** * - * The returned tuple is `[excluded, satisfying]`, where: - * - * - `excluded` contains all failures. - * - `satisfying` contains all successes. + * The returned tuple is `[excluded, satisfying]`, where `excluded` contains + * all failures and `satisfying` contains all successes. * * This function runs every effect and never fails. Use `concurrency` to control * parallelism. @@ -1083,10 +1081,12 @@ export const succeedSome: (value: A) => Effect> = internal.succeedS * * **Details** * - * `suspend` takes a thunk that represents the effect and wraps it in a suspended effect. This means the effect will not be created until it is explicitly needed, which is helpful in various scenarios: - * - **Lazy Evaluation**: Helps optimize performance by deferring computations, especially when the effect might not be needed, or when its computation is expensive. This also ensures that any side effects or scoped captures are re-executed on each invocation. - * - **Handling Circular Dependencies**: Useful in managing circular dependencies, such as recursive functions that need to avoid eager evaluation to prevent stack overflow. - * - **Unifying Return Types**: Can help TypeScript unify return types in situations where multiple branches of logic return different effects, simplifying type inference. + * `suspend` takes a thunk that represents an effect and delays creating it + * until the suspended effect is evaluated. This is useful for optimizing + * expensive computations, managing circular dependencies such as recursive + * functions, and helping TypeScript unify return types when branches construct + * different effects. Any side effects or scoped captures inside the thunk are + * re-executed on each invocation. * * **Example** (Lazily evaluating side effects) * @@ -2644,8 +2644,10 @@ export { * effect. This ensures that the program continues without failing by recovering * from errors using the provided fallback logic. * - * **Note**: `catch` only handles recoverable errors. It will not recover - * from unrecoverable defects. + * **Gotchas** + * + * `catch` only handles recoverable errors. It will not recover from + * unrecoverable defects. * * @see {@link catchCause} for a version that can recover from both recoverable and unrecoverable errors. * @@ -8961,10 +8963,9 @@ export const runPromiseWith: ( * * **Details** * - * The `Exit` type represents the result of the effect: - * - If the effect succeeds, the result is wrapped in a `Success`. - * - If it fails, the failure information is provided as a `Failure` containing - * a `Cause` type. + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. * * **Example** (Observing promise results as Exit) * @@ -9149,10 +9150,9 @@ export const runSyncWith: ( * * **Details** * - * The `Exit` type represents the result of the effect: - * - If the effect succeeds, the result is wrapped in a `Success`. - * - If it fails, the failure information is provided as a `Failure` containing - * a `Cause` type. + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. * * If the effect contains asynchronous operations, `runSyncExit` will * return an `Failure` with a `Die` cause, indicating that the effect cannot be @@ -14302,13 +14302,10 @@ export class Transaction extends Context.Service< * If called inside an active transaction, `tx` composes with the current transaction and reuses * its journal and retry state instead of creating a nested boundary. * - * In Effect transactions are optimistic with retry, that means transactions are retried when: - * - * - the body of the transaction explicitely calls to `Effect.txRetry` and any of the - * accessed transactional values changes. - * - * - any of the accessed transactional values change during the execution of the transaction - * due to a different transaction committing before the current. + * Effect transactions are optimistic with retry. A transaction is retried when + * its body explicitly calls `Effect.txRetry` and any accessed transactional + * value changes, or when any accessed transactional value changes because a + * different transaction commits before the current one. * * The outermost `tx` call creates the transaction boundary and commits or rolls back the full * composed transaction. @@ -14901,11 +14898,8 @@ export const satisfiesServicesType = () => (effect: Effec * * **Details** * - * Behavior: - * - * - For **Success effects**: Applies the mapping function immediately to the value - * - For **Failure effects**: Returns the failure as-is without applying the mapping - * - For **Pending effects**: Falls back to the regular `map` behavior + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` behavior. * * **Example** (Mapping already completed effects) * @@ -14940,11 +14934,9 @@ export const mapEager: { * * **Details** * - * Behavior: - * - * - For **Success effects**: Returns the success as-is (no error to transform) - * - For **Failure effects**: Applies the mapping function immediately to the error - * - For **Pending effects**: Falls back to the regular `mapError` behavior + * Success effects pass through unchanged because there is no error to + * transform. Failure effects apply the mapping function immediately, and + * pending effects fall back to regular `mapError` behavior. * * **Example** (Mapping errors eagerly when possible) * @@ -14981,11 +14973,9 @@ export const mapErrorEager: { * * **Details** * - * Behavior: - * - * - For **Success effects**: Applies the `onSuccess` function immediately to the value - * - For **Failure effects**: Applies the `onFailure` function immediately to the error - * - For **Pending effects**: Falls back to the regular `mapBoth` behavior + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * behavior. * * **Example** (Mapping both channels eagerly when possible) * @@ -15029,11 +15019,9 @@ export const mapBothEager: { * * **Details** * - * Behavior: - * - * - For **Success effects**: Applies the flatMap function immediately to the value - * - For **Failure effects**: Returns the failure as-is without applying the flatMap - * - For **Pending effects**: Falls back to the regular `flatMap` behavior + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * behavior. * * **Example** (Flat mapping eagerly when possible) * @@ -15070,11 +15058,9 @@ export const flatMapEager: { * * **Details** * - * Behavior: - * - * - For **Success effects**: Returns the success as-is (no error to catch) - * - For **Failure effects**: Applies the catch function immediately to the error - * - For **Pending effects**: Falls back to the regular `catch` behavior + * Success effects pass through unchanged because there is no error to catch. + * Failure effects apply the catch function immediately, and pending effects + * fall back to regular `catch` behavior. * * **Example** (Catching failures eagerly when possible) * diff --git a/packages/effect/src/Exit.ts b/packages/effect/src/Exit.ts index 771f458abc..19e4275907 100644 --- a/packages/effect/src/Exit.ts +++ b/packages/effect/src/Exit.ts @@ -76,9 +76,9 @@ const TypeId = core.ExitTypeId * * **Details** * - * An `Exit` is either: - * - `Success` containing a value of type `A` - * - `Failure` containing a `Cause` describing why the computation failed + * An `Exit` is either `Success` containing a value of type `A`, or + * `Failure` containing a `Cause` describing why the computation + * failed. * * Since `Exit` is also an `Effect`, you can yield it inside `Effect.gen`. * @@ -179,7 +179,7 @@ export interface Success extends Exit.Proto { * * **Details** * - * - The `Cause` may contain typed errors, defects, or interruptions + * The `Cause` may contain typed errors, defects, or interruptions. * * **Example** (Accessing the failure cause) * @@ -210,8 +210,8 @@ export interface Failure extends Exit.Proto { * * **When to use** * - * Use to validate unknown values at system boundaries - * - Works as a type guard, narrowing to `Exit` + * Use to validate unknown values at system boundaries and narrow them to + * `Exit`. * * **Details** * @@ -271,7 +271,8 @@ export const succeed: (a: A) => Exit = core.exitSucceed * **When to use** * * Use when you already have a `Cause` and want to wrap it in an Exit - * - Use for advanced error handling where you need full control over the Cause structure + * for advanced error handling where you need full control over the Cause + * structure. * * **Details** * @@ -305,7 +306,7 @@ export const failCause: (cause: Cause.Cause) => Exit = core.exit * * **Details** * - * - The error is wrapped in a `Cause.Fail` internally + * The error is wrapped in a `Cause.Fail` internally. * * Returns a `Failure`. * @@ -332,11 +333,12 @@ export const fail: (e: E) => Exit = core.exitFail * * **When to use** * - * Use when you need unexpected, unrecoverable errors that should not appear in the typed error channel + * Use when you need unexpected, unrecoverable errors that should not appear in + * the typed error channel. * * **Details** * - * - The defect is wrapped in a `Cause.Die` internally + * The defect is wrapped in a `Cause.Die` internally. * * Returns a `Failure` with `E = never`, since defects do not appear in * the typed error channel. @@ -424,8 +426,8 @@ export { * * **When to use** * - * Use as a type guard to narrow `Exit` to `Success` - * - After narrowing, the `value` property becomes accessible + * Use as a type guard to narrow `Exit` to `Success` and access the + * `value` property. * * **Example** (Narrowing to Success) * @@ -452,8 +454,8 @@ export const isSuccess: (self: Exit) => self is Success = effe * * **When to use** * - * Use as a type guard to narrow `Exit` to `Failure` - * - After narrowing, the `cause` property becomes accessible + * Use as a type guard to narrow `Exit` to `Failure` and access the + * `cause` property. * * **Example** (Narrowing to Failure) * @@ -852,7 +854,7 @@ export const match: { * * **Details** * - * - Has no effect on failures, which pass through unchanged + * Failures pass through unchanged. * * Allocates a new Exit if successful. * Supports both curried and direct call styles. @@ -887,7 +889,7 @@ export const map: { * * **Details** * - * - Has no effect on successes, which pass through unchanged + * Successes pass through unchanged. * * Allocates a new Exit if the error is transformed. * Supports both curried and direct call styles. @@ -978,7 +980,7 @@ export const mapBoth: { * * **Details** * - * - Failures pass through unchanged + * Failures pass through unchanged. * * Allocates a new Exit if successful. * @@ -1009,8 +1011,8 @@ export const asVoid: (self: Exit) => Exit = effect.exitAsVo * * **Details** * - * - If all exits are successful, returns a void success - * - If any exit is a failure, returns a single failure with all error causes combined + * If all exits are successful, this returns a void success. If any exit is a + * failure, this returns a single failure with all error causes combined. * * Iterates over the entire collection. Collects all failure causes, not just * the first. @@ -1046,7 +1048,7 @@ export const asVoidAll: >>( * * **Details** * - * - Returns `Option.some(value)` for a Success, `Option.none()` for a Failure + * Returns `Option.some(value)` for a Success and `Option.none()` for a Failure. * * **Example** (Getting the success value) * @@ -1075,7 +1077,7 @@ export const getSuccess: (self: Exit) => Option = effect.exitGetS * * **Details** * - * - Returns `Option.some(cause)` for a Failure, `Option.none()` for a Success + * Returns `Option.some(cause)` for a Failure and `Option.none()` for a Success. * * **Example** (Getting the failure cause) * @@ -1104,8 +1106,8 @@ export const getCause: (self: Exit) => Option> = effe * * **Details** * - * - Returns `Option.some(error)` if the Cause contains a Fail reason, `Option.none()` otherwise - * - Returns `Option.none()` for successes, defect-only failures, and interrupt-only failures + * Returns `Option.some(error)` if the Cause contains a Fail reason. Successes, + * defect-only failures, and interrupt-only failures return `Option.none()`. * * **Gotchas** * diff --git a/packages/effect/src/Iterable.ts b/packages/effect/src/Iterable.ts index 921bf56f12..2e6eedf75d 100644 --- a/packages/effect/src/Iterable.ts +++ b/packages/effect/src/Iterable.ts @@ -1492,7 +1492,7 @@ export const of = (a: A): Iterable => [a] * * This is one of the most fundamental operations for working with iterables. * It applies a transformation function to each element, creating a new iterable - * with the transformed values. The operation is lazy - elements are only + * with the transformed values. The operation is lazy, so elements are only * transformed when the iterable is consumed. * * **Example** (Mapping elements) @@ -1650,8 +1650,9 @@ export const flatten = (self: Iterable>): Iterable => ({ * * **Details** * - * This combines mapping and filtering in a single operation - the function is applied to each element, - * and only elements that result in `Result.succeed` are included in the result. + * This combines mapping and filtering in a single operation. The function is + * applied to each element, and only elements that result in `Result.succeed` + * are included in the result. * * **Example** (Filtering and transforming Result values) * diff --git a/packages/effect/src/Logger.ts b/packages/effect/src/Logger.ts index 1c7da15052..da78163637 100644 --- a/packages/effect/src/Logger.ts +++ b/packages/effect/src/Logger.ts @@ -393,12 +393,9 @@ export const withConsoleError = ( * Will use the appropriate console method (i.e. `console.log`, `console.error`, * etc.) based upon the current `LogLevel`. * - * - `Debug` -> `console.debug` - * - `Info` -> `console.info` - * - `Trace` -> `console.trace` - * - `Warn` -> `console.warn` - * - `Error` and `Fatal` -> `console.error` - * - Others -> `console.log` + * `Debug` uses `console.debug`, `Info` uses `console.info`, `Trace` uses + * `console.trace`, `Warn` uses `console.warn`, `Error` and `Fatal` use + * `console.error`, and all other levels use `console.log`. * * **Example** (Writing logs with level-based console methods) * diff --git a/packages/effect/src/Metric.ts b/packages/effect/src/Metric.ts index 354411a25d..b03365ad71 100644 --- a/packages/effect/src/Metric.ts +++ b/packages/effect/src/Metric.ts @@ -2193,11 +2193,10 @@ export const isMetric = (u: unknown): u is Metric => * * **Details** * - * - `description` - A description of the `Counter`. - * - `attributes` - The attributes to associate with the `Counter`. - * - `bigint` - Indicates if the `Counter` should use the `bigint` type. - * - `incremental` - Set to `true` to create a `Counter` that can only ever be - * incremented. + * The optional `description` describes the counter, and `attributes` attach + * dimensions to it. Set `bigint` to create a counter that accepts `bigint` + * inputs. Set `incremental` to `true` to create a counter that can only ever be + * incremented. * * **Example** (Creating counter metrics) * @@ -2277,9 +2276,9 @@ export const counter: { * * **Details** * - * - `description` - A description of the `Gauge`. - * - `attributes` - The attributes to associate with the `Gauge`. - * - `bigint` - Indicates if the `Gauge` should use the `bigint` type. + * The optional `description` describes the gauge, and `attributes` attach + * dimensions to it. Set `bigint` to create a gauge that accepts `bigint` + * inputs. * * **Example** (Creating gauge metrics) * @@ -2356,10 +2355,9 @@ export const gauge: { * * **Details** * - * - `description` - A description of the `Frequency`. - * - `attributes` - The attributes to associate with the `Frequency`. - * - `preregisteredWords` - Occurrences which are pre-registered with the - * `Frequency` metric occurrences. + * The optional `description` describes the frequency, and `attributes` attach + * dimensions to it. Use `preregisteredWords` to initialize occurrence counts + * for known string values before updates arrive. * * **Example** (Creating frequency metrics) * @@ -2439,9 +2437,9 @@ export const frequency = (name: string, options?: { * * **Details** * - * - `description` - A description of the `Histogram`. - * - `attributes` - The attributes to associate with the `Histogram`. - * - `boundaries` - The bucket boundaries of the `Histogram` + * The optional `description` describes the histogram, and `attributes` attach + * dimensions to it. The required `boundaries` option defines the histogram + * bucket boundaries. * * **Example** (Creating histogram metrics) * @@ -2519,11 +2517,10 @@ export const histogram = (name: string, options: { * * **Details** * - * - `description` - An description of the `Summary`. - * - `attributes` - The attributes to associate with the `Summary`. - * - `maxAge` - The maximum age of observations to retain. - * - `maxSize` - The maximum number of observations to keep. - * - `quantiles` - An array of quantiles to calculate (e.g., [0.5, 0.9]). + * The optional `description` describes the summary, and `attributes` attach + * dimensions to it. `maxAge` controls how long observations are retained, + * `maxSize` controls how many observations are kept, and `quantiles` lists the + * quantiles to calculate, such as `[0.5, 0.9]`. * * **Example** (Creating summary metrics) * @@ -2618,11 +2615,10 @@ export const summary = (name: string, options: { * Inputs to this metric are `[value, timestamp]` pairs; the current clock is * used when reading quantiles against the configured `maxAge`. * - * - `description` - An description of the `Summary`. - * - `attributes` - The attributes to associate with the `Summary`. - * - `maxAge` - The maximum age of observations to retain. - * - `maxSize` - The maximum number of observations to keep. - * - `quantiles` - An array of quantiles to calculate (e.g., [0.5, 0.9]). + * The optional `description` describes the summary, and `attributes` attach + * dimensions to it. `maxAge` controls how long observations are retained, + * `maxSize` controls how many observations are kept, and `quantiles` lists the + * quantiles to calculate, such as `[0.5, 0.9]`. * * **Example** (Creating summaries with explicit timestamps) * @@ -2714,13 +2710,12 @@ export const timer = (name: string, options?: { * * **Details** * - * The returned state depends on the metric type: - * - * - Counter: `CounterState` with `count` and `incremental` - * - Gauge: `GaugeState` with `value` - * - Frequency: `FrequencyState` with `occurrences` - * - Histogram: `HistogramState` with buckets, count, min, max, and sum - * - Summary: `SummaryState` with quantiles, count, min, max, and sum + * The returned state depends on the metric type. Counters return + * `CounterState` with `count` and `incremental`, gauges return + * `GaugeState` with `value`, frequencies return + * `FrequencyState` with `occurrences`, histograms return `HistogramState` with + * buckets, count, min, max, and sum, and summaries return `SummaryState` with + * quantiles, count, min, max, and sum. * * **Example** (Reading metric state) * @@ -2767,13 +2762,11 @@ export const value = ( * * **Details** * - * The behavior of `modify` depends on the metric type: - * - * - **Counter**: Adds the input value to the current count - * - **Gauge**: Adds the input value to the current gauge value - * - **Frequency**: Same as `update` - increments the occurrence count for the input string - * - **Histogram**: Same as `update` - records the input value in the appropriate bucket - * - **Summary**: Same as `update` - records the input observation + * The behavior of `modify` depends on the metric type. Counters add the input + * value to the current count, gauges add the input value to the current gauge + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input observation. * * **Example** (Modifying metric values) * @@ -2823,13 +2816,11 @@ export const modify: { * * **Details** * - * The behavior of `update` depends on the metric type: - * - * - **Counter**: Adds the input value to the current count (same as `modify`) - * - **Gauge**: Sets the gauge to the specified value (replaces current value) - * - **Frequency**: Increments the occurrence count for the input string by 1 - * - **Histogram**: Records the input value in the appropriate bucket - * - **Summary**: Records the input value as a new observation + * The behavior of `update` depends on the metric type. Counters add the input + * value to the current count, gauges replace the current value with the input + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input value as a new observation. * * **Example** (Updating metric values) * diff --git a/packages/effect/src/Order.ts b/packages/effect/src/Order.ts index b70cc25def..a4b3c9f226 100644 --- a/packages/effect/src/Order.ts +++ b/packages/effect/src/Order.ts @@ -92,10 +92,10 @@ import * as Reducer from "./Reducer.ts" * * **Details** * - * - Returns `-1` if the first value is less than the second - * - Returns `0` if the values are equal according to this ordering - * - Returns `1` if the first value is greater than the second - * - Must satisfy total ordering laws (totality, antisymmetry, transitivity) + * An order returns `-1` when the first value is less than the second, `0` when + * the values are equal according to this ordering, and `1` when the first value + * is greater than the second. It must satisfy total ordering laws: totality, + * antisymmetry, and transitivity. * * **Example** (Custom Order) * @@ -131,8 +131,8 @@ export interface Order { * * **Details** * - * - Type-level only: no runtime representation - * - Used internally by the Effect type system + * This is type-level only, has no runtime representation, and is used + * internally by the Effect type system. * * @category type lambdas * @since 2.0.0 @@ -150,9 +150,10 @@ export interface OrderTypeLambda extends TypeLambda { * * **Details** * - * - Uses reference equality (`===`) as a shortcut: if `self === that`, returns `0` without calling the comparison function - * - The comparison function should return `-1`, `0`, or `1` based on the comparison result - * - The returned order satisfies total ordering laws if the comparison function does + * Uses reference equality (`===`) as a shortcut: if `self === that`, it returns + * `0` without calling the comparison function. The comparison function should + * return `-1`, `0`, or `1`, and the returned order satisfies total ordering + * laws when the comparison function does. * * **Example** (Creating an Order) * @@ -189,9 +190,8 @@ export function make( * * **Details** * - * - Uses lexicographic (dictionary) ordering - * - Empty string is less than any non-empty string - * - Comparison is case-sensitive + * Uses lexicographic dictionary ordering. The empty string is less than any + * non-empty string, and comparisons are case-sensitive. * * **Example** (String Ordering) * @@ -219,10 +219,9 @@ export const String: Order = make((self, that) => self < that ? -1 : 1) * * **Details** * - * - `0` is considered equal to `-0` - * - All `NaN` values are considered equal to each other - * - Any `NaN` is considered less than any non-NaN number - * - Uses standard numeric comparison for all other values + * `0` is considered equal to `-0`. All `NaN` values are considered equal to + * each other, and any `NaN` is considered less than any non-`NaN` number. All + * other values use standard numeric comparison. * * **Example** (Number Ordering) * @@ -258,8 +257,7 @@ export const Number: Order = make((self, that) => { * * **Details** * - * - `false` is less than `true` - * - Equal values return `0` + * `false` is less than `true`, and equal values return `0`. * * **Example** (Boolean Ordering) * @@ -286,8 +284,8 @@ export const Boolean: Order = make((self, that) => self < that ? -1 : 1 * * **Details** * - * - Uses standard numeric comparison for bigint values - * - Handles arbitrarily large integers + * Uses standard numeric comparison for bigint values and handles arbitrarily + * large integers. * * **Example** (BigInt Ordering) * @@ -315,9 +313,9 @@ export const BigInt: Order = make((self, that) => self < that ? -1 : 1) * * **Details** * - * - Returns a new order that swaps the arguments before comparison - * - If the original order returns `-1`, the flipped order returns `1`, and vice versa - * - Equal comparisons remain `0` + * Returns a new order that swaps the arguments before comparison. If the + * original order returns `-1`, the flipped order returns `1`, and vice versa. + * Equal comparisons remain `0`. * * **Example** (Reversing Order) * @@ -349,9 +347,9 @@ export function flip(O: Order): Order { * * **Details** * - * - First applies the first order; if the result is non-zero, returns that result - * - If the first order returns `0` (equal), applies the second order - * - Returns the first non-zero result, or `0` if both orders return `0` + * First applies the first order. If the result is non-zero, that result is + * returned; otherwise, the second order is applied. The result is the first + * non-zero comparison result, or `0` if both orders return `0`. * * **Example** (Combining Orders) * @@ -402,8 +400,8 @@ export const combine: { * * **Details** * - * - Always returns `0` regardless of input values - * - Useful as a neutral element in order composition + * Always returns `0` regardless of input values, making it useful as a neutral + * element in order composition. * * **Example** (Always Equal Order) * @@ -435,10 +433,8 @@ export function alwaysEqual(): Order { * * **Details** * - * - Applies orders in iteration order - * - Returns the first non-zero result from any order - * - Returns `0` only if all orders return `0` - * - Short-circuits on the first non-zero result + * Applies orders in iteration order and short-circuits on the first non-zero + * result. It returns `0` only if all orders return `0`. * * **Example** (Combining Multiple Orders) * @@ -490,9 +486,9 @@ export function combineAll(collection: Iterable>): Order { * * **Details** * - * - Applies the mapping function to both values before comparison - * - The mapping function should be pure and not have side effects - * - Preserves the ordering properties of the original order + * Applies the mapping function to both values before comparison. The mapping + * function should be pure and not have side effects so the ordering properties + * of the original order are preserved. * * **Example** (Mapping Input) * @@ -528,9 +524,9 @@ export const mapInput: { * * **Details** * - * - Compares dates by their underlying timestamp (milliseconds since epoch) - * - Earlier dates are less than later dates - * - Invalid dates are compared as if they were valid (uses `getTime()` result) + * Compares dates by their underlying timestamp in milliseconds since the epoch. + * Earlier dates are less than later dates. Invalid dates are compared through + * their `getTime()` result. * * **Example** (Date Ordering) * @@ -560,10 +556,9 @@ export const Date: Order = mapInput(Number, (date) => date.getTime()) * * **Details** * - * - Compares tuples element-by-element using the corresponding order - * - Stops at the first non-zero comparison result - * - Requires tuples to have the same length as the order collection - * - Returns `0` if all elements are equal + * Compares tuples element-by-element using the corresponding order and stops at + * the first non-zero comparison result. Tuples must have the same length as the + * order collection, and the result is `0` only if all elements are equal. * * **Example** (Tuple Ordering) * @@ -624,10 +619,10 @@ export { * * **Details** * - * - Compares arrays element-by-element using the provided order - * - Stops at the first non-zero comparison result - * - If all elements are equal, shorter arrays are less than longer arrays - * - Returns `0` only if arrays have the same length and all elements are equal + * Compares arrays element-by-element using the provided order and stops at the + * first non-zero comparison result. If all elements are equal, shorter arrays + * are less than longer arrays. The result is `0` only if arrays have the same + * length and all elements are equal. * * **Example** (Array Element Ordering) * @@ -658,10 +653,9 @@ export { * * **Details** * - * - Compares structs field-by-field in the order of keys in the fields object - * - Stops at the first non-zero comparison result - * - Returns `0` only if all fields are equal - * - Field order matters: earlier fields take precedence + * Compares structs field-by-field in the key order of the fields object and + * stops at the first non-zero comparison result. Field order matters: earlier + * fields take precedence. The result is `0` only if all fields are equal. * * **Example** (Struct Ordering) * @@ -711,9 +705,9 @@ export function Struct }>( * * **Details** * - * - Returns `true` if the order returns `-1` (first value is less than second) - * - Returns `false` for equal or greater values - * - Supports curried and uncurried call styles + * Returns `true` if the order returns `-1`, meaning the first value is less + * than the second. Equal or greater values return `false`. Both curried and + * uncurried call styles are supported. * * **Example** (Less Than) * @@ -746,9 +740,9 @@ export const isLessThan = (O: Order): { * * **Details** * - * - Returns `true` if the order returns `1` (first value is greater than second) - * - Returns `false` for equal or lesser values - * - Supports curried and uncurried call styles + * Returns `true` if the order returns `1`, meaning the first value is greater + * than the second. Equal or lesser values return `false`. Both curried and + * uncurried call styles are supported. * * **Example** (Greater Than) * @@ -781,9 +775,8 @@ export const isGreaterThan = (O: Order): { * * **Details** * - * - Returns `true` if the order returns `-1` or `0` (less than or equal) - * - Returns `false` only if the order returns `1` (greater than) - * - Supports curried and uncurried call styles + * Returns `true` if the order returns `-1` or `0`, and returns `false` only if + * the order returns `1`. * * **Example** (Less Than Or Equal) * @@ -816,9 +809,8 @@ export const isLessThanOrEqualTo = (O: Order): { * * **Details** * - * - Returns `true` if the order returns `1` or `0` (greater than or equal) - * - Returns `false` only if the order returns `-1` (less than) - * - Supports curried and uncurried call styles + * Returns `true` if the order returns `1` or `0`, and returns `false` only if + * the order returns `-1`. * * **Example** (Greater Than Or Equal) * @@ -851,9 +843,9 @@ export const isGreaterThanOrEqualTo = (O: Order): { * * **Details** * - * - Returns the value that compares as less than or equal to the other - * - If values are equal, returns the first argument - * - Supports curried and uncurried call styles + * Returns the value that compares as less than or equal to the other value. If + * values are equal, the first argument is returned. Both curried and uncurried + * call styles are supported. * * **Example** (Minimum Value) * @@ -886,9 +878,9 @@ export const min = (O: Order): { * * **Details** * - * - Returns the value that compares as greater than or equal to the other - * - If values are equal, returns the first argument - * - Supports curried and uncurried call styles + * Returns the value that compares as greater than or equal to the other value. + * If values are equal, the first argument is returned. Both curried and + * uncurried call styles are supported. * * **Example** (Maximum Value) * @@ -921,11 +913,10 @@ export const max = (O: Order): { * * **Details** * - * - Returns the value if it's between minimum and maximum (inclusive) - * - Returns minimum if the value is less than minimum - * - Returns maximum if the value is greater than maximum - * - Supports curried and uncurried call styles - * - Requires that minimum <= maximum according to the order + * Returns the value itself when it is between minimum and maximum, inclusive. + * Values below the range return minimum, and values above the range return + * maximum. The minimum must be less than or equal to the maximum according to + * the order. * * **Example** (Clamping Values) * @@ -972,10 +963,9 @@ export const clamp = (O: Order): { * * **Details** * - * - Returns `true` if the value is greater than or equal to minimum and less than or equal to maximum - * - Returns `false` if the value is outside the range - * - Supports curried and uncurried call styles - * - Both bounds are inclusive + * Returns `true` when the value is greater than or equal to minimum and less + * than or equal to maximum. Values outside the range return `false`. Both + * bounds are inclusive. * * **Example** (Checking Range) * @@ -1024,10 +1014,10 @@ export const isBetween = (O: Order): { * * **Details** * - * - Returns a reducer that combines orders using {@link combine} - * - Uses {@link alwaysEqual} as the identity element (returns `0` for empty collections) - * - Uses {@link combineAll} for combining collections of orders - * - The reducer can be used with fold operations on collections + * Returns a reducer that combines orders using `combine`, uses `alwaysEqual` as + * the identity element for empty collections, and uses `combineAll` for + * combining collections of orders. The reducer can be used with fold operations + * on collections. * * **Example** (Creating a Reducer) * diff --git a/packages/effect/src/Predicate.ts b/packages/effect/src/Predicate.ts index 06ab9d9e70..5fa42f9894 100644 --- a/packages/effect/src/Predicate.ts +++ b/packages/effect/src/Predicate.ts @@ -73,14 +73,14 @@ import type { TupleOf, TupleOfAtLeast } from "./Types.ts" * * **When to use** * - * Use when you want a reusable boolean check for `A`. - * - You plan to combine checks with {@link and}/{@link or}. - * - You want a simple filter predicate for arrays or iterables. + * Use when you want a reusable boolean check for `A`, especially when you plan + * to combine checks with {@link and}/{@link or} or pass a predicate to arrays + * and iterables. * * **Details** * - * - Returns `true` or `false`; never throws by itself. - * - Does not narrow types unless you use {@link Refinement}. + * A predicate returns `true` or `false` and never throws by itself. It does not + * narrow types unless you use `Refinement`. * * **Example** (Define a predicate) * @@ -107,13 +107,13 @@ export interface Predicate { * * **When to use** * - * Use when you are defining APIs that abstract over predicates with HKTs. - * - You need a `TypeLambda` instance for predicate-based type classes. + * Use when you are defining APIs that abstract over predicates with HKTs and + * need a `TypeLambda` instance for predicate-based type classes. * * **Details** * - * - Type-only; no runtime value is created. - * - Does not affect emitted JavaScript. + * This is type-only, creates no runtime value, and does not affect emitted + * JavaScript. * * **Example** (Type-level usage) * @@ -137,14 +137,14 @@ export interface PredicateTypeLambda extends TypeLambda { * * **When to use** * - * Use when you want a runtime check that refines `A` to `B` for TypeScript. - * - You want to compose multiple type guards with {@link compose}. - * - You need to guard `unknown` values safely. + * Use when you want a runtime check that refines `A` to `B` for TypeScript, + * especially when composing type guards with {@link compose} or safely + * checking `unknown` values. * * **Details** * - * - Returns a type predicate (`a is B`). - * - Use with `if`/`filter` to narrow types. + * A refinement returns a type predicate (`a is B`). Use it with `if` or + * `filter` to narrow types. * * **Example** (Narrow unknown) * @@ -174,13 +174,13 @@ export interface Refinement { * * **When to use** * - * Use when you need to extract input types from predicate signatures. - * - You want to write generic helpers over predicate types. + * Use when you need to extract input types from predicate signatures while + * writing generic helpers over predicate types. * * **Details** * - * - Type-only; no runtime value is created. - * - The namespace is erased at runtime. + * These utilities are type-only, create no runtime values, and the namespace is + * erased at runtime. * * **Example** (Extract predicate input) * @@ -201,13 +201,13 @@ export declare namespace Predicate { * * **When to use** * - * Use when you want to infer the input type from a predicate type. - * - You are defining generic utilities over predicates. + * Use when you want to infer the input type from a predicate type while + * defining generic utilities over predicates. * * **Details** * - * - Type-only; no runtime value is created. - * - Resolves to `never` if the type does not match `Predicate`. + * This is type-only and creates no runtime value. It resolves to `never` if + * the type does not match `Predicate`. * * **Example** (Infer input) * @@ -234,7 +234,7 @@ export declare namespace Predicate { * * **Details** * - * - Type-only; no runtime value is created. + * This is type-only and creates no runtime value. * * **Example** (Generic constraint) * @@ -256,13 +256,13 @@ export declare namespace Predicate { * * **When to use** * - * Use when you need to extract input/output types from refinement signatures. - * - You want to write generic helpers over refinements. + * Use when you need to extract input and output types from refinement + * signatures while writing generic helpers over refinements. * * **Details** * - * - Type-only; no runtime value is created. - * - The namespace is erased at runtime. + * These utilities are type-only, create no runtime values, and the namespace is + * erased at runtime. * * **Example** (Extract refinement types) * @@ -288,8 +288,8 @@ export declare namespace Refinement { * * **Details** * - * - Type-only; no runtime value is created. - * - Resolves to `never` if the type does not match `Refinement`. + * This is type-only and creates no runtime value. It resolves to `never` if + * the type does not match `Refinement`. * * **Example** (Infer input) * @@ -317,8 +317,8 @@ export declare namespace Refinement { * * **Details** * - * - Type-only; no runtime value is created. - * - Resolves to `never` if the type does not match `Refinement`. + * This is type-only and creates no runtime value. It resolves to `never` if + * the type does not match `Refinement`. * * **Example** (Infer output) * @@ -344,7 +344,7 @@ export declare namespace Refinement { * * **Details** * - * - Type-only; no runtime value is created. + * This is type-only and creates no runtime value. * * **Example** (Generic constraint) * @@ -367,13 +367,13 @@ export declare namespace Refinement { * * **When to use** * - * Use when you have a predicate on `A` and want one on `B` via `B -> A`. - * - You want to check derived values (lengths, projections, etc.). + * Use when you have a predicate on `A` and want to check `B` values by mapping + * each `B` to an `A`, such as checking lengths or projections. * * **Details** * - * - Returns a new predicate that applies `f` before `self`. - * - No short-circuit beyond what `self` does. + * Returns a new predicate that applies `f` before `self`. There is no + * additional short-circuiting beyond what `self` does. * * **Example** (Check string length) * @@ -403,13 +403,13 @@ export const mapInput: { * * **When to use** * - * Use when you need a runtime check for tuple length. - * - You want to narrow `ReadonlyArray` to `TupleOf`. + * Use when you need a runtime check for exact tuple length that narrows + * `ReadonlyArray` to `TupleOf`. * * **Details** * - * - Only checks length, not element types. - * - Returns a refinement on the array type. + * This only checks length, not element types, and returns a refinement on the + * array type. * * **Example** (Exact length) * @@ -436,13 +436,13 @@ export const isTupleOf: { * * **When to use** * - * Use when you need a runtime check for tuple-like minimum length. - * - You want to narrow `ReadonlyArray` to `TupleOfAtLeast`. + * Use when you need a runtime check for tuple-like minimum length that narrows + * `ReadonlyArray` to `TupleOfAtLeast`. * * **Details** * - * - Only checks length, not element types. - * - Returns a refinement on the array type. + * This only checks length, not element types, and returns a refinement on the + * array type. * * **Example** (Minimum length) * @@ -469,13 +469,13 @@ export const isTupleOfAtLeast: { * * **When to use** * - * Use when you want a predicate that mirrors JavaScript truthiness. - * - You need to filter out falsy values like `0`, "", and `false`. + * Use when you want a predicate that mirrors JavaScript truthiness and filters + * out falsy values like `0`, `""`, and `false`. * * **Details** * - * - Uses `!!input` under the hood. - * - Treats `0`, "", `false`, `null`, and `undefined` as false. + * This uses `!!input` and treats `0`, `""`, `false`, `null`, and `undefined` + * as false. * * **Example** (Filter truthy) * @@ -506,7 +506,7 @@ export function isTruthy(input: unknown): boolean { * * **Details** * - * - Uses `instanceof Set`. + * Uses `instanceof Set`. * * **Example** (Guard a Set) * @@ -538,7 +538,7 @@ export function isSet(input: unknown): input is Set { * * **Details** * - * - Uses `instanceof Map`. + * Uses `instanceof Map`. * * **Example** (Guard a Map) * @@ -566,12 +566,12 @@ export function isMap(input: unknown): input is Map { * * **When to use** * - * Use when you need to guard an `unknown` value as a string. - * - You want to narrow in `if` statements. + * Use when you need to guard an `unknown` value as a string and narrow it in + * `if` statements. * * **Details** * - * - Uses `typeof input === "string"`. + * Uses `typeof input === "string"`. * * **Example** (Guard string) * @@ -604,8 +604,7 @@ export function isString(input: unknown): input is string { * * **Details** * - * - Uses `typeof input === "number"`. - * - Does not exclude `NaN` or `Infinity`. + * Uses `typeof input === "number"` and does not exclude `NaN` or `Infinity`. * * **Example** (Guard number) * @@ -637,7 +636,7 @@ export function isNumber(input: unknown): input is number { * * **Details** * - * - Uses `typeof input === "boolean"`. + * Uses `typeof input === "boolean"`. * * **Example** (Guard boolean) * @@ -669,7 +668,7 @@ export function isBoolean(input: unknown): input is boolean { * * **Details** * - * - Uses `typeof input === "bigint"`. + * Uses `typeof input === "bigint"`. * * **Example** (Guard bigint) * @@ -700,7 +699,7 @@ export function isBigInt(input: unknown): input is bigint { * * **Details** * - * - Uses `typeof input === "symbol"`. + * Uses `typeof input === "symbol"`. * * **Example** (Guard symbol) * @@ -731,7 +730,7 @@ export function isSymbol(input: unknown): input is symbol { * * **Details** * - * - Uses {@link isString}, {@link isNumber}, and {@link isSymbol}. + * Uses `isString`, `isNumber`, and `isSymbol`. * * **Example** (Guard property key) * @@ -765,7 +764,7 @@ export function isPropertyKey(u: unknown): u is PropertyKey { * * **Details** * - * - Uses `typeof input === "function"`. + * Uses `typeof input === "function"`. * * **Example** (Guard function) * @@ -796,7 +795,7 @@ export function isFunction(input: unknown): input is Function { * * **Details** * - * - Uses `input === undefined`. + * Uses `input === undefined`. * * **Example** (Guard undefined) * @@ -826,7 +825,7 @@ export function isUndefined(input: unknown): input is undefined { * * **Details** * - * - Returns a refinement that excludes `undefined`. + * Returns a refinement that excludes `undefined`. * * **Example** (Filter undefined) * @@ -857,7 +856,7 @@ export function isNotUndefined(input: A): input is Exclude { * * **Details** * - * - Uses `input === null`. + * Uses `input === null`. * * **Example** (Guard null) * @@ -887,7 +886,7 @@ export function isNull(input: unknown): input is null { * * **Details** * - * - Returns a refinement that excludes `null`. + * Returns a refinement that excludes `null`. * * **Example** (Filter null) * @@ -918,7 +917,7 @@ export function isNotNull(input: A): input is Exclude { * * **Details** * - * - Uses `input === null || input === undefined`. + * Uses `input === null || input === undefined`. * * **Example** (Guard nullish) * @@ -950,7 +949,7 @@ export function isNullish(input: A): input is A & (null | undefined) { * * **Details** * - * - Uses `input != null`. + * Uses `input != null`. * * **Example** (Filter non-nullish) * @@ -982,7 +981,7 @@ export function isNotNullish(input: A): input is NonNullable { * * **Details** * - * - Always returns `false`. + * Always returns `false`. * * **Example** (Never matches) * @@ -1009,7 +1008,7 @@ export function isNever(_: unknown): _ is never { * * **Details** * - * - Always returns `true`. + * Always returns `true`. * * **Example** (Always matches) * @@ -1036,8 +1035,7 @@ export function isUnknown(_: unknown): _ is unknown { * * **Details** * - * - Uses `typeof input === "object" && input !== null`. - * - Includes arrays. + * Uses `typeof input === "object" && input !== null` and includes arrays. * * **Example** (Object or array) * @@ -1129,7 +1127,7 @@ export function isReadonlyObject(input: unknown): input is { readonly [x: Proper * * **Details** * - * - Returns `true` for arrays and functions, `false` for `null`. + * Returns `true` for arrays and functions, and `false` for `null`. * * **Example** (Object keyword) * @@ -1154,13 +1152,13 @@ export function isObjectKeyword(input: unknown): input is object { * * **When to use** * - * Use when you need to guard property access on `unknown` values. - * - You want a simple structural guard for objects. + * Use when you need to guard property access on `unknown` values with a simple + * structural object check. * * **Details** * - * - Uses the `in` operator and {@link isObjectKeyword}. - * - Does not check property value types. + * Uses the `in` operator and `isObjectKeyword`. This does not check property + * value types. * * **Example** (Guard property) * @@ -1194,12 +1192,12 @@ export const hasProperty: { * * **When to use** * - * Use when you model tagged unions with a `_tag` field. - * - You want a quick, structural guard for tagged values. + * Use when you model tagged unions with a `_tag` field and want a quick, + * structural guard for tagged values. * * **Details** * - * - Uses {@link hasProperty} and strict equality on `_tag`. + * Uses `hasProperty` and strict equality on `_tag`. * * **Example** (Guard tagged) * @@ -1232,7 +1230,7 @@ export const isTagged: { * * **Details** * - * - Uses `instanceof Error`. + * Uses `instanceof Error`. * * **Example** (Guard error) * @@ -1261,7 +1259,7 @@ export function isError(input: unknown): input is Error { * * **Details** * - * - Uses `instanceof Uint8Array`. + * Uses `instanceof Uint8Array`. * * **Example** (Guard Uint8Array) * @@ -1291,7 +1289,7 @@ export function isUint8Array(input: unknown): input is Uint8Array { * * **Details** * - * - Uses `instanceof Date`. + * Uses `instanceof Date`. * * **Example** (Guard Date) * @@ -1320,8 +1318,7 @@ export function isDate(input: unknown): input is Date { * * **Details** * - * - Accepts strings as iterable. - * - Uses {@link hasProperty} for `Symbol.iterator`. + * Accepts strings as iterable and uses `hasProperty` for `Symbol.iterator`. * * **Example** (Guard iterable) * @@ -1351,7 +1348,7 @@ export function isIterable(input: unknown): input is Iterable { * * **Details** * - * - Structural check for `then` and `catch` functions. + * Performs a structural check for `then` and `catch` functions. * * **Example** (Guard promise) * @@ -1381,7 +1378,7 @@ export function isPromise(input: unknown): input is Promise { * * **Details** * - * - Structural check for a callable `then`. + * Performs a structural check for a callable `then`. * * **Example** (Guard promise-like) * @@ -1410,7 +1407,7 @@ export function isPromiseLike(input: unknown): input is PromiseLike { * * **Details** * - * - Uses `instanceof RegExp`. + * Uses `instanceof RegExp`. * * **Example** (Guard RegExp) * @@ -1435,13 +1432,13 @@ export function isRegExp(input: unknown): input is RegExp { * * **When to use** * - * Use when you want to chain two refinements for progressive narrowing. - * - You want a predicate that applies two checks in sequence. + * Use when you want to apply two checks in sequence, especially when chaining + * refinements for progressive narrowing. * * **Details** * - * - For refinements, the output type is narrowed by both. - * - Short-circuits on the first `false`. + * For refinements, the output type is narrowed by both checks. Evaluation + * short-circuits on the first `false`. * * **Example** (Compose refinements) * @@ -1477,13 +1474,13 @@ export const compose: { * * **When to use** * - * Use when you want to validate tuple positions independently. - * - You want to lift element predicates into a tuple predicate. + * Use when you want to validate tuple positions independently by lifting + * element predicates into a tuple predicate. * * **Details** * - * - Returns a refinement if any element predicate is a refinement. - * - Stops at the first failing element. + * Returns a refinement if any element predicate is a refinement. Evaluation + * stops at the first failing element. * * **Example** (Tuple predicate) * @@ -1523,13 +1520,13 @@ export function Tuple>( * * **When to use** * - * Use when you want to validate a record shape at runtime. - * - You want to lift property predicates into an object predicate. + * Use when you want to validate a record shape at runtime by lifting property + * predicates into an object predicate. * * **Details** * - * - Returns a refinement if any field predicate is a refinement. - * - Checks only the specified keys; extra keys are ignored. + * Returns a refinement if any field predicate is a refinement. Only the + * specified keys are checked, and extra keys are ignored. * * **Example** (Struct predicate) * @@ -1577,7 +1574,7 @@ export function Struct>( * * **Details** * - * - Returns a new predicate that flips the boolean result. + * Returns a new predicate that flips the boolean result. * * **Example** (Negate) * @@ -1604,13 +1601,13 @@ export function not(self: Predicate): Predicate { * * **When to use** * - * Use when you want to accept values that satisfy at least one condition. - * - You want to combine refinements with union narrowing. + * Use when you want to accept values that satisfy at least one condition, + * including refinements that should narrow to a union. * * **Details** * - * - Short-circuits on the first `true`. - * - For refinements, the output type is a union. + * Evaluation short-circuits on the first `true`. For refinements, the output + * type is a union. * * **Example** (Either condition) * @@ -1639,13 +1636,13 @@ export const or: { * * **When to use** * - * Use when you want to accept values that satisfy multiple conditions. - * - You want to combine refinements with intersection narrowing. + * Use when you want to accept values that satisfy multiple conditions, + * including refinements that should narrow to an intersection. * * **Details** * - * - Short-circuits on the first `false`. - * - For refinements, the output type is an intersection. + * Evaluation short-circuits on the first `false`. For refinements, the output + * type is an intersection. * * **Example** (Both conditions) * @@ -1686,7 +1683,7 @@ export const and: { * * **Details** * - * - Returns `true` when results differ. + * Returns `true` when results differ. * * **Example** (Exclusive or) * @@ -1719,7 +1716,7 @@ export const xor: { * * **Details** * - * - Returns `true` when both results are equal. + * Returns `true` when both results are equal. * * **Example** (Equivalence) * @@ -1751,8 +1748,8 @@ export const eqv: { * * **Details** * - * - Models constraints like "if A then B". - * - Returns `true` when the antecedent is `false`. + * Models constraints like "if A then B" and returns `true` when the antecedent + * is `false`. * * **Example** (Implication) * @@ -1788,7 +1785,7 @@ export const implies: { * * **Details** * - * - Returns the negation of {@link or}. + * Returns the negation of `or`. * * **Example** (NOR) * @@ -1822,7 +1819,7 @@ export const nor: { * * **Details** * - * - Returns the negation of {@link and}. + * Returns the negation of `and`. * * **Example** (NAND) * @@ -1856,8 +1853,8 @@ export const nand: { * * **Details** * - * - Short-circuits on the first `false`. - * - Iterates the collection each time the predicate is called. + * Evaluation short-circuits on the first `false`. The collection is iterated + * each time the predicate is called. * * **Example** (All checks) * @@ -1894,8 +1891,8 @@ export function every(collection: Iterable>): Predicate { * * **Details** * - * - Short-circuits on the first `true`. - * - Iterates the collection each time the predicate is called. + * Evaluation short-circuits on the first `true`. The collection is iterated + * each time the predicate is called. * * **Example** (Any check) * diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index 62ea51ec07..e820b43f17 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -107,14 +107,14 @@ import * as Str from "./String.ts" * * **Details** * - * - A getter wraps a function `Option -> Effect, Issue, R>`. - * - Receives `Option.None` when the encoded key is absent (e.g. missing struct field). - * - Returns `Option.None` to omit the value from the decoded output. - * - Fails with `Issue` on invalid input. - * - May require Effect services via `R`. - * - `.map(f)` applies `f` to the decoded value (inside the `Some`), leaving `None` unchanged. - * - `.compose(other)` chains two getters: the output of `this` feeds into `other`. - * Passthrough getters on either side are optimized away. + * A getter wraps a function `Option -> Effect, Issue, R>`. It + * receives `Option.None` when the encoded key is absent, such as a missing + * struct field, and returns `Option.None` to omit the value from the decoded + * output. It fails with `Issue` on invalid input and may require Effect + * services via `R`. `.map(f)` applies `f` to the decoded value inside `Some` + * while leaving `None` unchanged. `.compose(other)` chains two getters by + * feeding the output of `this` into `other`; passthrough getters on either side + * are optimized away. * * **Example** (Creating and composing getters) * diff --git a/packages/effect/src/UndefinedOr.ts b/packages/effect/src/UndefinedOr.ts index 099a5470c8..116e8498a2 100644 --- a/packages/effect/src/UndefinedOr.ts +++ b/packages/effect/src/UndefinedOr.ts @@ -205,11 +205,11 @@ export const liftThrowable = , B>( * * **Details** * - * - `undefined` + `undefined` -> `undefined` - * - `a` + `undefined` -> `a` (first value wins) - * - `undefined` + `b` -> `b` (second value wins) - * - `a` + `b` -> `combiner.combine(a, b)` - * - Initial value is `undefined` + * Combining `undefined` with `undefined` returns `undefined`. Combining a + * defined value with `undefined` keeps the defined value, so the first defined + * value wins when only one side is present. When both values are defined, they + * are combined with `combiner.combine`. The reducer's initial value is + * `undefined`. * * @category constructors * @since 4.0.0 diff --git a/packages/effect/src/unstable/cli/Param.ts b/packages/effect/src/unstable/cli/Param.ts index 1963ac0b0d..5597e31e3e 100644 --- a/packages/effect/src/unstable/cli/Param.ts +++ b/packages/effect/src/unstable/cli/Param.ts @@ -1479,8 +1479,8 @@ export type VariadicParamOptions = { * **Details** * * This is the base combinator for creating parameters that accept multiple values. - * The min and max parameters are optional - if not provided, the parameter can be - * specified any number of times (0 to infinity). + * The `min` and `max` parameters are optional. When they are not provided, the + * parameter can be specified any number of times, from 0 to infinity. * * **Example** (Accepting multiple values) * From 1f47a385f517ad482eb75a0341d93c54d8e0beda Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 16:12:51 +0200 Subject: [PATCH 22/29] wip --- packages/effect/src/Array.ts | 33 +++--- packages/effect/src/Context.ts | 10 +- packages/effect/src/Effect.ts | 59 +++++----- packages/effect/src/Exit.ts | 17 ++- packages/effect/src/Layer.ts | 34 +++--- packages/effect/src/Order.ts | 36 +++--- packages/effect/src/Predicate.ts | 112 +++++++++++-------- packages/effect/src/Result.ts | 18 +-- packages/effect/src/SchemaIssue.ts | 13 +-- packages/effect/src/SchemaParser.ts | 10 +- packages/effect/src/Struct.ts | 2 +- packages/effect/src/unstable/ai/Telemetry.ts | 9 +- 12 files changed, 189 insertions(+), 164 deletions(-) diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 2dd5277d14..c0e1ab064d 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -1459,8 +1459,8 @@ export const takeWhile: { * * **When to use** * - * Use when you need to take a prefix of elements while a function can - * successfully extract or transform them, stopping at the first element + * Use when you need to take a prefix from an iterable while a function can + * successfully extract or transform elements, stopping at the first element * that produces a failure result. * * **Details** @@ -1663,8 +1663,8 @@ export const dropWhile: { * * **When to use** * - * Use when you need to drop a prefix by computing a `Result` per element - * instead of using a simple boolean predicate. + * Use when you need to drop a prefix from an iterable by computing a `Result` + * per element instead of using a simple boolean predicate. * * **Details** * @@ -3616,8 +3616,8 @@ export const flatten: >>(self: * * **When to use** * - * Use to collect only present values from `Option` values while discarding - * `None` values. + * Use to collect only present values from an iterable of `Option` values while + * discarding `None` values. * * **Example** (Extracting Some values) * @@ -3652,8 +3652,8 @@ export const getSomes: >, X = any>( * * **When to use** * - * Use to collect only failure values from `Result` values while discarding - * successes. + * Use to collect only failure values from an iterable of `Result` values while + * discarding successes. * * **Example** (Extracting failures) * @@ -3689,8 +3689,8 @@ export const getFailures = >>( * * **When to use** * - * Use to collect only success values from `Result` values while discarding - * failures. + * Use to collect only success values from an iterable of `Result` values while + * discarding failures. * * **Example** (Extracting successes) * @@ -3725,8 +3725,8 @@ export const getSuccesses = >>( * * **When to use** * - * Use to transform elements with a `Result`-returning filter while discarding - * failures. + * Use to filter an iterable with a `Result`-returning transformation while + * discarding failures. * * **Details** * @@ -3767,7 +3767,8 @@ export const filterMap: { * * **When to use** * - * Use to keep original elements that satisfy a boolean predicate or refinement. + * Use to keep original elements from an iterable that satisfy a boolean + * predicate or refinement. * * **Details** * @@ -3812,8 +3813,8 @@ export const filter: { * * **When to use** * - * Use to evaluate each element with a `Result`-returning filter and keep both - * failure and success values. + * Use to partition an iterable by evaluating each element with a + * `Result`-returning filter and keeping both failure and success values. * * **Details** * @@ -3871,7 +3872,7 @@ export const partition: { * * **When to use** * - * Use to split existing `Result` values into failure and success arrays. + * Use to split an iterable of `Result` values into failure and success arrays. * * **Details** * diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index 9076e0ff75..bcd2bfb02e 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -742,7 +742,7 @@ export const add: { * * **When to use** * - * Use when you already have service presence represented as an `Option`. + * Use when you need to add or omit a `Context` service based on an `Option`. * * **Details** * @@ -1048,8 +1048,8 @@ const serviceNotFoundError = (service: Key) => { * * **When to use** * - * Use when you expect a service to be absent and want absence represented as - * data. + * Use when you need to read a `Context` service as an `Option` so absence is + * represented as data. * * **Details** * @@ -1195,7 +1195,7 @@ export const mergeAll = >( * * **When to use** * - * Use when you want to keep a small allowlist of services. + * Use when you want to keep an allowlist of services in a `Context`. * * **Example** (Picking services from a context) * @@ -1242,7 +1242,7 @@ export const pick = >>( * * **When to use** * - * Use when you want to remove a small denylist of services. + * Use when you want to remove a denylist of services from a `Context`. * * **Example** (Omitting services from a context) * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 62d4ae70b9..88447bd3e8 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -2159,15 +2159,15 @@ export const tap: { * * **When to use** * - * Use when you want to handle typed failures as data while preserving the original - * error value. + * Use when you want an `Effect`'s typed failures to be handled as `Result` + * data while preserving the original error value. * * **Details** * * This function converts an effect that may fail into an effect that always * succeeds, wrapping the outcome in a `Result` type. The result will be - * `Result.Err` if the effect fails, containing the recoverable error, or - * `Result.Ok` if it succeeds, containing the result. + * `Result.Failure` if the effect fails, containing the recoverable error, or + * `Result.Success` if it succeeds, containing the result. * * Using this function, you can handle recoverable errors explicitly without * causing the effect to fail. This is particularly useful in scenarios where @@ -2442,8 +2442,7 @@ export const asVoid: (self: Effect) => Effect = in * * **When to use** * - * Use to handle the failure value as a success, or move the success value into - * the failure channel. + * Use to swap an `Effect`'s success and failure channels. * * **Details** * @@ -3495,7 +3494,8 @@ export const catchCauseFilter: { * * **When to use** * - * Use to translate typed failures while leaving successful values unchanged. + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. * * **Details** * @@ -3537,8 +3537,8 @@ export const mapError: { * * **When to use** * - * Use to transform both success and failure values without changing whether the - * effect succeeds or fails. + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. * * **Details** * @@ -3588,8 +3588,8 @@ export const mapBoth: { * * **When to use** * - * Use when you need to turn a typed failure that represents an unrecoverable bug - * or invalid state into a defect. + * Use when you need to turn an `Effect` typed failure that represents an + * unrecoverable bug or invalid state into a defect. * * **Example** (Converting typed failures into defects) * @@ -4375,9 +4375,9 @@ export const orElseSucceed: { * * **When to use** * - * Use when you have prioritized fallback strategies, such as - * attempting multiple APIs, reading configuration from several sources, or - * trying alternative resource locations in order. + * Use when you have prioritized fallback `Effect`s, such as attempting + * multiple APIs, reading configuration from several sources, or trying + * alternative resource locations in order. * * **Details** * @@ -4427,7 +4427,8 @@ export const firstSuccessOf: >( * * **When to use** * - * Use when you need to represent exceeding the time limit as a typed failure. + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. * * **Details** * @@ -4493,7 +4494,7 @@ export const timeout: { * * **When to use** * - * Use when a timeout should be handled as absence. + * Use when a timeout of an `Effect` should be handled as `Option.none`. * * **Details** * @@ -4551,7 +4552,7 @@ export const timeoutOption: { * * **When to use** * - * Use when a timeout should switch to a fallback effect. + * Use when a timeout of an `Effect` should switch to a fallback effect. * * **Details** * @@ -5245,8 +5246,8 @@ export const when: { * * **When to use** * - * Use when you need to respond differently to success or failure without - * triggering side effects. + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. * * **Details** * @@ -5311,8 +5312,8 @@ export const match: { * * **When to use** * - * Use when you need to handle both success and failure cases and want optimized - * handling for effects that may already be resolved. + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. * * **Details** * @@ -5359,7 +5360,8 @@ export const matchEager: { * * **When to use** * - * Use when you need failure handling to inspect the full cause. + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. * * **Details** * @@ -5407,8 +5409,8 @@ export const matchCause: { * * **When to use** * - * Use when you expect effects to already be resolved and want to match the - * cause without regular effect pipeline overhead. + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. * * **Details** * @@ -5450,7 +5452,7 @@ export const matchCauseEager: { * **When to use** * * Use when you need effectful success and cause-aware failure handlers for - * inputs that may already be resolved. + * `Effect` inputs that may already be resolved. * * **Details** * @@ -5485,8 +5487,8 @@ export const matchCauseEffectEager: { * * **When to use** * - * Use when you need both success and failure handlers to return effects and the - * failure handler to inspect the full `Cause`. + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. * * **Details** * @@ -5558,7 +5560,8 @@ export const matchCauseEffect: { * * **When to use** * - * Use when you need the failure or success handler to run additional effects. + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. * * **Details** * diff --git a/packages/effect/src/Exit.ts b/packages/effect/src/Exit.ts index 19e4275907..a6261cd9a4 100644 --- a/packages/effect/src/Exit.ts +++ b/packages/effect/src/Exit.ts @@ -512,7 +512,7 @@ export const hasFails: (self: Exit) => self is Failure = effec * * **When to use** * - * Use to check for unexpected errors. + * Use to check whether an `Exit` failure cause contains unexpected errors. * * **Details** * @@ -542,7 +542,7 @@ export const hasDies: (self: Exit) => self is Failure = effect * * **When to use** * - * Use to check if a fiber was interrupted. + * Use to check whether an `Exit` contains fiber interruption. * * **Details** * @@ -804,13 +804,13 @@ export const findDefect: (input: Exit) => Result.Result = succeedContext(Context.empty()) * * **When to use** * - * Use when you need to provide one service whose value is created + * Use when you need a `Layer` that provides one service whose value is created * synchronously, but creation should be deferred until the layer is built. * * **Details** @@ -933,8 +934,8 @@ export const sync: { * * **When to use** * - * Use when you need to create multiple services synchronously but defer that - * work until the layer is built. + * Use when you need a `Layer` that creates multiple services synchronously but + * defers that work until the layer is built. * * **Details** * @@ -971,8 +972,8 @@ export const syncContext = (evaluate: LazyArg>): Layer * * **When to use** * - * Use when you need to construct a service with an Effect, dependencies, or - * scoped resource acquisition. + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. * * **Details** * @@ -1028,8 +1029,8 @@ const effectImpl = ( * * **When to use** * - * Use when you need effectful construction to provide multiple services at - * once. + * Use when you need a `Layer` that effectfully constructs a `Context` with + * multiple services. * * **Details** * @@ -1440,8 +1441,8 @@ export const provide: { * * **When to use** * - * Use when you need both the constructed service and the dependency used to - * build it to remain available. + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. * * **Details** * @@ -1837,7 +1838,8 @@ export { * * **When to use** * - * Use when every typed construction error should use the same recovery path. + * Use when every typed `Layer` construction error should use the same + * recovery path. * * @see {@link catchTag} for recovering from specific tagged errors * @see {@link catchCause} for recovering with access to the full cause @@ -1853,7 +1855,7 @@ export { * * **When to use** * - * Use when only some tagged construction errors should be recovered. + * Use when only some tagged `Layer` construction errors should be recovered. * * **Example** (Recovering from tagged layer errors) * @@ -1936,8 +1938,8 @@ export const catchTag: { * * **When to use** * - * Use when you need recovery to inspect more than the typed error, such as - * defects or interruption information. + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. * * **Details** * diff --git a/packages/effect/src/Order.ts b/packages/effect/src/Order.ts index a4b3c9f226..234f28119b 100644 --- a/packages/effect/src/Order.ts +++ b/packages/effect/src/Order.ts @@ -482,7 +482,8 @@ export function combineAll(collection: Iterable>): Order { * * **When to use** * - * Use when you need to compare a larger value by one derived property. + * Use when you need to adapt an `Order` to compare a larger value by one + * derived property. * * **Details** * @@ -701,13 +702,12 @@ export function Struct }>( * * **When to use** * - * Use when you need a boolean less-than predicate. + * Use when you need a boolean less-than predicate using an `Order`. * * **Details** * * Returns `true` if the order returns `-1`, meaning the first value is less - * than the second. Equal or greater values return `false`. Both curried and - * uncurried call styles are supported. + * than the second. Equal or greater values return `false`. * * **Example** (Less Than) * @@ -736,13 +736,12 @@ export const isLessThan = (O: Order): { * * **When to use** * - * Use when you need a boolean greater-than predicate. + * Use when you need a boolean greater-than predicate using an `Order`. * * **Details** * * Returns `true` if the order returns `1`, meaning the first value is greater - * than the second. Equal or lesser values return `false`. Both curried and - * uncurried call styles are supported. + * than the second. Equal or lesser values return `false`. * * **Example** (Greater Than) * @@ -771,7 +770,7 @@ export const isGreaterThan = (O: Order): { * * **When to use** * - * Use when you need a boolean less-than-or-equal predicate. + * Use when you need a boolean less-than-or-equal predicate using an `Order`. * * **Details** * @@ -805,7 +804,8 @@ export const isLessThanOrEqualTo = (O: Order): { * * **When to use** * - * Use when you need a boolean greater-than-or-equal predicate. + * Use when you need a boolean greater-than-or-equal predicate using an + * `Order`. * * **Details** * @@ -839,13 +839,13 @@ export const isGreaterThanOrEqualTo = (O: Order): { * * **When to use** * - * Use when you need to select the smaller of two values. + * Use when you need to select the smaller of two values according to an + * `Order`. * * **Details** * * Returns the value that compares as less than or equal to the other value. If - * values are equal, the first argument is returned. Both curried and uncurried - * call styles are supported. + * values are equal, the first argument is returned. * * **Example** (Minimum Value) * @@ -874,13 +874,13 @@ export const min = (O: Order): { * * **When to use** * - * Use when you need to select the larger of two values. + * Use when you need to select the larger of two values according to an + * `Order`. * * **Details** * * Returns the value that compares as greater than or equal to the other value. - * If values are equal, the first argument is returned. Both curried and - * uncurried call styles are supported. + * If values are equal, the first argument is returned. * * **Example** (Maximum Value) * @@ -909,7 +909,8 @@ export const max = (O: Order): { * * **When to use** * - * Use when you need to clamp a value to an inclusive range. + * Use when you need to clamp a value to an inclusive range according to an + * `Order`. * * **Details** * @@ -959,7 +960,8 @@ export const clamp = (O: Order): { * * **When to use** * - * Use when you need to check whether a value is within an inclusive range. + * Use when you need to check whether a value is within an inclusive range + * according to an `Order`. * * **Details** * diff --git a/packages/effect/src/Predicate.ts b/packages/effect/src/Predicate.ts index 5fa42f9894..5888df08a9 100644 --- a/packages/effect/src/Predicate.ts +++ b/packages/effect/src/Predicate.ts @@ -403,7 +403,7 @@ export const mapInput: { * * **When to use** * - * Use when you need a runtime check for exact tuple length that narrows + * Use when you need a `Predicate` guard for exact tuple length that narrows * `ReadonlyArray` to `TupleOf`. * * **Details** @@ -436,8 +436,8 @@ export const isTupleOf: { * * **When to use** * - * Use when you need a runtime check for tuple-like minimum length that narrows - * `ReadonlyArray` to `TupleOfAtLeast`. + * Use when you need a `Predicate` guard for tuple-like minimum length that + * narrows `ReadonlyArray` to `TupleOfAtLeast`. * * **Details** * @@ -502,7 +502,7 @@ export function isTruthy(input: unknown): boolean { * * **When to use** * - * Use when you need a runtime guard for `Set` values. + * Use when you need a `Predicate` runtime guard for `Set` values. * * **Details** * @@ -534,7 +534,7 @@ export function isSet(input: unknown): input is Set { * * **When to use** * - * Use when you need a runtime guard for `Map` values. + * Use when you need a `Predicate` runtime guard for `Map` values. * * **Details** * @@ -566,8 +566,8 @@ export function isMap(input: unknown): input is Map { * * **When to use** * - * Use when you need to guard an `unknown` value as a string and narrow it in - * `if` statements. + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * string. * * **Details** * @@ -600,7 +600,8 @@ export function isString(input: unknown): input is string { * * **When to use** * - * Use when you need to guard an `unknown` value as a number. + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * number. * * **Details** * @@ -632,7 +633,8 @@ export function isNumber(input: unknown): input is number { * * **When to use** * - * Use when you need to guard an `unknown` value as a boolean. + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * boolean. * * **Details** * @@ -664,7 +666,8 @@ export function isBoolean(input: unknown): input is boolean { * * **When to use** * - * Use when you need to guard an `unknown` value as a bigint. + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * bigint. * * **Details** * @@ -695,7 +698,8 @@ export function isBigInt(input: unknown): input is bigint { * * **When to use** * - * Use when you need to guard an `unknown` value as a symbol. + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * symbol. * * **Details** * @@ -726,7 +730,8 @@ export function isSymbol(input: unknown): input is symbol { * * **When to use** * - * Use when you need to guard unknown keys before indexing. + * Use when you need a `Predicate` guard for unknown property keys before + * indexing. * * **Details** * @@ -760,7 +765,8 @@ export function isPropertyKey(u: unknown): u is PropertyKey { * * **When to use** * - * Use when you need to guard an `unknown` value as callable. + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * callable function. * * **Details** * @@ -791,7 +797,8 @@ export function isFunction(input: unknown): input is Function { * * **When to use** * - * Use when you need to guard unknown values that are exactly `undefined`. + * Use when you need a `Predicate` guard for values that are exactly + * `undefined`. * * **Details** * @@ -821,7 +828,8 @@ export function isUndefined(input: unknown): input is undefined { * * **When to use** * - * Use when you want to filter out `undefined` while preserving other falsy values. + * Use when you need a `Predicate` refinement that filters out `undefined` + * while preserving other falsy values. * * **Details** * @@ -852,7 +860,7 @@ export function isNotUndefined(input: A): input is Exclude { * * **When to use** * - * Use when you need a guard for nullable values. + * Use when you need a `Predicate` guard for nullable values. * * **Details** * @@ -882,7 +890,8 @@ export function isNull(input: unknown): input is null { * * **When to use** * - * Use when you want to filter out `null` while preserving other falsy values. + * Use when you need a `Predicate` refinement that filters out `null` while + * preserving other falsy values. * * **Details** * @@ -913,7 +922,7 @@ export function isNotNull(input: A): input is Exclude { * * **When to use** * - * Use when you want to guard nullish values explicitly. + * Use when you need a `Predicate` guard for nullish values. * * **Details** * @@ -945,7 +954,8 @@ export function isNullish(input: A): input is A & (null | undefined) { * * **When to use** * - * Use when you want to filter out nullish values but keep other falsy ones. + * Use when you need a `Predicate` refinement that filters out nullish values + * but keeps other falsy ones. * * **Details** * @@ -977,7 +987,7 @@ export function isNotNullish(input: A): input is NonNullable { * * **When to use** * - * Use when you need a predicate that never accepts, e.g. in default branches. + * Use when you need a `Predicate` that never accepts, e.g. in default branches. * * **Details** * @@ -1004,7 +1014,7 @@ export function isNever(_: unknown): _ is never { * * **When to use** * - * Use when you need a predicate that always accepts, e.g. as a placeholder. + * Use when you need a `Predicate` that always accepts, e.g. as a placeholder. * * **Details** * @@ -1031,7 +1041,8 @@ export function isUnknown(_: unknown): _ is unknown { * * **When to use** * - * Use when you want to accept plain objects and arrays, but not `null`. + * Use when you need a `Predicate` guard that accepts plain objects and arrays, + * but not `null`. * * **Details** * @@ -1059,7 +1070,8 @@ export function isObjectOrArray(input: unknown): input is { [x: PropertyKey]: un * * **When to use** * - * Use to narrow unknown input to a non-null, non-array object. + * Use to narrow unknown input to a non-null, non-array object with a + * `Predicate` guard. * * **Details** * @@ -1092,7 +1104,7 @@ export function isObject(input: unknown): input is { [x: PropertyKey]: unknown } * **When to use** * * Use to narrow unknown input to a readonly view of a non-null, non-array - * object. + * object with a `Predicate` guard. * * **Details** * @@ -1123,7 +1135,8 @@ export function isReadonlyObject(input: unknown): input is { readonly [x: Proper * * **When to use** * - * Use when you want to accept arrays and functions as well as objects. + * Use when you need a `Predicate` guard that accepts arrays and functions as + * well as objects. * * **Details** * @@ -1152,8 +1165,8 @@ export function isObjectKeyword(input: unknown): input is object { * * **When to use** * - * Use when you need to guard property access on `unknown` values with a simple - * structural object check. + * Use when you need a `Predicate` guard for property access on `unknown` + * values with a simple structural object check. * * **Details** * @@ -1192,8 +1205,8 @@ export const hasProperty: { * * **When to use** * - * Use when you model tagged unions with a `_tag` field and want a quick, - * structural guard for tagged values. + * Use when you model tagged unions with a `_tag` field and want a quick + * `Predicate` guard for tagged values. * * **Details** * @@ -1226,7 +1239,7 @@ export const isTagged: { * * **When to use** * - * Use when you need to guard errors caught from unknown sources. + * Use when you need a `Predicate` guard for errors caught from unknown sources. * * **Details** * @@ -1255,7 +1268,7 @@ export function isError(input: unknown): input is Error { * * **When to use** * - * Use when you need to guard binary data at runtime. + * Use when you need a `Predicate` runtime guard for binary data. * * **Details** * @@ -1285,7 +1298,7 @@ export function isUint8Array(input: unknown): input is Uint8Array { * * **When to use** * - * Use when you need to guard dates at runtime. + * Use when you need a `Predicate` runtime guard for dates. * * **Details** * @@ -1314,7 +1327,7 @@ export function isDate(input: unknown): input is Date { * * **When to use** * - * Use when you need a guard before iterating an unknown value. + * Use when you need a `Predicate` guard before iterating an unknown value. * * **Details** * @@ -1344,7 +1357,7 @@ export function isIterable(input: unknown): input is Iterable { * * **When to use** * - * Use when you need to detect promise instances across realms. + * Use when you need a `Predicate` guard for promise instances across realms. * * **Details** * @@ -1373,8 +1386,8 @@ export function isPromise(input: unknown): input is Promise { * * **When to use** * - * Use when you need to recognize promise-like values by a callable `then` - * method. + * Use when you need a `Predicate` guard for promise-like values with a + * callable `then` method. * * **Details** * @@ -1403,7 +1416,7 @@ export function isPromiseLike(input: unknown): input is PromiseLike { * * **When to use** * - * Use when you need a runtime guard for regular expressions. + * Use when you need a `Predicate` runtime guard for regular expressions. * * **Details** * @@ -1432,8 +1445,8 @@ export function isRegExp(input: unknown): input is RegExp { * * **When to use** * - * Use when you want to apply two checks in sequence, especially when chaining - * refinements for progressive narrowing. + * Use when you want to compose two `Predicate` checks in sequence, especially + * when chaining refinements for progressive narrowing. * * **Details** * @@ -1601,8 +1614,8 @@ export function not(self: Predicate): Predicate { * * **When to use** * - * Use when you want to accept values that satisfy at least one condition, - * including refinements that should narrow to a union. + * Use when you want to combine `Predicate`s with OR, accepting values that + * satisfy at least one condition, including refinements that narrow to a union. * * **Details** * @@ -1636,8 +1649,9 @@ export const or: { * * **When to use** * - * Use when you want to accept values that satisfy multiple conditions, - * including refinements that should narrow to an intersection. + * Use when you want to combine `Predicate`s with AND, accepting values that + * satisfy multiple conditions, including refinements that narrow to an + * intersection. * * **Details** * @@ -1679,7 +1693,7 @@ export const and: { * * **When to use** * - * Use when you want an exclusive-or between two conditions. + * Use when you want to combine two `Predicate`s with exclusive-or semantics. * * **Details** * @@ -1712,7 +1726,7 @@ export const xor: { * * **When to use** * - * Use when you want to check equivalence of two predicates. + * Use when you want to check equivalence of two `Predicate`s. * * **Details** * @@ -1743,8 +1757,8 @@ export const eqv: { * * **When to use** * - * Use when you need to encode logical implication for a predicate rule that - * only applies when a precondition holds. + * Use when you need to encode logical implication between `Predicate` rules, + * where one rule only applies when a precondition holds. * * **Details** * @@ -1781,7 +1795,7 @@ export const implies: { * * **When to use** * - * Use when you want the logical NOR of two conditions. + * Use when you want to combine two `Predicate`s with logical NOR semantics. * * **Details** * @@ -1815,7 +1829,7 @@ export const nor: { * * **When to use** * - * Use when you want the logical NAND of two conditions. + * Use when you want to combine two `Predicate`s with logical NAND semantics. * * **Details** * diff --git a/packages/effect/src/Result.ts b/packages/effect/src/Result.ts index e275becf56..730a842bfd 100644 --- a/packages/effect/src/Result.ts +++ b/packages/effect/src/Result.ts @@ -341,7 +341,7 @@ export const succeed: (right: A) => Result = result.succeed * * **When to use** * - * Use to represent a failed computation with a typed failure value. + * Use to represent a failed `Result` with a typed failure value. * * **Details** * @@ -373,8 +373,8 @@ export { * * **When to use** * - * Use when a success should signal completion without carrying a meaningful - * value. + * Use when you need a successful `Result` value that signals completion + * without carrying meaningful data. * * **Details** * @@ -405,8 +405,8 @@ export { * * **When to use** * - * Use when a failure should act only as a control signal and no failure value - * is needed. + * Use when you need a failed `Result` value that acts only as a control signal + * without failure data. * * **Details** * @@ -682,8 +682,8 @@ export const isSuccess: (self: Result) => self is Success = re * * **When to use** * - * Use when you need to extract the success value as an `Option` and discard - * failure information. + * Use when you need to extract the success value from a `Result` as an + * `Option` and discard failure information. * * **Details** * @@ -715,8 +715,8 @@ export const getSuccess: (self: Result) => Option = result.getSuc * * **When to use** * - * Use when you need to extract the failure value as an `Option` and discard - * successful values. + * Use when you need to extract the failure value from a `Result` as an + * `Option` and discard successful values. * * **Details** * diff --git a/packages/effect/src/SchemaIssue.ts b/packages/effect/src/SchemaIssue.ts index 47c5ca2a0b..9d04973848 100644 --- a/packages/effect/src/SchemaIssue.ts +++ b/packages/effect/src/SchemaIssue.ts @@ -129,8 +129,8 @@ export function isIssue(u: unknown): u is Issue { * * **When to use** * - * Use when constraining formatter hooks to only handle terminal nodes. - * - Pattern-matching on the `_tag` of an issue when you only care about leaves. + * Use when constraining formatter hooks to only handle terminal nodes or when + * pattern matching on the `_tag` of an issue and only leaf nodes matter. * * **Details** * @@ -156,9 +156,8 @@ export type Leaf = * * **When to use** * - * Use when typing the error channel in `Effect` results from schema - * parsing. - * - Writing custom formatters or issue-tree walkers. + * Use when typing the error channel in `Effect` results from + * schema parsing, or when writing custom formatters or issue-tree walkers. * * **Details** * @@ -1139,8 +1138,8 @@ function formatCheck(check: SchemaAST.Check): string { * * **When to use** * - * Use when you need error messages for logging, CLI output, or - * developer-facing diagnostics. + * Use when you need to format a `SchemaIssue.Issue` as error messages for + * logging, CLI output, or developer-facing diagnostics. * * **Details** * diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaParser.ts index 26777dcdd6..02321d5e5c 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaParser.ts @@ -89,7 +89,7 @@ const recurDefaults = memoize((ast: SchemaAST.AST): SchemaAST.AST => { * **When to use** * * Use to construct decoded schema values in `Effect` while preserving - * construction issues in the error channel. + * construction failures as `SchemaIssue.Issue` values in the error channel. * * **Details** * @@ -119,8 +119,8 @@ export function makeEffect(schema: S) { * * **When to use** * - * Use when you need to validate constructor input and only care whether - * construction succeeds. + * Use when you need to validate schema constructor input and only care whether + * construction succeeds, without exposing `SchemaIssue.Issue` details. * * @category constructors * @since 4.0.0 @@ -138,7 +138,7 @@ export function makeOption(schema: S) { * **When to use** * * Use to construct decoded schema values synchronously when invalid input - * should throw. + * should throw an `Error` whose cause is `SchemaIssue.Issue`. * * **Details** * @@ -206,7 +206,7 @@ export function _issue(ast: SchemaAST.AST) { * **When to use** * * Use to assert that an input satisfies the decoded side of a schema, throwing - * when validation fails. + * an `Error` whose cause is `SchemaIssue.Issue` when validation fails. * * **Details** * diff --git a/packages/effect/src/Struct.ts b/packages/effect/src/Struct.ts index 8b149708c7..82b55febdf 100644 --- a/packages/effect/src/Struct.ts +++ b/packages/effect/src/Struct.ts @@ -175,7 +175,7 @@ export type Assign = Simplify Date: Fri, 29 May 2026 18:58:54 +0200 Subject: [PATCH 23/29] fix CI --- packages/effect/src/Schema.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index c33c666aaf..50ab40c539 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -1359,7 +1359,10 @@ export const decodeExit: >( * @category decoding * @since 3.10.0 */ -export const decodeUnknownOption = SchemaParser.decodeUnknownOption +export const decodeUnknownOption: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: unknown, options?: SchemaAST.ParseOptions) => Option_.Option = SchemaParser.decodeUnknownOption /** * Decodes a typed input (the schema's `Encoded` type) against a schema, @@ -1380,7 +1383,10 @@ export const decodeUnknownOption = SchemaParser.decodeUnknownOption * @category decoding * @since 3.10.0 */ -export const decodeOption = SchemaParser.decodeOption +export const decodeOption: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Option_.Option = decodeUnknownOption /** * Decodes an `unknown` input against a schema, returning a `Result` that @@ -1711,7 +1717,11 @@ export const encodeExit: >( * @category encoding * @since 3.10.0 */ -export const encodeUnknownOption = SchemaParser.encodeUnknownOption +export const encodeUnknownOption: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: unknown, options?: SchemaAST.ParseOptions) => Option_.Option = + SchemaParser.encodeUnknownOption /** * Encodes a typed input (the schema's `Type`) against a schema, returning an @@ -1732,7 +1742,10 @@ export const encodeUnknownOption = SchemaParser.encodeUnknownOption * @category encoding * @since 3.10.0 */ -export const encodeOption = SchemaParser.encodeOption +export const encodeOption: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Option_.Option = encodeUnknownOption /** * Encodes an `unknown` input against a schema, returning a `Result` that From d131597289ae7e50aca9998c89f350a0f2444661 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 19:21:34 +0200 Subject: [PATCH 24/29] wip --- packages/effect/src/Deferred.ts | 13 ++++++----- packages/effect/src/Effect.ts | 23 +++++++++++--------- packages/effect/src/Equivalence.ts | 10 +++++---- packages/effect/src/Option.ts | 35 +++++++++++++++--------------- 4 files changed, 45 insertions(+), 36 deletions(-) diff --git a/packages/effect/src/Deferred.ts b/packages/effect/src/Deferred.ts index d4d3fcaef8..a05f084261 100644 --- a/packages/effect/src/Deferred.ts +++ b/packages/effect/src/Deferred.ts @@ -289,8 +289,8 @@ export { * * **When to use** * - * Use when completion should run an effect once and share its result with all - * awaiters. + * Use when completing a `Deferred` should run an effect once and share its + * result with all awaiters. * * **Details** * @@ -453,7 +453,8 @@ export const fail: { * * **When to use** * - * Use to lazily compute a typed failure value when the completion effect runs. + * Use to lazily compute a typed failure value when the `Deferred` completion + * effect runs. * * **Details** * @@ -530,7 +531,8 @@ export const failCause: { * * **When to use** * - * Use to lazily compute a full failure cause when the completion effect runs. + * Use to lazily compute a full failure cause when the `Deferred` completion + * effect runs. * * **Details** * @@ -831,7 +833,8 @@ export const succeed: { * * **When to use** * - * Use to lazily compute a successful value when the completion effect runs. + * Use to lazily compute a successful value when the `Deferred` completion + * effect runs. * * **Details** * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 88447bd3e8..b3846e0b05 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1630,7 +1630,8 @@ export const failCauseSync: ( * * **When to use** * - * Use when you need to report an unrecoverable defect instead of a typed error. + * Use when you need an `Effect` to report an unrecoverable defect instead of a + * typed error. * * **Details** * @@ -2865,8 +2866,8 @@ export const catchTags: { * * **When to use** * - * Use to handle one nested reason inside a tagged error while preserving the - * parent error shape for unmatched reasons. + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. * * **Details** * @@ -3163,8 +3164,9 @@ export const unwrapReason: { * * **When to use** * - * Use when you need recovery to inspect the full `Cause`, including recoverable - * failures, defects, and interruptions, instead of only the typed error value. + * Use when you need to recover from an `Effect` by inspecting the full `Cause`, + * including recoverable failures, defects, and interruptions, instead of only + * the typed error value. * * **Details** * @@ -3406,7 +3408,7 @@ export const catchNoSuchElement: ( * * **When to use** * - * Use to recover from full causes selected by a predicate. + * Use to recover an `Effect` from full causes selected by a predicate. * * **Details** * @@ -3461,8 +3463,9 @@ export const catchCauseIf: { * * **When to use** * - * Use when you need to recover only from causes selected by a `Filter`, while - * giving the recovery both the selected value and the original `Cause`. + * Use when you need to recover an `Effect` only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. * * **Details** * @@ -4938,8 +4941,8 @@ export const filter: { * * **When to use** * - * Use to keep only iterable elements accepted by a `Filter` and collect each - * filter success value. + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. * * **Details** * diff --git a/packages/effect/src/Equivalence.ts b/packages/effect/src/Equivalence.ts index 92d93dde6d..03d794f8a3 100644 --- a/packages/effect/src/Equivalence.ts +++ b/packages/effect/src/Equivalence.ts @@ -390,7 +390,7 @@ export const combine: { * * **When to use** * - * Use when you need to combine many equivalences from an iterable. + * Use when you need to combine many `Equivalence` instances from an iterable. * * **Details** * @@ -532,7 +532,7 @@ export const mapInput: { * * **When to use** * - * Use when you need to compare fixed-length tuples with per-position + * Use when you need an `Equivalence` for fixed-length tuples with per-position * equivalences. * * **Details** @@ -673,7 +673,8 @@ export { * * **When to use** * - * Use when you need to compare objects with known, fixed property names. + * Use when you need an `Equivalence` for objects with known, fixed property + * names. * * **Details** * @@ -866,7 +867,8 @@ export function makeReducer() { * * **When to use** * - * Use when comparing JavaScript date objects by their millisecond timestamp. + * Use when you need an `Equivalence` for JavaScript date objects by their + * millisecond timestamp. * * **Details** * diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index b2f9ecf220..2b7e710f88 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -1115,8 +1115,8 @@ export const liftThrowable = , B>( * * **When to use** * - * Use when you need fail-fast unwrapping for unexpected absence and want to - * provide a descriptive debugging error. + * Use when you need fail-fast unwrapping of an `Option` for unexpected absence + * and want to provide a descriptive debugging error. * * **Details** * @@ -1156,8 +1156,8 @@ export const getOrThrowWith: { * * **When to use** * - * Use when you need quick fail-fast unwrapping and a generic error is - * acceptable. + * Use when you need quick fail-fast unwrapping of an `Option` and a generic + * error is acceptable. * * **Details** * @@ -1190,8 +1190,8 @@ export const getOrThrow: (self: Option) => A = getOrThrowWith(() => new Er * * **When to use** * - * Use to apply a pure transformation to an optional value, especially when - * chaining transformations in a pipeline. + * Use to apply a pure transformation to an `Option`'s present value, especially + * when chaining transformations in a pipeline. * * **Details** * @@ -1325,7 +1325,7 @@ export { * * **When to use** * - * Use when you need to chain dependent optional computations where each step + * Use when you need to chain dependent `Option` computations where each step * may return `None`. * * **Details** @@ -1634,8 +1634,8 @@ export const composeK: { * * **When to use** * - * Use to validate a value without transforming it - * - Adding a side-condition check in a pipeline + * Use to validate an `Option`'s present value without transforming it, such as + * adding a side-condition check in a pipeline. * * **Details** * @@ -2010,7 +2010,8 @@ export const partitionMap: { * * **When to use** * - * Use to transform a present value and discard it when the `Filter` fails. + * Use to transform an `Option`'s present value and discard it when the `Filter` + * fails. * * **Details** * @@ -2051,8 +2052,8 @@ export const filterMap: { * * **When to use** * - * Use when you need to discard values that don't meet a condition and narrow - * the type via a refinement predicate. + * Use when you need to discard an `Option`'s present value when it does not + * meet a condition, while narrowing the type via a refinement predicate. * * **Details** * @@ -2554,7 +2555,7 @@ export const Do: Option<{}> = some({}) * * **When to use** * - * Use when you need generator syntax for a sequence of optional steps that + * Use when you need generator syntax for a sequence of `Option` steps that * should short-circuit on `None`. * * **Details** @@ -2607,8 +2608,8 @@ export const gen: Gen.Gen = (...args) => { * * **When to use** * - * Use to build a reducer that falls back to the first available value - * - Combining optional values where either side may be absent + * Use to build an `Option` reducer that falls back to the first available value + * when either side may be absent. * * **Details** * @@ -2647,8 +2648,8 @@ export function makeReducer(combiner: Combiner.Combiner): Reducer.Reducer< * * **When to use** * - * Use when you need a combiner that returns `None` unless both operands are - * `Some`. + * Use when you need an `Option` combiner that returns `None` unless both + * operands are `Some`. * * **Details** * From bf17a1c694340208016fcc930f292dceafbd20ba Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 19:38:21 +0200 Subject: [PATCH 25/29] wip --- packages/effect/src/Array.ts | 36 ++++++++++--------- packages/effect/src/Chunk.ts | 6 ++-- packages/effect/src/JsonPatch.ts | 5 ++- packages/effect/src/Latch.ts | 3 +- packages/effect/src/Layer.ts | 3 +- packages/effect/src/MutableHashMap.ts | 11 +++--- packages/effect/src/Tuple.ts | 11 +++--- .../effect/src/unstable/http/HttpClient.ts | 4 +-- 8 files changed, 43 insertions(+), 36 deletions(-) diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index c0e1ab064d..531a6aeb85 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -632,7 +632,8 @@ export const matchRight: { * * **When to use** * - * Use to add a single element at the start of an iterable and get a `NonEmptyArray`. + * Use to add a single element at the start of an iterable and return a + * `NonEmptyArray`. * * **Details** * @@ -701,7 +702,7 @@ export const prependAll: { * * **When to use** * - * Use to add one element to the end of an iterable and get a new + * Use to add one element to the end of an iterable and return a new * `NonEmptyArray`. * * **Details** @@ -1033,8 +1034,8 @@ export const get: { * * **When to use** * - * Use to read an element at a known valid index when out-of-bounds would be a - * programming error. + * Use to read an array element at a known valid index when out-of-bounds would + * be a programming error. * * **Details** * @@ -2007,8 +2008,8 @@ export const replace: { * * **When to use** * - * Use to derive a replacement value from the current element at a specific - * index while leaving the other elements unchanged. + * Use to derive a replacement value from an array element at a specific index + * while leaving the other elements unchanged. * * **Details** * @@ -2057,7 +2058,7 @@ export const modify: { * * **When to use** * - * Use to remove a single element at a known index. + * Use to remove a single array element at a known index. * * **Example** (Removing an element) * @@ -2091,7 +2092,8 @@ export const remove: { * * **When to use** * - * Use to reverse the order of elements without mutating the original input. + * Use to reverse an iterable into a new array without mutating the original + * input. * * **Details** * @@ -2604,8 +2606,8 @@ export const containsWith = (isEquivalent: (self: A, that: A) => boolean): { * * **When to use** * - * Use to check membership with Effect's default equality instead of providing a - * comparison function. + * Use to check whether an iterable contains a value using Effect's default + * equality instead of providing a comparison function. * * **Example** (Checking membership) * @@ -2907,8 +2909,8 @@ export const pad: { * * **When to use** * - * Use to divide an iterable into non-overlapping chunks with a maximum chunk - * size. + * Use to divide an iterable into a new array of non-overlapping chunks with a + * maximum chunk size. * * **Details** * @@ -3542,8 +3544,8 @@ export const map: { * * **When to use** * - * Use to map each element to zero or more values and concatenate the results in - * one pass. + * Use to map each array element to zero or more values and concatenate the + * results in one pass. * * **Details** * @@ -3767,8 +3769,8 @@ export const filterMap: { * * **When to use** * - * Use to keep original elements from an iterable that satisfy a boolean - * predicate or refinement. + * Use to filter an iterable into a new array of original elements that satisfy + * a boolean predicate or refinement. * * **Details** * @@ -4151,7 +4153,7 @@ export const liftResult = , E, B>( * * **When to use** * - * Use to check that all elements satisfy a predicate, including + * Use to check whether every array element satisfies a predicate, including * refinement-based type narrowing. * * **Example** (Testing all elements) diff --git a/packages/effect/src/Chunk.ts b/packages/effect/src/Chunk.ts index 666b19676a..f9d2439e17 100644 --- a/packages/effect/src/Chunk.ts +++ b/packages/effect/src/Chunk.ts @@ -704,8 +704,8 @@ export const getUnsafe: { * * **When to use** * - * Use to add one element after the existing elements and get a non-empty - * result. + * Use to add one element after the existing chunk elements and return a + * `NonEmptyChunk`. * * **Example** (Appending an element) * @@ -1296,7 +1296,7 @@ export const flatten: >>(self: S) => Chunk.Flatten * * **When to use** * - * Use to divide a chunk into ordered, non-overlapping batches with at most `n` + * Use to divide a chunk into ordered, non-overlapping chunks with at most `n` * elements each. * * **Details** diff --git a/packages/effect/src/JsonPatch.ts b/packages/effect/src/JsonPatch.ts index 75d7611058..eb12307fe2 100644 --- a/packages/effect/src/JsonPatch.ts +++ b/packages/effect/src/JsonPatch.ts @@ -194,9 +194,8 @@ export type JsonPatch = ReadonlyArray * * **When to use** * - * Use to compute differences between JSON documents, detect structural - * changes, or create deterministic update operations from before and after - * states. + * Use to compute a JSON Patch from before and after JSON documents, detect + * structural changes, or create deterministic update operations. * * **Details** * diff --git a/packages/effect/src/Latch.ts b/packages/effect/src/Latch.ts index 98dc88d82b..bd1b680d0f 100644 --- a/packages/effect/src/Latch.ts +++ b/packages/effect/src/Latch.ts @@ -146,7 +146,8 @@ export interface Latch { * * **When to use** * - * Use when you need synchronous allocation outside an Effect workflow. + * Use when you need to allocate a `Latch` synchronously outside an Effect + * workflow. * * **Details** * diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index d1b8a4d747..508d78cbca 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -1237,7 +1237,8 @@ export const mergeAll = , ...Array(entries: Iterable): MutableH * * **When to use** * - * Use to safely read the value for a key as an `Option`. + * Use to safely read a `MutableHashMap` value for a key as an `Option`. * * **Details** * @@ -414,7 +414,8 @@ const getFromBucket = ( * * **When to use** * - * Use to test whether a key is present without reading its value. + * Use to test whether a key is present in a `MutableHashMap` without reading + * its value. * * **Example** (Checking for a key) * @@ -450,7 +451,8 @@ export const has: { * * **When to use** * - * Use to insert a new entry or replace an existing entry in place. + * Use to insert a new `MutableHashMap` entry or replace an existing entry in + * place. * * **Example** (Setting key-value pairs) * @@ -535,7 +537,8 @@ const getRefKey = ( * * **When to use** * - * Use to transform an existing value in place without inserting missing keys. + * Use to transform an existing `MutableHashMap` value in place without + * inserting missing keys. * * **Example** (Modifying existing values) * diff --git a/packages/effect/src/Tuple.ts b/packages/effect/src/Tuple.ts index bf7bcc9dcf..f664540ed1 100644 --- a/packages/effect/src/Tuple.ts +++ b/packages/effect/src/Tuple.ts @@ -411,7 +411,7 @@ export const renameIndices: { * * **When to use** * - * Use when you want to apply the same transformation to every element. + * Use when you want to apply the same transformation to every tuple element. * * **Details** * @@ -579,7 +579,7 @@ export const mapOmit: { * * **When to use** * - * Use when you need to compare tuples element-by-element. + * Use when you need an `Equivalence` to compare tuples element-by-element. * * **Details** * @@ -642,7 +642,8 @@ export { * * **When to use** * - * Use to guard against unexpected array lengths at runtime. + * Use to guard that an array has exactly the tuple length expected at + * runtime. * * **Details** * @@ -676,8 +677,8 @@ export { * * **When to use** * - * Use to guard that an array has at least the expected number of - * elements. + * Use to guard that an array has at least the tuple length expected at + * runtime. * * **Details** * diff --git a/packages/effect/src/unstable/http/HttpClient.ts b/packages/effect/src/unstable/http/HttpClient.ts index 11eaf92964..641789bda9 100644 --- a/packages/effect/src/unstable/http/HttpClient.ts +++ b/packages/effect/src/unstable/http/HttpClient.ts @@ -165,8 +165,8 @@ export declare namespace HttpClient { * * **When to use** * - * Use to provide the HTTP client implementation consumed by the module's - * request accessor functions. + * Use to provide the default outgoing HTTP client service used by request + * accessors such as `execute`, `get`, and `post`. * * @category services * @since 4.0.0 From 0daca5008971555b80e3c875c3105840af5748c8 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 20:10:24 +0200 Subject: [PATCH 26/29] wip --- packages/effect/src/Newtype.ts | 13 ++++++++----- packages/effect/src/Option.ts | 14 +++++++++----- packages/effect/src/Result.ts | 8 +++++--- packages/effect/src/SchemaIssue.ts | 3 ++- packages/effect/src/Stream.ts | 5 +++-- packages/effect/src/Struct.ts | 14 ++++++++------ packages/effect/src/Tuple.ts | 10 ++++++---- packages/effect/src/TxReentrantLock.ts | 3 ++- packages/effect/src/UndefinedOr.ts | 5 +++-- packages/effect/src/unstable/ai/McpSchema.ts | 18 ++++++++++-------- packages/effect/src/unstable/ai/McpServer.ts | 7 +++++-- 11 files changed, 61 insertions(+), 39 deletions(-) diff --git a/packages/effect/src/Newtype.ts b/packages/effect/src/Newtype.ts index 6cc7938ff4..cff5f3b833 100644 --- a/packages/effect/src/Newtype.ts +++ b/packages/effect/src/Newtype.ts @@ -237,7 +237,8 @@ export function makeIso(): Optic.Iso( * * **When to use** * - * Use when you need to sort or compare newtype values. + * Use when you need to sort newtype-wrapped values according to the ordering + * of the wrapped carrier value, without manually unwrapping. * * **Details** * @@ -303,7 +305,8 @@ export const makeOrder: (order: Order.Order( * * **When to use** * - * Use when you need to fold or reduce over a collection of newtype - * values. + * Use when you need to reduce a collection of newtype-wrapped values with the + * carrier's reducer, without manually unwrapping. * * **Details** * diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index 2b7e710f88..a26efbb766 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -1590,7 +1590,8 @@ export const zipLeft: { * * **When to use** * - * Use to build pipelines of partial functions (Kleisli composition) + * Use when you need to compose two functions that each return an `Option`, so + * `None` short-circuits without calling the next function. * * **Details** * @@ -2102,7 +2103,8 @@ export const filter: { * * **When to use** * - * Use to compare two `Option` values for structural equality + * Use when you need equality to treat two `None` values as equal and compare + * two `Some` values with a supplied equality rule. * * **Details** * @@ -2138,7 +2140,9 @@ export const makeEquivalence = (isEquivalent: Equivalence.Equivalence): Eq * * **When to use** * - * Use to sort collections of `Option` values + * Use when you need to sort `Some` and `None` values, with `None` ordered + * before present values and present values compared by a supplied ordering + * rule. * * **Details** * @@ -2688,8 +2692,8 @@ export function makeCombinerFailFast(combiner: Combiner.Combiner): Combine * * **When to use** * - * Use to wrap an existing `Reducer` to work with `Option` values - * - Reductions where any `None` should abort the entire result + * Use when you need to reduce `Option` values with fail-fast semantics, where + * any `None` aborts the entire result instead of being skipped. * * **Details** * diff --git a/packages/effect/src/Result.ts b/packages/effect/src/Result.ts index 730a842bfd..19c3d2d9ca 100644 --- a/packages/effect/src/Result.ts +++ b/packages/effect/src/Result.ts @@ -1666,8 +1666,9 @@ export const Do: Result<{}> = succeed({}) * * **When to use** * - * Use when adding a `Result`-producing step to a do-notation pipeline and - * storing its successful value under a named field in the accumulated object. + * Use when you need to add a `Result`-producing step to a `Result` + * do-notation pipeline and store its successful value under a named field in + * the accumulated object. * * **Details** * @@ -1765,7 +1766,8 @@ export { * * **When to use** * - * Use to add a pure computed field to a do-notation accumulator. + * Use when you need to add a pure computed field to a `Result` + * do-notation accumulator. * * **Details** * diff --git a/packages/effect/src/SchemaIssue.ts b/packages/effect/src/SchemaIssue.ts index 9d04973848..5996e9f49a 100644 --- a/packages/effect/src/SchemaIssue.ts +++ b/packages/effect/src/SchemaIssue.ts @@ -195,7 +195,8 @@ class Base { * * **When to use** * - * Use when you need to inspect which filter rejected the value. + * Use when you need to inspect a schema issue that records which refinement + * check rejected the value. * * **Details** * diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 2417ba3a93..1a8d1e6d68 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -1559,8 +1559,9 @@ export const fromSchedule = (schedule: Schedule.Schedule( * * **When to use** * - * Use to fold a collection of structs into a single summary struct. + * Use when you need to fold same-shape records by accumulating each property + * independently into one summary record. * * **Details** * diff --git a/packages/effect/src/Tuple.ts b/packages/effect/src/Tuple.ts index f664540ed1..cffcd429b5 100644 --- a/packages/effect/src/Tuple.ts +++ b/packages/effect/src/Tuple.ts @@ -612,7 +612,8 @@ export const makeEquivalence = Equivalence.Tuple * * **When to use** * - * Use to sort or compare tuples lexicographically by element position. + * Use when you need to sort fixed-position arrays lexicographically, with each + * position using its own ordering rule. * * **Details** * @@ -715,8 +716,8 @@ export { * * **When to use** * - * Use when you need to merge two tuples of the same shape, such as summing - * counters or concatenating strings. + * Use when you need to merge two same-shape tuples by combining each position + * independently, such as summing counters or concatenating strings. * * **Example** (Combining tuple elements) * @@ -756,7 +757,8 @@ export function makeCombiner>( * * **When to use** * - * Use to fold a collection of tuples into a single summary tuple. + * Use when you need to fold same-shape tuples by accumulating each position + * independently into one summary tuple. * * **Example** (Reducing a collection of tuples) * diff --git a/packages/effect/src/TxReentrantLock.ts b/packages/effect/src/TxReentrantLock.ts index 726adb4cf5..9427f4c456 100644 --- a/packages/effect/src/TxReentrantLock.ts +++ b/packages/effect/src/TxReentrantLock.ts @@ -506,7 +506,8 @@ export const withWriteLock: { * * **When to use** * - * Use as the short alias for {@link withWriteLock}. + * Use when you need to run an effect with exclusive write access through a + * `TxReentrantLock` and prefer the concise lock helper. * * **Example** (Running an effect with exclusive access) * diff --git a/packages/effect/src/UndefinedOr.ts b/packages/effect/src/UndefinedOr.ts index 116e8498a2..9475f5235a 100644 --- a/packages/effect/src/UndefinedOr.ts +++ b/packages/effect/src/UndefinedOr.ts @@ -200,8 +200,9 @@ export const liftThrowable = , B>( * * **When to use** * - * Use to take the first available value like a fallback chain, combining values - * only when both operands are present. + * Use when you need to reduce values that may be `undefined`, keeping the + * first defined value as a fallback and combining only when both operands are + * defined. * * **Details** * diff --git a/packages/effect/src/unstable/ai/McpSchema.ts b/packages/effect/src/unstable/ai/McpSchema.ts index 16dd05b5ef..6f08c6132a 100644 --- a/packages/effect/src/unstable/ai/McpSchema.ts +++ b/packages/effect/src/unstable/ai/McpSchema.ts @@ -484,8 +484,8 @@ export class McpErrorBase extends Schema.Class( * * **When to use** * - * Use when you need the JSON-RPC error code for requests that are not valid - * request objects. + * Use when building an MCP/JSON-RPC error response for a syntactically parsed + * request object that fails request-shape validation. * * @category constants * @since 4.0.0 @@ -497,8 +497,8 @@ export const INVALID_REQUEST_ERROR_CODE = -32600 as const * * **When to use** * - * Use when you need the JSON-RPC error code for requests whose method does not - * exist or is not available. + * Use when building an MCP/JSON-RPC error response for a request whose + * `method` is unknown or unavailable. * * @category constants * @since 4.0.0 @@ -509,7 +509,8 @@ export const METHOD_NOT_FOUND_ERROR_CODE = -32601 as const * * **When to use** * - * Use when you need the JSON-RPC error code for invalid method parameters. + * Use when building an MCP/JSON-RPC error response for decoded request + * parameters that fail method-specific validation. * * @category constants * @since 4.0.0 @@ -520,7 +521,8 @@ export const INVALID_PARAMS_ERROR_CODE = -32602 as const * * **When to use** * - * Use when you need the JSON-RPC error code for internal server errors. + * Use when building an MCP/JSON-RPC error response for an unexpected + * server-side failure. * * @category constants * @since 4.0.0 @@ -531,8 +533,8 @@ export const INTERNAL_ERROR_CODE = -32603 as const * * **When to use** * - * Use when you need the JSON-RPC error code for invalid JSON that could not be - * parsed. + * Use when building an MCP/JSON-RPC error response before a request object is + * available because the JSON payload could not be parsed. * * @category constants * @since 4.0.0 diff --git a/packages/effect/src/unstable/ai/McpServer.ts b/packages/effect/src/unstable/ai/McpServer.ts index bac04e72ce..a8627e3467 100644 --- a/packages/effect/src/unstable/ai/McpServer.ts +++ b/packages/effect/src/unstable/ai/McpServer.ts @@ -808,7 +808,9 @@ export type ResourceCompletions> = { * * **When to use** * - * Use to add a resource to an existing MCP server from an Effect program. + * Use when you are already inside an Effect program with an `McpServer` + * service and need to add a concrete resource or URI-template resource + * directly. * * @see {@link resource} for the layer-based resource registration wrapper * @@ -1036,7 +1038,8 @@ export const resource: { * * **When to use** * - * Use to register an MCP prompt from an Effect program. + * Use when you are already inside an Effect program with an `McpServer` + * service and need to add a prompt handler directly. * * **Details** * From c67e7f07550cc6067de7065fd74f309e5bd7ffaa Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Fri, 29 May 2026 22:03:03 +0200 Subject: [PATCH 27/29] wip --- packages/ai/anthropic/src/AnthropicTool.ts | 15 ++++++----- packages/ai/openai/src/OpenAiSchema.ts | 4 ++- packages/atom/solid/src/RegistryContext.ts | 4 +-- packages/effect/src/Array.ts | 27 +++++++------------ packages/effect/src/BigDecimal.ts | 9 ++++--- packages/effect/src/BigInt.ts | 14 +++++----- packages/effect/src/Config.ts | 3 ++- packages/effect/src/Console.ts | 4 +-- packages/effect/src/Data.ts | 6 +++-- packages/effect/src/Effect.ts | 3 ++- packages/effect/src/Equivalence.ts | 16 +++++------ packages/effect/src/Function.ts | 3 ++- packages/effect/src/Hash.ts | 3 ++- packages/effect/src/HashRing.ts | 4 +-- packages/effect/src/Option.ts | 7 ++--- packages/effect/src/Order.ts | 8 +++--- packages/effect/src/PubSub.ts | 4 +-- packages/effect/src/RcRef.ts | 4 --- packages/effect/src/Redacted.ts | 4 +-- packages/effect/src/Result.ts | 4 +-- packages/effect/src/Schedule.ts | 8 ++---- packages/effect/src/Scheduler.ts | 6 +++-- packages/effect/src/Schema.ts | 4 +-- packages/effect/src/SchemaRepresentation.ts | 4 +-- packages/effect/src/Tuple.ts | 3 ++- .../effect/src/unstable/ai/LanguageModel.ts | 5 ++-- .../unstable/eventlog/EventLogSessionAuth.ts | 8 +++--- .../platform-browser/src/BrowserSocket.ts | 4 +-- 28 files changed, 93 insertions(+), 95 deletions(-) diff --git a/packages/ai/anthropic/src/AnthropicTool.ts b/packages/ai/anthropic/src/AnthropicTool.ts index edeb55d3a7..bf645cdde0 100644 --- a/packages/ai/anthropic/src/AnthropicTool.ts +++ b/packages/ai/anthropic/src/AnthropicTool.ts @@ -250,8 +250,8 @@ export type CodeExecutionBashCommand = typeof CodeExecutionBashCommand.Type * * **When to use** * - * Use to validate or construct the `view` command for Anthropic code execution - * text editor tool calls. + * Use when you need the schema for provider-bound code-execution view requests + * before distinguishing them from create or replace text-editor commands. * * **Details** * @@ -277,8 +277,8 @@ export const CodeExecutionTextEditorView = Schema.Struct({ * * **When to use** * - * Use when handling or validating the `view` command for Anthropic's text - * editor code execution tool. + * Use when working at the Anthropic protocol boundary and the code-execution + * view request must be distinguished from standalone text-editor view requests. * * **Details** * @@ -400,8 +400,8 @@ const CodeExecution_20250522_Parameters = Schema.Union([ * * **When to use** * - * Use when validating or constructing the input payload for the 2025-08-25 - * Anthropic code execution tool. + * Use when you need the schema for code-execution input at the Anthropic + * protocol boundary before sending source code to the 2025-08-25 tool. * * @see {@link CodeExecution_20250825} for the provider-defined tool that consumes this schema * @@ -419,7 +419,8 @@ export const CodeExecution_20250825_Parameters = Schema.Struct({ * * **When to use** * - * Use when typing input passed to the 2025-08-25 Anthropic code execution tool. + * Use when exposing the 2025-08-25 code-execution payload separately from the + * provider tool definition, such as at a transport or persistence boundary. * * **Details** * diff --git a/packages/ai/openai/src/OpenAiSchema.ts b/packages/ai/openai/src/OpenAiSchema.ts index 40af5b206b..bd02d1bb01 100644 --- a/packages/ai/openai/src/OpenAiSchema.ts +++ b/packages/ai/openai/src/OpenAiSchema.ts @@ -1240,7 +1240,9 @@ export type CreateEmbeddingRequest = typeof CreateEmbeddingRequest.Type * * **When to use** * - * Use to decode successful OpenAI embeddings responses. + * Use when you need to validate embeddings responses at an OpenAI client + * boundary before trusting item shapes, especially when numeric and string + * embeddings are both allowed. * * **Details** * diff --git a/packages/atom/solid/src/RegistryContext.ts b/packages/atom/solid/src/RegistryContext.ts index be6924466f..2db8daf367 100644 --- a/packages/atom/solid/src/RegistryContext.ts +++ b/packages/atom/solid/src/RegistryContext.ts @@ -34,8 +34,8 @@ import { createComponent, createContext, onCleanup } from "solid-js" * * **When to use** * - * Use when you need to access or provide an `AtomRegistry` directly for the - * current Solid owner tree. + * Use when you need to integrate lower-level Solid context APIs, such as custom + * providers or hooks, instead of using the default atom hook setup. * * **Details** * diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 531a6aeb85..31ec543cf8 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -632,12 +632,8 @@ export const matchRight: { * * **When to use** * - * Use to add a single element at the start of an iterable and return a - * `NonEmptyArray`. - * - * **Details** - * - * Always returns a non-empty array. + * Use when you need to guarantee a non-empty result after adding a required + * leading value. * * **Example** (Prepending an element) * @@ -702,12 +698,8 @@ export const prependAll: { * * **When to use** * - * Use to add one element to the end of an iterable and return a new - * `NonEmptyArray`. - * - * **Details** - * - * Always returns a non-empty array. + * Use when you need to guarantee a non-empty result after adding a required + * trailing value. * * **Example** (Appending an element) * @@ -2058,7 +2050,8 @@ export const modify: { * * **When to use** * - * Use to remove a single array element at a known index. + * Use when you want a missing index to be a no-op and need a fresh array result + * instead of an optional failure. * * **Example** (Removing an element) * @@ -3654,8 +3647,8 @@ export const getSomes: >, X = any>( * * **When to use** * - * Use to collect only failure values from an iterable of `Result` values while - * discarding successes. + * Use when you can drop the success channel and only need the failure + * payloads, not the original result wrappers. * * **Example** (Extracting failures) * @@ -3691,8 +3684,8 @@ export const getFailures = >>( * * **When to use** * - * Use to collect only success values from an iterable of `Result` values while - * discarding failures. + * Use when you can drop the failure channel and only need the success + * payloads, not the original result wrappers. * * **Example** (Extracting successes) * diff --git a/packages/effect/src/BigDecimal.ts b/packages/effect/src/BigDecimal.ts index 3498cabbe9..b1ff98cd11 100644 --- a/packages/effect/src/BigDecimal.ts +++ b/packages/effect/src/BigDecimal.ts @@ -325,7 +325,8 @@ export const scale: { * * **When to use** * - * Use to add two `BigDecimal` values. + * Use when you need a decimal addition function for piping or higher-order APIs + * while preserving decimal precision. * * **Example** (Adding decimals) * @@ -372,7 +373,8 @@ export const sum: { * * **When to use** * - * Use to sum all `BigDecimal` values in an iterable. + * Use when you need to aggregate decimal quantities with decimal precision + * instead of converting through JavaScript numbers. * * **Example** (Adding multiple decimals) * @@ -1851,7 +1853,8 @@ export const round: { * * **When to use** * - * Use to remove digits beyond a requested scale by rounding toward zero. + * Use when you need to discard fractional digits beyond a scale rather than + * round half up, half down, or toward an infinity. * * **Example** (Truncating decimals) * diff --git a/packages/effect/src/BigInt.ts b/packages/effect/src/BigInt.ts index 1fbec2b043..16883ea2de 100644 --- a/packages/effect/src/BigInt.ts +++ b/packages/effect/src/BigInt.ts @@ -141,7 +141,8 @@ export const isBigInt: (u: unknown) => u is bigint = predicate.isBigInt * * **When to use** * - * Use to add two `bigint` values. + * Use when you need a binary addition function for piping or higher-order APIs + * instead of the infix addition operator. * * **Example** (Adding bigints) * @@ -806,7 +807,8 @@ export const sqrt = (n: bigint): Option.Option => * * **When to use** * - * Use to sum all `bigint` values in an iterable. + * Use when you want an immediate aggregate from an iterable instead of a + * folding reducer owned by another API. * * **Example** (Summing iterable bigints) * @@ -983,12 +985,8 @@ export function fromNumber(n: number): Option.Option { * * **When to use** * - * Use to compute the JavaScript `%` remainder for two `bigint` values. - * - * **Details** - * - * The result follows JavaScript `%` semantics, including the sign of the - * dividend. + * Use when you want native remainder semantics, including signed remainders and + * a thrown division-by-zero error. * * **Gotchas** * diff --git a/packages/effect/src/Config.ts b/packages/effect/src/Config.ts index 9202eebb59..f37093921e 100644 --- a/packages/effect/src/Config.ts +++ b/packages/effect/src/Config.ts @@ -978,7 +978,8 @@ export function nonEmptyString(name?: string) { * * **When to use** * - * Use to read a numeric config value when `NaN` and `Infinity` are acceptable. + * Use when you need config input to accept JavaScript's full number domain, + * including NaN and infinities, rather than reject non-finite values. * * **Details** * diff --git a/packages/effect/src/Console.ts b/packages/effect/src/Console.ts index c14f65aa19..294c9c4db8 100644 --- a/packages/effect/src/Console.ts +++ b/packages/effect/src/Console.ts @@ -113,8 +113,8 @@ export interface Console { * * **When to use** * - * Use when you need to access, provide, or override the current console service - * through Effect context. + * Use when you need an effect to run against a provided console implementation, + * such as tests or alternate runtimes, rather than the default console. * * **Details** * diff --git a/packages/effect/src/Data.ts b/packages/effect/src/Data.ts index e741558ed9..83c7a01c4a 100644 --- a/packages/effect/src/Data.ts +++ b/packages/effect/src/Data.ts @@ -420,7 +420,8 @@ export declare namespace TaggedEnum { * * **When to use** * - * Use to type the constructors-and-matchers object returned by `taggedEnum`. + * Use when you want to annotate an exported constructor bundle so downstream + * code keeps exact variant constructors and exhaustive matching. * * **Details** * @@ -586,7 +587,8 @@ export declare namespace TaggedEnum { * * **When to use** * - * Use when you have a `TaggedEnum` type and need constructors and matchers for its values. + * Use when you model a closed union with plain data objects and want + * construction, tag checks, and exhaustive matching from the same definition. * * **Details** * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index b3846e0b05..931b01ed9d 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -3373,7 +3373,8 @@ export const catchFilter: { * * **When to use** * - * Use to convert `NoSuchElementError` failures into `Option.none`. + * Use when you expect missing-value failures and want them to become an + * optional success while all other failures keep failing. * * **Details** * diff --git a/packages/effect/src/Equivalence.ts b/packages/effect/src/Equivalence.ts index 03d794f8a3..c185addebd 100644 --- a/packages/effect/src/Equivalence.ts +++ b/packages/effect/src/Equivalence.ts @@ -143,7 +143,8 @@ export interface EquivalenceTypeLambda extends TypeLambda { * * **When to use** * - * Use when you need a custom equivalence relation. + * Use when you need an equality rule that the built-in instances and input + * mapping helpers cannot express, and you can provide a law-abiding comparison. * * **Details** * @@ -244,7 +245,7 @@ export const strictEqual: () => Equivalence = () => isStrictEquivalent * * **When to use** * - * Use when an API needs an `Equivalence` instance for string equality. + * Use when you need to supply case-sensitive string equality. * * **Example** (Comparing strings) * @@ -265,12 +266,7 @@ export const String: Equivalence = isStrictEquivalent * * **When to use** * - * Use when an API needs an `Equivalence` instance for numeric equality where - * `NaN` equals `NaN`. - * - * **Details** - * - * `NaN` is considered equal to `NaN`. + * Use when you need numeric equality that treats NaN as equal to itself. * * **Example** (Comparing numbers) * @@ -294,7 +290,7 @@ export const Number: Equivalence = make((self, that) => * * **When to use** * - * Use when an API needs an `Equivalence` instance for boolean equality. + * Use when you need to supply boolean equality. * * **Example** (Comparing booleans) * @@ -315,7 +311,7 @@ export const Boolean: Equivalence = isStrictEquivalent * * **When to use** * - * Use when an API needs an `Equivalence` instance for `bigint` equality. + * Use when you need to supply bigint equality. * * **Example** (Comparing bigints) * diff --git a/packages/effect/src/Function.ts b/packages/effect/src/Function.ts index dfc684d19c..f96035433a 100644 --- a/packages/effect/src/Function.ts +++ b/packages/effect/src/Function.ts @@ -54,7 +54,8 @@ import { pipeArguments } from "./Pipeable.ts" * * **When to use** * - * Use to represent unary function types in higher-kinded type operations. + * Use when defining higher-kinded abstractions that must accept function types + * as one of their type-lambda inputs. * * **Example** (Creating a function type with a type lambda) * diff --git a/packages/effect/src/Hash.ts b/packages/effect/src/Hash.ts index b1b216108f..9323456488 100644 --- a/packages/effect/src/Hash.ts +++ b/packages/effect/src/Hash.ts @@ -400,7 +400,8 @@ export const number = (n: number) => { * * **When to use** * - * Use to hash a string directly. + * Use when you need a string field to contribute to a custom structural hash + * implementation. * * **Details** * diff --git a/packages/effect/src/HashRing.ts b/packages/effect/src/HashRing.ts index ca1065238d..e1f50fc42f 100644 --- a/packages/effect/src/HashRing.ts +++ b/packages/effect/src/HashRing.ts @@ -306,8 +306,8 @@ export const remove: { * * **When to use** * - * Use to check whether a node value is already registered in a ring by its - * `PrimaryKey` value. + * Use when you need to know whether registering a node would update an existing + * ring member because another node already has the same primary-key identity. * * **Details** * diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index a26efbb766..d17f8153b7 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -276,7 +276,8 @@ export interface OptionUnifyIgnore {} * * **When to use** * - * Use to represent `Option` in higher-kinded type operations. + * Use when defining higher-kinded abstractions that must accept optional-value + * types as one of their type-lambda inputs. * * @category type lambdas * @since 2.0.0 @@ -848,8 +849,8 @@ export const firstSomeOf = > = Iterable(O: Order): { * * **When to use** * - * Use when you need to check whether a value is within an inclusive range - * according to an `Order`. + * Use when you need range checks that respect domain-specific ordering, such as + * dates, versions, or custom priorities, instead of JavaScript numeric + * comparison. * * **Details** * diff --git a/packages/effect/src/PubSub.ts b/packages/effect/src/PubSub.ts index 56eb408c4f..052bd78c0b 100644 --- a/packages/effect/src/PubSub.ts +++ b/packages/effect/src/PubSub.ts @@ -1476,8 +1476,8 @@ export const remaining = (self: Subscription): Effect.Effect => * * **When to use** * - * Use when you need a synchronous check of messages currently available in a - * subscription where `Option.none()` represents a shut-down subscription. + * Use when you need synchronous polling outside a managed workflow and want + * shutdown observed as data instead of interruption. * * **Example** (Checking remaining messages synchronously) * diff --git a/packages/effect/src/RcRef.ts b/packages/effect/src/RcRef.ts index 62c7371b23..5a9ebc1c05 100644 --- a/packages/effect/src/RcRef.ts +++ b/packages/effect/src/RcRef.ts @@ -97,10 +97,6 @@ export interface RcRef extends Pipeable { /** * Namespace containing type-level members associated with `RcRef`. * - * **When to use** - * - * Use to reference type-level members associated with `RcRef`. - * * **Example** (Referencing namespace types) * * ```ts diff --git a/packages/effect/src/Redacted.ts b/packages/effect/src/Redacted.ts index b2e8416ddc..39911f13a6 100644 --- a/packages/effect/src/Redacted.ts +++ b/packages/effect/src/Redacted.ts @@ -321,8 +321,8 @@ export const wipeUnsafe = (self: Redacted): boolean => redacted.redactedRe * * **When to use** * - * Use when an API needs an `Equivalence` for `Redacted` values based on their - * underlying values. + * Use when you need to compare wrapped secrets through an approved equality + * rule without exposing the underlying values at each comparison site. * * **Example** (Comparing redacted values) * diff --git a/packages/effect/src/Result.ts b/packages/effect/src/Result.ts index 19c3d2d9ca..5b73bb3e64 100644 --- a/packages/effect/src/Result.ts +++ b/packages/effect/src/Result.ts @@ -1766,8 +1766,8 @@ export { * * **When to use** * - * Use when you need to add a pure computed field to a `Result` - * do-notation accumulator. + * Use when you need to add a derived field that cannot fail inside a + * do-notation pipeline. * * **Details** * diff --git a/packages/effect/src/Schedule.ts b/packages/effect/src/Schedule.ts index 0221d8f33c..65ef1c5ca2 100644 --- a/packages/effect/src/Schedule.ts +++ b/packages/effect/src/Schedule.ts @@ -3421,12 +3421,8 @@ export { * * **When to use** * - * Use to check an existing schedule input type. - * - * **Details** - * - * This helper is checked at compile time and does not change the schedule's - * runtime behavior. + * Use when you need a generic helper to prove that an existing schedule can + * consume a required input type without changing runtime behavior. * * **Example** (Constraining schedule input types) * diff --git a/packages/effect/src/Scheduler.ts b/packages/effect/src/Scheduler.ts index edfebfe909..bdd6c5a8cb 100644 --- a/packages/effect/src/Scheduler.ts +++ b/packages/effect/src/Scheduler.ts @@ -75,7 +75,8 @@ export interface SchedulerDispatcher { * * **When to use** * - * Use to provide or override the scheduler used by the Effect runtime. + * Use when you need to replace scheduling behavior globally in tests or runtime + * setup, such as forcing deterministic task dispatch. * * **Details** * @@ -179,7 +180,8 @@ export class MixedScheduler implements Scheduler { * * **When to use** * - * Use to create a dispatcher for enqueuing work through this scheduler. + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. * * @since 4.0.0 */ diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 50ab40c539..b6e956c2e6 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -8652,8 +8652,8 @@ export type CauseReasonIso = { * * **When to use** * - * Use to validate, transform, or serialize individual `Cause.Reason` values - * when typed failures and unexpected defects need separate schemas. + * Use when serializing or decoding individual cause reasons separately from a + * full failure cause, with distinct schemas for typed errors and defects. * * **Details** * diff --git a/packages/effect/src/SchemaRepresentation.ts b/packages/effect/src/SchemaRepresentation.ts index c46bfd2357..0ca82d32e9 100644 --- a/packages/effect/src/SchemaRepresentation.ts +++ b/packages/effect/src/SchemaRepresentation.ts @@ -2270,8 +2270,8 @@ export const toJsonSchemaDocument: ( * * **When to use** * - * Use when you already have a schema representation `MultiDocument` and need a - * Draft 2020-12 JSON Schema multi-document. + * Use when you need to export related schema representation documents together + * so shared definitions stay in multi-document JSON Schema form. * * @see {@link MultiDocument} * @see {@link toJsonSchemaDocument} diff --git a/packages/effect/src/Tuple.ts b/packages/effect/src/Tuple.ts index cffcd429b5..5c3751b96c 100644 --- a/packages/effect/src/Tuple.ts +++ b/packages/effect/src/Tuple.ts @@ -245,7 +245,8 @@ export const omit: { * * **When to use** * - * Use to add one element to the end of a tuple while preserving tuple types. + * Use when you need the appended value to remain part of the tuple's type-level + * shape and preserve literal element positions. * * **Details** * diff --git a/packages/effect/src/unstable/ai/LanguageModel.ts b/packages/effect/src/unstable/ai/LanguageModel.ts index 981590fc92..89b0ffbab8 100644 --- a/packages/effect/src/unstable/ai/LanguageModel.ts +++ b/packages/effect/src/unstable/ai/LanguageModel.ts @@ -758,8 +758,9 @@ export interface ProviderOptions { * * **When to use** * - * Use to build a `LanguageModel.Service` from provider-specific final and - * streaming text generation functions. + * Use when you are implementing a provider adapter and need to expose the + * standard language-model service while keeping provider-specific request hooks + * behind it. * * **Details** * diff --git a/packages/effect/src/unstable/eventlog/EventLogSessionAuth.ts b/packages/effect/src/unstable/eventlog/EventLogSessionAuth.ts index 637c23e0f4..c279964075 100644 --- a/packages/effect/src/unstable/eventlog/EventLogSessionAuth.ts +++ b/packages/effect/src/unstable/eventlog/EventLogSessionAuth.ts @@ -65,8 +65,8 @@ export const AuthPayloadContext = "eventlog-auth-v1" * * **When to use** * - * Use when you need to validate the byte length of raw Ed25519 public keys for - * session authentication. + * Use when implementing session-auth serialization or validation that must + * reject public keys with a non-canonical raw byte length. * * @category constants * @since 4.0.0 @@ -78,8 +78,8 @@ export const Ed25519PublicKeyLength = 32 * * **When to use** * - * Use when you need to validate the byte length of Ed25519 signatures for - * session authentication. + * Use when implementing session-auth verification that must reject signatures + * with a non-canonical byte length before cryptographic checking. * * @category constants * @since 4.0.0 diff --git a/packages/platform-browser/src/BrowserSocket.ts b/packages/platform-browser/src/BrowserSocket.ts index 921b788cc8..5bbc2ef9bc 100644 --- a/packages/platform-browser/src/BrowserSocket.ts +++ b/packages/platform-browser/src/BrowserSocket.ts @@ -46,8 +46,8 @@ import * as Socket from "effect/unstable/socket/Socket" * * **When to use** * - * Use when you need a complete browser `Socket` layer connected to a WebSocket - * URL. + * Use when you need browser code to satisfy the platform socket service from a + * URL without wiring the browser constructor service separately. * * **Details** * From a42a3d1e7f673466c04d16e1300ab62e9019d282 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Sat, 30 May 2026 08:49:14 +0200 Subject: [PATCH 28/29] wip --- packages/ai/anthropic/src/AnthropicTool.ts | 46 ++++++++ packages/ai/openai/src/OpenAiSchema.ts | 25 ++++ packages/effect/src/Array.ts | 55 +++++++++ packages/effect/src/BigDecimal.ts | 12 +- packages/effect/src/Channel.ts | 80 +++++++++++++ packages/effect/src/Chunk.ts | 45 ++++++- packages/effect/src/Context.ts | 8 +- packages/effect/src/DateTime.ts | 35 ++++++ packages/effect/src/Duration.ts | 17 ++- packages/effect/src/Effect.ts | 86 ++++++++++++++ packages/effect/src/Encoding.ts | 5 + packages/effect/src/FiberHandle.ts | 15 +++ packages/effect/src/FiberMap.ts | 15 +++ packages/effect/src/FiberSet.ts | 10 ++ packages/effect/src/HashMap.ts | 5 + packages/effect/src/Iterable.ts | 11 +- packages/effect/src/MutableList.ts | 15 +++ packages/effect/src/Number.ts | 8 +- packages/effect/src/PubSub.ts | 10 ++ packages/effect/src/Queue.ts | 40 +++++++ packages/effect/src/Result.ts | 27 ++++- packages/effect/src/Schedule.ts | 30 +++++ packages/effect/src/Schema.ts | 46 +++++++- packages/effect/src/SchemaAST.ts | 20 ++++ packages/effect/src/SchemaRepresentation.ts | 5 + packages/effect/src/Scope.ts | 15 +++ packages/effect/src/Stream.ts | 111 ++++++++++++++++++ packages/effect/src/SubscriptionRef.ts | 5 + packages/effect/src/Trie.ts | 5 + packages/effect/src/unstable/cli/Command.ts | 5 + .../effect/src/unstable/cli/GlobalFlag.ts | 5 + .../src/unstable/cluster/ClusterMetrics.ts | 5 + .../src/unstable/cluster/EntityResource.ts | 10 ++ .../effect/src/unstable/encoding/Ndjson.ts | 5 + .../src/unstable/eventlog/EventJournal.ts | 10 ++ .../src/unstable/http/HttpClientRequest.ts | 11 +- .../src/unstable/http/HttpServerResponse.ts | 5 + .../effect/src/unstable/http/UrlParams.ts | 10 ++ .../unstable/observability/OtlpResource.ts | 5 + .../effect/src/unstable/workflow/Workflow.ts | 5 + .../src/unstable/workflow/WorkflowEngine.ts | 12 +- packages/platform-browser/src/Clipboard.ts | 5 + .../platform-browser/src/IndexedDbVersion.ts | 5 + 43 files changed, 880 insertions(+), 25 deletions(-) diff --git a/packages/ai/anthropic/src/AnthropicTool.ts b/packages/ai/anthropic/src/AnthropicTool.ts index bf645cdde0..77a0aeff64 100644 --- a/packages/ai/anthropic/src/AnthropicTool.ts +++ b/packages/ai/anthropic/src/AnthropicTool.ts @@ -515,6 +515,11 @@ export const CodeExecution_20250825 = Tool.providerDefined({ /** * Schema for an `[x, y]` screen coordinate in pixels. * + * **When to use** + * + * Use when validating computer-use action payloads that carry a single screen + * position and provider-side bounds checks remain acceptable. + * * **Details** * * This is a two-number tuple used by computer-use actions that accept screen @@ -539,6 +544,11 @@ export type Coordinate = typeof Coordinate.Type /** * Schema for an `[x1, y1, x2, y2]` screen region in pixels. * + * **When to use** + * + * Use when validating computer-use action payloads that carry a rectangular + * screen region and provider-side bounds checks remain acceptable. + * * **Details** * * The tuple represents top-left and bottom-right corners. @@ -657,6 +667,12 @@ export const ComputerUseKeyAction = Schema.Struct({ /** * Computer-use action payload for pressing a key or key combination. * + * **When to use** + * + * Use when typing parsed computer-use key action payloads after schema + * validation, where provider-specific key-name validation is handled outside + * TypeScript. + * * **Details** * * The payload uses `action: "key"` and stores the key or key combination to @@ -1251,6 +1267,11 @@ const ComputerUse_20250124_Actions = Schema.Union([ /** * Zooms into a specific region of the screen at full resolution. * + * **When to use** + * + * Use when building or validating the 2025-11-24 computer-use action for a + * zoom-enabled tool definition. + * * **Details** * * The encoded payload uses `action: "zoom"` and a `region` tuple. @@ -1735,6 +1756,11 @@ export const TextEditorCreateCommand = Schema.Struct({ /** * Text editor command payload for creating a new file with the specified content. * + * **When to use** + * + * Use when typing parsed text-editor create command payloads after schema + * validation and before dispatching to Anthropic tool handlers. + * * **Gotchas** * * The command fails if the file already exists or if parent directories are missing. @@ -1786,6 +1812,11 @@ export const TextEditorStrReplaceCommand = Schema.Struct({ /** * Text editor command payload for replacing one exact, unique string in a file. * + * **When to use** + * + * Use when typing parsed text-editor replace command payloads that must carry + * one exact `old_str` match. + * * **Gotchas** * * The `old_str` must match exactly, including whitespace and indentation, and @@ -2225,6 +2256,11 @@ export const WebFetchCitationsConfig = Schema.Struct({ /** * Configuration payload for enabling or disabling citations on web fetch results. * + * **When to use** + * + * Use when typing parsed web-fetch citation configuration shared between + * request arguments and handler code. + * * **Details** * * The payload contains the `enabled` flag. `citations` is optional on @@ -2295,6 +2331,11 @@ export const WebFetch_20250910_Args = Schema.Struct({ /** * Configuration arguments for the Anthropic web fetch tool, including usage limits, domain filters, citation settings, and token limits. * + * **When to use** + * + * Use when typing parsed web-fetch tool configuration shared by the + * provider-defined tool and request-building code. + * * **Gotchas** * * `allowedDomains` and `blockedDomains` are mutually exclusive. @@ -2342,6 +2383,11 @@ export const WebFetchParameters = Schema.Struct({ /** * Type of the parameters Claude supplies when invoking the Anthropic web fetch tool. * + * **When to use** + * + * Use when typing Claude-supplied web-fetch tool parameters after schema + * validation, before enforcing URL provenance or length constraints. + * * **Details** * * The payload contains the single `url` parameter for Anthropic web fetch. diff --git a/packages/ai/openai/src/OpenAiSchema.ts b/packages/ai/openai/src/OpenAiSchema.ts index bd02d1bb01..dc26ee9601 100644 --- a/packages/ai/openai/src/OpenAiSchema.ts +++ b/packages/ai/openai/src/OpenAiSchema.ts @@ -512,6 +512,11 @@ const ProviderDefinedTool = Schema.StructWithRest( /** * Schema for tool definitions that can be supplied to an OpenAI Responses request. * + * **When to use** + * + * Use when validating or encoding the `tools` array for a Responses request, + * including provider-defined tool records with provider-specific fields. + * * **Details** * * Accepted variants are function tools, custom tools, and provider-defined @@ -548,6 +553,11 @@ export type Tool = typeof Tool.Type /** * Schema for selecting whether and which tools the model may call in a Responses request. * + * **When to use** + * + * Use when validating or encoding the `tool_choice` field that constrains model + * tool use separately from the tool definitions themselves. + * * **Details** * * Accepted forms are `"none"`, `"auto"`, `"required"`, an allowed-tools set, @@ -608,6 +618,11 @@ export type ToolChoice = typeof ToolChoice.Type /** * Schema for text output format configuration, including plain text, JSON object, and JSON Schema responses. * + * **When to use** + * + * Use when validating or encoding the `text.format` setting for a Responses + * request, especially when choosing structured JSON Schema output. + * * **Details** * * Accepted variants are `text`, `json_schema`, and `json_object`. @@ -1161,6 +1176,11 @@ export type ResponseStreamEvent = typeof ResponseStreamEvent.Type /** * Schema for one embedding item returned by the OpenAI embeddings API. * + * **When to use** + * + * Use when validating individual embedding entries at the OpenAI client boundary + * before assuming the embedding payload is a numeric vector. + * * **Details** * * An embedding item contains its `index`, optional `object` marker, and an @@ -1199,6 +1219,11 @@ export type Embedding = typeof Embedding.Type /** * Schema for the request payload sent to the OpenAI embeddings endpoint. * + * **When to use** + * + * Use when validating or encoding embeddings requests before sending them to + * OpenAI, while leaving model-specific limits to the provider. + * * **Details** * * Requires `input` and `model`. `input` may be a string, an array of strings, diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 31ec543cf8..c67a728d38 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -918,6 +918,11 @@ export const isReadonlyArrayEmpty: (self: ReadonlyArray) => self is readon * Checks whether a mutable `Array` is non-empty, narrowing the type to * `NonEmptyArray`. * + * **When to use** + * + * Use when you need the narrowed value to remain a mutable `Array` after proving + * it has at least one element. + * * **Example** (Checking for a non-empty array) * * ```ts @@ -939,6 +944,11 @@ export const isArrayNonEmpty: (self: Array) => self is NonEmptyArray = * Checks whether a `ReadonlyArray` is non-empty, narrowing the type to * `NonEmptyReadonlyArray`. * + * **When to use** + * + * Use when you need to prove a readonly array has at least one element without + * requiring mutable array methods afterward. + * * **Example** (Checking for a non-empty readonly array) * * ```ts @@ -2284,6 +2294,11 @@ export const zip: { * Combines elements from two iterables pairwise using a function. If the * iterables differ in length, extra elements are discarded. * + * **When to use** + * + * Use when zipping two iterables in an array pipeline and each pair should + * become a computed array element instead of a tuple. + * * **Example** (Zipping with addition) * * ```ts @@ -2433,6 +2448,11 @@ export const modifyHeadNonEmpty: { /** * Replaces the first element of a non-empty array with a new value. * + * **When to use** + * + * Use when you already know the array is non-empty and the replacement value + * does not depend on the current first element. + * * **Example** (Setting the head) * * ```ts @@ -2459,6 +2479,11 @@ export const setHeadNonEmpty: { * Applies a function to the last element of a non-empty array, returning a * new array. * + * **When to use** + * + * Use when you already know the array is non-empty and the new last element + * depends on the current last element. + * * **Example** (Modifying the last element) * * ```ts @@ -2485,6 +2510,11 @@ export const modifyLastNonEmpty: { /** * Replaces the last element of a non-empty array with a new value. * + * **When to use** + * + * Use when you already know the array is non-empty and the replacement value + * does not depend on the current last element. + * * **Example** (Setting the last element) * * ```ts @@ -2728,6 +2758,11 @@ export const splitAt: { * Splits a non-empty array into two parts at the given index. The first part * is guaranteed to be non-empty (`n` is clamped to >= 1). * + * **When to use** + * + * Use when downstream code requires the left side of the split to contain at + * least one element. + * * **Example** (Splitting a non-empty array) * * ```ts @@ -3250,6 +3285,11 @@ export const intersectionWith = (isEquivalent: (self: A, that: A) => boolean) * Computes the intersection of two arrays using `Equal.equivalence()`. Order is * determined by the first array. * + * **When to use** + * + * Use when Effect equality is the right membership test and you want to keep + * values present in both inputs while preserving the first input's order. + * * **Example** (Array intersection) * * ```ts @@ -3997,6 +4037,11 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * Lifts an `Option`-returning function into one that returns an array: * `Some(a)` becomes `[a]`, `None` becomes `[]`. * + * **When to use** + * + * Use when an optional parser or lookup should participate in array pipelines + * as zero-or-one results. + * * **Example** (Lifting an Option function) * * ```ts @@ -4111,6 +4156,11 @@ export const flatMapNullishOr: { * Lifts a `Result`-returning function into one that returns an array: failures * produce `[]`, successes produce `[value]`. * + * **When to use** + * + * Use when a fallible parser or lookup should participate in array pipelines as + * zero-or-one results and the failure value should be discarded. + * * **Example** (Lifting a Result function) * * ```ts @@ -4824,6 +4874,11 @@ export { /** * Adds a computed plain value to the do-notation scope without introducing a new array dimension. * + * **When to use** + * + * Use when each do-notation branch needs a derived field from the current + * bindings without multiplying the number of branches. + * * **Details** * * Unlike `bind`, the callback returns a single value instead of an array, so diff --git a/packages/effect/src/BigDecimal.ts b/packages/effect/src/BigDecimal.ts index b1ff98cd11..16876a7100 100644 --- a/packages/effect/src/BigDecimal.ts +++ b/packages/effect/src/BigDecimal.ts @@ -1168,12 +1168,12 @@ export const remainder: { /** * Returns the decimal remainder left over when one operand is divided by a - * non-zero second operand, throwing for division by zero. + * non-zero second operand. * * **When to use** * - * Use when you need to compute a `BigDecimal` remainder where the divisor is - * known to be non-zero, so division by zero should be a thrown exception. + * Use when you need to compute a `BigDecimal` remainder with a divisor known to + * be non-zero and want a plain `BigDecimal` result instead of an `Option`. * * **Gotchas** * @@ -1309,12 +1309,12 @@ export const equals: { export const fromBigInt = (n: bigint): BigDecimal => make(n, 0) /** - * Creates a `BigDecimal` from a finite `number`, throwing for non-finite input. + * Creates a `BigDecimal` from a finite `number`. * * **When to use** * - * Use when you need to convert a finite JavaScript number to a `BigDecimal` and - * invalid input should throw. + * Use when you need to convert a trusted finite JavaScript number to a + * `BigDecimal` and want a plain result instead of an `Option`. * * **Gotchas** * diff --git a/packages/effect/src/Channel.ts b/packages/effect/src/Channel.ts index 0b237e92c0..db9a5f0081 100644 --- a/packages/effect/src/Channel.ts +++ b/packages/effect/src/Channel.ts @@ -1013,6 +1013,11 @@ export const fail = (error: E): Channel => fromPull(Effect.s * Constructs a channel that fails immediately with the specified lazily * evaluated error. * + * **When to use** + * + * Use when the error value should be computed each time the channel runs instead + * of when the channel is constructed. + * * **Example** (Failing with a lazy error) * * ```ts @@ -1046,6 +1051,11 @@ export const failSync = (evaluate: LazyArg): Channel => f /** * Constructs a channel that fails immediately with the specified `Cause`. * + * **When to use** + * + * Use when the channel failure must preserve a full `Cause`, such as defects, + * interruptions, or combined failures. + * * **Example** (Failing with causes) * * ```ts @@ -1860,6 +1870,11 @@ export const mapDone: { /** * Maps the done value of this channel using the specified effectful function. * + * **When to use** + * + * Use when the terminal done value transformation needs services or can fail, + * while emitted elements should pass through unchanged. + * * @category sequencing * @since 4.0.0 */ @@ -1894,6 +1909,11 @@ const concurrencyIsSequential = ( * Maps each output element with an effectful function, preserving the source * channel's done value. * + * **When to use** + * + * Use when transforming each channel output needs an Effect, service + * dependency, failure channel, or configured concurrency. + * * **Details** * * The mapping function receives the output element and its zero-based index. @@ -3288,6 +3308,11 @@ export const filterMap: { /** * Filters output elements with an effectful predicate. * + * **When to use** + * + * Use when the keep/discard decision depends on an Effect or service and + * predicate failures should fail the returned channel. + * * **Details** * * Elements for which the predicate succeeds with `true` are emitted. Elements @@ -3501,6 +3526,11 @@ export const filterMapArray: { * Filters each element inside emitted non-empty arrays with an effectful * predicate. * + * **When to use** + * + * Use when filtering array-valued channel outputs requires Effects or services, + * and arrays that become empty should be skipped. + * * **Details** * * The predicate receives the element and its index within the array. Elements @@ -3538,6 +3568,11 @@ export const filterArrayEffect: { * Filters and maps each element inside emitted non-empty arrays using an * effectful `Filter`. * + * **When to use** + * + * Use when array-valued channel outputs need an effectful filter-map that can + * fail and can discard arrays that become empty. + * * **Details** * * Successful filter results are kept as mapped values. Failed filter results @@ -3779,6 +3814,11 @@ export const scan: { * Transforms a channel statefully by scanning over its output with an effectful accumulator function. * Emits the intermediate results of the scan operation. * + * **When to use** + * + * Use when maintaining accumulated state over channel output requires Effects + * or can fail, while still emitting each intermediate state. + * * **Example** (Scanning channel output with effects) * * ```ts @@ -4003,6 +4043,11 @@ export const catchCause: { * Runs an effect with the full failure `Cause` when the channel fails, then * fails the returned channel with the original cause. * + * **When to use** + * + * Use when observing the full channel failure `Cause` is needed without + * changing successful output or replacing the original cause. + * * **Details** * * Use this for observing failures, such as logging or metrics. If the observer @@ -5684,6 +5729,11 @@ const ignoreCause_ = < /** * Ignores all errors in the channel including defects, converting them to an empty channel. * + * **When to use** + * + * Use when a channel should become best-effort and all failure causes, including + * defects and interruptions, can be converted to empty output. + * * **Details** * * Use the `log` option to emit the full {@link Cause} when the channel fails. @@ -5919,6 +5969,11 @@ export const switchMap: { /** * Merges multiple channels with specified concurrency and buffering options. * + * **When to use** + * + * Use when channel outputs are themselves channels and multiple inner channels + * should run with configured concurrency and buffering. + * * **Example** (Merging nested channels) * * ```ts @@ -6273,6 +6328,11 @@ export const merge: { * Runs an effect concurrently with a channel while emitting only the channel's * output elements. * + * **When to use** + * + * Use when a side effect should run for the lifetime of a channel and only the + * channel's output elements should be emitted. + * * **Details** * * The effect's successful value is ignored. If the effect fails while the @@ -6724,6 +6784,11 @@ export const embedInput: { * Buffers individual output elements in a queue with the configured `capacity` * so a faster producer can progress independently of a slower consumer. * + * **When to use** + * + * Use when output elements can be decoupled from downstream demand and the + * configured backpressure or loss strategy is acceptable. + * * **Details** * * Finite queues use the `strategy` option. The default `"suspend"` strategy @@ -6783,6 +6848,11 @@ export const buffer: { * Buffers array output elements in a queue with the configured `capacity` so a * faster producer can progress independently of a slower consumer. * + * **When to use** + * + * Use when emitted arrays are batches of elements and it is acceptable for + * buffering to flatten and rebuild those batches. + * * **Details** * * Finite queues use the `strategy` option. The default `"suspend"` strategy @@ -7024,6 +7094,11 @@ export const onStart: { /** * Runs an effect the first time the channel emits an output element. * + * **When to use** + * + * Use when initialization depends on the first output element rather than only + * on channel startup. + * * **Details** * * The effect receives the first emitted element. The first element is still @@ -7954,6 +8029,11 @@ export const runFold: { /** * Runs a channel and effectfully folds all output elements with an accumulator. * + * **When to use** + * + * Use when folding channel output needs effects, services, or an additional + * failure channel during accumulation. + * * **Details** * * The initial accumulator is evaluated lazily. Each output element is passed to diff --git a/packages/effect/src/Chunk.ts b/packages/effect/src/Chunk.ts index f9d2439e17..72c847dbb1 100644 --- a/packages/effect/src/Chunk.ts +++ b/packages/effect/src/Chunk.ts @@ -601,8 +601,16 @@ export const get: { ) /** - * Wraps an array into a chunk without copying, so mutating the source array can - * mutate the chunk. + * Wraps an array into a chunk without copying. + * + * **When to use** + * + * Use when the input array can be shared with the resulting `Chunk` and avoiding + * a copy matters. + * + * **Gotchas** + * + * Mutating the source array after wrapping can mutate the resulting `Chunk`. * * **Example** (Creating chunks without copying arrays) * @@ -625,8 +633,16 @@ export const fromArrayUnsafe = (self: ReadonlyArray): Chunk => self.length === 0 ? empty() : self.length === 1 ? of(self[0]) : makeChunk({ _tag: "IArray", array: self }) /** - * Wraps a non-empty array into a non-empty chunk without copying, so mutating - * the source array can mutate the chunk. + * Wraps a non-empty array into a non-empty chunk without copying. + * + * **When to use** + * + * Use when the input array is already known to be non-empty, can be shared with + * the resulting `Chunk`, and avoiding a copy matters. + * + * **Gotchas** + * + * Mutating the source array after wrapping can mutate the resulting `Chunk`. * * **Example** (Creating non-empty chunks without copying arrays) * @@ -648,7 +664,16 @@ export const fromNonEmptyArrayUnsafe = (self: NonEmptyReadonlyArray): NonE fromArrayUnsafe(self) as any /** - * Gets an element unsafely, will throw on out of bounds + * Gets an element at the specified index without returning an `Option`. + * + * **When to use** + * + * Use when reading from a `Chunk` at an index known to be in bounds and direct + * element access is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws if the index is out of bounds. * * **Example** (Accessing elements unsafely) * @@ -1444,6 +1469,11 @@ export const head: (self: Chunk) => Option = get(0) /** * Returns the first element of this chunk. * + * **When to use** + * + * Use when the chunk is known to be non-empty and you want direct access without + * handling `Option.none`. + * * **Gotchas** * * Throws an error if the chunk is empty. @@ -1511,6 +1541,11 @@ export const last = (self: Chunk): Option => get(self, self.length - 1) /** * Returns the last element of this chunk. * + * **When to use** + * + * Use when the chunk is known to be non-empty and you want direct access without + * handling `Option.none`. + * * **Gotchas** * * Throws an error if the chunk is empty. diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts index bcd2bfb02e..6b5a65d069 100644 --- a/packages/effect/src/Context.ts +++ b/packages/effect/src/Context.ts @@ -502,8 +502,12 @@ export interface Context extends Equal.Equal, Pipeable, Inspectable } /** - * Creates a `Context` from an existing service map without validating or - * copying it. + * Creates a `Context` from an existing service map. + * + * **When to use** + * + * Use when constructing a low-level `Context` from a trusted map whose lifecycle + * you control. * * **Gotchas** * diff --git a/packages/effect/src/DateTime.ts b/packages/effect/src/DateTime.ts index d3e47fdca5..0569a3cb00 100644 --- a/packages/effect/src/DateTime.ts +++ b/packages/effect/src/DateTime.ts @@ -659,6 +659,11 @@ export const fromDateUnsafe: (date: Date) => Utc = Internal.fromDateUnsafe /** * Create a `DateTime` from supported input values. * + * **When to use** + * + * Use when creating a `DateTime` from trusted input and construction failures + * should throw an `IllegalArgumentError` instead of returning `Option.none`. + * * **Details** * * - A `DateTime` @@ -693,6 +698,11 @@ export const makeUnsafe: (input: A) => DateTime.Preser /** * Create a `DateTime.Zoned` using `DateTime.makeUnsafe` and a time zone. * + * **When to use** + * + * Use when the date/time input and zone options are trusted and invalid or + * rejected ambiguous times should throw instead of returning `Option.none`. + * * **Details** * * The input is treated as UTC and then the time zone is attached, unless @@ -889,6 +899,11 @@ export const nowAsDate: Effect.Effect = Internal.nowAsDate /** * Gets the current time using `Date.now`. * + * **When to use** + * + * Use when synchronous wall-clock access outside an Effect program is + * acceptable and testability through the `Clock` service is not needed. + * * **Details** * * This is a synchronous version of `now` that directly uses `Date.now()` @@ -1010,6 +1025,11 @@ export const setZoneOffset: { /** * Attempts to create a named time zone from an IANA time zone identifier. * + * **When to use** + * + * Use when the IANA zone id is trusted and invalid zones should throw instead + * of returning `Option.none` or failing in `Effect`. + * * **Details** * * If the time zone is invalid, an `IllegalArgumentError` will be thrown. @@ -1087,6 +1107,11 @@ export const zoneMakeNamed: (zoneId: string) => Option.Option = /** * Creates a named time zone effectfully from an IANA time zone identifier. * + * **When to use** + * + * Use when invalid IANA zone ids should fail in the Effect error channel + * instead of returning `Option.none` or throwing. + * * **Details** * * If the time zone is invalid, it will fail with an `IllegalArgumentError`. @@ -1465,6 +1490,11 @@ export const isFuture: (self: DateTime) => Effect.Effect = Internal.isF /** * Checks synchronously if a `DateTime` is in the future compared to the current time. * + * **When to use** + * + * Use when checking whether a `DateTime` is in the future with a synchronous + * live-clock read and `Clock`-based testability is not needed. + * * **Details** * * This is a synchronous version that uses `Date.now()` directly. @@ -1513,6 +1543,11 @@ export const isPast: (self: DateTime) => Effect.Effect = Internal.isPas /** * Checks synchronously if a `DateTime` is in the past compared to the current time. * + * **When to use** + * + * Use when checking whether a `DateTime` is in the past with a synchronous + * live-clock read and `Clock`-based testability is not needed. + * * **Details** * * This is a synchronous version that uses `Date.now()` directly. diff --git a/packages/effect/src/Duration.ts b/packages/effect/src/Duration.ts index 4a15e5ca3c..43c243a570 100644 --- a/packages/effect/src/Duration.ts +++ b/packages/effect/src/Duration.ts @@ -222,6 +222,11 @@ const DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|m /** * Decodes a `Duration.Input` into a `Duration`. * + * **When to use** + * + * Use when the input has already been validated or comes from a trusted source + * and throwing is acceptable for invalid duration syntax. + * * **Gotchas** * * If the input is not a valid `Duration.Input`, it throws an error. @@ -909,7 +914,12 @@ export const toWeeks = (self: Input): number => }) /** - * Gets the duration in nanoseconds as a bigint, throwing for infinite durations. + * Gets the duration in nanoseconds as a bigint. + * + * **When to use** + * + * Use when the duration is known to be finite and you need the nanosecond value + * as a `bigint`. * * **Gotchas** * @@ -1350,6 +1360,11 @@ export const divide: { * Divides a `Duration` by a number using fallback rules instead of returning * an `Option`. * + * **When to use** + * + * Use when dividing a `Duration` should return `Duration.zero` or signed + * infinity for invalid cases instead of forcing callers to handle `Option.none`. + * * **Details** * * Non-finite divisors return `Duration.zero`. Division by positive or negative diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 931b01ed9d..8f3267aabd 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1571,6 +1571,12 @@ export const failSync: (evaluate: LazyArg) => Effect = internal. /** * Creates an `Effect` that represents a failure with a specific `Cause`. * + * **When to use** + * + * Use when you already have a full `Cause` and need to preserve defects, + * interruptions, annotations, or combined failures in the effect's failure + * channel. + * * **Details** * * This function allows you to create effects that fail with complex error @@ -1836,6 +1842,11 @@ export const fromResult: (result: Result.Result) => Effect = i /** * Converts an `Option` into an `Effect`. * + * **When to use** + * + * Use when absence should become a typed `NoSuchElementError` in the effect error + * channel. + * * **Details** * * `Option.some` becomes a successful effect with the contained value, while @@ -2637,6 +2648,11 @@ export { /** * Handles all errors in an effect by providing a fallback effect. * + * **When to use** + * + * Use when every recoverable error from an effect should be handled by the same + * fallback function while unrecoverable defects remain defects. + * * **Details** * * The `catch` function catches any errors that may occur during the @@ -3725,6 +3741,11 @@ export const tapErrorTag: { * Runs an effectful operation with the full `Cause` when the source effect * fails. * + * **When to use** + * + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. + * * **Details** * * Use this to log or inspect typed failures, defects, and interruptions. When @@ -4218,6 +4239,11 @@ export const ignore: < /** * Ignores the effect's failure cause, including defects and interruptions. * + * **When to use** + * + * Use when a best-effort effect should never fail, even from defects or + * interruption, and optional cause logging is enough. + * * **Details** * * Use the `log` option to emit the full {@link Cause} when the effect fails, @@ -4839,6 +4865,11 @@ export const race: { * Races two effects and returns the result of the first one to complete, whether * it succeeds or fails. * + * **When to use** + * + * Use when any completion, including failure, should decide the race and + * interrupt the losing effect. + * * **Details** * * The losing effect is interrupted, and `onWinner` can observe the winning fiber. @@ -5005,6 +5036,11 @@ export const filterMapEffect: { /** * Filters an effect, providing an alternative effect if the predicate fails. * + * **When to use** + * + * Use when a successful value that fails a predicate should continue with an + * effectful fallback instead of failing the effect. + * * **Details** * * This function applies a predicate to the result of an effect. If the @@ -6173,6 +6209,11 @@ export const provideService: { /** * Provides one service to an effect using an effectful acquisition. * + * **When to use** + * + * Use when the service implementation must be created by an effect and its + * acquisition failure should remain in the returned effect. + * * **Details** * * `provideServiceEffect` runs the acquisition effect to produce the service @@ -6365,6 +6406,11 @@ export const scoped: ( /** * Creates a scoped effect by providing access to the scope. * + * **When to use** + * + * Use when resource acquisition needs direct access to the scope being created, + * for example to register finalizers manually. + * * **Example** (Working with an explicit scope) * * ```ts @@ -7553,6 +7599,11 @@ export const repeat: { * Repeats an effect according to a schedule and runs a fallback effect if * repetition fails before the schedule completes. * + * **When to use** + * + * Use when successful repetitions should follow a schedule, but failures from + * the repeated effect or schedule need an effectful fallback. + * * **Details** * * If the repeated effect or schedule step fails, `orElse` receives the failure @@ -7629,6 +7680,11 @@ export const replicate: { /** * Performs this effect `n` times and collects results with `Effect.all` semantics. * + * **When to use** + * + * Use when you want to run the repeated effects immediately, with optional + * concurrency control or result discarding. + * * **Details** * * Use `concurrency` to control parallelism and `discard: true` to ignore results. @@ -8759,6 +8815,11 @@ export const runFork: (effect: Effect, options?: RunOptions | /** * Runs an effect in the background with the provided services. * + * **When to use** + * + * Use when an effect still requires services, you already have a `Context`, and + * you want a background fiber. + * * **Example** (Running with services in the background) * * ```ts @@ -8793,6 +8854,11 @@ export const runForkWith: ( /** * Forks an effect with the provided services, registers `onExit` as a fiber observer, and returns an interruptor. * + * **When to use** + * + * Use when embedding an effect into callback-style code with explicit services + * and a synchronous interruptor. + * * **Details** * * The returned interruptor calls `fiber.interruptUnsafe`, optionally with an interruptor id. @@ -8929,6 +8995,11 @@ export const runPromise: ( /** * Executes an effect as a Promise with the provided services. * + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that rejects on + * effect failure. + * * **Example** (Running with services as a promise) * * ```ts @@ -9015,6 +9086,11 @@ export const runPromiseExit: ( /** * Runs an effect and returns a Promise of Exit with provided services. * + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that preserves + * success and failure as an `Exit`. + * * **Example** (Running with services as an Exit promise) * * ```ts @@ -9115,6 +9191,11 @@ export const runSync: (effect: Effect) => A = internal.runSync /** * Executes an effect synchronously with provided services. * + * **When to use** + * + * Use when you already have a `Context`, the effect is known to complete + * synchronously, and failures should throw. + * * **Example** (Running synchronously with services) * * ```ts @@ -9223,6 +9304,11 @@ export const runSyncExit: (effect: Effect) => Exit.Exit = inte /** * Runs an effect synchronously with provided services, returning an Exit result safely. * + * **When to use** + * + * Use when you already have a `Context` and need a synchronous `Exit` instead of + * throwing on failure. + * * **Example** (Running synchronously with services as Exit) * * ```ts diff --git a/packages/effect/src/Encoding.ts b/packages/effect/src/Encoding.ts index 18ee0c9032..7209eafbb8 100644 --- a/packages/effect/src/Encoding.ts +++ b/packages/effect/src/Encoding.ts @@ -60,6 +60,11 @@ import * as Result from "./Result.ts" * Type identifier stored on `EncodingError` values and used by * `isEncodingError`. * + * **When to use** + * + * Use when implementing low-level `EncodingError`-compatible values that need + * to carry the runtime marker. + * * **Details** * * This marker is part of the runtime representation of `EncodingError`. Prefer diff --git a/packages/effect/src/FiberHandle.ts b/packages/effect/src/FiberHandle.ts index 9b403f3ee4..c55603397e 100644 --- a/packages/effect/src/FiberHandle.ts +++ b/packages/effect/src/FiberHandle.ts @@ -235,6 +235,11 @@ export const makeRuntime = (): Effect.Effect< * Creates a scoped run function that forks effects into a new `FiberHandle` * and returns a `Promise` for each effect result. * + * **When to use** + * + * Use when integrating a scoped `FiberHandle` runner with Promise-based APIs + * and Promise rejection from squashed failures is the desired boundary. + * * **Details** * * Each call stores the fiber in the handle and interrupts the previous fiber @@ -287,6 +292,11 @@ const isInternalInterruption = Filter.toPredicate(Filter.compose( * Sets the fiber in a FiberHandle. When the fiber completes, it will be removed from the FiberHandle. * If a fiber is already running, it will be interrupted unless `options.onlyIfMissing` is set. * + * **When to use** + * + * Use when an existing forked fiber must be installed synchronously into a + * handle and immediate interruption of replaced or closed fibers is acceptable. + * * **Example** (Setting a fiber unsafely) * * ```ts @@ -428,6 +438,11 @@ export const set: { /** * Retrieves the fiber from the FiberHandle synchronously. * + * **When to use** + * + * Use when synchronous inspection of the current fiber is needed and an + * `Option` result is enough outside the Effect workflow. + * * **Example** (Reading the current fiber unsafely) * * ```ts diff --git a/packages/effect/src/FiberMap.ts b/packages/effect/src/FiberMap.ts index 595628ff38..460c18117d 100644 --- a/packages/effect/src/FiberMap.ts +++ b/packages/effect/src/FiberMap.ts @@ -253,6 +253,11 @@ export const makeRuntime = (): Effect.Effect< * Creates a scoped run function that forks effects into a new `FiberMap` and * returns a `Promise` for each effect result. * + * **When to use** + * + * Use when keyed fibers must be managed in a scoped map while exposing their + * results through Promise-based APIs. + * * **Details** * * Each call stores the fiber under the supplied key, interrupting any previous @@ -311,6 +316,11 @@ const isInternalInterruption = Filter.toPredicate(Filter.compose( * Adds a fiber to the `FiberMap` under a key using a synchronous, unsafe * mutation. * + * **When to use** + * + * Use when an existing forked fiber must be installed under a key immediately + * and synchronous interruption of the replaced fiber is acceptable. + * * **Details** * * When the fiber completes, it is removed from the map. If the key already has @@ -472,6 +482,11 @@ export const set: { /** * Retrieves a fiber from the FiberMap synchronously. * + * **When to use** + * + * Use when synchronous keyed lookup of a fiber in a `FiberMap` is needed and an + * `Option` result is enough outside the Effect workflow. + * * **Example** (Retrieving a fiber unsafely) * * ```ts diff --git a/packages/effect/src/FiberSet.ts b/packages/effect/src/FiberSet.ts index 85a3a2992d..7689b876d1 100644 --- a/packages/effect/src/FiberSet.ts +++ b/packages/effect/src/FiberSet.ts @@ -233,6 +233,11 @@ export const makeRuntime = (): Effect.Effec * Creates a scoped run function that forks effects into a new `FiberSet` and * returns a `Promise` for each effect result. * + * **When to use** + * + * Use when many scoped fibers should be tracked as a set while exposing each + * result through Promise-based APIs. + * * **Details** * * Managed fibers are removed when they complete and are interrupted when the @@ -284,6 +289,11 @@ const isInternalInterruption = Filter.toPredicate(Filter.compose( * Adds an existing fiber to the `FiberSet` using a synchronous, unsafe * mutation. * + * **When to use** + * + * Use when an already forked fiber must be registered immediately and + * synchronous interruption on a closed set is acceptable. + * * **Details** * * When the fiber completes, it is removed from the set. If the set is already diff --git a/packages/effect/src/HashMap.ts b/packages/effect/src/HashMap.ts index 437e60d69d..d66f5287c5 100644 --- a/packages/effect/src/HashMap.ts +++ b/packages/effect/src/HashMap.ts @@ -436,6 +436,11 @@ export const getHash: { * Looks up the value for the specified key in the `HashMap` unsafely using the * internal hashing function. * + * **When to use** + * + * Use when reading from a `HashMap` by a key known to exist, and throwing is an + * acceptable programming error for a missing key. + * * **Gotchas** * * This function throws an error if the key is not found. Use `HashMap.get` for diff --git a/packages/effect/src/Iterable.ts b/packages/effect/src/Iterable.ts index 2e6eedf75d..c80f9f192e 100644 --- a/packages/effect/src/Iterable.ts +++ b/packages/effect/src/Iterable.ts @@ -555,7 +555,16 @@ export const head = (self: Iterable): Option => { } /** - * Gets the first element of a `Iterable`, or throw an error if the `Iterable` is empty. + * Gets the first element of an `Iterable` without returning an `Option`. + * + * **When to use** + * + * Use when the `Iterable` is known to be non-empty and direct access to the + * first element is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws if the `Iterable` is empty. * * **Example** (Getting the first element unsafely) * diff --git a/packages/effect/src/MutableList.ts b/packages/effect/src/MutableList.ts index a65dc3387e..be745a46a4 100644 --- a/packages/effect/src/MutableList.ts +++ b/packages/effect/src/MutableList.ts @@ -427,6 +427,11 @@ export const prependAll = (self: MutableList, messages: Iterable): void * Prepends all elements from a ReadonlyArray to the beginning of the MutableList. * This is an optimized version that can reuse the array when mutable=true. * + * **When to use** + * + * Use when prepending a trusted array directly is worth the optimized path and + * you control whether the input may be reused. + * * **Gotchas** * * When mutable=true, the input array may be modified internally. Only use @@ -512,6 +517,11 @@ export const appendAll = (self: MutableList, messages: Iterable): numbe * This is an optimized version that can reuse the array when mutable=true. * Returns the number of elements added. * + * **When to use** + * + * Use when appending a trusted array directly is worth the optimized path and + * you control whether the input may be reused. + * * **Gotchas** * * When mutable=true, the input array may be modified internally. Only use @@ -942,6 +952,11 @@ export const filter = (self: MutableList, f: (value: A, i: number) => bool * Removes all occurrences of a value from the `MutableList` using JavaScript * strict equality semantics. * + * **When to use** + * + * Use when in-place removal should use JavaScript identity/strict equality + * rather than Effect structural equality. + * * **Details** * * The list is modified in place. diff --git a/packages/effect/src/Number.ts b/packages/effect/src/Number.ts index cc0067909a..3fd44589d9 100644 --- a/packages/effect/src/Number.ts +++ b/packages/effect/src/Number.ts @@ -227,12 +227,16 @@ export const divide: { ) /** - * Provides an unsafe division operation on `number`s that throws a `RangeError` if the divisor is `0`. + * Divides two `number` values without returning an `Option`. * * **When to use** * * Use to divide `number` values where the divisor is known to be non-zero and - * division by zero should be a thrown exception. + * a plain `number` result is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws a `RangeError` if the divisor is `0`. * * **Example** (Dividing numbers unsafely) * diff --git a/packages/effect/src/PubSub.ts b/packages/effect/src/PubSub.ts index 052bd78c0b..f73d231cc7 100644 --- a/packages/effect/src/PubSub.ts +++ b/packages/effect/src/PubSub.ts @@ -663,6 +663,11 @@ export const size = (self: PubSub): Effect.Effect => Effect.sync(( * Returns the current number of messages retained by the `PubSub` for active * subscribers synchronously. * + * **When to use** + * + * Use when an immediate `PubSub` size snapshot is needed outside effectful code + * and concurrent changes between the check and later use are acceptable. + * * **Details** * * Returns `0` after shutdown. Because this is an unsafe synchronous snapshot, @@ -840,6 +845,11 @@ export const isShutdown = (self: PubSub): Effect.Effect => Effect * Checks synchronously whether `shutdown` has been called, returning `true` * after shutdown and `false` otherwise. * + * **When to use** + * + * Use when an immediate `PubSub` shutdown-state snapshot is needed outside + * effectful code and racing shutdown changes are acceptable. + * * **Example** (Checking shutdown synchronously) * * ```ts diff --git a/packages/effect/src/Queue.ts b/packages/effect/src/Queue.ts index bd517de15c..9fe9e6e387 100644 --- a/packages/effect/src/Queue.ts +++ b/packages/effect/src/Queue.ts @@ -715,6 +715,11 @@ export const offer = (self: Enqueue, message: Types.NoInfer): Eff /** * Adds a message to the queue synchronously. Returns `false` if the queue is done. * + * **When to use** + * + * Use when you are already in synchronous queue internals or a performance + * boundary where wrapping the mutation in `Effect` is intentionally avoided. + * * **Gotchas** * * This is an unsafe operation that directly modifies the queue without Effect wrapping. @@ -767,6 +772,11 @@ export const offerUnsafe = (self: Enqueue, message: Types.NoInfer * Adds multiple messages to the queue. Returns the remaining messages that * were not added. * + * **When to use** + * + * Use when producers can submit a batch at once and need to know which messages + * did not fit under the queue's capacity strategy. + * * **Details** * * For bounded queues, this operation may suspend if the queue doesn't have @@ -808,6 +818,11 @@ export const offerAll = (self: Enqueue, messages: Iterable): Effe * Adds multiple messages to the queue synchronously. Returns the remaining messages that * were not added. * + * **When to use** + * + * Use when queue internals or a performance boundary need a synchronous batch + * offer and can handle any messages that do not fit. + * * **Gotchas** * * This is an unsafe operation that directly modifies the queue without Effect wrapping. @@ -933,6 +948,11 @@ export const failCause: { * Fails the queue with a cause synchronously. If the queue is already done, `false` is * returned. * + * **When to use** + * + * Use when queue completion must be driven from synchronous internals while + * preserving the full failure `Cause`. + * * **Gotchas** * * This is an unsafe operation that directly modifies the queue without Effect wrapping. @@ -1222,6 +1242,11 @@ export const clear = (self: Dequeue): Effect, Pull.ExcludeD * Takes all currently available messages, waiting until at least one message * is available when the queue is empty. * + * **When to use** + * + * Use when consumers should process the next non-empty batch of buffered + * messages instead of repeatedly taking one message at a time. + * * **Details** * * Returns a non-empty array. If the queue completes or fails before a message @@ -1514,6 +1539,11 @@ export const peek = (self: Dequeue): Effect => /** * Attempts to take one message from the queue synchronously. * + * **When to use** + * + * Use when polling queue internals must not suspend or register a waiting taker, + * and `undefined` is an acceptable result for an empty queue. + * * **Details** * * Returns an `Exit` for an immediately available message or for the queue's @@ -1684,6 +1714,11 @@ export const isFull = (self: Dequeue): Effect => internalEf /** * Returns the current number of buffered messages in the queue synchronously. * + * **When to use** + * + * Use when you need an immediate `Queue` size snapshot for diagnostics or + * internals and do not need the read wrapped in `Effect`. + * * **Details** * * Completed queues report a size of `0`. This unsafe operation reads the queue @@ -1727,6 +1762,11 @@ export const sizeUnsafe = (self: Dequeue): number => self.state._tag /** * Checks whether the queue is full synchronously. * + * **When to use** + * + * Use when an immediate `Queue` capacity snapshot is needed outside effectful + * code and racing queue changes are acceptable. + * * **Example** (Checking fullness synchronously) * * ```ts diff --git a/packages/effect/src/Result.ts b/packages/effect/src/Result.ts index 5b73bb3e64..01e3116f94 100644 --- a/packages/effect/src/Result.ts +++ b/packages/effect/src/Result.ts @@ -89,6 +89,11 @@ const TypeId = "~effect/data/Result" /** * A value that is either `Success` or `Failure`. * + * **When to use** + * + * Use when both success and failure should remain available as data and + * `Option` would lose failure information. + * * **Details** * * - Use {@link succeed} / {@link fail} to construct @@ -921,12 +926,16 @@ export const map: { /** * Folds a `Result` into a single value by applying one of two functions. * + * **When to use** + * + * Use when a `Result`'s success and failure branches should be collapsed into + * one plain output type. + * * **Details** * * - Applies `onSuccess` if the result is a `Success` * - Applies `onFailure` if the result is a `Failure` * - Both branches must return the same type (or a common supertype) - * - Use when you need to "exit" the `Result` type and produce a plain value * * **Example** (Folding to a string) * @@ -1309,11 +1318,15 @@ export const getOrThrow: (self: Result) => A = getOrThrowWith(identi * Returns the original `Result` if it is a `Success`, otherwise applies * `that` to the error and returns the resulting `Result`. * + * **When to use** + * + * Use when a failure should recover into another `Result` while keeping + * successes unchanged. + * * **Details** * * - `Success` is returned unchanged * - `Failure` calls `that(e)` to produce a new `Result` - * - Use to provide a recovery path or fallback computation on failure * * **Example** (Recovering from a failure) * @@ -1801,6 +1814,11 @@ export { /** * Transforms `Option>` into `Result, E>`. * + * **When to use** + * + * Use when optional absence should be treated as a successful `None`, while an + * inner `Result` failure should still fail the whole result. + * * **Details** * * - `None` becomes `Success(None)` @@ -1836,6 +1854,11 @@ export const transposeOption = ( * Maps an `Option` value with a `Result`-producing function, then transposes * the structure from `Option>` to `Result, E>`. * + * **When to use** + * + * Use when an optional value should be validated only when present, preserving + * absence as a successful `None`. + * * **Details** * * - `None` becomes `Success(None)` (the function is never called) diff --git a/packages/effect/src/Schedule.ts b/packages/effect/src/Schedule.ts index 65ef1c5ca2..12ff3df824 100644 --- a/packages/effect/src/Schedule.ts +++ b/packages/effect/src/Schedule.ts @@ -942,6 +942,11 @@ export const both: { * to recur, using the maximum of the two durations between recurrences and * outputting the result of the left schedule (i.e. `self`). * + * **When to use** + * + * Use when two schedules must both allow recurrence and only the left schedule's + * output is needed. + * * **Example** (Combining schedules and keeping the left output) * * ```ts @@ -989,6 +994,11 @@ export const bothLeft: { * to recur, using the maximum of the two durations between recurrences and * outputting the result of the right schedule (i.e. `other`). * + * **When to use** + * + * Use when two schedules must both allow recurrence and only the right + * schedule's output is needed. + * * **Example** (Combining schedules and keeping the right output) * * ```ts @@ -1039,6 +1049,11 @@ export const bothRight: { * outputting the result of the combination of both schedule outputs using the * specified `combine` function. * + * **When to use** + * + * Use when two schedules must both allow recurrence and their outputs should be + * combined into a custom value. + * * **Example** (Combining schedule outputs) * * ```ts @@ -1769,6 +1784,11 @@ export const either: { * to recur, using the minimum of the two durations between recurrences and * outputting the result of the left schedule (i.e. `self`). * + * **When to use** + * + * Use when either schedule may keep recurrence going and only the left + * schedule's output is needed. + * * **Example** (Combining either schedules and keeping the left output) * * ```ts @@ -1819,6 +1839,11 @@ export const eitherLeft: { * to recur, using the minimum of the two durations between recurrences and * outputting the result of the right schedule (i.e. `other`). * + * **When to use** + * + * Use when either schedule may keep recurrence going and only the right + * schedule's output is needed. + * * **Example** (Combining either schedules and keeping the right output) * * ```ts @@ -1870,6 +1895,11 @@ export const eitherRight: { * outputting the result of the combination of both schedule outputs using the * specified `combine` function. * + * **When to use** + * + * Use when either schedule may keep recurrence going and their outputs should be + * combined into a custom value. + * * **Example** (Combining either schedule outputs) * * ```ts diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index b6e956c2e6..b90f7739fd 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -337,6 +337,11 @@ export interface declareConstructor`, `Option`, etc.) by accepting a list of type-parameter schemas * and a decoder factory. * + * **When to use** + * + * Use when you are defining a schema for a generic container whose validation + * depends on one or more type-parameter schemas. + * * **Details** * * The outer call `declareConstructor()` fixes the decoded type `T`, @@ -420,10 +425,10 @@ export interface declare extends declareConstructor` or `Array`, use {@link declareConstructor} instead. + * Use when you are defining a schema for an opaque type with no type parameters + * and validation can be expressed as a type guard. * * **Example** (Schema for a custom `UserId` branded type) * @@ -2456,6 +2461,11 @@ function templateLiteralFromParts(parts: Pa * Creates a schema that validates strings matching a template literal pattern. Each part can be * a literal string/number/bigint or a schema whose encoded type is a string, number, or bigint. * + * **When to use** + * + * Use when the decoded value should remain the matched string and you do not + * need the individual template parts parsed into a tuple. + * * **Example** (URL path pattern) * * ```ts @@ -2637,6 +2647,11 @@ export interface Unknown extends Bottom extends decodeTo extends decodeTo< * and provides a default `Encoded` value when the field is missing or * `undefined` during decoding. * + * **When to use** + * + * Use when the default is expressed in the encoded representation, before the + * field's decoding transformation runs. + * * **Details** * * The default value is specified in terms of the `Encoded` type (before any @@ -5440,6 +5470,11 @@ export interface withDecodingDefaultType * and provides a default `Type` value when the field is missing or * `undefined` during decoding. * + * **When to use** + * + * Use when the default is already in the decoded representation and should not + * pass through the field's decoding transformation. + * * **Details** * * Unlike {@link withDecodingDefault}, the default value is specified in terms @@ -9087,6 +9122,11 @@ export type ExitIso = { * Creates a schema for `Exit` values using schemas for the success value, typed * failure, and unexpected defect channels. * + * **When to use** + * + * Use when serializing or validating an effect outcome where success, typed + * failure, and defects each need their own schema. + * * @category Exit * @since 3.10.0 */ diff --git a/packages/effect/src/SchemaAST.ts b/packages/effect/src/SchemaAST.ts index 637151e0b0..7210ce3e7e 100644 --- a/packages/effect/src/SchemaAST.ts +++ b/packages/effect/src/SchemaAST.ts @@ -1572,6 +1572,11 @@ export const bigInt = new BigInt() /** * AST node for array-like types — both tuples and arrays. * + * **When to use** + * + * Use when constructing or inspecting AST nodes for tuple or array-like schemas, + * including rest elements. + * * **Details** * * - `elements` — positional element types (tuple elements). An element is @@ -1890,6 +1895,11 @@ export class KeyValueCombiner { /** * Represents an index signature entry within an {@link Objects} node. * + * **When to use** + * + * Use when constructing or inspecting object AST entries for record-like keys + * and values. + * * **Details** * * - `parameter` — the key type AST (e.g. {@link String} for `string` keys, @@ -1929,6 +1939,11 @@ export class IndexSignature { /** * AST node for object-like schemas, including structs and records. * + * **When to use** + * + * Use when constructing or inspecting AST nodes for structs or records rather + * than array-like schemas. + * * **Details** * * - `propertySignatures` — named properties with their types (struct fields). @@ -2902,6 +2917,11 @@ export function makeFilterByGuard( /** * Creates a {@link Filter} that validates strings by running `RegExp.test`. * + * **When to use** + * + * Use when string validation should be represented as a schema `Filter` backed + * by a regular expression. + * * **Details** * * The filter can be used with `Schema.filter` or attached directly to a diff --git a/packages/effect/src/SchemaRepresentation.ts b/packages/effect/src/SchemaRepresentation.ts index 0ca82d32e9..c136324243 100644 --- a/packages/effect/src/SchemaRepresentation.ts +++ b/packages/effect/src/SchemaRepresentation.ts @@ -154,6 +154,11 @@ export interface Suspend { /** * A named reference to a definition in the {@link References} map. * + * **When to use** + * + * Use when a representation should point to a named definition instead of + * embedding the definition inline. + * * **Details** * * `$ref` is the key into `Document.references` or `MultiDocument.references`. diff --git a/packages/effect/src/Scope.ts b/packages/effect/src/Scope.ts index 349fb08582..63bf4d6c52 100644 --- a/packages/effect/src/Scope.ts +++ b/packages/effect/src/Scope.ts @@ -290,6 +290,11 @@ export const make: (finalizerStrategy?: "sequential" | "parallel") => Effect( /** * Creates a stream from an effect producing an iterable of values. * + * **When to use** + * + * Use when the iterable must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * * **Example** (Creating a stream from an iterable effect) * * ```ts @@ -1272,6 +1277,11 @@ export const fromArray = (array: ReadonlyArray): Stream => /** * Creates a stream from an effect that produces an array of values. * + * **When to use** + * + * Use when the array must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * * **Example** (Creating a stream from an effect that produces an array of values) * * ```ts @@ -2041,6 +2051,11 @@ export const mapArray: { /** * Maps over elements of the stream with the specified effectful function. * + * **When to use** + * + * Use when each stream element transformation needs an Effect, service + * dependency, failure channel, or configured concurrency. + * * **Example** (Effectfully mapping stream values) * * ```ts @@ -2107,6 +2122,11 @@ export const mapEffect: { /** * Flattens a stream of `Effect` values into a stream of their results. * + * **When to use** + * + * Use when stream elements already are effects and their successes should become + * stream elements while their failures enter the stream error channel. + * * **Example** (Flattening a stream of Effect values into a stream of their results) * * ```ts @@ -2156,6 +2176,11 @@ export const flattenEffect: < /** * Maps over non-empty array chunks emitted by the stream effectfully. * + * **When to use** + * + * Use when transformation needs to see and replace each non-empty emitted chunk + * effectfully instead of mapping individual stream elements. + * * **Example** (Effectfully mapping stream chunks) * * ```ts @@ -3199,6 +3224,11 @@ export const merge: { /** * Merges this stream with a background effect, keeping the stream's elements. * + * **When to use** + * + * Use when an effect should run concurrently for the lifetime of a stream while + * only the stream's elements remain in the output. + * * **Details** * * The effect runs concurrently, fails the stream if it fails, and is interrupted @@ -3242,6 +3272,12 @@ export const mergeEffect: { * Merges this stream and the specified stream together, tagging values from the * left stream as `Result.succeed` and values from the right stream as `Result.fail`. * + * **When to use** + * + * Use when values from both streams should be emitted and downstream code needs + * left values wrapped as successful `Result` values and right values wrapped as + * failed `Result` values. + * * **Example** (Merging streams into results) * * ```ts @@ -3292,6 +3328,11 @@ export const mergeResult: { /** * Merges two streams while emitting only the values from the left stream. * + * **When to use** + * + * Use when the right stream is needed for its effects or failures, but downstream + * consumers should only receive values from the left stream. + * * **Details** * * The right stream still runs for its effects, and any failures from the right @@ -3330,6 +3371,11 @@ export const mergeLeft: { * Merges this stream and the specified stream together, emitting only the * values from the right stream while the left stream runs for its effects. * + * **When to use** + * + * Use when the left stream is needed for its effects or failures, but downstream + * consumers should only receive values from the right stream. + * * **Details** * * The merged stream ends when the right stream completes, interrupting the @@ -4022,6 +4068,11 @@ export const zipWithPreviousAndNext = ( * Zips multiple streams so that when a value is emitted by any stream, it is * combined with the latest values from the other streams to produce a result. * + * **When to use** + * + * Use when each stream should contribute its latest value after all streams have + * emitted at least once. + * * **Gotchas** * * Note: tracking the latest value is done on a per-array basis. That means @@ -4093,6 +4144,11 @@ export const zipLatestAll = >>( /** * Combines two streams by emitting each new element with the latest value from the other stream. * + * **When to use** + * + * Use when two streams should start emitting combined pairs after both have + * produced at least one value. + * * **Gotchas** * * Note: tracking the latest value is done on a per-array basis. That means @@ -4138,6 +4194,11 @@ export const zipLatest: { * Combines the latest values from both streams whenever either emits, using * the provided function. * + * **When to use** + * + * Use when two streams should start emitting custom combined values after both + * have produced at least one value. + * * **Gotchas** * * Note: tracking the latest value is done on a per-array basis. That means @@ -6455,6 +6516,11 @@ export const takeUntil: { /** * Takes stream elements until an effectful predicate returns `true`. * + * **When to use** + * + * Use when the stopping condition needs an Effect or service and predicate + * failure should fail the stream. + * * **Example** (Taking until an effectful predicate matches) * * ```ts @@ -6625,6 +6691,11 @@ export const takeWhileFilter: { /** * Takes elements from the stream while the effectful predicate is `true`. * + * **When to use** + * + * Use when the leading-prefix predicate needs an Effect or service and the + * stream should stop before the first false result. + * * **Example** (Effectfully taking while a predicate holds) * * ```ts @@ -6740,6 +6811,11 @@ export const dropUntil: { * Drops all elements of the stream until the specified effectful predicate * evaluates to `true`. * + * **When to use** + * + * Use when dropping the leading prefix requires an Effect or service and the + * first matching element should also be dropped. + * * **Details** * * The first element that satisfies the predicate is also dropped. @@ -7545,6 +7621,11 @@ const emptyArr = Arr.empty() * Maps each element statefully and effectfully, emitting zero or more output * values per input. * + * **When to use** + * + * Use when stateful element mapping needs Effects or can fail while emitting + * zero or more values per input element. + * * **Details** * * The mapping effect receives the current state and element, then returns the @@ -7626,6 +7707,11 @@ export const mapAccumEffect: { * Maps each non-empty input chunk statefully and effectfully, emitting zero or * more output values per chunk. * + * **When to use** + * + * Use when stateful mapping should process each emitted non-empty chunk with an + * Effect instead of each element separately. + * * **Details** * * The mapping effect receives the current state and chunk, then returns the @@ -10720,6 +10806,11 @@ export const runFold: { /** * Runs the stream and folds elements using an effectful reducer. * + * **When to use** + * + * Use when reducing stream elements needs Effects, services, or failures in the + * reducer. + * * **Example** (Effectfully folding stream values) * * ```ts @@ -11105,6 +11196,11 @@ export const mkUint8Array = (self: Stream): Effect.Effec /** * Converts the stream to a `ReadableStream` using the provided services. * + * **When to use** + * + * Use when bridging to Web Streams and you already have the `Context` required + * to run the stream outside an `Effect`. + * * **Details** * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. @@ -11218,6 +11314,11 @@ export const toReadableStream: { /** * Creates an Effect that builds a ReadableStream from the stream. * + * **When to use** + * + * Use when bridging to Web Streams from inside an `Effect` so the required + * services can be captured from the current context. + * * **Details** * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. @@ -11265,6 +11366,11 @@ export const toReadableStreamEffect: { /** * Converts the stream to an `AsyncIterable` using the provided services. * + * **When to use** + * + * Use when converting outside an Effect and you already have the `Context` + * needed to run the stream. + * * **Example** (Converting to an AsyncIterable with services) * * ```ts @@ -11337,6 +11443,11 @@ export const toAsyncIterableWith: { /** * Creates an effect that yields an `AsyncIterable` using the current services. * + * **When to use** + * + * Use when the `AsyncIterable` should be created inside Effect with the current + * context supplying the stream's services. + * * **Example** (Creating an AsyncIterable effect) * * ```ts diff --git a/packages/effect/src/SubscriptionRef.ts b/packages/effect/src/SubscriptionRef.ts index 79caa900a3..67fe307050 100644 --- a/packages/effect/src/SubscriptionRef.ts +++ b/packages/effect/src/SubscriptionRef.ts @@ -209,6 +209,11 @@ export const changes = (self: SubscriptionRef): Stream.Stream => Stream /** * Retrieves the current value of the `SubscriptionRef` unsafely. * + * **When to use** + * + * Use when you are in synchronous internals or test setup where concurrent + * updates are controlled. + * * **Gotchas** * * This function directly accesses the underlying reference without any diff --git a/packages/effect/src/Trie.ts b/packages/effect/src/Trie.ts index 898b8a9404..9a89ed8641 100644 --- a/packages/effect/src/Trie.ts +++ b/packages/effect/src/Trie.ts @@ -598,6 +598,11 @@ export const isEmpty: (self: Trie) => boolean = TR.isEmpty /** * Looks up the value for the specified key in the `Trie` unsafely. * + * **When to use** + * + * Use when the trie key is known to exist and a missing key should be treated + * as a programming error. + * * **Gotchas** * * `getUnsafe` throws if the key is not found. Use `get` instead to safely get diff --git a/packages/effect/src/unstable/cli/Command.ts b/packages/effect/src/unstable/cli/Command.ts index 30d019b175..2705cb6d8f 100644 --- a/packages/effect/src/unstable/cli/Command.ts +++ b/packages/effect/src/unstable/cli/Command.ts @@ -1274,6 +1274,11 @@ export const provide: { * Provides the handler of a command with the implementation of a service that * optionally depends on the command-line input to be constructed. * + * **When to use** + * + * Use when a command handler needs a pure service implementation, optionally + * derived from the parsed command input. + * * @category providing services * @since 4.0.0 */ diff --git a/packages/effect/src/unstable/cli/GlobalFlag.ts b/packages/effect/src/unstable/cli/GlobalFlag.ts index 6ae28d8f03..fad537a107 100644 --- a/packages/effect/src/unstable/cli/GlobalFlag.ts +++ b/packages/effect/src/unstable/cli/GlobalFlag.ts @@ -266,6 +266,11 @@ export const LogLevel: Setting<"log-level", Option.Option> = setti /** * Built-in global flags in default precedence order. * + * **When to use** + * + * Use when extending or inspecting the default global-flag set that + * `Command.runWith` prepends before user-defined global flags. + * * **Details** * * The built-ins are `Help`, `Version`, `Completions`, and `LogLevel`. diff --git a/packages/effect/src/unstable/cluster/ClusterMetrics.ts b/packages/effect/src/unstable/cluster/ClusterMetrics.ts index 49f24f015d..9049a7f22a 100644 --- a/packages/effect/src/unstable/cluster/ClusterMetrics.ts +++ b/packages/effect/src/unstable/cluster/ClusterMetrics.ts @@ -29,6 +29,11 @@ import * as Metric from "../../Metric.ts" * Creates a gauge tracking the number of active entity instances for each entity type on * the current runner. * + * **When to use** + * + * Use when instrumenting runner-local entity counts and tagging them by entity + * type for cluster dashboards. + * * **Details** * * Bigint gauge named `effect_cluster_entities`, updated with the entity type as diff --git a/packages/effect/src/unstable/cluster/EntityResource.ts b/packages/effect/src/unstable/cluster/EntityResource.ts index 2723f9c0bd..d9ebb68daa 100644 --- a/packages/effect/src/unstable/cluster/EntityResource.ts +++ b/packages/effect/src/unstable/cluster/EntityResource.ts @@ -71,6 +71,11 @@ export interface EntityResource { /** * Context service for a Scope that is only closed when the resource is explicitly closed. * + * **When to use** + * + * Use when a cluster entity resource needs a scope that survives restarts and + * closes only through the resource lifecycle. + * * **Gotchas** * * It is not closed during restarts, due to shard movement or node shutdowns. @@ -86,6 +91,11 @@ export class CloseScope extends Context.Service< /** * Creates an `EntityResource` that can be acquired inside a cluster entity. * + * **When to use** + * + * Use when a cluster entity should lazily share an acquired resource across + * messages and release it only on idle timeout or explicit close. + * * **Details** * * The resource will only be fully released when the idle time to live is diff --git a/packages/effect/src/unstable/encoding/Ndjson.ts b/packages/effect/src/unstable/encoding/Ndjson.ts index ac6f53e5c9..e94bcdb51c 100644 --- a/packages/effect/src/unstable/encoding/Ndjson.ts +++ b/packages/effect/src/unstable/encoding/Ndjson.ts @@ -170,6 +170,11 @@ export const encodeSchemaString = ( /** * Creates a channel that parses NDJSON string chunks into values. * + * **When to use** + * + * Use when NDJSON input arrives as string chunks and each complete line should + * be parsed into a JSON value. + * * **Details** * * Lines may span input chunks. diff --git a/packages/effect/src/unstable/eventlog/EventJournal.ts b/packages/effect/src/unstable/eventlog/EventJournal.ts index d313bf296f..1912a890a9 100644 --- a/packages/effect/src/unstable/eventlog/EventJournal.ts +++ b/packages/effect/src/unstable/eventlog/EventJournal.ts @@ -188,6 +188,11 @@ export const RemoteId = Schema.Uint8Array.pipe(Schema.brand(RemoteIdTypeId)) /** * Generates a new random `RemoteId`. * + * **When to use** + * + * Use when generating a fresh event-log remote id internally and the UUID bytes + * are trusted to satisfy the brand. + * * **Gotchas** * * This is unsafe because the generated UUID bytes are cast to the brand without @@ -251,6 +256,11 @@ export const EntryIdOrder = Order.make((a, b) => { * Generates a UUID v7 `EntryId`, optionally using the supplied millisecond * timestamp. * + * **When to use** + * + * Use when generating an event-log entry id internally and the UUID v7 bytes + * are trusted to satisfy the brand. + * * **Gotchas** * * This is unsafe because the generated UUID bytes are cast to the brand without diff --git a/packages/effect/src/unstable/http/HttpClientRequest.ts b/packages/effect/src/unstable/http/HttpClientRequest.ts index e55fd541f5..e69ce3a409 100644 --- a/packages/effect/src/unstable/http/HttpClientRequest.ts +++ b/packages/effect/src/unstable/http/HttpClientRequest.ts @@ -713,7 +713,16 @@ export const bodyJson: { ) /** - * Sets a JSON request body using unsafe JSON encoding, which may throw instead of failing in the Effect error channel. + * Sets a JSON request body using unsafe JSON encoding. + * + * **When to use** + * + * Use when the request body is known to be JSON-serializable and a synchronous + * `HttpClientRequest` result is needed. + * + * **Gotchas** + * + * JSON encoding may throw instead of failing in the Effect error channel. * * @category combinators * @since 4.0.0 diff --git a/packages/effect/src/unstable/http/HttpServerResponse.ts b/packages/effect/src/unstable/http/HttpServerResponse.ts index 9cd40d559c..d5d7367c58 100644 --- a/packages/effect/src/unstable/http/HttpServerResponse.ts +++ b/packages/effect/src/unstable/http/HttpServerResponse.ts @@ -370,6 +370,11 @@ export const schemaJson = ( /** * Creates a JSON HTTP response synchronously. * + * **When to use** + * + * Use when the response body is known to be JSON-serializable and you need a + * synchronous `HttpServerResponse`. + * * **Gotchas** * * Unlike `json`, serialization errors from `JSON.stringify` are not captured in diff --git a/packages/effect/src/unstable/http/UrlParams.ts b/packages/effect/src/unstable/http/UrlParams.ts index 0f77661a6f..71dcbe2459 100644 --- a/packages/effect/src/unstable/http/UrlParams.ts +++ b/packages/effect/src/unstable/http/UrlParams.ts @@ -319,6 +319,11 @@ export const getAll: { /** * Returns the first value for a query parameter key safely. * + * **When to use** + * + * Use when duplicate query parameters are ordered and the first occurrence has + * precedence. + * * **Details** * * Returns `Option.none` when the key is absent. @@ -340,6 +345,11 @@ export const getFirst: { /** * Returns the last value for a query parameter key safely. * + * **When to use** + * + * Use when duplicate query parameters are ordered and the last occurrence has + * precedence. + * * **Details** * * Returns `Option.none` when the key is absent. diff --git a/packages/effect/src/unstable/observability/OtlpResource.ts b/packages/effect/src/unstable/observability/OtlpResource.ts index 718f1e4ede..67161dcf7f 100644 --- a/packages/effect/src/unstable/observability/OtlpResource.ts +++ b/packages/effect/src/unstable/observability/OtlpResource.ts @@ -143,6 +143,11 @@ export const fromConfig: ( /** * Returns the `service.name` attribute from an OTLP resource. * + * **When to use** + * + * Use when an OTLP resource is known to contain a string `service.name` and + * throwing is acceptable if that invariant is broken. + * * **Gotchas** * * Throws if the resource does not contain a string `service.name` attribute. diff --git a/packages/effect/src/unstable/workflow/Workflow.ts b/packages/effect/src/unstable/workflow/Workflow.ts index fce27804f7..33a65ce839 100644 --- a/packages/effect/src/unstable/workflow/Workflow.ts +++ b/packages/effect/src/unstable/workflow/Workflow.ts @@ -794,6 +794,11 @@ export const addFinalizer: ( /** * Adds compensation logic to an effect inside a Workflow. * + * **When to use** + * + * Use when a top-level workflow step needs compensating cleanup if the overall + * workflow later fails after the step succeeds. + * * **Details** * * The compensation finalizer is called if the entire workflow fails, allowing you to perform cleanup or other actions based on the success value and the cause of the workflow failure. diff --git a/packages/effect/src/unstable/workflow/WorkflowEngine.ts b/packages/effect/src/unstable/workflow/WorkflowEngine.ts index 52b98ba717..81a444a3e1 100644 --- a/packages/effect/src/unstable/workflow/WorkflowEngine.ts +++ b/packages/effect/src/unstable/workflow/WorkflowEngine.ts @@ -372,8 +372,16 @@ export interface Encoded { /** * Builds a typed `WorkflowEngine` service from a low-level encoded - * implementation. This is unsafe because the implementation must correctly - * persist, resume, and encode workflow state. + * implementation. + * + * **When to use** + * + * Use when wiring a trusted low-level workflow engine implementation into the + * typed `WorkflowEngine` service. + * + * **Gotchas** + * + * The implementation must correctly persist, resume, and encode workflow state. * * @category constructors * @since 4.0.0 diff --git a/packages/platform-browser/src/Clipboard.ts b/packages/platform-browser/src/Clipboard.ts index acf7a618a8..2f3adafa15 100644 --- a/packages/platform-browser/src/Clipboard.ts +++ b/packages/platform-browser/src/Clipboard.ts @@ -44,6 +44,11 @@ const ErrorTypeId = "~@effect/platform-browser/Clipboard/ClipboardError" /** * Defines the service interface for reading from, writing to, and clearing the browser clipboard. * + * **When to use** + * + * Use when an application needs clipboard operations through an Effect service + * so browser failures stay in the error channel. + * * **Details** * * `read` and `write` work with `ClipboardItem` arrays. `readString` and diff --git a/packages/platform-browser/src/IndexedDbVersion.ts b/packages/platform-browser/src/IndexedDbVersion.ts index 5312f9750f..1e471d7f68 100644 --- a/packages/platform-browser/src/IndexedDbVersion.ts +++ b/packages/platform-browser/src/IndexedDbVersion.ts @@ -106,6 +106,11 @@ const makeProto = (options: { /** * Creates an `IndexedDbVersion` from one or more table definitions. * + * **When to use** + * + * Use when you need a typed description of the target IndexedDB schema that a + * database migration will materialize. + * * **Details** * * The returned version exposes a `tables` map keyed by each table's From f8762b9f16c7323d5c7164db467e36329d0ec067 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Sat, 30 May 2026 18:44:37 +0200 Subject: [PATCH 29/29] wip --- .changeset/remove-types-mergerecord.md | 5 +++ packages/effect/src/Chunk.ts | 8 ++-- packages/effect/src/DateTime.ts | 8 ---- packages/effect/src/Option.ts | 10 ----- packages/effect/src/Predicate.ts | 8 ---- packages/effect/src/Stream.ts | 4 -- packages/effect/src/Types.ts | 51 ++++++-------------------- 7 files changed, 21 insertions(+), 73 deletions(-) create mode 100644 .changeset/remove-types-mergerecord.md diff --git a/.changeset/remove-types-mergerecord.md b/.changeset/remove-types-mergerecord.md new file mode 100644 index 0000000000..6533e1bfeb --- /dev/null +++ b/.changeset/remove-types-mergerecord.md @@ -0,0 +1,5 @@ +--- +"effect": patch +--- + +Remove the `Types.MergeRecord` alias. Use `Types.MergeLeft` instead. diff --git a/packages/effect/src/Chunk.ts b/packages/effect/src/Chunk.ts index 72c847dbb1..cfe27038eb 100644 --- a/packages/effect/src/Chunk.ts +++ b/packages/effect/src/Chunk.ts @@ -1471,8 +1471,8 @@ export const head: (self: Chunk) => Option = get(0) * * **When to use** * - * Use when the chunk is known to be non-empty and you want direct access without - * handling `Option.none`. + * Use when you know the chunk is non-empty and need the first element directly + * without handling `Option.none`. * * **Gotchas** * @@ -1543,8 +1543,8 @@ export const last = (self: Chunk): Option => get(self, self.length - 1) * * **When to use** * - * Use when the chunk is known to be non-empty and you want direct access without - * handling `Option.none`. + * Use when you know the chunk is non-empty and need the last element directly + * without handling `Option.none`. * * **Gotchas** * diff --git a/packages/effect/src/DateTime.ts b/packages/effect/src/DateTime.ts index 0569a3cb00..410dcd2aa8 100644 --- a/packages/effect/src/DateTime.ts +++ b/packages/effect/src/DateTime.ts @@ -1112,10 +1112,6 @@ export const zoneMakeNamed: (zoneId: string) => Option.Option = * Use when invalid IANA zone ids should fail in the Effect error channel * instead of returning `Option.none` or throwing. * - * **Details** - * - * If the time zone is invalid, it will fail with an `IllegalArgumentError`. - * * **Example** (Creating named time zones effectfully) * * ```ts @@ -2575,10 +2571,6 @@ export const format: { * Formats a `DateTime` with `Intl.DateTimeFormat` using the system local time * zone and locale. * - * **Details** - * - * It will use the system's local time zone & locale. - * * **Example** (Formatting DateTime values locally) * * ```ts diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index d17f8153b7..865b0dde30 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -1233,11 +1233,6 @@ export const map: { * Use when you need to replace a present `Option` value while preserving * whether it was `Some` or `None`. * - * **Details** - * - * - `Some` → `Some(b)` - * - `None` → `None` - * * **Example** (Replacing a value) * * ```ts @@ -1270,11 +1265,6 @@ export const as: { * Use when you need to discard a present `Option` value while preserving * whether it was `Some` or `None`. * - * **Details** - * - * - `Some` → `Some(undefined)` - * - `None` → `None` - * * **Example** (Voiding the value) * * ```ts diff --git a/packages/effect/src/Predicate.ts b/packages/effect/src/Predicate.ts index 5888df08a9..84a057041c 100644 --- a/packages/effect/src/Predicate.ts +++ b/packages/effect/src/Predicate.ts @@ -989,10 +989,6 @@ export function isNotNullish(input: A): input is NonNullable { * * Use when you need a `Predicate` that never accepts, e.g. in default branches. * - * **Details** - * - * Always returns `false`. - * * **Example** (Never matches) * * ```ts @@ -1016,10 +1012,6 @@ export function isNever(_: unknown): _ is never { * * Use when you need a `Predicate` that always accepts, e.g. as a placeholder. * - * **Details** - * - * Always returns `true`. - * * **Example** (Always matches) * * ```ts diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 0d06da2213..d492264121 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -6816,10 +6816,6 @@ export const dropUntil: { * Use when dropping the leading prefix requires an Effect or service and the * first matching element should also be dropped. * - * **Details** - * - * The first element that satisfies the predicate is also dropped. - * * **Example** (Dropping until an effectful predicate matches) * * ```ts diff --git a/packages/effect/src/Types.ts b/packages/effect/src/Types.ts index 6f88ee7f25..4320d4ec4f 100644 --- a/packages/effect/src/Types.ts +++ b/packages/effect/src/Types.ts @@ -43,8 +43,6 @@ * * - {@link TupleOf} with a non-literal `number` (e.g. `TupleOf`) * degrades to `Array`. - * - {@link MergeRecord} is an alias for {@link MergeLeft}; prefer - * {@link MergeLeft} or {@link MergeRight} for clarity. * - {@link NoInfer} uses the `[A][A extends any ? 0 : never]` trick, not the * built-in `NoInfer` from TypeScript 5.4+. * - {@link DeepMutable} recurses into `Map`, `Set`, arrays, and objects but @@ -168,7 +166,8 @@ export type Tags = E extends { readonly _tag: string } ? E["_tag"] : never * * **When to use** * - * Use to narrow a union by removing a specific variant. + * Use to remove tagged-union members whose `_tag` matches a specific value in + * type-level code. * * **Details** * @@ -201,7 +200,8 @@ export type ExcludeTag = Exclude * * **When to use** * - * Use to narrow a union down to a single variant. + * Use to select tagged-union members whose `_tag` matches a specific value in + * type-level code. * * **Details** * @@ -358,7 +358,8 @@ export type EqualsWith = (() => T extends A ? 1 : 2) extends ( * * **When to use** * - * Use to conditionally branch based on the presence of keys in a type. + * Use to branch type-level logic when at least one key from a candidate key set + * exists on an object type. * * **Details** * @@ -406,7 +407,6 @@ export type Has = (Key extends infer K ? K extends keyof * ``` * * @see {@link MergeRight} - * @see {@link MergeRecord} * @see {@link Simplify} * * @category models @@ -451,35 +451,6 @@ export type MergeRight = Simplify< } > -/** - * Alias for {@link MergeLeft}. Merges two object types where keys from - * `Source` take precedence on conflict. - * - * **When to use** - * - * Use when prefer {@link MergeLeft} or {@link MergeRight} for clarity about which - * side wins. - * - * **Example** (Merging records) - * - * ```ts - * import type { Types } from "effect" - * - * type Result = Types.MergeRecord< - * { a: number; b: number }, - * { a: string; c: boolean } - * > - * // { a: number; b: number; c: boolean } - * ``` - * - * @see {@link MergeLeft} - * @see {@link MergeRight} - * - * @category models - * @since 2.0.0 - */ -export type MergeRecord = MergeLeft - /** * Describes the concurrency level for Effect operations that run multiple * effects. @@ -963,8 +934,8 @@ export type IsUnion = [T] extends [UnionToIntersection] ? false : true * * **When to use** * - * Use with the nested error pattern where errors wrap sub-errors in a `reason` - * field. + * Use when an error type stores nested sub-errors in a `reason` field and you + * need that field's full union type as a standalone type. * * **Details** * @@ -1033,7 +1004,8 @@ export type ReasonTags = E extends { readonly reason: { readonly _tag: string * * **When to use** * - * Use to extract only the matching reason variant from a nested error type. + * Use when you need the nested reason variant type itself, selected by `_tag`, + * rather than the enclosing error type. * * **Details** * @@ -1147,7 +1119,8 @@ export type OmitReason = E extends { readonly reason: infer * * **When to use** * - * Use to remove a handled reason variant from an error's reason union. + * Use when you need the remaining nested reason union type after removing + * variants handled by `_tag`, rather than the enclosing error type. * * **Details** *