diff --git "a/.opencode/node_modules/effect/src/Effect.ts" "b/.opencode/node_modules/effect/src/Effect.ts" --- "a/.opencode/node_modules/effect/src/Effect.ts" +++ "b/.opencode/node_modules/effect/src/Effect.ts" @@ -1,70 +1,12 @@ /** - * The `Effect` module is the core of the Effect library, providing a powerful and expressive - * way to model and compose asynchronous, concurrent, and effectful computations. + * Describes workflows that run only when executed by the Effect runtime. * - * An `Effect` represents a computation that: - * - May succeed with a value of type `A` - * - May fail with an error of type `E` - * - Requires a context/environment of type `R` - * - * Effects are lazy and immutable - they describe computations that can be executed later. - * This allows for powerful composition, error handling, resource management, and concurrency - * patterns. - * - * ## Key Features - * - * - **Type-safe error handling**: Errors are tracked in the type system - * - **Resource management**: Automatic cleanup with scoped resources - * - **Structured concurrency**: Safe parallel and concurrent execution - * - **Composable**: Effects can be combined using operators like `flatMap`, `map`, `zip` - * - **Testable**: Built-in support for testing with controlled environments - * - **Interruptible**: Effects can be safely interrupted and cancelled - * - * @example - * ```ts - * import { Console, Effect } from "effect" - * - * // Creating a simple effect - * const hello = Effect.succeed("Hello, World!") - * - * // Composing effects - * const program = Effect.gen(function*() { - * const message = yield* hello - * yield* Console.log(message) - * return message.length - * }) - * - * // Running the effect - * Effect.runPromise(program).then(console.log) // 13 - * ``` - * - * @example - * ```ts - * import { Data, Effect } from "effect" - * - * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} - * - * // Effect that may fail - * const divide = (a: number, b: number) => - * b === 0 - * ? Effect.fail(new DiscountRateError()) - * : Effect.succeed(a / b) - * - * // Error handling - * const program = Effect.gen(function*() { - * const result = yield* divide(10, 2) - * console.log("Result:", result) // Result: 5 - * return result - * }) - * - * // Handle errors - * const safeProgram = program.pipe( - * Effect.match({ - * onFailure: (error) => -1, - * onSuccess: (value) => value - * }) - * ) - * ``` + * An `Effect` can succeed with an `A`, fail with an `E`, and require + * services `R`. Creating an effect does not perform the work; it builds a value + * that can be composed, provided with services, retried, interrupted, run + * concurrently, or inspected by the runtime. This module is the main API for + * creating effects, combining them, handling failures, managing resources, and + * running effect programs. * * @since 2.0.0 */ @@ -129,15 +71,36 @@ import type { unassigned } from "./Types.ts" import type * as Unify from "./Unify.ts" -import { internalCall, SingleShotGen } from "./Utils.ts" +import { internalCall } from "./Utils.ts" -const TypeId = core.EffectTypeId +/** + * Type-level identifier for `Effect` values. + * + * @category type IDs + * @since 4.0.0 + */ +export type TypeId = "~effect/Effect" + +/** + * Runtime identifier used to recognize `Effect` values. + * + * @category type IDs + * @since 4.0.0 + */ +export const TypeId: TypeId = core.EffectTypeId /** * The `Effect` interface defines a value that lazily describes a workflow or * job. The workflow requires some context `R`, and may fail with an error of * type `E`, or succeed with a value of type `A`. * + * **When to use** + * + * Use when you need to represent a lazy, composable workflow that can require + * services, fail with a typed error, or succeed with a typed value. + * + * **Details** + * * `Effect` values model resourceful interaction with the outside world, * including synchronous, asynchronous, concurrent, and parallel interaction. * They use a fiber-based concurrency model, with built-in support for @@ -147,96 +110,22 @@ const TypeId = core.EffectTypeId * To run an `Effect` value, you need a `Runtime`, which is a type that is * capable of executing `Effect` values. * - * @example - * ```ts - * import { Data, Effect } from "effect" - * - * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} - * - * // A simple effect that succeeds with a value - * const success = Effect.succeed(42) - * - * // An effect that will always fail - * const risky = Effect.fail(new TaskError({ message: "Something went wrong" })) - * - * // Effects can be composed using generator functions - * const program = Effect.gen(function*() { - * const value = yield* success - * console.log(value) // 42 - * return value * 2 - * }) - * ``` - * + * @category models * @since 2.0.0 - * @category Models */ -export interface Effect - extends Pipeable, Inspectable, Yieldable, A, E, R> -{ +export interface Effect extends Pipeable, Inspectable { readonly [TypeId]: Variance + [Symbol.iterator](): EffectIterator> [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: EffectUnify [Unify.ignoreSymbol]?: {} } /** - * A type that can be yielded in an Effect generator function. - * - * The `Yieldable` interface allows values to be used with the `yield*` syntax - * in Effect generator functions, providing a clean way to sequence effectful operations. - * - * @example - * ```ts - * import { Effect } from "effect" + * Type-level unification support for `Effect` values. * - * // Effects implement Yieldable and can be used with yield* - * const effect1 = Effect.succeed(10) - * const effect2 = Effect.succeed(20) - * - * const program = Effect.gen(function*() { - * const a = yield* effect1 // yields the Effect which implements Yieldable - * const b = yield* effect2 - * return a + b - * }) - * - * Effect.runPromise(program).then(console.log) // 30 - * ``` - * - * @since 4.0.0 - * @category Yieldable - */ -export interface Yieldable< - out Self extends Yieldable, - out A, - out E = never, - out R = never -> { - asEffect(): Effect - [Symbol.iterator](): EffectIterator -} - -/** - * @since 4.0.0 - * @category Yieldable - */ -export abstract class YieldableClass implements Yieldable { - [Symbol.iterator](): EffectIterator { - return new SingleShotGen(this) as any - } - abstract asEffect(): Effect -} - -/** - * @category Models + * @category models * @since 2.0.0 - * @example - * ```ts - * import type { Effect } from "effect" - * - * // EffectUnify is used internally for type unification - * // It enables automatic unification of Effect types in unions - * declare const unified: Effect.EffectUnify - * ``` */ export interface EffectUnify { Effect?: () => A[Unify.typeSymbol] extends @@ -246,16 +135,10 @@ export interface EffectUnify { } /** - * @category Type Lambdas - * @since 2.0.0 - * @example - * ```ts - * import type { Effect } from "effect" + * Type lambda used to represent `Effect` in higher-kinded APIs. * - * // EffectTypeLambda is used for higher-kinded type operations - * // It defines the type structure for Effect in higher-kinded contexts - * declare const lambda: Effect.EffectTypeLambda - * ``` + * @category type lambdas + * @since 2.0.0 */ export interface EffectTypeLambda extends TypeLambda { readonly type: Effect @@ -264,8 +147,8 @@ export interface EffectTypeLambda extends TypeLambda { /** * Variance interface for Effect, encoding the type parameters' variance. * + * @category models * @since 2.0.0 - * @category Models */ export interface Variance { _A: Covariant @@ -274,82 +157,65 @@ export interface Variance { } /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Extracts the success type from an `Effect`. * - * // Extract the success type from an Effect - * declare const myEffect: Effect.Effect - * // This type utility extracts the success type A from Effect - * ``` + * **When to use** + * + * Use to derive the value produced by an existing effect when declaring + * reusable type aliases, service interfaces, or function signatures. + * + * @see {@link Error} for extracting the failure type from the same `Effect` + * @see {@link Services} for extracting the required services from the same `Effect` + * + * @category models + * @since 2.0.0 */ export type Success = T extends Effect ? _A : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Extracts the error type from an `Effect`. * - * // Extract the error type from an Effect - * declare const myEffect: Effect.Effect - * // This type utility extracts the error type E from Effect - * ``` + * **When to use** + * + * Use to derive the error type from an existing `Effect` type when declaring + * helper types, wrappers, or APIs that preserve the effect's failure channel. + * + * **Details** + * + * Non-`Effect` inputs resolve to `never`. + * + * @see {@link Success} for extracting the success value type instead + * @see {@link Services} for extracting the required services type instead + * + * @category models + * @since 2.0.0 */ export type Error = T extends Effect ? _E : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Extracts the required services type from an `Effect`. * - * // Extract the context/services type from an Effect - * declare const myEffect: Effect.Effect - * // This type utility extracts the context type R from Effect - * ``` + * **When to use** + * + * Use to derive the context requirements of a generic or inferred `Effect` + * without restating its `R` type parameter. + * + * @see {@link Success} for extracting the success value type instead + * @see {@link Error} for extracting the failure type instead + * + * @category models + * @since 4.0.0 */ export type Services = T extends Effect ? _R : never /** - * Namespace containing type utilities for Yieldable values. + * Checks whether a value is an `Effect`. * - * @since 4.0.0 - * @category Yieldable - */ -export declare namespace Yieldable { - /** - * @since 4.0.0 - * @category Yieldable - */ - export type Any = Yieldable - - /** - * @since 4.0.0 - * @category Yieldable - * @example - * ```ts - * import type { Effect } from "effect" - * - * // Extract the success type from a Yieldable - * type SuccessType = Effect.Yieldable.Success> // string - * ``` - */ - export type Success = T extends Yieldable ? _A - : never -} - -/** - * Tests if a value is an `Effect`. + * **Example** (Checking whether a value is an Effect) * - * @example * ```ts * import { Effect } from "effect" * @@ -357,37 +223,28 @@ export declare namespace Yieldable { * console.log(Effect.isEffect("hello")) // false * ``` * + * @category guards * @since 2.0.0 - * @category Guards */ export const isEffect: (u: unknown) => u is Effect = core.isEffect /** * Iterator interface for Effect generators, enabling Effect values to work with generator functions. * - * @example - * ```ts - * import { Effect } from "effect" + * **When to use** * - * // Effects are iterable and work with generator functions - * const program = Effect.gen(function*() { - * const effect: Effect.Effect = Effect.succeed(42) + * Use when defining or typing `[Symbol.iterator]()` for values typed as + * `Effect`s so `yield*` can pass their success type back into `Effect.gen`. * - * // The effect's iterator is used internally by yield* - * const result = yield* effect - * return result * 2 - * }) + * @see {@link gen} for writing generator-based `Effect` programs that consume this iterator protocol * - * Effect.runPromise(program).then(console.log) // 84 - * ``` - * - * @since 2.0.0 - * @category Models + * @category models + * @since 4.0.0 */ -export interface EffectIterator> { +export interface EffectIterator> { next( ...args: ReadonlyArray - ): IteratorResult> + ): IteratorResult> } // ======================================================================== @@ -398,59 +255,22 @@ export interface EffectIterator> { * Namespace containing type utilities for the `Effect.all` function, which handles * collecting multiple effects into various output structures. * - * @example - * ```ts - * import { Effect } from "effect" - * - * // All namespace types are used when working with Effect.all - * const effects = [ - * Effect.succeed(1), - * Effect.succeed("hello"), - * Effect.succeed(true) - * ] as const - * - * const program = Effect.all(effects).pipe( - * Effect.map(([num, str, bool]) => ({ num, str, bool })) - * ) - * - * Effect.runPromise(program).then(console.log) // { num: 1, str: "hello", bool: true } - * ``` - * * @since 2.0.0 - * @category Models */ export declare namespace All { /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import { Data, Effect } from "effect" - * - * class OopsError extends Data.TaggedError("OopsError")<{}> {} + * Alias for any `Effect` value accepted by `Effect.all`. * - * // EffectAny represents an Effect with any type parameters - * const effects: Array = [ - * Effect.succeed(42), - * Effect.succeed("hello"), - * Effect.fail(new OopsError()) - * ] - * ``` + * @category utility types + * @since 2.0.0 */ export type EffectAny = Effect /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the return type for `Effect.all` when collecting an iterable. * - * // ReturnIterable computes the return type for Effect.all with iterables - * type EffectArray = Array> - * type Result = Effect.All.ReturnIterable - * // Result: Effect, string, never> - * ``` + * @category utility types + * @since 2.0.0 */ export type ReturnIterable< T extends Iterable, @@ -464,20 +284,10 @@ export declare namespace All { : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the return type for `Effect.all` when collecting a tuple. * - * // ReturnTuple computes the return type for Effect.all with tuples - * type EffectTuple = [ - * Effect.Effect, - * Effect.Effect - * ] - * type Result = Effect.All.ReturnTuple - * // Result: Effect<[string, number], Error, never> - * ``` + * @category utility types + * @since 2.0.0 */ export type ReturnTuple< T extends ReadonlyArray, @@ -505,20 +315,10 @@ export declare namespace All { : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the return type for `Effect.all` when collecting a record. * - * // ReturnObject computes the return type for Effect.all with objects - * type EffectRecord = { - * a: Effect.Effect - * b: Effect.Effect - * } - * type Result = Effect.All.ReturnObject - * // Result: Effect<{ a: string, b: number }, Error, never> - * ``` + * @category utility types + * @since 2.0.0 */ export type ReturnObject = [T] extends [ Record @@ -541,18 +341,10 @@ export declare namespace All { : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Detects whether `Effect.all` should discard collected values. * - * // IsDiscard checks if options have discard flag set to true - * type DiscardOptions = { discard: true } - * type NoDiscardOptions = { discard: false } - * type WithDiscard = Effect.All.IsDiscard // true - * type WithoutDiscard = Effect.All.IsDiscard // false - * ``` + * @category utility types + * @since 2.0.0 */ export type IsDiscard = [Extract] extends [ never @@ -560,24 +352,18 @@ export declare namespace All { : true /** + * Detects whether `Effect.all` should collect results in `Result` mode. + * + * @category utility types * @since 4.0.0 - * @category Models */ export type IsResult = [Extract] extends [never] ? false : true /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the return type for `Effect.all` from its input and options. * - * // Return determines the result type based on input and options - * type EffectArray = Array> - * type Options = { discard: false } - * type Result = Effect.All.Return - * // Result: Effect, string, never> - * ``` + * @category utility types + * @since 2.0.0 */ export type Return< Arg extends Iterable | Record, @@ -593,49 +379,30 @@ export declare namespace All { } /** - * Combines multiple effects into one, returning results based on the input - * structure. - * - * **Details** - * - * Use this function when you need to run multiple effects and combine their - * results into a single output. It supports tuples, iterables, structs, and - * records, making it flexible for different input types. - * - * For instance, if the input is a tuple: + * Combines an iterable or record of effects into one effect whose success shape + * follows the input. * - * ```ts skip-type-checking - * // ┌─── a tuple of effects - * // ▼ - * Effect.all([effect1, effect2, ...]) - * ``` - * - * the effects are executed sequentially, and the result is a new effect - * containing the results as a tuple. The results in the tuple match the order - * of the effects passed to `Effect.all`. + * **When to use** * - * **Concurrency** + * Use to run a known collection of effects and collect results in the same + * tuple, iterable, or record shape. * - * You can control the execution order (e.g., sequential vs. concurrent) using - * the `concurrency` option. + * **Details** * - * **Short-Circuiting Behavior** + * Tuple and iterable inputs collect results in order. Record inputs collect + * results under the same keys. By default, the combined effect fails on the + * first failure; with concurrent execution, effects that have already started + * may be interrupted, while effects not yet started are skipped. * - * This function stops execution on the first error it encounters, this is - * called "short-circuiting". If any effect in the collection fails, the - * remaining effects will not run, and the error will be propagated. To change - * this behavior, you can use the `mode` option, which allows all effects to run - * and collect every success / failure as `Result` values. + * Options: * - * **The `mode` option** + * Use `concurrency` to control sequential or concurrent execution. Use + * `mode: "result"` to run every effect and collect each success or failure as a + * `Result` in the same output shape. Use `discard: true` to ignore successful + * values and return `void`. * - * The `{ mode: "result" }` option changes the behavior of `Effect.all` to - * ensure all effects run, even if some fail. Instead of stopping on the first - * failure, this mode collects both successes and failures, returning an array - * of `Result` instances where each result is either an `Ok` (success) or a - * `Err` (failure). + * **Example** (Collecting tuple results in order) * - * @example Combining Effects in Tuples * ```ts * import { Console, Effect } from "effect" * @@ -655,7 +422,8 @@ export declare namespace All { * // [ 42, 'Hello' ] * ``` * - * @example Combining Effects in Iterables + * **Example** (Collecting iterable results in order) + * * ```ts * import { Console, Effect } from "effect" * @@ -675,7 +443,8 @@ export declare namespace All { * // [ 1, 2, 3 ] * ``` * - * @example Combining Effects in Structs + * **Example** (Collecting struct results by key) + * * ```ts * import { Console, Effect } from "effect" * @@ -695,7 +464,8 @@ export declare namespace All { * // { a: 42, b: 'Hello' } * ``` * - * @example Combining Effects in Records + * **Example** (Collecting record results by key) + * * ```ts * import { Console, Effect } from "effect" * @@ -715,7 +485,8 @@ export declare namespace All { * // { key1: 1, key2: 2 } * ``` * - * @example Short-Circuiting Behavior + * **Example** (Stopping on the first failure) + * * ```ts * import { Console, Effect } from "effect" * @@ -737,9 +508,8 @@ export declare namespace All { * ``` * * @see {@link forEach} for iterating over elements and applying an effect. - * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const all: < const Arg extends @@ -759,15 +529,16 @@ export const all: < * Applies an effectful function to each element and partitions failures and * successes. * - * The returned tuple is `[excluded, satisfying]`, where: + * **Details** * - * - `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. * - * @example + * **Example** (Separating successes and failures) + * * ```ts * import { Effect } from "effect" * @@ -779,23 +550,24 @@ export const all: < * // [ ["0 is even", "2 is even"], [1, 3] ] * ``` * - * @since 3.0.0 - * @category Collecting + * @category collecting + * @since 2.0.0 */ export const partition: { /** * Applies an effectful function to each element and partitions failures and * successes. * - * The returned tuple is `[excluded, satisfying]`, where: + * **Details** * - * - `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. * - * @example + * **Example** (Separating successes and failures) + * * ```ts * import { Effect } from "effect" * @@ -807,8 +579,8 @@ export const partition: { * // [ ["0 is even", "2 is even"], [1, 3] ] * ``` * - * @since 3.0.0 - * @category Collecting + * @category collecting + * @since 2.0.0 */ ( f: (a: A, i: number) => Effect, @@ -818,15 +590,16 @@ export const partition: { * Applies an effectful function to each element and partitions failures and * successes. * - * The returned tuple is `[excluded, satisfying]`, where: + * **Details** * - * - `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. * - * @example + * **Example** (Separating successes and failures) + * * ```ts * import { Effect } from "effect" * @@ -838,8 +611,8 @@ export const partition: { * // [ ["0 is even", "2 is even"], [1, 3] ] * ``` * - * @since 3.0.0 - * @category Collecting + * @category collecting + * @since 2.0.0 */ ( elements: Iterable, @@ -851,6 +624,8 @@ export const partition: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -858,7 +633,8 @@ export const partition: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -880,13 +656,15 @@ export const partition: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ export const validate: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -894,7 +672,8 @@ export const validate: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -916,8 +695,8 @@ export const validate: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ ( f: (a: A, i: number) => Effect, @@ -929,6 +708,8 @@ export const validate: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -936,7 +717,8 @@ export const validate: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -958,8 +740,8 @@ export const validate: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ ( f: (a: A, i: number) => Effect, @@ -971,6 +753,8 @@ export const validate: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -978,7 +762,8 @@ export const validate: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -1000,8 +785,8 @@ export const validate: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ ( elements: Iterable, @@ -1014,6 +799,8 @@ export const validate: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -1021,7 +808,8 @@ export const validate: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -1043,8 +831,8 @@ export const validate: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ ( elements: Iterable, @@ -1059,10 +847,13 @@ export const validate: { /** * Returns the first element that satisfies an effectful predicate. * + * **Details** + * * The predicate receives the element and its index. Evaluation short-circuits * as soon as an element matches. * - * @example + * **Example** (Finding the first successful match) + * * ```ts * import { Effect } from "effect" * @@ -1072,17 +863,20 @@ export const validate: { * // { _id: 'Option', _tag: 'Some', value: 3 } * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const findFirst: { /** * Returns the first element that satisfies an effectful predicate. * + * **Details** + * * The predicate receives the element and its index. Evaluation short-circuits * as soon as an element matches. * - * @example + * **Example** (Finding the first successful match) + * * ```ts * import { Effect } from "effect" * @@ -1092,17 +886,20 @@ export const findFirst: { * // { _id: 'Option', _tag: 'Some', value: 3 } * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ (predicate: (a: NoInfer, i: number) => Effect): (elements: Iterable) => Effect, E, R> /** * Returns the first element that satisfies an effectful predicate. * + * **Details** + * * The predicate receives the element and its index. Evaluation short-circuits * as soon as an element matches. * - * @example + * **Example** (Finding the first successful match) + * * ```ts * import { Effect } from "effect" * @@ -1112,8 +909,8 @@ export const findFirst: { * // { _id: 'Option', _tag: 'Some', value: 3 } * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( elements: Iterable, @@ -1124,21 +921,39 @@ export const findFirst: { /** * Returns the first value that passes an effectful `FilterEffect`. * + * **When to use** + * + * Use when you need to find the first element that satisfies an effectful + * filter returning a `Result`, which also transforms the matching element. + * + * **Details** + * * The filter receives the element and index. Evaluation short-circuits on the * first `Result.succeed` and returns the transformed value in `Option.some`. * + * @see {@link findFirst} for the simpler effectful predicate-based variant + * + * @category collecting * @since 4.0.0 - * @category Collecting */ export const findFirstFilter: { /** * Returns the first value that passes an effectful `FilterEffect`. * + * **When to use** + * + * Use when you need to find the first element that satisfies an effectful + * filter returning a `Result`, which also transforms the matching element. + * + * **Details** + * * The filter receives the element and index. Evaluation short-circuits on the * first `Result.succeed` and returns the transformed value in `Option.some`. * + * @see {@link findFirst} for the simpler effectful predicate-based variant + * + * @category collecting * @since 4.0.0 - * @category Collecting */ ( filter: (input: NoInfer, i: number) => Effect, E, R> @@ -1146,11 +961,20 @@ export const findFirstFilter: { /** * Returns the first value that passes an effectful `FilterEffect`. * + * **When to use** + * + * Use when you need to find the first element that satisfies an effectful + * filter returning a `Result`, which also transforms the matching element. + * + * **Details** + * * The filter receives the element and index. Evaluation short-circuits on the * first `Result.succeed` and returns the transformed value in `Option.some`. * + * @see {@link findFirst} for the simpler effectful predicate-based variant + * + * @category collecting * @since 4.0.0 - * @category Collecting */ ( elements: Iterable, @@ -1161,6 +985,11 @@ export const findFirstFilter: { /** * Executes an effectful operation for each element in an `Iterable`. * + * **When to use** + * + * Use to traverse an iterable with an effectful function while preserving + * element order in the collected results. + * * **Details** * * The `forEach` function applies a provided operation to each element in the @@ -1169,23 +998,20 @@ export const findFirstFilter: { * If any effect fails, the iteration stops immediately (short-circuiting), and * the error is propagated. * - * **Concurrency** + * Concurrency: * * The `concurrency` option controls how many operations are performed * concurrently. By default, the operations are performed sequentially. * - * **Discarding Results** + * Discarding Results: * * If the `discard` option is set to `true`, the intermediate results are not * collected, and the final result of the operation is `void`. * - * @see {@link all} for combining multiple effects into one. + * **Example** (Mapping over an iterable with effects) * - * @example * ```ts - * // Title: Applying Effects to Iterable Elements - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const result = Effect.forEach( * [1, 2, 3, 4, 5], @@ -1203,10 +1029,10 @@ export const findFirstFilter: { * // [ 2, 4, 6, 8, 10 ] * ``` * - * @example - * // Title: Using discard to Ignore Results - * import { Effect } from "effect" - * import { Console } from "effect" + * **Example** (Running effects without collecting results) + * + * ```ts + * import { Console, Effect } from "effect" * * // Apply effects but discard the results * const result = Effect.forEach( @@ -1224,14 +1050,21 @@ export const findFirstFilter: { * // Currently at index 3 * // Currently at index 4 * // undefined + * ``` * + * @see {@link all} for combining multiple effects into one. + * @category collecting * @since 2.0.0 - * @category Collecting */ export const forEach: { /** * Executes an effectful operation for each element in an `Iterable`. * + * **When to use** + * + * Use to traverse an iterable with an effectful function while preserving + * element order in the collected results. + * * **Details** * * The `forEach` function applies a provided operation to each element in the @@ -1240,23 +1073,20 @@ export const forEach: { * If any effect fails, the iteration stops immediately (short-circuiting), and * the error is propagated. * - * **Concurrency** + * Concurrency: * * The `concurrency` option controls how many operations are performed * concurrently. By default, the operations are performed sequentially. * - * **Discarding Results** + * Discarding Results: * * If the `discard` option is set to `true`, the intermediate results are not * collected, and the final result of the operation is `void`. * - * @see {@link all} for combining multiple effects into one. + * **Example** (Mapping over an iterable with effects) * - * @example * ```ts - * // Title: Applying Effects to Iterable Elements - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const result = Effect.forEach( * [1, 2, 3, 4, 5], @@ -1274,10 +1104,10 @@ export const forEach: { * // [ 2, 4, 6, 8, 10 ] * ``` * - * @example - * // Title: Using discard to Ignore Results - * import { Effect } from "effect" - * import { Console } from "effect" + * **Example** (Running effects without collecting results) + * + * ```ts + * import { Console, Effect } from "effect" * * // Apply effects but discard the results * const result = Effect.forEach( @@ -1295,9 +1125,11 @@ export const forEach: { * // Currently at index 3 * // Currently at index 4 * // undefined + * ``` * + * @see {@link all} for combining multiple effects into one. + * @category collecting * @since 2.0.0 - * @category Collecting */ , const Discard extends boolean = false>( f: (a: Arr.ReadonlyArray.Infer, i: number) => Effect, @@ -1306,6 +1138,11 @@ export const forEach: { /** * Executes an effectful operation for each element in an `Iterable`. * + * **When to use** + * + * Use to traverse an iterable with an effectful function while preserving + * element order in the collected results. + * * **Details** * * The `forEach` function applies a provided operation to each element in the @@ -1314,23 +1151,20 @@ export const forEach: { * If any effect fails, the iteration stops immediately (short-circuiting), and * the error is propagated. * - * **Concurrency** + * Concurrency: * * The `concurrency` option controls how many operations are performed * concurrently. By default, the operations are performed sequentially. * - * **Discarding Results** + * Discarding Results: * * If the `discard` option is set to `true`, the intermediate results are not * collected, and the final result of the operation is `void`. * - * @see {@link all} for combining multiple effects into one. + * **Example** (Mapping over an iterable with effects) * - * @example * ```ts - * // Title: Applying Effects to Iterable Elements - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const result = Effect.forEach( * [1, 2, 3, 4, 5], @@ -1348,10 +1182,10 @@ export const forEach: { * // [ 2, 4, 6, 8, 10 ] * ``` * - * @example - * // Title: Using discard to Ignore Results - * import { Effect } from "effect" - * import { Console } from "effect" + * **Example** (Running effects without collecting results) + * + * ```ts + * import { Console, Effect } from "effect" * * // Apply effects but discard the results * const result = Effect.forEach( @@ -1369,9 +1203,11 @@ export const forEach: { * // Currently at index 3 * // Currently at index 4 * // undefined + * ``` * + * @see {@link all} for combining multiple effects into one. + * @category collecting * @since 2.0.0 - * @category Collecting */ , const Discard extends boolean = false>( self: S, @@ -1383,7 +1219,8 @@ export const forEach: { /** * Executes a body effect repeatedly while a condition holds true. * - * @example + * **Example** (Repeating an effectful loop) + * * ```ts * import { Effect } from "effect" * @@ -1404,8 +1241,8 @@ export const forEach: { * // Current count: 5 * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const whileLoop: (options: { readonly while: LazyArg @@ -1421,30 +1258,27 @@ export const whileLoop: (options: { * Creates an `Effect` that represents an asynchronous computation guaranteed to * succeed. * - * **When to Use** + * **When to use** * - * Use `promise` when you are sure the operation will not reject. + * Use to convert a `Promise` into an `Effect` when the async operation is + * guaranteed to succeed and will not reject. * * **Details** * - * The provided function (`thunk`) returns a `Promise` that should never reject; if it does, the error - * will be treated as a "defect". + * An optional `AbortSignal` can be provided to allow for interruption of the + * wrapped `Promise` API. * - * This defect is not a standard error but indicates a flaw in the logic that - * was expected to be error-free. You can think of it similar to an unexpected - * crash in the program, which can be further managed or logged using tools like - * {@link catchAllDefect}. + * **Gotchas** * - * **Interruptions** + * The `Promise` must not reject. If it rejects, the rejection is treated as a + * defect, not as a typed failure. Use `tryPromise` when rejection is expected. * - * An optional `AbortSignal` can be provided to allow for interruption of the - * wrapped `Promise` API. + * Interruption aborts the provided `AbortSignal`, but the underlying + * asynchronous operation only stops if it observes that signal. * - * @see {@link tryPromise} for a version that can handle failures. + * **Example** (Wrapping a non-rejecting Promise) * - * @example * ```ts - * // Title: Delayed Message * import { Effect } from "effect" * * const delay = (message: string) => @@ -1462,8 +1296,9 @@ export const whileLoop: (options: { * const program = delay("Async operation completed successfully!") * ``` * + * @see {@link tryPromise} for a version that can handle failures. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const promise: ( evaluate: (signal: AbortSignal) => PromiseLike @@ -1473,15 +1308,15 @@ export const promise: ( * Creates an `Effect` that represents an asynchronous computation that might * fail. * - * **When to Use** + * **When to use** + * + * Use when you need to perform asynchronous operations that might fail, such + * as fetching data from an API, and want thrown exceptions or rejected promises + * captured as Effect errors. * - * In situations where you need to perform asynchronous operations that might - * fail, such as fetching data from an API, you can use the `tryPromise` - * constructor. This constructor is designed to handle operations that could - * throw exceptions by capturing those exceptions and transforming them into - * manageable errors. + * **Details** * - * **Error Handling** + * Error Handling: * * There are two ways to handle errors with `tryPromise`: * @@ -1490,12 +1325,13 @@ export const promise: ( * 2. If you provide a `catch` function, the error is caught and the `catch` * function maps it to an error of type `E`. * - * **Interruptions** + * Interruptions: * * An optional `AbortSignal` can be provided to allow for interruption of the * wrapped `Promise` API. * - * @example Fetching a TODO Item + * **Example** (Wrapping a fetch request that may fail) + * * ```ts * import { Effect } from "effect" * @@ -1510,7 +1346,8 @@ export const promise: ( * const program = getTodo(1) * ``` * - * @example Custom Error Handling + * **Example** (Mapping Promise rejections to a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -1529,9 +1366,8 @@ export const promise: ( * ``` * * @see {@link promise} if the effectful computation is asynchronous and does not throw errors. - * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const tryPromise: ( options: @@ -1542,16 +1378,14 @@ export const tryPromise: ( /** * Creates an `Effect` that always succeeds with a given value. * - * **When to Use** + * **When to use** * - * 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. * - * @see {@link fail} to create an effect that represents a failure. + * **Example** (Creating a successful effect) * - * @example * ```ts - * // Title: Creating a Successful Effect * import { Effect } from "effect" * * // Creating an effect that represents a successful scenario @@ -1561,15 +1395,17 @@ export const tryPromise: ( * const success = Effect.succeed(42) * ``` * + * @see {@link fail} to create an effect that represents a failure. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const succeed: (value: A) => Effect = internal.succeed /** * Returns an effect which succeeds with `None`. * - * @example + * **Example** (Succeeding with Option.none) + * * ```ts * import { Effect } from "effect" * @@ -1579,15 +1415,16 @@ export const succeed: (value: A) => Effect = internal.succeed * // Output: { _id: 'Option', _tag: 'None' } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const succeedNone: Effect> = internal.succeedNone /** * Returns an effect which succeeds with the value wrapped in a `Some`. * - * @example + * **Example** (Succeeding with Option.some) + * * ```ts * import { Effect } from "effect" * @@ -1597,28 +1434,30 @@ export const succeedNone: Effect> = internal.succeedNone * // Output: { _id: 'Option', _tag: 'Some', value: 42 } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const succeedSome: (value: A) => Effect> = internal.succeedSome /** - * Delays the creation of an `Effect` until it is actually needed. + * Creates an `Effect` lazily, delaying construction until it is needed. * - * **When to Use** + * **When to use** * - * Use `suspend` 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** * - * `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) * - * @example * ```ts - * // Title: Lazy Evaluation with Side Effects * import { Effect } from "effect" * * let i = 0 @@ -1634,8 +1473,9 @@ export const succeedSome: (value: A) => Effect> = internal.succeedS * console.log(Effect.runSync(good)) // Output: 2 * ``` * - * @example - * // Title: Recursive Fibonacci + * **Example** (Suspending recursive Fibonacci evaluation) + * + * ```ts * import { Effect } from "effect" * * const blowsUp = (n: number): Effect.Effect => @@ -1657,9 +1497,11 @@ export const succeedSome: (value: A) => Effect> = internal.succeedS * * console.log(Effect.runSync(allGood(32))) * // Output: 3524578 + * ``` * - * @example - * // Title: Using Effect.suspend to Help TypeScript Infer Types + * **Example** (Helping TypeScript infer recursive effect types) + * + * ```ts * import { Effect } from "effect" * * // Without suspend, TypeScript may struggle with type inference. @@ -1680,9 +1522,10 @@ export const succeedSome: (value: A) => Effect> = internal.succeedS * ? Effect.fail(new Error("Cannot divide by zero")) * : Effect.succeed(a / b) * ) + * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const suspend: ( effect: LazyArg> @@ -1691,25 +1534,23 @@ export const suspend: ( /** * Creates an `Effect` that represents a synchronous side-effectful computation. * - * **When to Use** + * **When to use** * - * Use `sync` 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** * - * The provided function (`thunk`) must not throw errors; if it does, the error - * will be treated as a "defect". + * The provided function is evaluated lazily when the effect runs. * - * This defect is not a standard error but indicates a flaw in the logic that - * was expected to be error-free. You can think of it similar to an unexpected - * crash in the program, which can be further managed or logged using tools like - * {@link catchAllDefect}. + * **Gotchas** * - * @see {@link try_ | try} for a version that can handle failures. + * The function must not throw. If it throws, the thrown value is treated as a + * defect, not as a typed failure. Use `try` when throwing is expected. + * + * **Example** (Capturing synchronous logging in an Effect) * - * @example * ```ts - * // Title: Logging a Message * import { Effect } from "effect" * * const log = (message: string) => @@ -1722,16 +1563,19 @@ export const suspend: ( * const program = log("Hello, World!") * ``` * + * @see {@link try_ | try} for a version that can handle failures. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const sync: (thunk: LazyArg) => Effect = internal.sync const void_: Effect = internal.void export { /** + * Returns an effect that succeeds with `void`. + * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ void_ as void } @@ -1739,42 +1583,31 @@ export { const undefined_: Effect = internal.undefined export { /** + * Returns an effect that succeeds with `undefined`. + * + * @category constructors * @since 4.0.0 - * @category Creating Effects */ undefined_ as undefined } /** - * Creates an `Effect` from a callback-based asynchronous function. - * - * **Details** + * Creates an `Effect` from a callback-based asynchronous API. * - * The `resume` function: - * - Must be called exactly once. Any additional calls will be ignored. - * - Can return an optional `Effect` that will be run if the `Fiber` executing - * this `Effect` is interrupted. This can be useful in scenarios where you - * need to handle resource cleanup if the operation is interrupted. - * - Can receive an `AbortSignal` to handle interruption if needed. + * **When to use** * - * The `FiberId` of the fiber that may complete the async callback may also be - * specified using the `blockingOn` argument. This is called the "blocking - * fiber" because it suspends the fiber executing the `async` effect (i.e. - * semantically blocks the fiber from making progress). Specifying this fiber id - * in cases where it is known will improve diagnostics, but not affect the - * behavior of the returned effect. + * Use when you need to integrate APIs that complete through callbacks instead + * of returning a `Promise`. * - * **When to Use** - * - * Use `Effect.callback` when dealing with APIs that use callback-style instead of - * `async/await` or `Promise`. - * * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * The registration function receives a `resume` callback and, when requested, + * an `AbortSignal`. Call `resume` at most once with the effect that should + * complete the fiber; later calls are ignored. Return an optional cleanup + * effect from the registration function to run if the fiber is interrupted. * - * - `Effect.async` + * **Example** (Integrating callback APIs) * - * @example * ```ts * import { Effect } from "effect" * @@ -1790,8 +1623,8 @@ export { * const program = delay(1000) * ``` * - * @since 2.0.0 - * @category Creating Effects + * @category constructors + * @since 4.0.0 */ export const callback: ( register: ( @@ -1805,7 +1638,8 @@ export const callback: ( * Returns an effect that will never produce anything. The moral equivalent of * `while(true) {}`, only without the wasted CPU cycles. * - * @example + * **Example** (Creating a never-ending effect) + * * ```ts * import { Effect } from "effect" * @@ -1819,19 +1653,19 @@ export const callback: ( * const timedProgram = Effect.timeout(program, "1 second") * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const never: Effect = internal.never /** - * An `Effect` containing an empty record `{}`, used as the starting point for - * do notation chains. + * Effect that succeeds with an empty record `{}`, used as the starting point + * for do notation chains. + * + * **Example** (Starting do notation) * - * @example * ```ts - * import { Effect } from "effect" - * import { pipe } from "effect/Function" + * import { Effect, pipe } from "effect" * * const program = pipe( * Effect.Do, @@ -1841,8 +1675,8 @@ export const never: Effect = internal.never * ) * ``` * - * @since 4.0.0 - * @category Do notation + * @category do notation + * @since 2.0.0 */ export const Do: Effect<{}> = internal.Do @@ -1850,24 +1684,48 @@ export const Do: Effect<{}> = internal.Do * Gives a name to the success value of an `Effect`, creating a single-key * record used in do notation pipelines. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to start a do-notation pipeline from an existing `Effect` when its + * success value should become the first named field in the accumulated record. + * + * @see {@link Do} for starting from an empty accumulated record + * @see {@link bind} for adding fields produced by effects + * + * @category do notation + * @since 2.0.0 */ export const bindTo: { /** * Gives a name to the success value of an `Effect`, creating a single-key * record used in do notation pipelines. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to start a do-notation pipeline from an existing `Effect` when its + * success value should become the first named field in the accumulated record. + * + * @see {@link Do} for starting from an empty accumulated record + * @see {@link bind} for adding fields produced by effects + * + * @category do notation + * @since 2.0.0 */ (name: N): (self: Effect) => Effect<{ [K in N]: A }, E, R> /** * Gives a name to the success value of an `Effect`, creating a single-key * record used in do notation pipelines. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to start a do-notation pipeline from an existing `Effect` when its + * success value should become the first named field in the accumulated record. + * + * @see {@link Do} for starting from an empty accumulated record + * @see {@link bind} for adding fields produced by effects + * + * @category do notation + * @since 2.0.0 */ (self: Effect, name: N): Effect<{ [K in N]: A }, E, R> } = internal.bindTo @@ -1890,8 +1748,24 @@ export { /** * Adds a computed plain value to the do notation record. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to add a derived, synchronous value to a do-notation pipeline when it + * depends on fields already accumulated in the record and does not need to run + * another `Effect`. + * + * **Details** + * + * The new field is added with object spreading. If the name already exists in + * the record, the computed value replaces it in the returned type. + * + * @see {@link bind} for adding fields produced by effects + * @see {@link bindTo} for naming an existing success value + * @see {@link Do} for starting from an empty accumulated record + * @see {@link gen} for sequencing without accumulating a record + * + * @category do notation + * @since 2.0.0 */ let_ as let } @@ -1899,15 +1773,57 @@ export { /** * Adds an `Effect` value to the do notation record under a given name. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to sequence an effectful step in a do-notation pipeline when that step + * depends on fields already accumulated in the record and its success value + * should be stored under a name. + * + * **Details** + * + * The function receives the current record, runs the returned effect after the + * input effect succeeds, and inserts its success value under `name`. The + * resulting effect combines the error and service requirements of both steps. + * + * **Gotchas** + * + * Binding a name that already exists replaces that field in the resulting + * record. + * + * @see {@link Do} for starting from an empty do-notation record + * @see {@link bindTo} for naming the success value of an existing effect + * @see {@link gen} for generator-based sequencing without accumulating a record + * + * @category do notation + * @since 2.0.0 */ export const bind: { /** * Adds an `Effect` value to the do notation record under a given name. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to sequence an effectful step in a do-notation pipeline when that step + * depends on fields already accumulated in the record and its success value + * should be stored under a name. + * + * **Details** + * + * The function receives the current record, runs the returned effect after the + * input effect succeeds, and inserts its success value under `name`. The + * resulting effect combines the error and service requirements of both steps. + * + * **Gotchas** + * + * Binding a name that already exists replaces that field in the resulting + * record. + * + * @see {@link Do} for starting from an empty do-notation record + * @see {@link bindTo} for naming the success value of an existing effect + * @see {@link gen} for generator-based sequencing without accumulating a record + * + * @category do notation + * @since 2.0.0 */ , B, E2, R2>(name: N, f: (a: NoInfer) => Effect): ( self: Effect @@ -1915,8 +1831,29 @@ export const bind: { /** * Adds an `Effect` value to the do notation record under a given name. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to sequence an effectful step in a do-notation pipeline when that step + * depends on fields already accumulated in the record and its success value + * should be stored under a name. + * + * **Details** + * + * The function receives the current record, runs the returned effect after the + * input effect succeeds, and inserts its success value under `name`. The + * resulting effect combines the error and service requirements of both steps. + * + * **Gotchas** + * + * Binding a name that already exists replaces that field in the resulting + * record. + * + * @see {@link Do} for starting from an empty do-notation record + * @see {@link bindTo} for naming the success value of an existing effect + * @see {@link gen} for generator-based sequencing without accumulating a record + * + * @category do notation + * @since 2.0.0 */ , E, R, B, E2, R2, N extends string>(self: Effect, name: N, f: (a: NoInfer) => Effect): Effect & Record>, E | E2, R | R2> } = internal.bind @@ -1925,18 +1862,18 @@ export const bind: { * Provides a way to write effectful code using generator functions, simplifying * control flow and error handling. * - * **When to Use** + * **When to use** * - * `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) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -1968,26 +1905,26 @@ export const bind: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const gen: { /** * Provides a way to write effectful code using generator functions, simplifying * control flow and error handling. * - * **When to Use** + * **When to use** + * + * 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. * - * `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. + * 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. * - * 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. + * **Example** (Sequencing effects with generators) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -2019,34 +1956,34 @@ export const gen: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ - , AEff>(f: () => Generator): Effect< + , AEff>(f: () => Generator): Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > /** * Provides a way to write effectful code using generator functions, simplifying * control flow and error handling. * - * **When to Use** + * **When to use** * - * `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) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -2078,10 +2015,10 @@ export const gen: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ - , AEff>( + , AEff>( options: { readonly self: Self }, @@ -2089,10 +2026,10 @@ export const gen: { ): Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > } = internal.gen @@ -2100,29 +2037,33 @@ export const gen: { /** * Type helpers for `Effect.gen` generator return signatures. * - * @since 4.0.0 + * @since 2.0.0 */ -export namespace gen { +export declare namespace gen { /** + * Generator return type accepted by `Effect.gen`. + * + * @category constructors * @since 4.0.0 */ - export type Return = Generator, A, any> + export type Return = Generator, A, any> } /** * Creates an `Effect` that represents a recoverable error. * - * **When to Use** + * **When to use** * - * Use this function 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 catchAll} or {@link catchTag}. + * Use to explicitly signal a recoverable error in an `Effect`. * - * @see {@link succeed} to create an effect that represents a successful value. + * **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) * - * @example * ```ts - * // Title: Creating a Failed Effect * import { Data, Effect } from "effect" * * class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {} @@ -2134,18 +2075,25 @@ export namespace gen { * ) * ``` * + * @see {@link succeed} to create an effect that represents a successful value. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const fail: (error: E) => Effect = internal.fail /** * Creates an `Effect` that represents a recoverable error using a lazy evaluation. * - * This function is useful when you need to create an error effect but want to - * defer the computation of the error value until the effect is actually run. + * **When to use** + * + * Use to defer computing a recoverable error value until the effect is run. + * + * **Details** + * + * The error-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating failures) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -2157,18 +2105,27 @@ export const fail: (error: E) => Effect = internal.fail * // Output: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const failSync: (evaluate: LazyArg) => Effect = internal.failSync /** * 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 * structures, including multiple errors, defects, interruptions, and more. * - * @example + * **Example** (Failing with a full Cause) + * * ```ts * import { Cause, Effect } from "effect" * @@ -2180,18 +2137,24 @@ export const failSync: (evaluate: LazyArg) => Effect = internal. * // Output: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const failCause: (cause: Cause.Cause) => Effect = internal.failCause /** * Creates an `Effect` that represents a failure with a `Cause` computed lazily. * - * This function is useful when you need to create a failure effect with a - * complex cause but want to defer the computation until the effect is run. + * **When to use** + * + * Use to defer computing a full `Cause` until the effect is run. + * + * **Details** + * + * The cause-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating a Cause) * - * @example * ```ts * import { Cause, Effect } from "effect" * @@ -2203,8 +2166,8 @@ export const failCause: (cause: Cause.Cause) => Effect = interna * // Output: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const failCauseSync: ( evaluate: LazyArg> @@ -2213,10 +2176,10 @@ export const failCauseSync: ( /** * Creates an effect that terminates a fiber with a specified error. * - * **When to Use** + * **When to use** * - * Use `die` when encountering unexpected conditions in your code that should - * not be handled as regular errors but instead represent unrecoverable defects. + * Use when you need an `Effect` to report an unrecoverable defect instead of a + * typed error. * * **Details** * @@ -2227,12 +2190,9 @@ export const failCauseSync: ( * The error channel of the resulting effect is of type `never`, indicating that * it cannot recover from this failure. * - * @see {@link dieSync} for a variant that throws a specified error, evaluated lazily. - * @see {@link dieMessage} for a variant that throws a `RuntimeException` with a message. + * **Example** (Failing when division by zero) * - * @example * ```ts - * // Title: Terminating on Division by Zero with a Specified Error * import { Effect } from "effect" * * const divide = (a: number, b: number) => @@ -2250,8 +2210,8 @@ export const failCauseSync: ( * // ...stack trace... * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const die: (defect: unknown) => Effect = internal.die @@ -2265,14 +2225,14 @@ export { * Creates an `Effect` that represents a synchronous computation that might * fail. * - * **When to Use** + * **When to use** * - * 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** * - * **Error Handling** + * Error Handling: * * There are two ways to handle errors with `try`: * @@ -2281,10 +2241,8 @@ export { * 2. If you provide a `catch` function, the error is caught and the `catch` * function maps it to an error of type `E`. * - * @see {@link sync} if the effectful computation is synchronous and does not - * throw errors. + * **Example** (Parsing JSON with typed error mapping) * - * @example Basic Usage with Default Error Handling * ```ts * import { Effect } from "effect" * @@ -2303,7 +2261,8 @@ export { * // Output: Exit.failure with Error * ``` * - * @example Custom Error Handling + * **Example** (Mapping synchronous exceptions to a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -2319,8 +2278,10 @@ export { * // Output: Exit.failure with custom Error message * ``` * + * @see {@link sync} if the effectful computation is synchronous and does not + * throw errors. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ try_ as try } @@ -2328,7 +2289,8 @@ export { /** * Yields control back to the Effect runtime, allowing other fibers to execute. * - * @example + * **Example** (Yielding to other fibers) + * * ```ts * import { Effect } from "effect" * @@ -2341,15 +2303,16 @@ export { * Effect.runPromise(program) * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const yieldNow: Effect = internal.yieldNow /** * Yields control back to the Effect runtime with a specified priority, allowing other fibers to execute. * - * @example + * **Example** (Yielding with priority) + * * ```ts * import { Effect } from "effect" * @@ -2362,15 +2325,16 @@ export const yieldNow: Effect = internal.yieldNow * Effect.runPromise(program) * ``` * - * @since 2.0.0 - * @category Creating Effects + * @category constructors + * @since 4.0.0 */ export const yieldNowWith: (priority?: number) => Effect = internal.yieldNowWith /** * Provides access to the current fiber within an effect computation. * - * @example + * **Example** (Reading the current fiber) + * * ```ts * import { Effect } from "effect" * @@ -2382,8 +2346,8 @@ export const yieldNowWith: (priority?: number) => Effect = internal.yieldN * // Output: Fiber ID: 1 * ``` * - * @since 2.0.0 - * @category Creating Effects + * @category constructors + * @since 4.0.0 */ export const withFiber: ( evaluate: (fiber: Fiber) => Effect @@ -2396,7 +2360,8 @@ export const withFiber: ( /** * Converts a `Result` to an `Effect`. * - * @example + * **Example** (Converting a Result into an Effect) + * * ```ts * import { Effect, Result } from "effect" * @@ -2411,15 +2376,26 @@ export const withFiber: ( * // { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Fail', failure: 'Something went wrong' } } * ``` * + * @category converting * @since 4.0.0 - * @category Conversions */ export const fromResult: (result: Result.Result) => Effect = internal.fromResult /** - * Converts an `Option` to an `Effect`. + * 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 + * `Option.none` becomes a failed effect with `NoSuchElementError`. + * + * **Example** (Converting an Option into an Effect) * - * @example * ```ts * import { Effect, Option } from "effect" * @@ -2434,8 +2410,8 @@ export const fromResult: (result: Result.Result) => Effect = i * // { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Fail', failure: { _id: 'NoSuchElementError' } } } * ``` * + * @category converting * @since 4.0.0 - * @category Conversions */ export const fromOption: ( option: Option @@ -2445,7 +2421,8 @@ export const fromOption: ( * Converts a nullable value to an `Effect`, failing with a `NoSuchElementError` * when the value is `null` or `undefined`. * - * @example + * **Example** (Failing on nullish values) + * * ```ts * import { Console, Effect } from "effect" * @@ -2462,36 +2439,11 @@ export const fromOption: ( * // Output: hello * ``` * + * @category converting * @since 4.0.0 - * @category Conversions */ export const fromNullishOr: (value: A) => Effect, Cause.NoSuchElementError> = internal.fromNullishOr -/** - * Converts a yieldable value to an Effect. - * - * @example - * ```ts - * import { Effect } from "effect" - * import * as Option from "effect/Option" - * - * // Option is yieldable in Effect - * const program = Effect.gen(function*() { - * const value = yield* Effect.fromYieldable(Option.some(42)) - * return value * 2 - * }) - * - * Effect.runPromise(program).then(console.log) - * // Output: 84 - * ``` - * - * @since 4.0.0 - * @category Conversions - */ -export const fromYieldable: ( - yieldable: Yieldable -) => Effect = internal.fromYieldable - // ----------------------------------------------------------------------------- // Mapping // ----------------------------------------------------------------------------- @@ -2500,15 +2452,11 @@ export const fromYieldable: ( * Chains effects to produce new `Effect` instances, useful for combining * operations that depend on previous results. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const flatMappedEffect = pipe(myEffect, Effect.flatMap(transformation)) - * // or - * const flatMappedEffect = Effect.flatMap(myEffect, transformation) - * // or - * const flatMappedEffect = myEffect.pipe(Effect.flatMap(transformation)) - * ``` + * Use when you need to chain multiple effects, ensuring that each + * step produces a new `Effect` while flattening any nested effects that may + * occur. * * **Details** * @@ -2520,13 +2468,21 @@ export const fromYieldable: ( * Since effects are immutable, `flatMap` always returns a new effect instead of * changing the original one. * - * **When to Use** + * **Example** (Syntax) * - * Use `flatMap` when you need to chain multiple effects, ensuring that each - * step produces a new `Effect` while flattening any nested effects that may - * occur. + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => Effect.succeed(n + 1) + * + * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation)) + * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation) + * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation)) + * ``` + * + * **Example** (Sequencing dependent effects) * - * @example * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2555,9 +2511,8 @@ export const fromYieldable: ( * ``` * * @see {@link tap} for a version that ignores the result of the effect. - * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const flatMap: { // ----------------------------------------------------------------------------- @@ -2568,15 +2523,11 @@ export const flatMap: { * Chains effects to produce new `Effect` instances, useful for combining * operations that depend on previous results. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const flatMappedEffect = pipe(myEffect, Effect.flatMap(transformation)) - * // or - * const flatMappedEffect = Effect.flatMap(myEffect, transformation) - * // or - * const flatMappedEffect = myEffect.pipe(Effect.flatMap(transformation)) - * ``` + * Use when you need to chain multiple effects, ensuring that each + * step produces a new `Effect` while flattening any nested effects that may + * occur. * * **Details** * @@ -2588,13 +2539,21 @@ export const flatMap: { * Since effects are immutable, `flatMap` always returns a new effect instead of * changing the original one. * - * **When to Use** + * **Example** (Syntax) * - * Use `flatMap` when you need to chain multiple effects, ensuring that each - * step produces a new `Effect` while flattening any nested effects that may - * occur. + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => Effect.succeed(n + 1) + * + * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation)) + * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation) + * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation)) + * ``` + * + * **Example** (Sequencing dependent effects) * - * @example * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2623,9 +2582,8 @@ export const flatMap: { * ``` * * @see {@link tap} for a version that ignores the result of the effect. - * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (a: A) => Effect): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -2636,15 +2594,11 @@ export const flatMap: { * Chains effects to produce new `Effect` instances, useful for combining * operations that depend on previous results. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const flatMappedEffect = pipe(myEffect, Effect.flatMap(transformation)) - * // or - * const flatMappedEffect = Effect.flatMap(myEffect, transformation) - * // or - * const flatMappedEffect = myEffect.pipe(Effect.flatMap(transformation)) - * ``` + * Use when you need to chain multiple effects, ensuring that each + * step produces a new `Effect` while flattening any nested effects that may + * occur. * * **Details** * @@ -2656,13 +2610,21 @@ export const flatMap: { * Since effects are immutable, `flatMap` always returns a new effect instead of * changing the original one. * - * **When to Use** + * **Example** (Syntax) * - * Use `flatMap` when you need to chain multiple effects, ensuring that each - * step produces a new `Effect` while flattening any nested effects that may - * occur. + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => Effect.succeed(n + 1) + * + * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation)) + * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation) + * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation)) + * ``` + * + * **Example** (Sequencing dependent effects) * - * @example * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2691,9 +2653,8 @@ export const flatMap: { * ``` * * @see {@link tap} for a version that ignores the result of the effect. - * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (a: A) => Effect): Effect } = internal.flatMap @@ -2701,7 +2662,8 @@ export const flatMap: { /** * Flattens an `Effect` that produces another `Effect` into a single effect. * - * @example + * **Example** (Flattening nested effects) + * * ```ts * import { Console, Effect } from "effect" * @@ -2714,53 +2676,46 @@ export const flatMap: { * }) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const flatten: (self: Effect, E2, R2>) => Effect = internal.flatten /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2799,51 +2754,44 @@ export const flatten: (self: Effect, E2, R2>) = * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const andThen: { /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2882,51 +2830,44 @@ export const andThen: { * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (a: A) => Effect): (self: Effect) => Effect /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2965,51 +2906,44 @@ export const andThen: { * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: Effect): (self: Effect) => Effect /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -3048,51 +2982,44 @@ export const andThen: { * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (a: A) => Effect): Effect /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -3131,8 +3058,8 @@ export const andThen: { * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: Effect): Effect } = internal.andThen @@ -3141,11 +3068,10 @@ export const andThen: { * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` 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** * @@ -3154,17 +3080,10 @@ export const andThen: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Logging a step in a pipeline) * - * - `Effect.zipLeft` - * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3194,19 +3113,18 @@ export const andThen: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tap: { /** * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` 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** * @@ -3215,17 +3133,10 @@ export const tap: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Effect.zipLeft` + * **Example** (Logging a step in a pipeline) * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3255,19 +3166,18 @@ export const tap: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (a: NoInfer) => Effect): (self: Effect) => Effect /** * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` 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** * @@ -3276,17 +3186,10 @@ export const tap: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Logging a step in a pipeline) * - * - `Effect.zipLeft` - * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3316,19 +3219,18 @@ export const tap: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: Effect): (self: Effect) => Effect /** * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` 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** * @@ -3337,17 +3239,10 @@ export const tap: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** + * **Example** (Logging a step in a pipeline) * - * This API replaces the following from Effect 3.x: - * - * - `Effect.zipLeft` - * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3377,19 +3272,18 @@ export const tap: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (a: NoInfer) => Effect): Effect /** * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` 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** * @@ -3398,17 +3292,10 @@ export const tap: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Logging a step in a pipeline) * - * - `Effect.zipLeft` - * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3438,42 +3325,43 @@ export const tap: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: Effect): Effect } = internal.tap /** - * Encapsulates both success and failure of an `Effect` into a `Result` type. + * Converts both success and failure of an `Effect` into a `Result` type. + * + * **When to use** + * + * 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 * you want to chain effects and manage both success and failure in the same * logical flow. * - * It's important to note that unrecoverable errors, often referred to as - * "defects," are still thrown and not captured within the `Result` type. Only - * failures that are explicitly represented as recoverable errors in the effect - * are encapsulated. - * * The resulting effect cannot fail directly because all recoverable failures * are represented inside the `Result` type. * - * **Previously Known As** + * **Gotchas** * - * This API replaces the following from Effect 3.x: + * `result` only captures typed, recoverable failures. Defects and + * interruptions are not captured inside the `Result` and still fail the + * effect. * - * - `Effect.either` + * **Example** (Capturing success or failure as Result) * - * @example * ```ts * import { Effect } from "effect" * @@ -3493,20 +3381,35 @@ export const tap: { * @see {@link option} for a version that uses `Option` instead. * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`. * + * @category outcome encapsulation * @since 4.0.0 - * @category Outcome Encapsulation */ export const result: (self: Effect) => Effect, never, R> = internal.result /** - * Convert success to `Option.some` and failure to `Option.none`. + * Converts success to `Option.some` and failure to `Option.none`. + * + * **When to use** + * + * Use when you only care whether an effect succeeds and want recoverable + * failures represented as `Option.none`. * * **Details** * * Success values become `Option.some`, recoverable failures become * `Option.none`, and defects still fail the effect. * - * @example + * **Gotchas** + * + * `option` only captures typed, recoverable failures as `Option.none`. + * Defects and interruptions are not captured inside the `Option` and still + * fail the effect. + * + * `option` also discards typed failure values. Use `result` if the failure + * value matters. + * + * **Example** (Capturing success or failure as Option) + * * ```ts * import { Console, Effect, Option } from "effect" * @@ -3526,8 +3429,8 @@ export const result: (self: Effect) => Effect(self: Effect) => Effect, never, R> = internal.option @@ -3535,6 +3438,11 @@ export const option: (self: Effect) => Effect, never * Transforms an effect to encapsulate both failure and success using the `Exit` * data type. * + * **When to use** + * + * Use when you need to inspect the full outcome, including typed failures, defects, + * and interruptions. + * * **Details** * * `exit` wraps an effect's success or failure inside an `Exit` type, allowing @@ -3544,7 +3452,8 @@ export const option: (self: Effect) => Effect, never * the `Exit.Failure` type. The error type is set to `never`, indicating that * the effect is structured to never fail directly. * - * @example + * **Example** (Capturing completion as Exit) + * * ```ts * import { Effect } from "effect" * @@ -3564,8 +3473,8 @@ export const option: (self: Effect) => Effect, never * @see {@link option} for a version that uses `Option` instead. * @see {@link result} for a version that uses `Result` instead. * + * @category outcome encapsulation * @since 2.0.0 - * @category Outcome Encapsulation */ export const exit: ( self: Effect @@ -3574,15 +3483,11 @@ export const exit: ( /** * Transforms the value inside an effect by applying a function to it. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const mappedEffect = pipe(myEffect, Effect.map(transformation)) - * // or - * const mappedEffect = Effect.map(myEffect, transformation) - * // or - * const mappedEffect = myEffect.pipe(Effect.map(transformation)) - * ``` + * Use to transform an effect's success value with a function that returns a + * plain value, producing a new effect without changing the original effect's + * typed error or context requirements. * * **Details** * @@ -3593,7 +3498,21 @@ export const exit: ( * effect is not modified. Instead, a new effect is returned with the updated * value. * - * @example Adding a Service Charge + * **Example** (Syntax) + * + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => n + 1 + * + * const mappedWithPipe = pipe(myEffect, Effect.map(transformation)) + * const mappedWithDataFirst = Effect.map(myEffect, transformation) + * const mappedWithMethod = myEffect.pipe(Effect.map(transformation)) + * ``` + * + * **Example** (Adding a service charge) + * * ```ts * import { Effect, pipe } from "effect" * @@ -3613,23 +3532,18 @@ export const exit: ( * @see {@link mapError} for a version that operates on the error channel. * @see {@link mapBoth} for a version that operates on both channels. * @see {@link flatMap} or {@link andThen} for a version that can return a new effect. - * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const map: { /** * Transforms the value inside an effect by applying a function to it. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const mappedEffect = pipe(myEffect, Effect.map(transformation)) - * // or - * const mappedEffect = Effect.map(myEffect, transformation) - * // or - * const mappedEffect = myEffect.pipe(Effect.map(transformation)) - * ``` + * Use to transform an effect's success value with a function that returns a + * plain value, producing a new effect without changing the original effect's + * typed error or context requirements. * * **Details** * @@ -3640,7 +3554,21 @@ export const map: { * effect is not modified. Instead, a new effect is returned with the updated * value. * - * @example Adding a Service Charge + * **Example** (Syntax) + * + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => n + 1 + * + * const mappedWithPipe = pipe(myEffect, Effect.map(transformation)) + * const mappedWithDataFirst = Effect.map(myEffect, transformation) + * const mappedWithMethod = myEffect.pipe(Effect.map(transformation)) + * ``` + * + * **Example** (Adding a service charge) + * * ```ts * import { Effect, pipe } from "effect" * @@ -3660,23 +3588,18 @@ export const map: { * @see {@link mapError} for a version that operates on the error channel. * @see {@link mapBoth} for a version that operates on both channels. * @see {@link flatMap} or {@link andThen} for a version that can return a new effect. - * + * @category mapping * @since 2.0.0 - * @category Mapping */ (f: (a: A) => B): (self: Effect) => Effect /** * Transforms the value inside an effect by applying a function to it. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const mappedEffect = pipe(myEffect, Effect.map(transformation)) - * // or - * const mappedEffect = Effect.map(myEffect, transformation) - * // or - * const mappedEffect = myEffect.pipe(Effect.map(transformation)) - * ``` + * Use to transform an effect's success value with a function that returns a + * plain value, producing a new effect without changing the original effect's + * typed error or context requirements. * * **Details** * @@ -3687,7 +3610,21 @@ export const map: { * effect is not modified. Instead, a new effect is returned with the updated * value. * - * @example Adding a Service Charge + * **Example** (Syntax) + * + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => n + 1 + * + * const mappedWithPipe = pipe(myEffect, Effect.map(transformation)) + * const mappedWithDataFirst = Effect.map(myEffect, transformation) + * const mappedWithMethod = myEffect.pipe(Effect.map(transformation)) + * ``` + * + * **Example** (Adding a service charge) + * * ```ts * import { Effect, pipe } from "effect" * @@ -3707,9 +3644,8 @@ export const map: { * @see {@link mapError} for a version that operates on the error channel. * @see {@link mapBoth} for a version that operates on both channels. * @see {@link flatMap} or {@link andThen} for a version that can return a new effect. - * + * @category mapping * @since 2.0.0 - * @category Mapping */ (self: Effect, f: (a: A) => B): Effect } = internal.map @@ -3717,12 +3653,19 @@ export const map: { /** * Replaces the value inside an effect with a constant value. * + * **When to use** + * + * Use to replace a successful value with a constant while preserving failures + * and requirements. + * + * **Details** + * * `as` allows you to ignore the original value inside an effect and * replace it with a new constant value. * - * @example + * **Example** (Replacing a success value) + * * ```ts - * // Title: Replacing a Value * import { Effect, pipe } from "effect" * * // Replaces the value 5 with the constant "new value" @@ -3732,19 +3675,29 @@ export const map: { * // Output: "new value" * ``` * + * @see {@link map} for deriving the replacement value from the success value + * @see {@link asVoid} for replacing the success value with `void` + * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const as: { /** * Replaces the value inside an effect with a constant value. * + * **When to use** + * + * Use to replace a successful value with a constant while preserving failures + * and requirements. + * + * **Details** + * * `as` allows you to ignore the original value inside an effect and * replace it with a new constant value. * - * @example + * **Example** (Replacing a success value) + * * ```ts - * // Title: Replacing a Value * import { Effect, pipe } from "effect" * * // Replaces the value 5 with the constant "new value" @@ -3754,19 +3707,29 @@ export const as: { * // Output: "new value" * ``` * + * @see {@link map} for deriving the replacement value from the success value + * @see {@link asVoid} for replacing the success value with `void` + * + * @category mapping * @since 2.0.0 - * @category Mapping */ (value: B): (self: Effect) => Effect /** * Replaces the value inside an effect with a constant value. * + * **When to use** + * + * Use to replace a successful value with a constant while preserving failures + * and requirements. + * + * **Details** + * * `as` allows you to ignore the original value inside an effect and * replace it with a new constant value. * - * @example + * **Example** (Replacing a success value) + * * ```ts - * // Title: Replacing a Value * import { Effect, pipe } from "effect" * * // Replaces the value 5 with the constant "new value" @@ -3776,18 +3739,20 @@ export const as: { * // Output: "new value" * ``` * + * @see {@link map} for deriving the replacement value from the success value + * @see {@link asVoid} for replacing the success value with `void` + * + * @category mapping * @since 2.0.0 - * @category Mapping */ (self: Effect, value: B): Effect } = internal.as /** - * This function maps the success value of an `Effect` value to a `Some` value - * in an `Option` value. If the original `Effect` value fails, the returned - * `Effect` value will also fail. + * Maps the success value of an `Effect` to `Some`, preserving failures. + * + * **Example** (Wrapping success in Option.some) * - * @example * ```ts * import { Effect } from "effect" * @@ -3797,18 +3762,16 @@ export const as: { * // { _id: 'Option', _tag: 'Some', value: 42 } * ``` * - * @category Mapping + * @category mapping * @since 2.0.0 */ export const asSome: (self: Effect) => Effect, E, R> = internal.asSome /** - * This function maps the success value of an `Effect` value to `void`. If the - * original `Effect` value succeeds, the returned `Effect` value will also - * succeed. If the original `Effect` value fails, the returned `Effect` value - * will fail with the same error. + * Maps the success value of an `Effect` to `void`, preserving failures. + * + * **Example** (Discarding success values) * - * @example * ```ts * import { Effect } from "effect" * @@ -3818,21 +3781,24 @@ export const asSome: (self: Effect) => Effect, E, R> * // undefined (void) * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const asVoid: (self: Effect) => Effect = internal.asVoid /** - * The `flip` function swaps the success and error channels of an effect, - * so that the success becomes the error, and the error becomes the success. + * Swaps an effect's success and failure channels. + * + * **When to use** + * + * Use to swap an `Effect`'s success and failure channels. + * + * **Details** + * + * For an `Effect`, the returned effect has type `Effect`. * - * This function is useful when you need to reverse the flow of an effect, - * treating the previously successful values as errors and vice versa. This can - * be helpful in scenarios where you want to handle a success as a failure or - * treat an error as a valid result. + * **Example** (Swapping success and failure channels) * - * @example * ```ts * import { Effect } from "effect" * @@ -3845,8 +3811,8 @@ export const asVoid: (self: Effect) => Effect = in * const flipped = Effect.flip(program) * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const flip: (self: Effect) => Effect = internal.flip @@ -3857,20 +3823,23 @@ export const flip: (self: Effect) => Effect = interna /** * Combines two effects into a single effect, producing a tuple with the results of both effects. * + * **When to use** + * + * Use to combine exactly two effects into a tuple. + * + * **Details** + * * The `zip` function executes the first effect (left) and then the second effect (right). * Once both effects succeed, their results are combined into a tuple. * - * **Concurrency** + * Concurrency: * * By default, `zip` processes the effects sequentially. To execute the effects concurrently, * use the `{ concurrent: true }` option. * - * @see {@link zipWith} for a version that combines the results with a custom function. - * @see {@link validate} for a version that accumulates errors. + * **Example** (Combining two effects sequentially) * - * @example * ```ts - * // Title: Combining Two Effects Sequentially * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -3895,8 +3864,9 @@ export const flip: (self: Effect) => Effect = interna * // [ 1, 'hello' ] * ``` * - * @example - * // Title: Combining Two Effects Concurrently + * **Example** (Combining two effects concurrently) + * + * ```ts * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -3916,9 +3886,13 @@ export const flip: (self: Effect) => Effect = interna * // timestamp=... level=INFO fiber=#0 message="task2 done" * // timestamp=... level=INFO fiber=#0 message="task1 done" * // [ 1, 'hello' ] + * ``` + * + * @see {@link zipWith} for a version that combines the results with a custom function. + * @see {@link all} for collecting a larger structure of effects. * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zip: { // ----------------------------------------------------------------------------- @@ -3928,20 +3902,23 @@ export const zip: { /** * Combines two effects into a single effect, producing a tuple with the results of both effects. * + * **When to use** + * + * Use to combine exactly two effects into a tuple. + * + * **Details** + * * The `zip` function executes the first effect (left) and then the second effect (right). * Once both effects succeed, their results are combined into a tuple. * - * **Concurrency** + * Concurrency: * * By default, `zip` processes the effects sequentially. To execute the effects concurrently, * use the `{ concurrent: true }` option. * - * @see {@link zipWith} for a version that combines the results with a custom function. - * @see {@link validate} for a version that accumulates errors. + * **Example** (Combining two effects sequentially) * - * @example * ```ts - * // Title: Combining Two Effects Sequentially * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -3966,8 +3943,9 @@ export const zip: { * // [ 1, 'hello' ] * ``` * - * @example - * // Title: Combining Two Effects Concurrently + * **Example** (Combining two effects concurrently) + * + * ```ts * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -3987,9 +3965,13 @@ export const zip: { * // timestamp=... level=INFO fiber=#0 message="task2 done" * // timestamp=... level=INFO fiber=#0 message="task1 done" * // [ 1, 'hello' ] + * ``` * + * @see {@link zipWith} for a version that combines the results with a custom function. + * @see {@link all} for collecting a larger structure of effects. + * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( that: Effect, @@ -4002,20 +3984,23 @@ export const zip: { /** * Combines two effects into a single effect, producing a tuple with the results of both effects. * + * **When to use** + * + * Use to combine exactly two effects into a tuple. + * + * **Details** + * * The `zip` function executes the first effect (left) and then the second effect (right). * Once both effects succeed, their results are combined into a tuple. * - * **Concurrency** + * Concurrency: * * By default, `zip` processes the effects sequentially. To execute the effects concurrently, * use the `{ concurrent: true }` option. * - * @see {@link zipWith} for a version that combines the results with a custom function. - * @see {@link validate} for a version that accumulates errors. + * **Example** (Combining two effects sequentially) * - * @example * ```ts - * // Title: Combining Two Effects Sequentially * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4040,8 +4025,9 @@ export const zip: { * // [ 1, 'hello' ] * ``` * - * @example - * // Title: Combining Two Effects Concurrently + * **Example** (Combining two effects concurrently) + * + * ```ts * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4061,9 +4047,13 @@ export const zip: { * // timestamp=... level=INFO fiber=#0 message="task2 done" * // timestamp=... level=INFO fiber=#0 message="task1 done" * // [ 1, 'hello' ] + * ``` + * + * @see {@link zipWith} for a version that combines the results with a custom function. + * @see {@link all} for collecting a larger structure of effects. * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( self: Effect, @@ -4076,20 +4066,21 @@ export const zip: { * Combines two effects sequentially and applies a function to their results to * produce a single value. * - * **When to Use** + * **When to use** * - * The `zipWith` function is similar to {@link zip}, but instead of returning a - * tuple of results, it applies a provided function to the results of the two - * effects, combining them into a single value. + * Use when you need to run two effects sequentially and combine their results + * with a function instead of keeping the results as a tuple. * - * **Concurrency** + * **Details** + * + * Concurrency: * * By default, the effects are run sequentially. To execute them concurrently, * use the `{ concurrent: true }` option. * - * @example + * **Example** (Combining two success values with a function) + * * ```ts - * // Title: Combining Effects with a Custom Function * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4115,28 +4106,29 @@ export const zip: { * // 6 * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWith: { /** * Combines two effects sequentially and applies a function to their results to * produce a single value. * - * **When to Use** + * **When to use** + * + * Use when you need to run two effects sequentially and combine their results + * with a function instead of keeping the results as a tuple. * - * The `zipWith` function is similar to {@link zip}, but instead of returning a - * tuple of results, it applies a provided function to the results of the two - * effects, combining them into a single value. + * **Details** * - * **Concurrency** + * Concurrency: * * By default, the effects are run sequentially. To execute them concurrently, * use the `{ concurrent: true }` option. * - * @example + * **Example** (Combining two success values with a function) + * * ```ts - * // Title: Combining Effects with a Custom Function * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4162,8 +4154,8 @@ export const zipWith: { * // 6 * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( that: Effect, @@ -4174,20 +4166,21 @@ export const zipWith: { * Combines two effects sequentially and applies a function to their results to * produce a single value. * - * **When to Use** + * **When to use** * - * The `zipWith` function is similar to {@link zip}, but instead of returning a - * tuple of results, it applies a provided function to the results of the two - * effects, combining them into a single value. + * Use when you need to run two effects sequentially and combine their results + * with a function instead of keeping the results as a tuple. + * + * **Details** * - * **Concurrency** + * Concurrency: * * By default, the effects are run sequentially. To execute them concurrently, * use the `{ concurrent: true }` option. * - * @example + * **Example** (Combining two success values with a function) + * * ```ts - * // Title: Combining Effects with a Custom Function * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4213,8 +4206,8 @@ export const zipWith: { * // 6 * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( self: Effect, @@ -4242,6 +4235,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 @@ -4249,19 +4247,15 @@ 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. - * - * @see {@link catchCause} for a version that can recover from both recoverable and unrecoverable errors. - * - * **Previously Known As** + * **Gotchas** * - * This API replaces the following from Effect 3.x: + * `catch` only handles recoverable errors. It will not recover from + * unrecoverable defects. * - * - `Effect.catchAll` + * @see {@link catchCause} for a version that can recover from both recoverable and unrecoverable errors. * + * @category error handling * @since 4.0.0 - * @category Error Handling */ catch_ as catch } @@ -4270,17 +4264,18 @@ export { * Catches and handles specific errors by their `_tag` field, which is used as a * discriminator. * - * **When to Use** + * **When to use** * - * `catchTag` is useful when your errors are tagged with a readonly `_tag` field - * that identifies the error type. You can use this function to handle specific - * error types by matching the `_tag` value. This allows for precise error - * handling, ensuring that only specific errors are caught and handled. + * Use when you need to recover from one specific tagged error in an effect + * error channel. * - * The error type must have a readonly `_tag` field to use `catchTag`. This - * field is used to identify and match errors. + * **Details** + * + * The error type must have a readonly `_tag` field. `catchTag` matches that + * field and only handles errors with the requested tag. + * + * **Example** (Handling a tagged error) * - * @example * ```ts * import { Effect } from "effect" * @@ -4303,25 +4298,29 @@ export { * ) * ``` * + * @see {@link catchTags} for handling multiple tagged errors in one call + * @see {@link catchIf} for recovering from errors that match a predicate + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const catchTag: { /** * Catches and handles specific errors by their `_tag` field, which is used as a * discriminator. * - * **When to Use** + * **When to use** * - * `catchTag` is useful when your errors are tagged with a readonly `_tag` field - * that identifies the error type. You can use this function to handle specific - * error types by matching the `_tag` value. This allows for precise error - * handling, ensuring that only specific errors are caught and handled. + * Use when you need to recover from one specific tagged error in an effect + * error channel. * - * The error type must have a readonly `_tag` field to use `catchTag`. This - * field is used to identify and match errors. + * **Details** + * + * The error type must have a readonly `_tag` field. `catchTag` matches that + * field and only handles errors with the requested tag. + * + * **Example** (Handling a tagged error) * - * @example * ```ts * import { Effect } from "effect" * @@ -4344,8 +4343,11 @@ export const catchTag: { * ) * ``` * + * @see {@link catchTags} for handling multiple tagged errors in one call + * @see {@link catchIf} for recovering from errors that match a predicate + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ < const K extends Tags | Arr.NonEmptyReadonlyArray>, @@ -4353,8 +4355,8 @@ export const catchTag: { A1, E1, R1, - A2 = never, - E2 = ExcludeTag, + A2 = unassigned, + E2 = never, R2 = never >( k: K, @@ -4362,22 +4364,31 @@ export const catchTag: { orElse?: | ((e: ExcludeTag ? K[number] : K>) => Effect) | undefined - ): (self: Effect) => Effect + ): ( + self: Effect + ) => Effect< + A | A1 | Exclude, + | E1 + | E2 + | (A2 extends unassigned ? ExcludeTag ? K[number] : K> : never), + R | R1 | R2 + > /** * Catches and handles specific errors by their `_tag` field, which is used as a * discriminator. * - * **When to Use** + * **When to use** * - * `catchTag` is useful when your errors are tagged with a readonly `_tag` field - * that identifies the error type. You can use this function to handle specific - * error types by matching the `_tag` value. This allows for precise error - * handling, ensuring that only specific errors are caught and handled. + * Use when you need to recover from one specific tagged error in an effect + * error channel. * - * The error type must have a readonly `_tag` field to use `catchTag`. This - * field is used to identify and match errors. + * **Details** + * + * The error type must have a readonly `_tag` field. `catchTag` matches that + * field and only handles errors with the requested tag. + * + * **Example** (Handling a tagged error) * - * @example * ```ts * import { Effect } from "effect" * @@ -4400,8 +4411,11 @@ export const catchTag: { * ) * ``` * + * @see {@link catchTags} for handling multiple tagged errors in one call + * @see {@link catchIf} for recovering from errors that match a predicate + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ < A, @@ -4411,8 +4425,8 @@ export const catchTag: { R1, E1, A1, - A2 = never, - E2 = ExcludeTag, + A2 = unassigned, + E2 = never, R2 = never >( self: Effect, @@ -4421,25 +4435,33 @@ export const catchTag: { orElse?: | ((e: ExcludeTag ? K[number] : K>) => Effect) | undefined - ): Effect + ): Effect< + A | A1 | Exclude, + | E1 + | E2 + | (A2 extends unassigned ? ExcludeTag ? K[number] : K> : never), + R | R1 | R2 + > } = internal.catchTag /** * Handles multiple errors in a single block of code using their `_tag` field. * - * **When to Use** + * **When to use** + * + * Use when one recovery step should handle several tagged error types by + * matching their readonly `_tag` fields. + * + * **Details** * - * `catchTags` is a convenient way to handle multiple error types at - * once. Instead of using {@link catchTag} multiple times, you can pass an - * object where each key is an error type's `_tag`, and the value is the handler - * for that specific error. This allows you to catch and recover from multiple - * error types in a single call. You can also provide a fallback handler for - * unhandled errors. + * 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 `catchTag`. This + * The error type must have a readonly `_tag` field to use `catchTags`. This * field is used to identify and match errors. * - * @example + * **Example** (Handling multiple tagged errors) + * * ```ts * import { Data, Effect } from "effect" * @@ -4463,26 +4485,28 @@ export const catchTag: { * }) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const catchTags: { /** * Handles multiple errors in a single block of code using their `_tag` field. * - * **When to Use** + * **When to use** + * + * Use when one recovery step should handle several tagged error types by + * matching their readonly `_tag` fields. + * + * **Details** * - * `catchTags` is a convenient way to handle multiple error types at - * once. Instead of using {@link catchTag} multiple times, you can pass an - * object where each key is an error type's `_tag`, and the value is the handler - * for that specific error. This allows you to catch and recover from multiple - * error types in a single call. You can also provide a fallback handler for - * unhandled errors. + * 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 `catchTag`. This + * The error type must have a readonly `_tag` field to use `catchTags`. This * field is used to identify and match errors. * - * @example + * **Example** (Handling multiple tagged errors) + * * ```ts * import { Data, Effect } from "effect" * @@ -4506,16 +4530,16 @@ export const catchTags: { * }) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ < E, Cases extends & { [K in Extract["_tag"]]+?: ((error: Extract) => Effect) } & (unknown extends E ? {} : { [K in Exclude["_tag"]>]: never }), - A2 = never, - E2 = Exclude, + A2 = unassigned, + E2 = never, R2 = never >( cases: Cases, @@ -4524,11 +4548,12 @@ export const catchTags: { self: Effect ) => Effect< | A - | A2 + | Exclude | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? A : never }[keyof Cases], | E2 + | (A2 extends unassigned ? Exclude : never) | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? E : never }[keyof Cases], @@ -4541,19 +4566,21 @@ export const catchTags: { /** * Handles multiple errors in a single block of code using their `_tag` field. * - * **When to Use** + * **When to use** + * + * Use when one recovery step should handle several tagged error types by + * matching their readonly `_tag` fields. + * + * **Details** * - * `catchTags` is a convenient way to handle multiple error types at - * once. Instead of using {@link catchTag} multiple times, you can pass an - * object where each key is an error type's `_tag`, and the value is the handler - * for that specific error. This allows you to catch and recover from multiple - * error types in a single call. You can also provide a fallback handler for - * unhandled errors. + * 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 `catchTag`. This + * The error type must have a readonly `_tag` field to use `catchTags`. This * field is used to identify and match errors. * - * @example + * **Example** (Handling multiple tagged errors) + * * ```ts * import { Data, Effect } from "effect" * @@ -4577,8 +4604,8 @@ export const catchTags: { * }) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ < R, @@ -4587,8 +4614,8 @@ export const catchTags: { Cases extends & { [K in Extract["_tag"]]+?: ((error: Extract) => Effect) } & (unknown extends E ? {} : { [K in Exclude["_tag"]>]: never }), - A2 = never, - E2 = Exclude, + A2 = unassigned, + E2 = never, R2 = never >( self: Effect, @@ -4596,11 +4623,12 @@ export const catchTags: { orElse?: ((e: Exclude) => Effect) | undefined ): Effect< | A - | A2 + | Exclude | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? A : never }[keyof Cases], | E2 + | (A2 extends unassigned ? Exclude : never) | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? E : never }[keyof Cases], @@ -4615,10 +4643,18 @@ export const catchTags: { /** * Catches a specific reason within a tagged error. * + * **When to use** + * + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. + * + * **Details** + * * Use this to handle nested error causes without removing the parent error * from the error channel. The handler receives the unwrapped reason. * - * @example + * **Example** (Handling an error reason) + * * ```ts * import { Data, Effect } from "effect" * @@ -4644,17 +4680,27 @@ export const catchTags: { * ) * ``` * + * @see {@link catchReasons} for handling several nested reason tags + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchReason: { /** * Catches a specific reason within a tagged error. * + * **When to use** + * + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. + * + * **Details** + * * Use this to handle nested error causes without removing the parent error * from the error channel. The handler receives the unwrapped reason. * - * @example + * **Example** (Handling an error reason) + * * ```ts * import { Data, Effect } from "effect" * @@ -4680,8 +4726,10 @@ export const catchReason: { * ) * ``` * + * @see {@link catchReasons} for handling several nested reason tags + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < K extends Tags, @@ -4708,14 +4756,26 @@ export const catchReason: { | undefined ): ( self: Effect - ) => Effect, (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, R | R2 | R3> + ) => Effect< + A | A2 | Exclude, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), + R | R2 | R3 + > /** * Catches a specific reason within a tagged error. * + * **When to use** + * + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. + * + * **Details** + * * Use this to handle nested error causes without removing the parent error * from the error channel. The handler receives the unwrapped reason. * - * @example + * **Example** (Handling an error reason) + * * ```ts * import { Data, Effect } from "effect" * @@ -4741,8 +4801,10 @@ export const catchReason: { * ) * ``` * + * @see {@link catchReasons} for handling several nested reason tags + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < A, @@ -4764,13 +4826,18 @@ export const catchReason: { orElse?: | ((reasons: ExcludeReason, RK>, error: OmitReason, RK>) => Effect) | undefined - ): Effect, (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, R | R2 | R3> + ): Effect< + A | A2 | Exclude, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), + R | R2 | R3 + > } = internal.catchReason /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Handling multiple error reasons) + * * ```ts * import { Data, Effect } from "effect" * @@ -4798,14 +4865,15 @@ export const catchReason: { * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchReasons: { /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Handling multiple error reasons) + * * ```ts * import { Data, Effect } from "effect" * @@ -4833,8 +4901,8 @@ export const catchReasons: { * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < K extends Tags, @@ -4865,8 +4933,9 @@ export const catchReasons: { | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect ? A : never }[keyof Cases], - | (A2 extends unassigned ? E : ExcludeTag) + | ExcludeTag | E2 + | (A2 extends unassigned ? ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect ? E : never }[keyof Cases], @@ -4879,7 +4948,8 @@ export const catchReasons: { /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Handling multiple error reasons) + * * ```ts * import { Data, Effect } from "effect" * @@ -4907,8 +4977,8 @@ export const catchReasons: { * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < A, @@ -4940,8 +5010,9 @@ export const catchReasons: { | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect ? A : never }[keyof Cases], - | (A2 extends unassigned ? E : ExcludeTag) + | ExcludeTag | E2 + | (A2 extends unassigned ? ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect ? E : never }[keyof Cases], @@ -4956,10 +5027,22 @@ export const catchReasons: { /** * Type helper that keeps only error tags whose tagged error contains a tagged `reason` field. * - * Used by `catchReasons` and `unwrapReason` to constrain the parent error tag to reason-bearing errors. + * **When to use** + * + * Use to constrain custom helpers or overloads to parent error tags whose error + * contains a tagged reason. + * + * **Details** + * + * The mapped type keeps each parent error tag whose extracted tagged error has + * at least one reason tag, and removes tags that do not carry tagged reasons. + * + * @see {@link unwrapReason} for promoting nested reason errors into the error channel + * @see {@link catchReason} for handling one nested reason tag + * @see {@link catchReasons} for handling several nested reason tags * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export type TagsWithReason = { [T in Tags]: ReasonTags> extends never ? never : T @@ -4969,7 +5052,8 @@ export type TagsWithReason = { * Promotes nested reason errors into the Effect error channel, replacing * the parent error. * - * @example + * **Example** (Extracting the reason from a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -4992,15 +5076,16 @@ export type TagsWithReason = { * const unwrapped = program.pipe(Effect.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const unwrapReason: { /** * Promotes nested reason errors into the Effect error channel, replacing * the parent error. * - * @example + * **Example** (Extracting the reason from a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -5023,8 +5108,8 @@ export const unwrapReason: { * const unwrapped = program.pipe(Effect.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < K extends TagsWithReason, @@ -5034,7 +5119,8 @@ export const unwrapReason: { * Promotes nested reason errors into the Effect error channel, replacing * the parent error. * - * @example + * **Example** (Extracting the reason from a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -5057,8 +5143,8 @@ export const unwrapReason: { * const unwrapped = program.pipe(Effect.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < A, @@ -5072,26 +5158,22 @@ export const unwrapReason: { * Handles both recoverable and unrecoverable errors by providing a recovery * effect. * - * **When to Use** + * **When to use** + * + * 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. * - * The `catchCause` function allows you to handle all errors, including - * unrecoverable defects, by providing a recovery effect. The recovery logic is - * based on the `Cause` of the error, which provides detailed information about - * the failure. + * **Details** * - * **When to Recover from Defects** + * When to Recover from Defects: * * Defects are unexpected errors that typically shouldn't be recovered from, as * they often indicate serious issues. However, in some cases, such as * dynamically loaded plugins, controlled recovery might be needed. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from full failure causes) * - * - `Effect.catchAllCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5109,34 +5191,30 @@ export const unwrapReason: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCause: { /** * Handles both recoverable and unrecoverable errors by providing a recovery * effect. * - * **When to Use** + * **When to use** + * + * 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. * - * The `catchCause` function allows you to handle all errors, including - * unrecoverable defects, by providing a recovery effect. The recovery logic is - * based on the `Cause` of the error, which provides detailed information about - * the failure. + * **Details** * - * **When to Recover from Defects** + * When to Recover from Defects: * * Defects are unexpected errors that typically shouldn't be recovered from, as * they often indicate serious issues. However, in some cases, such as * dynamically loaded plugins, controlled recovery might be needed. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from full failure causes) * - * - `Effect.catchAllCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5154,34 +5232,30 @@ export const catchCause: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ (f: (cause: Cause.Cause) => Effect): (self: Effect) => Effect /** * Handles both recoverable and unrecoverable errors by providing a recovery * effect. * - * **When to Use** + * **When to use** + * + * 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. * - * The `catchCause` function allows you to handle all errors, including - * unrecoverable defects, by providing a recovery effect. The recovery logic is - * based on the `Cause` of the error, which provides detailed information about - * the failure. + * **Details** * - * **When to Recover from Defects** + * When to Recover from Defects: * * Defects are unexpected errors that typically shouldn't be recovered from, as * they often indicate serious issues. However, in some cases, such as * dynamically loaded plugins, controlled recovery might be needed. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from full failure causes) * - * - `Effect.catchAllCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5199,42 +5273,32 @@ export const catchCause: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ (self: Effect, f: (cause: Cause.Cause) => Effect): Effect } = internal.catchCause /** - * Recovers from all defects using a provided recovery function. + * Recovers from defects using a provided recovery function. * - * **When to Use** + * **When to use** * - * There is no sensible way to recover from defects. This method should be used - * only at the boundary between Effect and an external system, to transmit - * information on a defect for diagnostic or explanatory purposes. + * Use when you need to report or translate defects at integration boundaries. * * **Details** * - * `catchAllDefect` allows you to handle defects, which are unexpected errors - * that usually cause the program to terminate. This function lets you recover - * from these defects by providing a function that handles the error. However, - * it does not handle expected errors (like those from {@link fail}) or - * execution interruptions (like those from {@link interrupt}). - * - * **When to Recover from Defects** - * - * Defects are unexpected errors that typically shouldn't be recovered from, as - * they often indicate serious issues. However, in some cases, such as - * dynamically loaded plugins, controlled recovery might be needed. + * `catchDefect` handles unexpected defects, such as thrown exceptions or + * values passed to `die`, without catching typed failures or interruptions. * - * **Previously Known As** + * When to Recover from Defects: * - * This API replaces the following from Effect 3.x: + * Defects are unexpected errors that typically should not be recovered from, as + * they often indicate serious issues. In some cases, such as dynamically loaded + * plugins, controlled recovery may be needed. * - * - `Effect.catchAllDefect` + * **Example** (Recovering from defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -5251,40 +5315,30 @@ export const catchCause: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchDefect: { /** - * Recovers from all defects using a provided recovery function. + * Recovers from defects using a provided recovery function. * - * **When to Use** + * **When to use** * - * There is no sensible way to recover from defects. This method should be used - * only at the boundary between Effect and an external system, to transmit - * information on a defect for diagnostic or explanatory purposes. + * Use when you need to report or translate defects at integration boundaries. * * **Details** * - * `catchAllDefect` allows you to handle defects, which are unexpected errors - * that usually cause the program to terminate. This function lets you recover - * from these defects by providing a function that handles the error. However, - * it does not handle expected errors (like those from {@link fail}) or - * execution interruptions (like those from {@link interrupt}). - * - * **When to Recover from Defects** - * - * Defects are unexpected errors that typically shouldn't be recovered from, as - * they often indicate serious issues. However, in some cases, such as - * dynamically loaded plugins, controlled recovery might be needed. + * `catchDefect` handles unexpected defects, such as thrown exceptions or + * values passed to `die`, without catching typed failures or interruptions. * - * **Previously Known As** + * When to Recover from Defects: * - * This API replaces the following from Effect 3.x: + * Defects are unexpected errors that typically should not be recovered from, as + * they often indicate serious issues. In some cases, such as dynamically loaded + * plugins, controlled recovery may be needed. * - * - `Effect.catchAllDefect` + * **Example** (Recovering from defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -5301,40 +5355,30 @@ export const catchDefect: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ (f: (defect: unknown) => Effect): (self: Effect) => Effect /** - * Recovers from all defects using a provided recovery function. + * Recovers from defects using a provided recovery function. * - * **When to Use** + * **When to use** * - * There is no sensible way to recover from defects. This method should be used - * only at the boundary between Effect and an external system, to transmit - * information on a defect for diagnostic or explanatory purposes. + * Use when you need to report or translate defects at integration boundaries. * * **Details** * - * `catchAllDefect` allows you to handle defects, which are unexpected errors - * that usually cause the program to terminate. This function lets you recover - * from these defects by providing a function that handles the error. However, - * it does not handle expected errors (like those from {@link fail}) or - * execution interruptions (like those from {@link interrupt}). - * - * **When to Recover from Defects** + * `catchDefect` handles unexpected defects, such as thrown exceptions or + * values passed to `die`, without catching typed failures or interruptions. * - * Defects are unexpected errors that typically shouldn't be recovered from, as - * they often indicate serious issues. However, in some cases, such as - * dynamically loaded plugins, controlled recovery might be needed. - * - * **Previously Known As** + * When to Recover from Defects: * - * This API replaces the following from Effect 3.x: + * Defects are unexpected errors that typically should not be recovered from, as + * they often indicate serious issues. In some cases, such as dynamically loaded + * plugins, controlled recovery may be needed. * - * - `Effect.catchAllDefect` + * **Example** (Recovering from defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -5351,8 +5395,8 @@ export const catchDefect: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ (self: Effect, f: (defect: unknown) => Effect): Effect } = internal.catchDefect @@ -5360,21 +5404,18 @@ export const catchDefect: { /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. 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. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * 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. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5399,28 +5440,25 @@ export const catchDefect: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const catchIf: { /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. 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. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * 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. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5445,32 +5483,31 @@ export const catchIf: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ - , R3 = never>( + ( refinement: Predicate.Refinement, EB>, f: (e: EB) => Effect, orElse?: ((e: Exclude) => Effect) | undefined - ): (self: Effect) => Effect + ): ( + self: Effect + ) => Effect, E2 | E3 | (A3 extends unassigned ? Exclude : never), R | R2 | R3> /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. 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. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * 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. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5495,32 +5532,31 @@ export const catchIf: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ - ( + ( predicate: Predicate.Predicate>, f: (e: NoInfer) => Effect, orElse?: ((e: NoInfer) => Effect) | undefined - ): (self: Effect) => Effect + ): ( + self: Effect + ) => Effect, E2 | E3 | (A3 extends unassigned ? E : never), R | R2 | R3> /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. 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. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * 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. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5545,33 +5581,30 @@ export const catchIf: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ - , R3 = never>( + ( self: Effect, refinement: Predicate.Refinement, f: (e: EB) => Effect, orElse?: ((e: Exclude) => Effect) | undefined - ): Effect + ): Effect, E2 | E3 | (A3 extends unassigned ? Exclude : never), R | R2 | R3> /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. 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. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * 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. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5596,56 +5629,120 @@ export const catchIf: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ - ( + ( self: Effect, predicate: Predicate.Predicate, f: (e: E) => Effect, orElse?: ((e: E) => Effect) | undefined - ): Effect + ): Effect, E2 | E3 | (A3 extends unassigned ? E : never), R | R2 | R3> } = internal.catchIf /** * Recovers from specific errors using a `Filter`. * + * **When to use** + * + * Use to recover from typed `Effect` errors with a reusable `Filter` when + * matching can also narrow or transform the error before choosing the recovery + * effect. + * + * **Details** + * + * The filter runs on typed failures extracted from the `Cause`. Successful + * filter results are passed to `f`; failed filter results are passed to + * `orElse` when provided. Without `orElse`, the original failure cause is + * preserved. + * + * @see {@link catchIf} for predicate-based recovery from typed errors + * @see {@link catchTag} for recovering from a single tagged error + * @see {@link catchTags} for recovering from several tagged errors + * @see {@link catchCauseFilter} for filtering full causes instead of typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchFilter: { /** * Recovers from specific errors using a `Filter`. * + * **When to use** + * + * Use to recover from typed `Effect` errors with a reusable `Filter` when + * matching can also narrow or transform the error before choosing the recovery + * effect. + * + * **Details** + * + * The filter runs on typed failures extracted from the `Cause`. Successful + * filter results are passed to `f`; failed filter results are passed to + * `orElse` when provided. Without `orElse`, the original failure cause is + * preserved. + * + * @see {@link catchIf} for predicate-based recovery from typed errors + * @see {@link catchTag} for recovering from a single tagged error + * @see {@link catchTags} for recovering from several tagged errors + * @see {@link catchCauseFilter} for filtering full causes instead of typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - ( + ( filter: Filter.Filter, EB, X>, f: (e: EB) => Effect, orElse?: ((e: X) => Effect) | undefined - ): (self: Effect) => Effect + ): ( + self: Effect + ) => Effect, E2 | E3 | (A3 extends unassigned ? X : never), R | R2 | R3> /** * Recovers from specific errors using a `Filter`. * + * **When to use** + * + * Use to recover from typed `Effect` errors with a reusable `Filter` when + * matching can also narrow or transform the error before choosing the recovery + * effect. + * + * **Details** + * + * The filter runs on typed failures extracted from the `Cause`. Successful + * filter results are passed to `f`; failed filter results are passed to + * `orElse` when provided. Without `orElse`, the original failure cause is + * preserved. + * + * @see {@link catchIf} for predicate-based recovery from typed errors + * @see {@link catchTag} for recovering from a single tagged error + * @see {@link catchTags} for recovering from several tagged errors + * @see {@link catchCauseFilter} for filtering full causes instead of typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - ( + ( self: Effect, filter: Filter.Filter, EB, X>, f: (e: EB) => Effect, orElse?: ((e: X) => Effect) | undefined - ): Effect + ): Effect, E2 | E3 | (A3 extends unassigned ? X : never), R | R2 | R3> } = internal.catchFilter /** * Catches `NoSuchElementError` failures and converts them to `Option.none`. * + * **When to use** + * + * Use when you expect missing-value failures and want them to become an + * optional success while all other failures keep failing. + * + * **Details** + * * Success values become `Option.some`, `NoSuchElementError` becomes * `Option.none`, and all other errors are preserved. * - * @example + * **Example** (Recovering from missing Option values) + * * ```ts * import { Effect, Option } from "effect" * @@ -5656,14 +5753,12 @@ export const catchFilter: { * Effect.runPromise(none).then(console.log) // { _id: 'Option', _tag: 'None' } * ``` * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * @see {@link fromOption} for converting `Option.none` into `NoSuchElementError` + * @see {@link fromNullishOr} for converting nullish values into `NoSuchElementError` + * @see {@link option} for converting any failure into `Option.none` * - * - `Effect.optionFromOptional` - * - * @since 2.0.0 - * @category Error Handling + * @category error handling + * @since 4.0.0 */ export const catchNoSuchElement: ( self: Effect @@ -5672,17 +5767,18 @@ export const catchNoSuchElement: ( /** * Recovers from specific failures based on a predicate. * + * **When to use** + * + * Use to recover an `Effect` from full causes selected by a predicate. + * + * **Details** + * * This function allows you to conditionally catch and recover from failures * that match a specific predicate. This is useful when you want to handle * only certain types of errors while letting others propagate. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from selected causes) * - * - `Effect.catchSomeCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5704,24 +5800,29 @@ export const catchNoSuchElement: ( * // Then: "Fallback response" * ``` * + * @see {@link catchCause} for recovering from every cause + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * @see {@link catchIf} for predicate-based recovery from typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCauseIf: { /** * Recovers from specific failures based on a predicate. * + * **When to use** + * + * Use to recover an `Effect` from full causes selected by a predicate. + * + * **Details** + * * This function allows you to conditionally catch and recover from failures * that match a specific predicate. This is useful when you want to handle * only certain types of errors while letting others propagate. * - * **Previously Known As** + * **Example** (Recovering from selected causes) * - * This API replaces the following from Effect 3.x: - * - * - `Effect.catchSomeCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5743,8 +5844,12 @@ export const catchCauseIf: { * // Then: "Fallback response" * ``` * + * @see {@link catchCause} for recovering from every cause + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * @see {@link catchIf} for predicate-based recovery from typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ ( predicate: Predicate.Predicate>, @@ -5753,17 +5858,18 @@ export const catchCauseIf: { /** * Recovers from specific failures based on a predicate. * + * **When to use** + * + * Use to recover an `Effect` from full causes selected by a predicate. + * + * **Details** + * * This function allows you to conditionally catch and recover from failures * that match a specific predicate. This is useful when you want to handle * only certain types of errors while letting others propagate. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from selected causes) * - * - `Effect.catchSomeCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5785,8 +5891,12 @@ export const catchCauseIf: { * // Then: "Fallback response" * ``` * + * @see {@link catchCause} for recovering from every cause + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * @see {@link catchIf} for predicate-based recovery from typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ ( self: Effect, @@ -5798,15 +5908,47 @@ export const catchCauseIf: { /** * Recovers from specific failures based on a `Filter`. * + * **When to use** + * + * 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** + * + * The filter is applied to the full `Cause`. When it succeeds, the handler + * receives the selected value and the original cause. When it fails, the effect + * re-fails with the residual cause returned by the filter. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCauseFilter: { /** * Recovers from specific failures based on a `Filter`. * + * **When to use** + * + * 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** + * + * The filter is applied to the full `Cause`. When it succeeds, the handler + * receives the selected value and the original cause. When it fails, the effect + * re-fails with the residual cause returned by the filter. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ >( filter: Filter.Filter, EB, X>, @@ -5815,8 +5957,24 @@ export const catchCauseFilter: { /** * Recovers from specific failures based on a `Filter`. * + * **When to use** + * + * 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** + * + * The filter is applied to the full `Cause`. When it succeeds, the handler + * receives the selected value and the original cause. When it fails, the effect + * re-fails with the residual cause returned by the filter. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ >( self: Effect, @@ -5826,19 +5984,20 @@ export const catchCauseFilter: { } = internal.catchCauseFilter /** - * The `mapError` function is used to transform or modify the error - * produced by an effect, without affecting its success value. + * Transforms the failure value of an effect without changing its success value. * - * This function is helpful when you want to enhance the error with additional - * information, change the error type, or apply custom error handling while - * keeping the original behavior of the effect's success values intact. It only - * operates on the error channel and leaves the success channel unchanged. + * **When to use** * - * @see {@link map} for a version that operates on the success channel. - * @see {@link mapBoth} for a version that operates on both channels. - * @see {@link orElseFail} if you want to replace the error with a new one. + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. + * + * **Details** + * + * Only the failure channel is transformed. The success channel and requirements + * are preserved. + * + * **Example** (Transforming the error channel) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -5856,24 +6015,28 @@ export const catchCauseFilter: { * ) * ``` * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapBoth} for a version that operates on both channels. + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const mapError: { /** - * The `mapError` function is used to transform or modify the error - * produced by an effect, without affecting its success value. + * Transforms the failure value of an effect without changing its success value. * - * This function is helpful when you want to enhance the error with additional - * information, change the error type, or apply custom error handling while - * keeping the original behavior of the effect's success values intact. It only - * operates on the error channel and leaves the success channel unchanged. + * **When to use** * - * @see {@link map} for a version that operates on the success channel. - * @see {@link mapBoth} for a version that operates on both channels. - * @see {@link orElseFail} if you want to replace the error with a new one. + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. + * + * **Details** + * + * Only the failure channel is transformed. The success channel and requirements + * are preserved. + * + * **Example** (Transforming the error channel) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -5891,24 +6054,28 @@ export const mapError: { * ) * ``` * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapBoth} for a version that operates on both channels. + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (f: (e: E) => E2): (self: Effect) => Effect /** - * The `mapError` function is used to transform or modify the error - * produced by an effect, without affecting its success value. + * Transforms the failure value of an effect without changing its success value. * - * This function is helpful when you want to enhance the error with additional - * information, change the error type, or apply custom error handling while - * keeping the original behavior of the effect's success values intact. It only - * operates on the error channel and leaves the success channel unchanged. + * **When to use** * - * @see {@link map} for a version that operates on the success channel. - * @see {@link mapBoth} for a version that operates on both channels. - * @see {@link orElseFail} if you want to replace the error with a new one. + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. + * + * **Details** + * + * Only the failure channel is transformed. The success channel and requirements + * are preserved. + * + * **Example** (Transforming the error channel) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -5926,8 +6093,11 @@ export const mapError: { * ) * ``` * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapBoth} for a version that operates on both channels. + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (self: Effect, f: (e: E) => E2): Effect } = internal.mapError @@ -5935,6 +6105,11 @@ export const mapError: { /** * Applies transformations to both the success and error channels of an effect. * + * **When to use** + * + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. + * * **Details** * * This function takes two map functions as arguments: one for the error channel @@ -5942,7 +6117,8 @@ export const mapError: { * the error and the success values without altering the overall success or * failure status of the effect. * - * @example + * **Example** (Transforming success and failure channels) + * * ```ts * import { Data, Effect } from "effect" * @@ -5963,13 +6139,18 @@ export const mapError: { * @see {@link map} for a version that operates on the success channel. * @see {@link mapError} for a version that operates on the error channel. * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapBoth: { /** * Applies transformations to both the success and error channels of an effect. * + * **When to use** + * + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. + * * **Details** * * This function takes two map functions as arguments: one for the error channel @@ -5977,7 +6158,8 @@ export const mapBoth: { * the error and the success values without altering the overall success or * failure status of the effect. * - * @example + * **Example** (Transforming success and failure channels) + * * ```ts * import { Data, Effect } from "effect" * @@ -5998,8 +6180,8 @@ export const mapBoth: { * @see {@link map} for a version that operates on the success channel. * @see {@link mapError} for a version that operates on the error channel. * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 } @@ -6007,6 +6189,11 @@ export const mapBoth: { /** * Applies transformations to both the success and error channels of an effect. * + * **When to use** + * + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. + * * **Details** * * This function takes two map functions as arguments: one for the error channel @@ -6014,7 +6201,8 @@ export const mapBoth: { * the error and the success values without altering the overall success or * failure status of the effect. * - * @example + * **Example** (Transforming success and failure channels) + * * ```ts * import { Data, Effect } from "effect" * @@ -6035,8 +6223,8 @@ export const mapBoth: { * @see {@link map} for a version that operates on the success channel. * @see {@link mapError} for a version that operates on the error channel. * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( self: Effect, @@ -6045,23 +6233,17 @@ export const mapBoth: { } = internal.mapBoth /** - * Converts an effect's failure into a fiber termination, removing the error from the effect's type. + * Converts typed failures from the error channel into defects, removing the + * error type from the returned effect. * - * **When to Use* + * **When to use** * - * Use `orDie` when failures should be treated as unrecoverable defects and no error handling is required. + * Use when you need to turn an `Effect` typed failure that represents an + * unrecoverable bug or invalid state into a defect. * - * **Details** - * - * The `orDie` function is used when you encounter errors that you do not want to handle or recover from. - * It removes the error type from the effect and ensures that any failure will terminate the fiber. - * This is useful for propagating failures as defects, signaling that they should not be handled within the effect. + * **Example** (Converting typed failures into defects) * - * @see {@link orDieWith} if you need to customize the error. - * - * @example * ```ts - * // Title: Propagating an Error as a Defect * import { Data, Effect } from "effect" * * class DivideByZeroError extends Data.TaggedError("DivideByZeroError")<{}> {} @@ -6081,21 +6263,23 @@ export const mapBoth: { * // ...stack trace... * ``` * + * @category converting failures to defects * @since 2.0.0 - * @category Converting Failures to Defects */ export const orDie: (self: Effect) => Effect = internal.orDie /** - * The `tapError` function executes an effectful operation to inspect the - * failure of an effect without modifying it. + * Runs an effectful operation when the source effect fails, while preserving + * the original failure when the operation succeeds. + * + * **Details** + * + * Use this for logging, metrics, or other failure-side observations. If the + * operation passed to `tapError` fails, that error is also represented in the + * returned effect's error channel. * - * This function is useful when you want to perform some side effect (like - * logging or tracking) on the failure of an effect, but without changing the - * result of the effect itself. The error remains in the effect's error channel, - * while the operation you provide can inspect or act on it. + * **Example** (Running effects on failure) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6113,20 +6297,22 @@ export const orDie: (self: Effect) => Effect = in * // expected error: NetworkError * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapError: { /** - * The `tapError` function executes an effectful operation to inspect the - * failure of an effect without modifying it. + * Runs an effectful operation when the source effect fails, while preserving + * the original failure when the operation succeeds. + * + * **Details** * - * This function is useful when you want to perform some side effect (like - * logging or tracking) on the failure of an effect, but without changing the - * result of the effect itself. The error remains in the effect's error channel, - * while the operation you provide can inspect or act on it. + * Use this for logging, metrics, or other failure-side observations. If the + * operation passed to `tapError` fails, that error is also represented in the + * returned effect's error channel. + * + * **Example** (Running effects on failure) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6144,20 +6330,22 @@ export const tapError: { * // expected error: NetworkError * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (e: NoInfer) => Effect): (self: Effect) => Effect /** - * The `tapError` function executes an effectful operation to inspect the - * failure of an effect without modifying it. + * Runs an effectful operation when the source effect fails, while preserving + * the original failure when the operation succeeds. + * + * **Details** + * + * Use this for logging, metrics, or other failure-side observations. If the + * operation passed to `tapError` fails, that error is also represented in the + * returned effect's error channel. * - * This function is useful when you want to perform some side effect (like - * logging or tracking) on the failure of an effect, but without changing the - * result of the effect itself. The error remains in the effect's error channel, - * while the operation you provide can inspect or act on it. + * **Example** (Running effects on failure) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6175,8 +6363,8 @@ export const tapError: { * // expected error: NetworkError * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (e: E) => Effect): Effect } = internal.tapError @@ -6184,10 +6372,14 @@ export const tapError: { /** * Runs an effectful handler when a failure's `_tag` matches. * - * Use this with tagged-union errors to perform side effects for a tag (or tag - * list) while preserving the original failure. + * **Details** + * + * Use this with tagged-union errors to perform side effects for one tag or a + * list of tags. When the handler succeeds, the original failure is preserved; + * if the handler fails, its error is also included in the returned effect. + * + * **Example** (Running effects for tagged failures) * - * @example * ```ts * import { Console, Data, Effect } from "effect" * @@ -6211,17 +6403,21 @@ export const tapError: { * // expected error: 504 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapErrorTag: { /** * Runs an effectful handler when a failure's `_tag` matches. * - * Use this with tagged-union errors to perform side effects for a tag (or tag - * list) while preserving the original failure. + * **Details** + * + * Use this with tagged-union errors to perform side effects for one tag or a + * list of tags. When the handler succeeds, the original failure is preserved; + * if the handler fails, its error is also included in the returned effect. + * + * **Example** (Running effects for tagged failures) * - * @example * ```ts * import { Console, Data, Effect } from "effect" * @@ -6245,8 +6441,8 @@ export const tapErrorTag: { * // expected error: 504 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ | Arr.NonEmptyReadonlyArray>, E, A1, E1, R1>( k: K, @@ -6255,10 +6451,14 @@ export const tapErrorTag: { /** * Runs an effectful handler when a failure's `_tag` matches. * - * Use this with tagged-union errors to perform side effects for a tag (or tag - * list) while preserving the original failure. + * **Details** + * + * Use this with tagged-union errors to perform side effects for one tag or a + * list of tags. When the handler succeeds, the original failure is preserved; + * if the handler fails, its error is also included in the returned effect. + * + * **Example** (Running effects for tagged failures) * - * @example * ```ts * import { Console, Data, Effect } from "effect" * @@ -6282,8 +6482,8 @@ export const tapErrorTag: { * // expected error: 504 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ < A, @@ -6301,21 +6501,22 @@ export const tapErrorTag: { } = internal.tapErrorTag /** - * The `tapCause` function allows you to inspect the complete cause - * of an error, including failures and defects. + * Runs an effectful operation with the full `Cause` when the source effect + * fails. + * + * **When to use** * - * This function is helpful when you need to log, monitor, or handle specific - * error causes in your effects. It gives you access to the full error cause, - * whether it's a failure, defect, or other exceptional conditions, without - * altering the error or the overall result of the effect. + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * Use this to log or inspect typed failures, defects, and interruptions. When + * the operation succeeds, the original cause is preserved. If the operation + * fails, its error is also represented in the returned effect. * - * - `Effect.tapErrorCause` + * **Example** (Observing full failure causes) * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6331,26 +6532,27 @@ export const tapErrorTag: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const tapCause: { /** - * The `tapCause` function allows you to inspect the complete cause - * of an error, including failures and defects. + * Runs an effectful operation with the full `Cause` when the source effect + * fails. + * + * **When to use** * - * This function is helpful when you need to log, monitor, or handle specific - * error causes in your effects. It gives you access to the full error cause, - * whether it's a failure, defect, or other exceptional conditions, without - * altering the error or the overall result of the effect. + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * Use this to log or inspect typed failures, defects, and interruptions. When + * the operation succeeds, the original cause is preserved. If the operation + * fails, its error is also represented in the returned effect. * - * - `Effect.tapErrorCause` + * **Example** (Observing full failure causes) * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6366,26 +6568,27 @@ export const tapCause: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ (f: (cause: Cause.Cause>) => Effect): (self: Effect) => Effect /** - * The `tapCause` function allows you to inspect the complete cause - * of an error, including failures and defects. + * Runs an effectful operation with the full `Cause` when the source effect + * fails. + * + * **When to use** * - * This function is helpful when you need to log, monitor, or handle specific - * error causes in your effects. It gives you access to the full error cause, - * whether it's a failure, defect, or other exceptional conditions, without - * altering the error or the overall result of the effect. + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * Use this to log or inspect typed failures, defects, and interruptions. When + * the operation succeeds, the original cause is preserved. If the operation + * fails, its error is also represented in the returned effect. * - * - `Effect.tapErrorCause` + * **Example** (Observing full failure causes) * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6401,20 +6604,23 @@ export const tapCause: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ (self: Effect, f: (cause: Cause.Cause) => Effect): Effect } = internal.tapCause /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause matches a predicate. + * + * **Details** * * This function allows you to tap into the cause of an effect's failure only when * the cause matches a specific predicate. This is useful for conditional logging, * monitoring, or other side effects based on the type of failure. * - * @example + * **Example** (Observing selected failure causes) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6432,18 +6638,21 @@ export const tapCause: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const tapCauseIf: { /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause matches a predicate. + * + * **Details** * * This function allows you to tap into the cause of an effect's failure only when * the cause matches a specific predicate. This is useful for conditional logging, * monitoring, or other side effects based on the type of failure. * - * @example + * **Example** (Observing selected failure causes) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6461,21 +6670,24 @@ export const tapCauseIf: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ ( predicate: Predicate.Predicate>, f: (cause: Cause.Cause) => Effect ): (self: Effect) => Effect /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause matches a predicate. + * + * **Details** * * This function allows you to tap into the cause of an effect's failure only when * the cause matches a specific predicate. This is useful for conditional logging, * monitoring, or other side effects based on the type of failure. * - * @example + * **Example** (Observing selected failure causes) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6493,8 +6705,8 @@ export const tapCauseIf: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ ( self: Effect, @@ -6504,27 +6716,75 @@ export const tapCauseIf: { } = internal.tapCauseIf /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause passes a filter. + * + * **When to use** + * + * 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** + * + * A successful filter result runs the side effect with the selected value and + * original cause. A failed filter result skips the side effect and preserves the + * original cause. + * + * @see {@link tapCauseIf} for selecting causes with a boolean predicate + * @see {@link tapCause} for observing every failure cause + * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them + * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const tapCauseFilter: { /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause passes a filter. + * + * **When to use** + * + * 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** * + * A successful filter result runs the side effect with the selected value and + * original cause. A failed filter result skips the side effect and preserves the + * original cause. + * + * @see {@link tapCauseIf} for selecting causes with a boolean predicate + * @see {@link tapCause} for observing every failure cause + * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them + * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ >( filter: Filter.Filter, EB, X>, f: (a: EB, cause: Cause.Cause) => Effect ): (self: Effect) => Effect /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause passes a filter. + * + * **When to use** + * + * 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** + * + * A successful filter result runs the side effect with the selected value and + * original cause. A failed filter result skips the side effect and preserves the + * original cause. + * + * @see {@link tapCauseIf} for selecting causes with a boolean predicate + * @see {@link tapCause} for observing every failure cause + * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ >( self: Effect, @@ -6534,22 +6794,17 @@ export const tapCauseFilter: { } = internal.tapCauseFilter /** - * Inspect severe errors or defects (non-recoverable failures) in an effect. + * Runs an effectful operation when the source effect dies with a defect. * * **Details** * - * This function is specifically designed to handle and inspect defects, which - * are critical failures in your program, such as unexpected runtime exceptions - * or system-level errors. Unlike normal recoverable errors, defects typically - * indicate serious issues that cannot be addressed through standard error - * handling. + * Use this for diagnostics such as logging unexpected thrown exceptions or + * values passed to `die`. Recoverable failures are not handled. When the + * operation succeeds, the original defect is preserved; if the operation fails, + * its error is also represented in the returned effect. * - * When a defect occurs in an effect, the function you provide to this function - * will be executed, allowing you to log, monitor, or handle the defect in some - * way. Importantly, this does not alter the main result of the effect. If no - * defect occurs, the effect behaves as if this function was not used. + * **Example** (Observing defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6582,27 +6837,22 @@ export const tapCauseFilter: { * // ... stack trace ... * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapDefect: { /** - * Inspect severe errors or defects (non-recoverable failures) in an effect. + * Runs an effectful operation when the source effect dies with a defect. * * **Details** * - * This function is specifically designed to handle and inspect defects, which - * are critical failures in your program, such as unexpected runtime exceptions - * or system-level errors. Unlike normal recoverable errors, defects typically - * indicate serious issues that cannot be addressed through standard error - * handling. + * Use this for diagnostics such as logging unexpected thrown exceptions or + * values passed to `die`. Recoverable failures are not handled. When the + * operation succeeds, the original defect is preserved; if the operation fails, + * its error is also represented in the returned effect. * - * When a defect occurs in an effect, the function you provide to this function - * will be executed, allowing you to log, monitor, or handle the defect in some - * way. Importantly, this does not alter the main result of the effect. If no - * defect occurs, the effect behaves as if this function was not used. + * **Example** (Observing defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6635,27 +6885,22 @@ export const tapDefect: { * // ... stack trace ... * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (defect: unknown) => Effect): (self: Effect) => Effect /** - * Inspect severe errors or defects (non-recoverable failures) in an effect. + * Runs an effectful operation when the source effect dies with a defect. * * **Details** * - * This function is specifically designed to handle and inspect defects, which - * are critical failures in your program, such as unexpected runtime exceptions - * or system-level errors. Unlike normal recoverable errors, defects typically - * indicate serious issues that cannot be addressed through standard error - * handling. + * Use this for diagnostics such as logging unexpected thrown exceptions or + * values passed to `die`. Recoverable failures are not handled. When the + * operation succeeds, the original defect is preserved; if the operation fails, + * its error is also represented in the returned effect. * - * When a defect occurs in an effect, the function you provide to this function - * will be executed, allowing you to log, monitor, or handle the defect in some - * way. Importantly, this does not alter the main result of the effect. If no - * defect occurs, the effect behaves as if this function was not used. + * **Example** (Observing defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6688,8 +6933,8 @@ export const tapDefect: { * // ... stack trace ... * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (defect: unknown) => Effect): Effect } = internal.tapDefect @@ -6697,9 +6942,12 @@ export const tapDefect: { /** * Retries an effect until it succeeds, discarding failures. * + * **Details** + * * Yields between attempts so other fibers can run. * - * @example + * **Example** (Retrying until success) + * * ```ts * import { Console, Effect } from "effect" * @@ -6724,8 +6972,8 @@ export const tapDefect: { * // Ready * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const eventually: (self: Effect) => Effect = internal.eventually @@ -6734,31 +6982,16 @@ export const eventually: (self: Effect) => Effect // ----------------------------------------------------------------------------- /** - * @since 2.0.0 - * @category Error Handling - * @example - * ```ts - * import type { Effect } from "effect" + * Type helpers for retrying effects. * - * // Retry namespace contains types for retry operations - * declare const effect: Effect.Effect - * declare const options: Effect.Retry.Options - * // Use Effect.retry with these types for retrying failed effects - * ``` + * @since 2.0.0 */ export declare namespace Retry { /** - * @since 2.0.0 - * @category Error Handling - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the result type of `Effect.retry` from the original effect and retry options. * - * // Return type for retry operations with specific options - * declare const options: Effect.Retry.Options - * type RetryResult = Effect.Retry.Return - * // Result: Effect with retried operation result types - * ``` + * @category error handling + * @since 2.0.0 */ export type Return> = Effect< A, @@ -6784,20 +7017,10 @@ export declare namespace Retry { : never /** - * @since 2.0.0 - * @category Error Handling - * @example - * ```ts - * import { Schedule } from "effect" - * import type { Effect } from "effect" + * Options that control whether and how a failing effect is retried. * - * // Options for configuring retry behavior - * const retryOptions: Effect.Retry.Options = { - * times: 3, - * schedule: Schedule.exponential("100 millis"), - * while: (error) => error.message !== "STOP" - * } - * ``` + * @category error handling + * @since 2.0.0 */ export interface Options { while?: ((error: E) => boolean | Effect) | undefined @@ -6808,27 +7031,30 @@ export declare namespace Retry { } /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -6853,33 +7079,35 @@ export declare namespace Retry { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const retry: { /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -6904,33 +7132,35 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ >(options: O): (self: Effect) => Retry.Return /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -6955,33 +7185,35 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (policy: Schedule, Error, Env>): (self: Effect) => Effect /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -7006,9 +7238,8 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( builder: ( @@ -7016,27 +7247,30 @@ export const retry: { ) => Schedule, Error, Env> ): (self: Effect) => Effect /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -7061,33 +7295,35 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ >(self: Effect, options: O): Retry.Return /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -7112,33 +7348,35 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (self: Effect, policy: Schedule, Error, Env>): Effect /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -7163,9 +7401,8 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( self: Effect, @@ -7178,6 +7415,11 @@ export const retry: { /** * Retries a failing effect and runs a fallback effect if retries are exhausted. * + * **When to use** + * + * Use when you want to handle failures gracefully by specifying an alternative + * action after repeated failures. + * * **Details** * * The `Effect.retryOrElse` function attempts to retry a failing effect multiple @@ -7186,14 +7428,8 @@ export const retry: { * If the retries are exhausted and the effect still fails, it runs a fallback * effect instead. * - * **When to Use** - * - * This function is useful when you want to handle failures gracefully by - * specifying an alternative action after repeated failures. + * **Example** (Falling back after retries are exhausted) * - * @see {@link retry} for a version that does not run a fallback effect. - * - * @example * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -7228,13 +7464,19 @@ export const retry: { * // Network data * ``` * + * @see {@link retry} for a version that does not run a fallback effect. + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const retryOrElse: { /** * Retries a failing effect and runs a fallback effect if retries are exhausted. * + * **When to use** + * + * Use when you want to handle failures gracefully by specifying an alternative + * action after repeated failures. + * * **Details** * * The `Effect.retryOrElse` function attempts to retry a failing effect multiple @@ -7243,14 +7485,8 @@ export const retryOrElse: { * If the retries are exhausted and the effect still fails, it runs a fallback * effect instead. * - * **When to Use** - * - * This function is useful when you want to handle failures gracefully by - * specifying an alternative action after repeated failures. - * - * @see {@link retry} for a version that does not run a fallback effect. + * **Example** (Falling back after retries are exhausted) * - * @example * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -7285,8 +7521,9 @@ export const retryOrElse: { * // Network data * ``` * + * @see {@link retry} for a version that does not run a fallback effect. + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( policy: Schedule, E1, R1>, @@ -7295,6 +7532,11 @@ export const retryOrElse: { /** * Retries a failing effect and runs a fallback effect if retries are exhausted. * + * **When to use** + * + * Use when you want to handle failures gracefully by specifying an alternative + * action after repeated failures. + * * **Details** * * The `Effect.retryOrElse` function attempts to retry a failing effect multiple @@ -7303,14 +7545,8 @@ export const retryOrElse: { * If the retries are exhausted and the effect still fails, it runs a fallback * effect instead. * - * **When to Use** - * - * This function is useful when you want to handle failures gracefully by - * specifying an alternative action after repeated failures. + * **Example** (Falling back after retries are exhausted) * - * @see {@link retry} for a version that does not run a fallback effect. - * - * @example * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -7345,8 +7581,9 @@ export const retryOrElse: { * // Network data * ``` * + * @see {@link retry} for a version that does not run a fallback effect. + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( self: Effect, @@ -7356,19 +7593,16 @@ export const retryOrElse: { } = internalSchedule.retryOrElse /** - * The `sandbox` function transforms an effect by exposing the full cause - * of any error, defect, or fiber interruption that might occur during its - * execution. It changes the error channel of the effect to include detailed - * information about the cause, which is wrapped in a `Cause` type. - * - * This function is useful when you need access to the complete underlying cause - * of failures, defects, or interruptions, enabling more detailed error - * handling. Once you apply `sandbox`, you can use operators like - * {@link catchAll} and {@link catchTags} to handle specific error conditions. - * If necessary, you can revert the sandboxing operation with {@link unsandbox} - * to return to the original error handling behavior. - * - * @example + * Exposes an effect's full failure cause in the error channel as `Cause`. + * + * **Details** + * + * Use `sandbox` when downstream error handling needs to distinguish typed + * failures, defects, and interruptions. Use `unsandbox` to restore the original + * typed error channel after cause-level handling. + * + * **Example** (Exposing failures as causes) + * * ```ts * import { Cause, Effect } from "effect" * @@ -7384,10 +7618,8 @@ export const retryOrElse: { * // Output: "Caught cause: Something went wrong" * ``` * - * @see {@link unsandbox} to restore the original error handling. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const sandbox: ( self: Effect @@ -7396,18 +7628,19 @@ export const sandbox: ( /** * Discards both the success and failure values of an effect. * - * **When to Use** + * **When to use** + * + * Use when an effect should run for its side effects while both success and + * failure values are discarded. * - * `ignore` allows you to run an effect without caring about its result, whether - * it succeeds or fails. This is useful when you only care about the side - * effects of the effect and do not need to handle or process its outcome. + * **Details** * * Use the `log` option to emit the full {@link Cause} when the effect fails, * and `message` to prepend a custom log message. * - * @example + * **Example** (Discarding success and failure values) + * * ```ts - * // Title: Using Effect.ignore to Discard Values * import { Effect } from "effect" * * // ┌─── Effect @@ -7419,9 +7652,9 @@ export const sandbox: ( * const program = task.pipe(Effect.ignore) * ``` * - * @example + * **Example** (Logging failures while ignoring results) + * * ```ts - * // Title: Logging failures while ignoring results * import { Effect } from "effect" * * const task = Effect.fail("Uh oh!") @@ -7430,14 +7663,8 @@ export const sandbox: ( * const programWarn = task.pipe(Effect.ignore({ log: "Warn", message: "Ignoring task failure" })) * ``` * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Effect.ignoreLogged` - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const ignore: < Arg extends Effect | { @@ -7459,10 +7686,18 @@ 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, * and `message` to prepend a custom log message. * - * @example + * **Example** (Ignoring failures and logging causes) + * * ```ts * import { Effect } from "effect" * @@ -7472,8 +7707,8 @@ export const ignore: < * const programLog = task.pipe(Effect.ignoreCause({ log: true, message: "Ignoring failure cause" })) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const ignoreCause: < Arg extends Effect | { @@ -7493,16 +7728,19 @@ export const ignoreCause: < : (self: Effect) => Effect = internal.ignoreCause /** - * Apply an `ExecutionPlan` to an effect, retrying with step-provided resources + * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index), * and retry timing is derived per step (the first attempt uses the remaining * attempts schedule; later retries apply the step schedule at least once). * - * @example + * **Example** (Retrying with an execution plan) + * * ```ts - * import { Effect, ExecutionPlan, Layer, Context } from "effect" + * import { Context, Effect, ExecutionPlan, Layer } from "effect" * * const Endpoint = Context.Service<{ url: string }>("Endpoint") * @@ -7522,21 +7760,24 @@ export const ignoreCause: < * const program = Effect.withExecutionPlan(fetchUrl, plan) * ``` * + * @category fallback * @since 3.16.0 - * @category Fallback */ export const withExecutionPlan: { /** - * Apply an `ExecutionPlan` to an effect, retrying with step-provided resources + * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index), * and retry timing is derived per step (the first attempt uses the remaining * attempts schedule; later retries apply the step schedule at least once). * - * @example + * **Example** (Retrying with an execution plan) + * * ```ts - * import { Effect, ExecutionPlan, Layer, Context } from "effect" + * import { Context, Effect, ExecutionPlan, Layer } from "effect" * * const Endpoint = Context.Service<{ url: string }>("Endpoint") * @@ -7556,8 +7797,8 @@ export const withExecutionPlan: { * const program = Effect.withExecutionPlan(fetchUrl, plan) * ``` * + * @category fallback * @since 3.16.0 - * @category Fallback */ ( plan: ExecutionPlan<{ provides: Provides; input: Input; error: PlanE; requirements: PlanR }> @@ -7565,16 +7806,19 @@ export const withExecutionPlan: { effect: Effect ) => Effect | PlanR> /** - * Apply an `ExecutionPlan` to an effect, retrying with step-provided resources + * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index), * and retry timing is derived per step (the first attempt uses the remaining * attempts schedule; later retries apply the step schedule at least once). * - * @example + * **Example** (Retrying with an execution plan) + * * ```ts - * import { Effect, ExecutionPlan, Layer, Context } from "effect" + * import { Context, Effect, ExecutionPlan, Layer } from "effect" * * const Endpoint = Context.Service<{ url: string }>("Endpoint") * @@ -7594,8 +7838,8 @@ export const withExecutionPlan: { * const program = Effect.withExecutionPlan(fetchUrl, plan) * ``` * + * @category fallback * @since 3.16.0 - * @category Fallback */ ( effect: Effect, @@ -7606,11 +7850,13 @@ export const withExecutionPlan: { /** * Runs an effect and reports any errors to the configured `ErrorReporter`s. * + * **Details** + * * If the `defectsOnly` option is set to `true`, only defects (unrecoverable * errors) will be reported, while regular failures will be ignored. * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const withErrorReporting: < Arg extends Effect | { readonly defectsOnly?: boolean | undefined } | undefined = { @@ -7627,23 +7873,18 @@ export const withErrorReporting: < // ----------------------------------------------------------------------------- /** - * Replaces the original failure with a success value, ensuring the effect - * cannot fail. + * Recovers from a typed failure by producing a fallback success value. * - * `orElseSucceed` allows you to replace the failure of an effect with a - * success value. If the effect fails, it will instead succeed with the provided - * value, ensuring the effect always completes successfully. This is useful when - * you want to guarantee a successful result regardless of whether the original - * effect failed. + * **Details** + * + * If the source effect succeeds, its value is preserved. If it fails in the + * error channel, `orElseSucceed` evaluates the fallback and succeeds with that + * value, removing the typed error from the returned effect. * - * The function ensures that any failure is effectively "swallowed" and replaced - * by a successful value, which can be helpful for providing default values in - * case of failure. + * Defects and interruptions are not recovered by this operator. * - * **Important**: This function only applies to failed effects. If the effect - * already succeeds, it will remain unchanged. + * **Example** (Replacing failures with a value) * - * @example * ```ts * import { Effect } from "effect" * @@ -7664,8 +7905,8 @@ export const withErrorReporting: < * // { _id: 'Exit', _tag: 'Success', value: 18 } * ``` * + * @category fallback * @since 2.0.0 - * @category Fallback */ export const orElseSucceed: { // ----------------------------------------------------------------------------- @@ -7673,23 +7914,18 @@ export const orElseSucceed: { // ----------------------------------------------------------------------------- /** - * Replaces the original failure with a success value, ensuring the effect - * cannot fail. + * Recovers from a typed failure by producing a fallback success value. + * + * **Details** * - * `orElseSucceed` allows you to replace the failure of an effect with a - * success value. If the effect fails, it will instead succeed with the provided - * value, ensuring the effect always completes successfully. This is useful when - * you want to guarantee a successful result regardless of whether the original - * effect failed. + * If the source effect succeeds, its value is preserved. If it fails in the + * error channel, `orElseSucceed` evaluates the fallback and succeeds with that + * value, removing the typed error from the returned effect. * - * The function ensures that any failure is effectively "swallowed" and replaced - * by a successful value, which can be helpful for providing default values in - * case of failure. + * Defects and interruptions are not recovered by this operator. * - * **Important**: This function only applies to failed effects. If the effect - * already succeeds, it will remain unchanged. + * **Example** (Replacing failures with a value) * - * @example * ```ts * import { Effect } from "effect" * @@ -7710,8 +7946,8 @@ export const orElseSucceed: { * // { _id: 'Exit', _tag: 'Success', value: 18 } * ``` * + * @category fallback * @since 2.0.0 - * @category Fallback */ (evaluate: LazyArg): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -7719,23 +7955,18 @@ export const orElseSucceed: { // ----------------------------------------------------------------------------- /** - * Replaces the original failure with a success value, ensuring the effect - * cannot fail. + * Recovers from a typed failure by producing a fallback success value. * - * `orElseSucceed` allows you to replace the failure of an effect with a - * success value. If the effect fails, it will instead succeed with the provided - * value, ensuring the effect always completes successfully. This is useful when - * you want to guarantee a successful result regardless of whether the original - * effect failed. + * **Details** + * + * If the source effect succeeds, its value is preserved. If it fails in the + * error channel, `orElseSucceed` evaluates the fallback and succeeds with that + * value, removing the typed error from the returned effect. * - * The function ensures that any failure is effectively "swallowed" and replaced - * by a successful value, which can be helpful for providing default values in - * case of failure. + * Defects and interruptions are not recovered by this operator. * - * **Important**: This function only applies to failed effects. If the effect - * already succeeds, it will remain unchanged. + * **Example** (Replacing failures with a value) * - * @example * ```ts * import { Effect } from "effect" * @@ -7756,8 +7987,8 @@ export const orElseSucceed: { * // { _id: 'Exit', _tag: 'Success', value: 18 } * ``` * + * @category fallback * @since 2.0.0 - * @category Fallback */ (self: Effect, evaluate: LazyArg): Effect } = internal.orElseSucceed @@ -7766,6 +7997,12 @@ export const orElseSucceed: { * Runs a sequence of effects and returns the result of the first successful * one. * + * **When to use** + * + * 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** * * This function executes the provided effects in sequence, stopping at the @@ -7776,13 +8013,8 @@ export const orElseSucceed: { * effect. If the collection is empty, the returned effect defects with an * `Error` whose message is `"Received an empty collection of effects"`. * - * **When to Use** + * **Example** (Trying alternatives until one succeeds) * - * Use `firstSuccessOf` when you have prioritized fallback strategies, such as - * attempting multiple APIs, reading configuration from several sources, or - * trying alternative resource locations in order. - * - * @example * ```ts * import { Effect } from "effect" * @@ -7802,8 +8034,8 @@ export const orElseSucceed: { * // Output: "secondary result" * ``` * + * @category fallback * @since 2.0.0 - * @category Fallback */ export const firstSuccessOf: >( effects: Iterable @@ -7817,17 +8049,25 @@ export const firstSuccessOf: >( * Adds a time limit to an effect, triggering a timeout if the effect exceeds * the duration. * + * **When to use** + * + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. + * + * **Details** + * * The `timeout` function allows you to specify a time limit for an * effect's execution. If the effect does not complete within the given time, a * `TimeoutException` is raised. This can be useful for controlling how long * your program waits for a task to finish, ensuring that it doesn't hang * indefinitely if the task takes too long. * - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted. + * + * **Example** (Failing when work takes too long) * - * @example * ```ts * import { Effect } from "effect" * @@ -7856,8 +8096,11 @@ export const firstSuccessOf: >( * // } * ``` * + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ export const timeout: { // ----------------------------------------------------------------------------- @@ -7868,17 +8111,25 @@ export const timeout: { * Adds a time limit to an effect, triggering a timeout if the effect exceeds * the duration. * + * **When to use** + * + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. + * + * **Details** + * * The `timeout` function allows you to specify a time limit for an * effect's execution. If the effect does not complete within the given time, a * `TimeoutException` is raised. This can be useful for controlling how long * your program waits for a task to finish, ensuring that it doesn't hang * indefinitely if the task takes too long. * - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted. + * + * **Example** (Failing when work takes too long) * - * @example * ```ts * import { Effect } from "effect" * @@ -7907,8 +8158,11 @@ export const timeout: { * // } * ``` * + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ (duration: Duration.Input): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -7919,17 +8173,25 @@ export const timeout: { * Adds a time limit to an effect, triggering a timeout if the effect exceeds * the duration. * + * **When to use** + * + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. + * + * **Details** + * * The `timeout` function allows you to specify a time limit for an * effect's execution. If the effect does not complete within the given time, a * `TimeoutException` is raised. This can be useful for controlling how long * your program waits for a task to finish, ensuring that it doesn't hang * indefinitely if the task takes too long. * - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted. + * + * **Example** (Failing when work takes too long) * - * @example * ```ts * import { Effect } from "effect" * @@ -7958,32 +8220,32 @@ export const timeout: { * // } * ``` * + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ (self: Effect, duration: Duration.Input): Effect } = internal.timeout /** - * Handles timeouts by returning an `Option` that represents either the result - * or a timeout. + * Runs an effect with a time limit and represents only the timeout case as + * `Option.none`. * - * The `timeoutOption` function provides a way to gracefully handle - * timeouts by wrapping the outcome of an effect in an `Option` type. If the - * effect completes within the specified time, it returns a `Some` containing - * the result. If the effect times out, it returns a `None`, allowing you to - * treat the timeout as a regular result instead of throwing an error. + * **When to use** * - * This is useful when you want to handle timeouts without causing the program - * to fail, making it easier to manage situations where you expect tasks might - * take too long but want to continue executing other tasks. + * Use when a timeout of an `Effect` should be handled as `Option.none`. * - * @see {@link timeout} for a version that raises a `TimeoutException`. - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Details** + * + * If the source effect succeeds before the timeout, the returned effect + * succeeds with `Option.some(value)`. If the timeout wins, the source effect is + * interrupted and the returned effect succeeds with `Option.none`. If the + * source effect fails before the timeout, that failure is preserved. + * + * **Example** (Returning None on timeout) * - * @example * ```ts * import { Effect } from "effect" * @@ -8010,30 +8272,30 @@ export const timeout: { * // ] * ``` * + * @see {@link timeout} for a version that raises a `TimeoutException`. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 3.1.0 - * @category Delays & Timeouts */ export const timeoutOption: { /** - * Handles timeouts by returning an `Option` that represents either the result - * or a timeout. + * Runs an effect with a time limit and represents only the timeout case as + * `Option.none`. * - * The `timeoutOption` function provides a way to gracefully handle - * timeouts by wrapping the outcome of an effect in an `Option` type. If the - * effect completes within the specified time, it returns a `Some` containing - * the result. If the effect times out, it returns a `None`, allowing you to - * treat the timeout as a regular result instead of throwing an error. + * **When to use** * - * This is useful when you want to handle timeouts without causing the program - * to fail, making it easier to manage situations where you expect tasks might - * take too long but want to continue executing other tasks. + * Use when a timeout of an `Effect` should be handled as `Option.none`. * - * @see {@link timeout} for a version that raises a `TimeoutException`. - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Details** + * + * If the source effect succeeds before the timeout, the returned effect + * succeeds with `Option.some(value)`. If the timeout wins, the source effect is + * interrupted and the returned effect succeeds with `Option.none`. If the + * source effect fails before the timeout, that failure is preserved. + * + * **Example** (Returning None on timeout) * - * @example * ```ts * import { Effect } from "effect" * @@ -8060,30 +8322,30 @@ export const timeoutOption: { * // ] * ``` * + * @see {@link timeout} for a version that raises a `TimeoutException`. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 3.1.0 - * @category Delays & Timeouts */ (duration: Duration.Input): (self: Effect) => Effect, E, R> /** - * Handles timeouts by returning an `Option` that represents either the result - * or a timeout. + * Runs an effect with a time limit and represents only the timeout case as + * `Option.none`. * - * The `timeoutOption` function provides a way to gracefully handle - * timeouts by wrapping the outcome of an effect in an `Option` type. If the - * effect completes within the specified time, it returns a `Some` containing - * the result. If the effect times out, it returns a `None`, allowing you to - * treat the timeout as a regular result instead of throwing an error. + * **When to use** * - * This is useful when you want to handle timeouts without causing the program - * to fail, making it easier to manage situations where you expect tasks might - * take too long but want to continue executing other tasks. + * Use when a timeout of an `Effect` should be handled as `Option.none`. * - * @see {@link timeout} for a version that raises a `TimeoutException`. - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Details** + * + * If the source effect succeeds before the timeout, the returned effect + * succeeds with `Option.some(value)`. If the timeout wins, the source effect is + * interrupted and the returned effect succeeds with `Option.none`. If the + * source effect fails before the timeout, that failure is preserved. + * + * **Example** (Returning None on timeout) * - * @example * ```ts * import { Effect } from "effect" * @@ -8110,8 +8372,11 @@ export const timeoutOption: { * // ] * ``` * + * @see {@link timeout} for a version that raises a `TimeoutException`. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 3.1.0 - * @category Delays & Timeouts */ (self: Effect, duration: Duration.Input): Effect, E, R> } = internal.timeoutOption @@ -8119,10 +8384,22 @@ export const timeoutOption: { /** * Applies a timeout to an effect, with a fallback effect executed if the timeout is reached. * - * This function is useful when you want to set a maximum duration for an operation - * and provide an alternative action if the timeout is exceeded. + * **When to use** + * + * Use when a timeout of an `Effect` should switch to a fallback effect. + * + * **Details** + * + * The fallback effect is created lazily by `orElse` and may introduce its own + * success, failure, and requirement types. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted before the fallback is + * run. + * + * **Example** (Falling back on timeout) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -8149,17 +8426,32 @@ export const timeoutOption: { * // Cached result * ``` * - * @since 3.1.0 - * @category Delays & Timeouts + * @see {@link timeout} for failing with a `TimeoutException`. + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * + * @category delays & timeouts + * @since 4.0.0 */ export const timeoutOrElse: { /** * Applies a timeout to an effect, with a fallback effect executed if the timeout is reached. * - * This function is useful when you want to set a maximum duration for an operation - * and provide an alternative action if the timeout is exceeded. + * **When to use** + * + * Use when a timeout of an `Effect` should switch to a fallback effect. + * + * **Details** + * + * The fallback effect is created lazily by `orElse` and may introduce its own + * success, failure, and requirement types. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted before the fallback is + * run. + * + * **Example** (Falling back on timeout) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -8186,8 +8478,11 @@ export const timeoutOrElse: { * // Cached result * ``` * - * @since 3.1.0 - * @category Delays & Timeouts + * @see {@link timeout} for failing with a `TimeoutException`. + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * + * @category delays & timeouts + * @since 4.0.0 */ ( options: { @@ -8198,10 +8493,22 @@ export const timeoutOrElse: { /** * Applies a timeout to an effect, with a fallback effect executed if the timeout is reached. * - * This function is useful when you want to set a maximum duration for an operation - * and provide an alternative action if the timeout is exceeded. + * **When to use** + * + * Use when a timeout of an `Effect` should switch to a fallback effect. + * + * **Details** + * + * The fallback effect is created lazily by `orElse` and may introduce its own + * success, failure, and requirement types. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted before the fallback is + * run. + * + * **Example** (Falling back on timeout) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -8228,8 +8535,11 @@ export const timeoutOrElse: { * // Cached result * ``` * - * @since 3.1.0 - * @category Delays & Timeouts + * @see {@link timeout} for failing with a `TimeoutException`. + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * + * @category delays & timeouts + * @since 4.0.0 */ ( self: Effect, @@ -8244,7 +8554,8 @@ export const timeoutOrElse: { * Returns an effect that is delayed from this effect by the specified * `Duration`. * - * @example + * **Example** (Delaying an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -8257,15 +8568,16 @@ export const timeoutOrElse: { * // Waits 1 second, then prints: "Delayed message" * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ export const delay: { /** * Returns an effect that is delayed from this effect by the specified * `Duration`. * - * @example + * **Example** (Delaying an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -8278,15 +8590,16 @@ export const delay: { * // Waits 1 second, then prints: "Delayed message" * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ (duration: Duration.Input): (self: Effect) => Effect /** * Returns an effect that is delayed from this effect by the specified * `Duration`. * - * @example + * **Example** (Delaying an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -8299,17 +8612,18 @@ export const delay: { * // Waits 1 second, then prints: "Delayed message" * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ (self: Effect, duration: Duration.Input): Effect } = internal.delay /** - * Returns an effect that suspends for the specified duration. This method is - * asynchronous, and does not actually block the fiber executing the effect. + * Returns an effect that suspends the current fiber for the specified duration + * without blocking a JavaScript thread. + * + * **Example** (Pausing without blocking) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -8324,18 +8638,21 @@ export const delay: { * // Output: "End" (after 2 seconds) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ export const sleep: (duration: Duration.Input) => Effect = internal.sleep /** - * Measures the runtime of an effect and returns the duration with its result. + * Returns the runtime duration of an effect together with its result. + * + * **Details** * * The original success, failure, or interruption is preserved; only the success * value is paired with the duration. * - * @example + * **Example** (Measuring execution time) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8345,8 +8662,8 @@ export const sleep: (duration: Duration.Input) => Effect = internal.sleep * }) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ export const timed: (self: Effect) => Effect<[duration: Duration.Duration, result: A], E, R> = internal.timed @@ -8356,27 +8673,22 @@ export const timed: (self: Effect) => Effect<[duration: Durati // ----------------------------------------------------------------------------- /** - * Races multiple effects and returns the first successful result. - * - * **Details** + * Runs multiple effects concurrently and returns the first successful result. * - * This function runs multiple effects concurrently and returns the result of - * the first one to succeed. If one effect succeeds, the others will be - * interrupted. + * **When to use** * - * If none of the effects succeed, the function will fail with the last error - * encountered. + * Use when early failures should be ignored until a success occurs + * or all effects fail. * - * **When to Use** + * **Details** * - * This is useful when you want to race multiple effects, but only care about - * the first one to succeed. It is commonly used in cases like timeouts, - * retries, or when you want to optimize for the faster response without - * worrying about the other effects. + * Early failures do not finish the race; `raceAll` keeps waiting until one + * effect succeeds or every effect has failed. When one effect succeeds, the + * remaining effects are interrupted. If every effect fails, the returned effect + * fails with a cause containing the collected failure reasons. * - * @see {@link race} for a version that handles only two effects. + * **Example** (Racing many effects) * - * @example * ```ts * import { Duration, Effect } from "effect" * @@ -8391,8 +8703,9 @@ export const timed: (self: Effect) => Effect<[duration: Durati * // Result: "Fast" (after ~100ms) * ``` * + * @see {@link race} for a version that handles only two effects. + * @category racing * @since 2.0.0 - * @category Racing */ export const raceAll: >( all: Iterable, @@ -8406,15 +8719,17 @@ export const raceAll: >( ) => Effect, Error, Services> = internal.raceAll /** - * Races multiple effects and returns the first successful result. + * Runs multiple effects concurrently and completes with the first effect to + * finish, whether it succeeds or fails. * * **Details** * - * Similar to `raceAll`, this function runs multiple effects concurrently - * and returns the result of the first one to succeed. If one effect succeeds, - * the others will be interrupted. + * After the first effect completes, all remaining effects are interrupted. Use + * `raceAll` when early failures should be ignored until a success occurs or + * all effects fail. + * + * **Example** (Taking the first settled result) * - * @example * ```ts * import { Duration, Effect } from "effect" * @@ -8429,8 +8744,8 @@ export const raceAll: >( * // Result: "First" (after ~200ms, even though effect2 completes first but fails) * ``` * + * @category racing * @since 4.0.0 - * @category Racing */ export const raceAllFirst: >( all: Iterable, @@ -8446,10 +8761,13 @@ export const raceAllFirst: >( /** * Races two effects and returns the first successful result. * + * **Details** + * * If one effect succeeds, the other is interrupted and `onWinner` can observe the * winning fiber. If both fail, the race fails. * - * @example + * **Example** (Racing two effects) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8465,17 +8783,20 @@ export const raceAllFirst: >( * // Output: winner: slow-success * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ export const race: { /** * Races two effects and returns the first successful result. * + * **Details** + * * If one effect succeeds, the other is interrupted and `onWinner` can observe the * winning fiber. If both fail, the race fails. * - * @example + * **Example** (Racing two effects) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8491,8 +8812,8 @@ export const race: { * // Output: winner: slow-success * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ ( that: Effect, @@ -8505,10 +8826,13 @@ export const race: { /** * Races two effects and returns the first successful result. * + * **Details** + * * If one effect succeeds, the other is interrupted and `onWinner` can observe the * winning fiber. If both fail, the race fails. * - * @example + * **Example** (Racing two effects) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8524,8 +8848,8 @@ export const race: { * // Output: winner: slow-success * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ ( self: Effect, @@ -8542,9 +8866,17 @@ 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. * - * @example + * **Example** (Observing the winning fiber) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8563,17 +8895,25 @@ export const race: { * // Output: failed: fast-fail * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ export const raceFirst: { /** * 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. * - * @example + * **Example** (Observing the winning fiber) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8592,8 +8932,8 @@ export const raceFirst: { * // Output: failed: fast-fail * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ ( that: Effect, @@ -8607,9 +8947,17 @@ export const raceFirst: { * 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. * - * @example + * **Example** (Observing the winning fiber) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8628,8 +8976,8 @@ export const raceFirst: { * // Output: failed: fast-fail * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ ( self: Effect, @@ -8650,7 +8998,8 @@ export const raceFirst: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8663,8 +9012,8 @@ export const raceFirst: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filter: { // ----------------------------------------------------------------------------- @@ -8675,7 +9024,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8688,8 +9038,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (refinement: Predicate.Refinement, B>): (elements: Iterable) => Effect> // ----------------------------------------------------------------------------- @@ -8700,7 +9050,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8713,8 +9064,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (predicate: Predicate.Predicate>): (elements: Iterable) => Effect> // ----------------------------------------------------------------------------- @@ -8725,7 +9076,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8738,8 +9090,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: (a: NoInfer, i: number) => Effect, @@ -8753,7 +9105,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8766,8 +9119,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (elements: Iterable, refinement: Predicate.Refinement): Effect> // ----------------------------------------------------------------------------- @@ -8778,7 +9131,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8791,8 +9145,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (elements: Iterable, predicate: Predicate.Predicate): Effect> // ----------------------------------------------------------------------------- @@ -8803,7 +9157,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8816,8 +9171,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( iterable: Iterable, @@ -8829,48 +9184,141 @@ export const filter: { /** * Filters and maps elements of an iterable with a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * + * @category filtering + * @since 2.0.0 */ export const filterMap: { /** * Filters and maps elements of an iterable with a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * + * @category filtering + * @since 2.0.0 */ (filter: Filter.Filter, B, X>): (elements: Iterable) => Effect> /** * Filters and maps elements of an iterable with a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * + * @category filtering + * @since 2.0.0 */ (elements: Iterable, filter: Filter.Filter, B, X>): Effect> } = internal.filterMap /** - * Effectfully filters and maps elements of an iterable with a `FilterEffect`. + * Filters and maps elements of an iterable effectfully with a `FilterEffect`. + * + * **When to use** + * + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * **Gotchas** + * + * With concurrent execution, successful values are collected in completion + * order, not input order. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filter} for keeping original elements with a predicate + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapEffect: { /** - * Effectfully filters and maps elements of an iterable with a `FilterEffect`. + * Filters and maps elements of an iterable effectfully with a `FilterEffect`. + * + * **When to use** + * + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * **Gotchas** + * + * With concurrent execution, successful values are collected in completion + * order, not input order. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filter} for keeping original elements with a predicate + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( filter: Filter.FilterEffect, B, X, E, R>, options?: { readonly concurrency?: Concurrency | undefined } ): (elements: Iterable) => Effect, E, R> /** - * Effectfully filters and maps elements of an iterable with a `FilterEffect`. + * Filters and maps elements of an iterable effectfully with a `FilterEffect`. + * + * **When to use** + * + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * **Gotchas** + * + * With concurrent execution, successful values are collected in completion + * order, not input order. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filter} for keeping original elements with a predicate + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( elements: Iterable, @@ -8882,6 +9330,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 @@ -8889,7 +9342,8 @@ export const filterMapEffect: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -8906,13 +9360,18 @@ export const filterMapEffect: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filterOrElse: { /** * 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 @@ -8920,7 +9379,8 @@ export const filterOrElse: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -8937,8 +9397,8 @@ export const filterOrElse: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( refinement: Predicate.Refinement, B>, @@ -8947,6 +9407,11 @@ export const filterOrElse: { /** * 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 @@ -8954,7 +9419,8 @@ export const filterOrElse: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -8971,8 +9437,8 @@ export const filterOrElse: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: Predicate.Predicate>, @@ -8981,6 +9447,11 @@ export const filterOrElse: { /** * 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 @@ -8988,7 +9459,8 @@ export const filterOrElse: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -9005,8 +9477,8 @@ export const filterOrElse: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Effect, @@ -9016,6 +9488,11 @@ export const filterOrElse: { /** * 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 @@ -9023,7 +9500,8 @@ export const filterOrElse: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -9040,8 +9518,8 @@ export const filterOrElse: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Effect, @@ -9053,15 +9531,43 @@ export const filterOrElse: { /** * Filters an effect with a `Filter`, providing an alternative effect on failure. * + * **When to use** + * + * Use when a successful effect value should be accepted and transformed by a + * `Filter`, while rejected values should continue with an alternative effect + * built from the filter failure. + * + * **Details** + * + * `Result.succeed` becomes the returned success value, and `Result.fail` is + * passed to `orElse`. + * + * @see {@link filterOrElse} for using a predicate and fallback effect + * @see {@link filterMapOrFail} for failing the effect when the filter fails + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapOrElse: { /** * Filters an effect with a `Filter`, providing an alternative effect on failure. * + * **When to use** + * + * Use when a successful effect value should be accepted and transformed by a + * `Filter`, while rejected values should continue with an alternative effect + * built from the filter failure. + * + * **Details** + * + * `Result.succeed` becomes the returned success value, and `Result.fail` is + * passed to `orElse`. + * + * @see {@link filterOrElse} for using a predicate and fallback effect + * @see {@link filterMapOrFail} for failing the effect when the filter fails + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( filter: Filter.Filter, B, X>, @@ -9070,8 +9576,22 @@ export const filterMapOrElse: { /** * Filters an effect with a `Filter`, providing an alternative effect on failure. * + * **When to use** + * + * Use when a successful effect value should be accepted and transformed by a + * `Filter`, while rejected values should continue with an alternative effect + * built from the filter failure. + * + * **Details** + * + * `Result.succeed` becomes the returned success value, and `Result.fail` is + * passed to `orElse`. + * + * @see {@link filterOrElse} for using a predicate and fallback effect + * @see {@link filterMapOrFail} for failing the effect when the filter fails + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Effect, @@ -9089,7 +9609,8 @@ export const filterMapOrElse: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9106,8 +9627,8 @@ export const filterMapOrElse: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filterOrFail: { /** @@ -9119,7 +9640,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9136,8 +9658,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( refinement: Predicate.Refinement, B>, @@ -9152,7 +9674,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9169,8 +9692,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: Predicate.Predicate>, @@ -9185,7 +9708,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9202,8 +9726,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (refinement: Predicate.Refinement, B>): (self: Effect) => Effect /** @@ -9215,7 +9739,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9232,8 +9757,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (predicate: Predicate.Predicate>): (self: Effect) => Effect /** @@ -9245,7 +9770,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9262,8 +9788,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Effect, @@ -9279,7 +9805,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9296,8 +9823,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Effect, @@ -9313,7 +9840,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9330,8 +9858,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Effect, refinement: Predicate.Refinement, B>): Effect /** @@ -9343,7 +9871,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9360,38 +9889,94 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Effect, predicate: Predicate.Predicate>): Effect } = internal.filterOrFail /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapOrFail: { /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. + * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (filter: Filter.Filter, B, X>, orFailWith: (x: X) => E2): (self: Effect) => Effect /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. + * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (filter: Filter.Filter, B, X>): (self: Effect) => Effect /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. + * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Effect, @@ -9399,10 +9984,24 @@ export const filterMapOrFail: { orFailWith: (x: X) => E2 ): Effect /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (self: Effect, filter: Filter.Filter): Effect } = internal.filterMapOrFail @@ -9412,22 +10011,23 @@ export const filterMapOrFail: { // ----------------------------------------------------------------------------- /** - * Conditionally executes an effect based on a boolean condition. + * Runs an effect conditionally based on the result of an effectful boolean + * condition. * - * **Details** + * **When to use** + * + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. * - * This function allows you to run an effect only if a given condition evaluates - * to `true`. If the condition is `true`, the effect is executed, and its result - * is wrapped in an `Option.some`. If the condition is `false`, the effect is - * skipped, and the result is `Option.none`. + * **Details** * - * **When to Use** + * The condition effect is evaluated first. If it succeeds with `true`, the + * source effect is run and its success value is wrapped in `Option.some`. If it + * succeeds with `false`, the source effect is skipped and the result is + * `Option.none`. If the condition effect fails, that failure is preserved. * - * This function is useful for scenarios where you need to dynamically decide - * whether to execute an effect based on runtime logic, while also representing - * the skipped case explicitly. + * **Example** (Conditionally running an effect) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -9443,11 +10043,8 @@ export const filterMapOrFail: { * // { _id: 'Option', _tag: 'Some', value: undefined } * ``` * - * @see {@link whenEffect} for a version that allows the condition to be an effect. - * @see {@link unless} for a version that executes the effect when the condition is `false`. - * + * @category conditional operators * @since 2.0.0 - * @category Conditional Operators */ export const when: { // ----------------------------------------------------------------------------- @@ -9455,22 +10052,23 @@ export const when: { // ----------------------------------------------------------------------------- /** - * Conditionally executes an effect based on a boolean condition. + * Runs an effect conditionally based on the result of an effectful boolean + * condition. * - * **Details** + * **When to use** + * + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. * - * This function allows you to run an effect only if a given condition evaluates - * to `true`. If the condition is `true`, the effect is executed, and its result - * is wrapped in an `Option.some`. If the condition is `false`, the effect is - * skipped, and the result is `Option.none`. + * **Details** * - * **When to Use** + * The condition effect is evaluated first. If it succeeds with `true`, the + * source effect is run and its success value is wrapped in `Option.some`. If it + * succeeds with `false`, the source effect is skipped and the result is + * `Option.none`. If the condition effect fails, that failure is preserved. * - * This function is useful for scenarios where you need to dynamically decide - * whether to execute an effect based on runtime logic, while also representing - * the skipped case explicitly. + * **Example** (Conditionally running an effect) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -9486,11 +10084,8 @@ export const when: { * // { _id: 'Option', _tag: 'Some', value: undefined } * ``` * - * @see {@link whenEffect} for a version that allows the condition to be an effect. - * @see {@link unless} for a version that executes the effect when the condition is `false`. - * + * @category conditional operators * @since 2.0.0 - * @category Conditional Operators */ (condition: Effect): (self: Effect) => Effect, E | E2, R | R2> // ----------------------------------------------------------------------------- @@ -9498,22 +10093,23 @@ export const when: { // ----------------------------------------------------------------------------- /** - * Conditionally executes an effect based on a boolean condition. + * Runs an effect conditionally based on the result of an effectful boolean + * condition. * - * **Details** + * **When to use** + * + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. * - * This function allows you to run an effect only if a given condition evaluates - * to `true`. If the condition is `true`, the effect is executed, and its result - * is wrapped in an `Option.some`. If the condition is `false`, the effect is - * skipped, and the result is `Option.none`. + * **Details** * - * **When to Use** + * The condition effect is evaluated first. If it succeeds with `true`, the + * source effect is run and its success value is wrapped in `Option.some`. If it + * succeeds with `false`, the source effect is skipped and the result is + * `Option.none`. If the condition effect fails, that failure is preserved. * - * This function is useful for scenarios where you need to dynamically decide - * whether to execute an effect based on runtime logic, while also representing - * the skipped case explicitly. + * **Example** (Conditionally running an effect) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -9529,11 +10125,8 @@ export const when: { * // { _id: 'Option', _tag: 'Some', value: undefined } * ``` * - * @see {@link whenEffect} for a version that allows the condition to be an effect. - * @see {@link unless} for a version that executes the effect when the condition is `false`. - * + * @category conditional operators * @since 2.0.0 - * @category Conditional Operators */ (self: Effect, condition: Effect): Effect, E | E2, R | R2> } = internal.when @@ -9546,6 +10139,11 @@ export const when: { * Handles both success and failure cases of an effect without performing side * effects. * + * **When to use** + * + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. + * * **Details** * * `match` lets you define custom handlers for both success and failure @@ -9553,16 +10151,9 @@ export const when: { * to process the result if the effect succeeds, or handle the error if the * effect fails. * - * **When to Use** + * **Example** (Matching success and failure values) * - * This is useful for structuring your code to respond differently to success or - * failure without triggering side effects. - * - * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -9592,8 +10183,9 @@ export const when: { * // Output: "failure: Uh oh!" * ``` * + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ export const match: { // ----------------------------------------------------------------------------- @@ -9604,6 +10196,11 @@ export const match: { * Handles both success and failure cases of an effect without performing side * effects. * + * **When to use** + * + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. + * * **Details** * * `match` lets you define custom handlers for both success and failure @@ -9611,16 +10208,9 @@ export const match: { * to process the result if the effect succeeds, or handle the error if the * effect fails. * - * **When to Use** - * - * This is useful for structuring your code to respond differently to success or - * failure without triggering side effects. - * - * @see {@link matchEffect} if you need to perform side effects in the handlers. + * **Example** (Matching success and failure values) * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -9650,8 +10240,9 @@ export const match: { * // Output: "failure: Uh oh!" * ``` * + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( options: { @@ -9667,6 +10258,11 @@ export const match: { * Handles both success and failure cases of an effect without performing side * effects. * + * **When to use** + * + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. + * * **Details** * * `match` lets you define custom handlers for both success and failure @@ -9674,16 +10270,9 @@ export const match: { * to process the result if the effect succeeds, or handle the error if the * effect fails. * - * **When to Use** + * **Example** (Matching success and failure values) * - * This is useful for structuring your code to respond differently to success or - * failure without triggering side effects. - * - * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -9713,8 +10302,9 @@ export const match: { * // Output: "failure: Uh oh!" * ``` * + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -9729,6 +10319,11 @@ export const match: { * Handles both success and failure cases of an effect without performing side * effects, with eager evaluation for resolved effects. * + * **When to use** + * + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. + * * **Details** * * `matchEager` works like `match` but provides better performance for resolved @@ -9736,13 +10331,8 @@ export const match: { * the handlers immediately without fiber scheduling. For unresolved effects, * it falls back to the regular `match` behavior. * - * **When to Use** + * **Example** (Pattern matching eagerly when possible) * - * Use this 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. - * - * @example * ```ts * import { Effect } from "effect" * @@ -9757,15 +10347,19 @@ export const match: { * * @see {@link match} for the non-eager version. * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @since 2.0.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ export const matchEager: { /** * Handles both success and failure cases of an effect without performing side * effects, with eager evaluation for resolved effects. * + * **When to use** + * + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. + * * **Details** * * `matchEager` works like `match` but provides better performance for resolved @@ -9773,13 +10367,8 @@ export const matchEager: { * the handlers immediately without fiber scheduling. For unresolved effects, * it falls back to the regular `match` behavior. * - * **When to Use** + * **Example** (Pattern matching eagerly when possible) * - * Use this 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. - * - * @example * ```ts * import { Effect } from "effect" * @@ -9794,9 +10383,8 @@ export const matchEager: { * * @see {@link match} for the non-eager version. * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @since 2.0.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ ( options: { @@ -9808,6 +10396,11 @@ export const matchEager: { * Handles both success and failure cases of an effect without performing side * effects, with eager evaluation for resolved effects. * + * **When to use** + * + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. + * * **Details** * * `matchEager` works like `match` but provides better performance for resolved @@ -9815,13 +10408,8 @@ export const matchEager: { * the handlers immediately without fiber scheduling. For unresolved effects, * it falls back to the regular `match` behavior. * - * **When to Use** + * **Example** (Pattern matching eagerly when possible) * - * Use this 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. - * - * @example * ```ts * import { Effect } from "effect" * @@ -9836,9 +10424,8 @@ export const matchEager: { * * @see {@link match} for the non-eager version. * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @since 2.0.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ ( self: Effect, @@ -9852,18 +10439,18 @@ export const matchEager: { /** * Handles failures by matching the cause of failure. * + * **When to use** + * + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. + * * **Details** * * The `matchCause` function allows you to handle failures with access to the * full cause of the failure within a fiber. * - * **When to Use** + * **Example** (Matching on success or failure causes) * - * 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. - * - * @example * ```ts * import { Cause, Effect } from "effect" * @@ -9881,26 +10468,25 @@ export const matchEager: { * @see {@link matchCauseEffect} if you need to perform side effects in the * handlers. * @see {@link match} if you don't need to handle the cause of the failure. - * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ export const matchCause: { /** * Handles failures by matching the cause of failure. * + * **When to use** + * + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. + * * **Details** * * The `matchCause` function allows you to handle failures with access to the * full cause of the failure within a fiber. * - * **When to Use** + * **Example** (Matching on success or failure causes) * - * 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. - * - * @example * ```ts * import { Cause, Effect } from "effect" * @@ -9918,9 +10504,8 @@ export const matchCause: { * @see {@link matchCauseEffect} if you need to perform side effects in the * handlers. * @see {@link match} if you don't need to handle the cause of the failure. - * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( options: { @@ -9931,18 +10516,18 @@ export const matchCause: { /** * Handles failures by matching the cause of failure. * + * **When to use** + * + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. + * * **Details** * * The `matchCause` function allows you to handle failures with access to the * full cause of the failure within a fiber. * - * **When to Use** + * **Example** (Matching on success or failure causes) * - * 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. - * - * @example * ```ts * import { Cause, Effect } from "effect" * @@ -9960,9 +10545,8 @@ export const matchCause: { * @see {@link matchCauseEffect} if you need to perform side effects in the * handlers. * @see {@link match} if you don't need to handle the cause of the failure. - * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -9976,19 +10560,19 @@ export const matchCause: { /** * Handles failures by matching the cause of failure with eager evaluation. * + * **When to use** + * + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. + * * **Details** * * `matchCauseEager` works like `matchCause` but provides better performance for resolved * effects by immediately applying the matching function instead of deferring it * through the effect pipeline. * - * **When to Use** + * **Example** (Eagerly matching already completed effects) * - * 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. - * - * @example * ```ts * import { Effect } from "effect" * @@ -9998,26 +10582,26 @@ export const matchCause: { * }) * ``` * - * @since 3.8.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ export const matchCauseEager: { /** * Handles failures by matching the cause of failure with eager evaluation. * + * **When to use** + * + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. + * * **Details** * * `matchCauseEager` works like `matchCause` but provides better performance for resolved * effects by immediately applying the matching function instead of deferring it * through the effect pipeline. * - * **When to Use** + * **Example** (Eagerly matching already completed effects) * - * 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. - * - * @example * ```ts * import { Effect } from "effect" * @@ -10027,8 +10611,8 @@ export const matchCauseEager: { * }) * ``` * - * @since 3.8.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ ( options: { @@ -10039,19 +10623,19 @@ export const matchCauseEager: { /** * Handles failures by matching the cause of failure with eager evaluation. * + * **When to use** + * + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. + * * **Details** * * `matchCauseEager` works like `matchCause` but provides better performance for resolved * effects by immediately applying the matching function instead of deferring it * through the effect pipeline. * - * **When to Use** + * **Example** (Eagerly matching already completed effects) * - * 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. - * - * @example * ```ts * import { Effect } from "effect" * @@ -10061,8 +10645,8 @@ export const matchCauseEager: { * }) * ``` * - * @since 3.8.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ ( self: Effect, @@ -10074,23 +10658,45 @@ export const matchCauseEager: { } = internal.matchCauseEager /** - * Eagerly handles success or failure with effectful handlers when the effect is already resolved. + * Handles success or failure eagerly with effectful handlers when the effect is already resolved. + * + * **When to use** + * + * Use when you need effectful success and cause-aware failure handlers for + * `Effect` inputs that may already be resolved. + * + * **Details** * * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like * {@link matchCauseEffect}. * + * @see {@link matchCauseEffect} for the non-eager effectful variant + * @see {@link matchCauseEager} for eager cause matching with pure handlers + * @see {@link matchEffect} for effectful matching on typed failures instead of full causes + * + * @category pattern matching * @since 4.0.0 - * @category Pattern Matching */ export const matchCauseEffectEager: { /** - * Eagerly handles success or failure with effectful handlers when the effect is already resolved. + * Handles success or failure eagerly with effectful handlers when the effect is already resolved. + * + * **When to use** + * + * Use when you need effectful success and cause-aware failure handlers for + * `Effect` inputs that may already be resolved. + * + * **Details** * * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like * {@link matchCauseEffect}. * + * @see {@link matchCauseEffect} for the non-eager effectful variant + * @see {@link matchCauseEager} for eager cause matching with pure handlers + * @see {@link matchEffect} for effectful matching on typed failures instead of full causes + * + * @category pattern matching * @since 4.0.0 - * @category Pattern Matching */ ( options: { @@ -10099,13 +10705,24 @@ export const matchCauseEffectEager: { } ): (self: Effect) => Effect /** - * Eagerly handles success or failure with effectful handlers when the effect is already resolved. + * Handles success or failure eagerly with effectful handlers when the effect is already resolved. + * + * **When to use** + * + * Use when you need effectful success and cause-aware failure handlers for + * `Effect` inputs that may already be resolved. + * + * **Details** * * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like * {@link matchCauseEffect}. * + * @see {@link matchCauseEffect} for the non-eager effectful variant + * @see {@link matchCauseEager} for eager cause matching with pure handlers + * @see {@link matchEffect} for effectful matching on typed failures instead of full causes + * + * @category pattern matching * @since 4.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -10119,6 +10736,11 @@ export const matchCauseEffectEager: { /** * Handles failures with access to the cause and allows performing side effects. * + * **When to use** + * + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. + * * **Details** * * The `matchCauseEffect` function works similarly to {@link matchCause}, but it @@ -10128,7 +10750,8 @@ export const matchCauseEffectEager: { * you to respond accordingly while performing side effects (like logging or * other operations). * - * @example + * **Example** (Effectfully matching on causes) + * * ```ts * import { Cause, Console, Data, Effect, Result } from "effect" * @@ -10166,13 +10789,18 @@ export const matchCauseEffectEager: { * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure. * @see {@link matchEffect} if you don't need to handle the cause of the failure. * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ export const matchCauseEffect: { /** * Handles failures with access to the cause and allows performing side effects. * + * **When to use** + * + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. + * * **Details** * * The `matchCauseEffect` function works similarly to {@link matchCause}, but it @@ -10182,7 +10810,8 @@ export const matchCauseEffect: { * you to respond accordingly while performing side effects (like logging or * other operations). * - * @example + * **Example** (Effectfully matching on causes) + * * ```ts * import { Cause, Console, Data, Effect, Result } from "effect" * @@ -10220,8 +10849,8 @@ export const matchCauseEffect: { * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure. * @see {@link matchEffect} if you don't need to handle the cause of the failure. * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( options: { @@ -10232,6 +10861,11 @@ export const matchCauseEffect: { /** * Handles failures with access to the cause and allows performing side effects. * + * **When to use** + * + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. + * * **Details** * * The `matchCauseEffect` function works similarly to {@link matchCause}, but it @@ -10241,7 +10875,8 @@ export const matchCauseEffect: { * you to respond accordingly while performing side effects (like logging or * other operations). * - * @example + * **Example** (Effectfully matching on causes) + * * ```ts * import { Cause, Console, Data, Effect, Result } from "effect" * @@ -10279,8 +10914,8 @@ export const matchCauseEffect: { * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure. * @see {@link matchEffect} if you don't need to handle the cause of the failure. * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -10292,25 +10927,22 @@ export const matchCauseEffect: { } = internal.matchCauseEffect /** - * Handles both success and failure cases of an effect, allowing for additional - * side effects. + * Handles both success and failure by running effectful handlers. * - * **Details** + * **When to use** * - * The `matchEffect` function is similar to {@link match}, but it enables you to - * perform side effects in the handlers for both success and failure outcomes. + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. * - * **When to Use** + * **Details** * - * This is useful when you need to execute additional actions, like logging or - * notifying users, based on whether an effect succeeds or fails. + * Use `matchEffect` when either branch needs to return an `Effect`, such as + * performing logging, recovery, notification, or other effectful work. The + * returned effect succeeds or fails according to the handler that is run. * - * @see {@link match} if you don't need side effects and only want to handle the - * result or failure. + * **Example** (Matching success and failure with effectful handlers) * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases with Side Effects * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -10349,30 +10981,29 @@ export const matchCauseEffect: { * // failure: Uh oh! * ``` * + * @see {@link match} if you don't need side effects and only want to handle the + * result or failure. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ export const matchEffect: { /** - * Handles both success and failure cases of an effect, allowing for additional - * side effects. + * Handles both success and failure by running effectful handlers. * - * **Details** + * **When to use** * - * The `matchEffect` function is similar to {@link match}, but it enables you to - * perform side effects in the handlers for both success and failure outcomes. + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. * - * **When to Use** + * **Details** * - * This is useful when you need to execute additional actions, like logging or - * notifying users, based on whether an effect succeeds or fails. + * Use `matchEffect` when either branch needs to return an `Effect`, such as + * performing logging, recovery, notification, or other effectful work. The + * returned effect succeeds or fails according to the handler that is run. * - * @see {@link match} if you don't need side effects and only want to handle the - * result or failure. + * **Example** (Matching success and failure with effectful handlers) * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases with Side Effects * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -10411,8 +11042,10 @@ export const matchEffect: { * // failure: Uh oh! * ``` * + * @see {@link match} if you don't need side effects and only want to handle the + * result or failure. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( options: { @@ -10421,25 +11054,22 @@ export const matchEffect: { } ): (self: Effect) => Effect /** - * Handles both success and failure cases of an effect, allowing for additional - * side effects. + * Handles both success and failure by running effectful handlers. * - * **Details** + * **When to use** * - * The `matchEffect` function is similar to {@link match}, but it enables you to - * perform side effects in the handlers for both success and failure outcomes. + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. * - * **When to Use** + * **Details** * - * This is useful when you need to execute additional actions, like logging or - * notifying users, based on whether an effect succeeds or fails. + * Use `matchEffect` when either branch needs to return an `Effect`, such as + * performing logging, recovery, notification, or other effectful work. The + * returned effect succeeds or fails according to the handler that is run. * - * @see {@link match} if you don't need side effects and only want to handle the - * result or failure. + * **Example** (Matching success and failure with effectful handlers) * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases with Side Effects * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -10478,8 +11108,10 @@ export const matchEffect: { * // failure: Uh oh! * ``` * + * @see {@link match} if you don't need side effects and only want to handle the + * result or failure. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -10497,9 +11129,11 @@ export const matchEffect: { /** * Determines whether an effect fails. * + * **Details** + * * Defects are not converted; if the effect dies, the resulting effect dies too. * - * **Example** + * **Example** (Checking whether an effect fails) * * ```ts * import { Console, Effect } from "effect" @@ -10513,18 +11147,20 @@ export const matchEffect: { * // Output: true * ``` * + * @category condition checking * @since 2.0.0 - * @category Condition Checking */ export const isFailure: (self: Effect) => Effect = internal.isFailure /** * Returns whether an effect completes successfully. * + * **Details** + * * Returns `false` for failures in the error channel, but defects still fail the * effect. * - * **Example** + * **Example** (Checking whether an effect succeeds) * * ```ts * import { Console, Effect } from "effect" @@ -10542,8 +11178,8 @@ export const isFailure: (self: Effect) => Effect(self: Effect) => Effect = internal.isSuccess @@ -10554,13 +11190,20 @@ export const isSuccess: (self: Effect) => Effect void @@ -10586,21 +11229,31 @@ export const isSuccess: (self: Effect) => Effect() => Effect, never, R> = internal.context /** * Transforms the current context using the provided function. * + * **When to use** + * + * Use to derive an effect from the complete `Context`. + * + * **Details** + * * This function allows you to access the complete context and perform * computations based on all available services. This is useful when you need * to conditionally execute logic based on what services are available. * - * @example + * **Example** (Deriving values from the context) + * * ```ts - * import { Console, Effect, Option, Context } from "effect" + * import { Console, Context, Effect, Option } from "effect" * * const Logger = Context.Service<{ * log: (msg: string) => void @@ -10632,8 +11285,11 @@ export const context: () => Effect, never, R> = in * }) * ``` * + * @see {@link context} for reading the complete context as a value + * @see {@link service} for reading one service from the context + * + * @category environment * @since 2.0.0 - * @category Environment */ export const contextWith: ( f: (context: Context.Context) => Effect @@ -10644,9 +11300,10 @@ export const contextWith: ( * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10669,8 +11326,8 @@ export const contextWith: ( * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ export const provide: { /** @@ -10678,9 +11335,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10703,8 +11361,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ ]>( layers: Layers, @@ -10723,9 +11381,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10748,8 +11407,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ ( layer: Layer.Layer, @@ -10764,9 +11423,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10789,8 +11449,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ (context: Context.Context): (self: Effect) => Effect> /** @@ -10798,9 +11458,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10823,8 +11484,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ ]>( self: Effect, @@ -10842,9 +11503,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10867,8 +11529,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ ( self: Effect, @@ -10882,9 +11544,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10907,8 +11570,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ (self: Effect, context: Context.Context): Effect> } = internalLayer.provide @@ -10922,9 +11585,10 @@ export const provide: { * that contains all the required services. It removes the provided services * from the effect's requirements, making them available to the effect. * - * @example + * **Example** (Providing a complete context) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define service keys * const Logger = Context.Service<{ @@ -10949,8 +11613,8 @@ export const provide: { * const provided = Effect.provideContext(program, context) * ``` * - * @since 2.0.0 - * @category Environment + * @category environment + * @since 4.0.0 */ export const provideContext: { /** @@ -10962,9 +11626,10 @@ export const provideContext: { * that contains all the required services. It removes the provided services * from the effect's requirements, making them available to the effect. * - * @example + * **Example** (Providing a complete context) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define service keys * const Logger = Context.Service<{ @@ -10989,8 +11654,8 @@ export const provideContext: { * const provided = Effect.provideContext(program, context) * ``` * - * @since 2.0.0 - * @category Environment + * @category environment + * @since 4.0.0 */ (context: Context.Context): (self: Effect) => Effect> /** @@ -11002,9 +11667,10 @@ export const provideContext: { * that contains all the required services. It removes the provided services * from the effect's requirements, making them available to the effect. * - * @example + * **Example** (Providing a complete context) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define service keys * const Logger = Context.Service<{ @@ -11029,8 +11695,8 @@ export const provideContext: { * const provided = Effect.provideContext(program, context) * ``` * - * @since 2.0.0 - * @category Environment + * @category environment + * @since 4.0.0 */ (self: Effect, context: Context.Context): Effect> } = internal.provideContext @@ -11038,9 +11704,10 @@ export const provideContext: { /** * Accesses a service from the context. * - * @example + * **Example** (Accessing a required service) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -11054,14 +11721,19 @@ export const provideContext: { * }) * ``` * + * @category context * @since 4.0.0 - * @category Context */ export const service: (service: Context.Key) => Effect = internal.service /** * Optionally accesses a service from the environment. * + * **When to use** + * + * Use to read an optional dependency from the current context without making + * that dependency part of the effect's required environment. + * * **Details** * * This function attempts to access a service from the environment. If the @@ -11069,9 +11741,10 @@ export const service: (service: Context.Key) => Effect * available, it returns `None`. Unlike `service`, this function does not * require the service to be present in the environment. * - * @example + * **Example** (Accessing an optional service) + * * ```ts - * import { Effect, Option, Context } from "effect" + * import { Context, Effect, Option } from "effect" * * // Define a service key * const Logger = Context.Service<{ @@ -11090,8 +11763,8 @@ export const service: (service: Context.Key) => Effect * }) * ``` * + * @category context * @since 2.0.0 - * @category Context */ export const serviceOption: (key: Context.Key) => Effect> = internal.serviceOption @@ -11103,9 +11776,10 @@ export const serviceOption: (key: Context.Key) => Effect> * This function allows you to transform the context required by an effect, * providing part of the context and leaving the rest to be fulfilled later. * - * @example + * **Example** (Updating the context before running) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define services * const Logger = Context.Service<{ @@ -11132,8 +11806,8 @@ export const serviceOption: (key: Context.Key) => Effect> * }) * ``` * + * @category context * @since 4.0.0 - * @category Context */ export const updateContext: { /** @@ -11144,9 +11818,10 @@ export const updateContext: { * This function allows you to transform the context required by an effect, * providing part of the context and leaving the rest to be fulfilled later. * - * @example + * **Example** (Updating the context before running) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define services * const Logger = Context.Service<{ @@ -11173,8 +11848,8 @@ export const updateContext: { * }) * ``` * + * @category context * @since 4.0.0 - * @category Context */ (f: (context: Context.Context) => Context.Context>): (self: Effect) => Effect /** @@ -11185,9 +11860,10 @@ export const updateContext: { * This function allows you to transform the context required by an effect, * providing part of the context and leaving the rest to be fulfilled later. * - * @example + * **Example** (Updating the context before running) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define services * const Logger = Context.Service<{ @@ -11214,8 +11890,8 @@ export const updateContext: { * }) * ``` * + * @category context * @since 4.0.0 - * @category Context */ ( self: Effect, @@ -11224,11 +11900,18 @@ export const updateContext: { } = internal.updateContext /** - * Updates the service with the required service entry. + * Runs an effect with a service implementation transformed by the provided + * function. + * + * **Details** + * + * The service must be available in the effect's context; `updateService` + * replaces it for the wrapped effect with the value returned by the updater. + * + * **Example** (Replacing a service for one effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a counter service * const Counter = Context.Service<{ count: number }>("Counter") @@ -11248,16 +11931,23 @@ export const updateContext: { * // 1 * ``` * + * @category context * @since 2.0.0 - * @category Context */ export const updateService: { /** - * Updates the service with the required service entry. + * Runs an effect with a service implementation transformed by the provided + * function. + * + * **Details** + * + * The service must be available in the effect's context; `updateService` + * replaces it for the wrapped effect with the value returned by the updater. + * + * **Example** (Replacing a service for one effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a counter service * const Counter = Context.Service<{ count: number }>("Counter") @@ -11277,16 +11967,23 @@ export const updateService: { * // 1 * ``` * + * @category context * @since 2.0.0 - * @category Context */ (service: Context.Key, f: (value: A) => A): (self: Effect) => Effect /** - * Updates the service with the required service entry. + * Runs an effect with a service implementation transformed by the provided + * function. + * + * **Details** + * + * The service must be available in the effect's context; `updateService` + * replaces it for the wrapped effect with the value returned by the updater. + * + * **Example** (Replacing a service for one effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a counter service * const Counter = Context.Service<{ count: number }>("Counter") @@ -11306,27 +12003,28 @@ export const updateService: { * // 1 * ``` * + * @category context * @since 2.0.0 - * @category Context */ (self: Effect, service: Context.Key, f: (value: A) => A): Effect } = internal.updateService /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11354,25 +12052,29 @@ export const updateService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ export const provideService: { /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11400,25 +12102,29 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (service: Context.Key): { /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11446,25 +12152,29 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (implementation: S): (self: Effect) => Effect> /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11492,26 +12202,30 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (self: Effect, implementation: S): Effect> } /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11539,25 +12253,29 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (service: Context.Key, implementation: S): (self: Effect) => Effect> /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11585,25 +12303,34 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (self: Effect, service: Context.Key, implementation: S): Effect> } = internal.provideService /** - * Provides the effect with the single service it requires. If the effect - * requires more than one service use `provide` instead. + * 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. * - * This function is similar to `provideService`, but instead of providing a - * static service implementation, it allows you to provide an effect that - * will produce the service. This is useful when the service needs to be - * acquired through an effectful computation (e.g., reading from a database, - * making an HTTP request, or allocating resources). + * **Details** + * + * `provideServiceEffect` runs the acquisition effect to produce the service + * implementation, removes that service from the wrapped effect's requirements, + * and leaves any other requirements to be provided later. Acquisition failures + * are included in the returned effect's error channel. + * + * **Example** (Providing a service with an effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a database connection service * interface DatabaseConnection { @@ -11640,23 +12367,29 @@ export const provideService: { * // Result for: SELECT * FROM users * ``` * + * @category context * @since 2.0.0 - * @category Context */ export const provideServiceEffect: { /** - * Provides the effect with the single service it requires. If the effect - * requires more than one service use `provide` instead. + * 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 + * implementation, removes that service from the wrapped effect's requirements, + * and leaves any other requirements to be provided later. Acquisition failures + * are included in the returned effect's error channel. * - * This function is similar to `provideService`, but instead of providing a - * static service implementation, it allows you to provide an effect that - * will produce the service. This is useful when the service needs to be - * acquired through an effectful computation (e.g., reading from a database, - * making an HTTP request, or allocating resources). + * **Example** (Providing a service with an effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a database connection service * interface DatabaseConnection { @@ -11693,23 +12426,29 @@ export const provideServiceEffect: { * // Result for: SELECT * FROM users * ``` * + * @category context * @since 2.0.0 - * @category Context */ (service: Context.Key, acquire: Effect): (self: Effect) => Effect | R2> /** - * Provides the effect with the single service it requires. If the effect - * requires more than one service use `provide` instead. + * Provides one service to an effect using an effectful acquisition. * - * This function is similar to `provideService`, but instead of providing a - * static service implementation, it allows you to provide an effect that - * will produce the service. This is useful when the service needs to be - * acquired through an effectful computation (e.g., reading from a database, - * making an HTTP request, or allocating resources). + * **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 + * implementation, removes that service from the wrapped effect's requirements, + * and leaves any other requirements to be provided later. Acquisition failures + * are included in the returned effect's error channel. + * + * **Example** (Providing a service with an effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a database connection service * interface DatabaseConnection { @@ -11746,8 +12485,8 @@ export const provideServiceEffect: { * // Result for: SELECT * FROM users * ``` * + * @category context * @since 2.0.0 - * @category Context */ ( self: Effect, @@ -11763,7 +12502,8 @@ export const provideServiceEffect: { /** * Sets the concurrency level for parallel operations within an effect. * - * @example + * **Example** (Setting local concurrency) + * * ```ts * import { Console, Effect } from "effect" * @@ -11788,8 +12528,8 @@ export const provideServiceEffect: { * // [1, 2, 3, 4, 5] * ``` * + * @category references * @since 2.0.0 - * @category References */ export const withConcurrency: { // ----------------------------------------------------------------------------- @@ -11799,7 +12539,8 @@ export const withConcurrency: { /** * Sets the concurrency level for parallel operations within an effect. * - * @example + * **Example** (Setting local concurrency) + * * ```ts * import { Console, Effect } from "effect" * @@ -11824,8 +12565,8 @@ export const withConcurrency: { * // [1, 2, 3, 4, 5] * ``` * + * @category references * @since 2.0.0 - * @category References */ (concurrency: number | "unbounded"): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -11835,7 +12576,8 @@ export const withConcurrency: { /** * Sets the concurrency level for parallel operations within an effect. * - * @example + * **Example** (Setting local concurrency) + * * ```ts * import { Console, Effect } from "effect" * @@ -11860,8 +12602,8 @@ export const withConcurrency: { * // [1, 2, 3, 4, 5] * ``` * + * @category references * @since 2.0.0 - * @category References */ (self: Effect, concurrency: number | "unbounded"): Effect } = internal.withConcurrency @@ -11873,7 +12615,8 @@ export const withConcurrency: { /** * Returns the current scope for resource management. * - * @example + * **Example** (Accessing the current scope) + * * ```ts * import { Console, Effect } from "effect" * @@ -11898,17 +12641,25 @@ export const withConcurrency: { * // Releasing resource * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const scope: Effect = internal.scope /** - * Scopes all resources used in this workflow to the lifetime of the workflow, - * ensuring that their finalizers are run as soon as this workflow completes - * execution, whether by success, failure, or interruption. + * Runs an effect with a scope that closes when the effect completes. + * + * **When to use** + * + * Use to acquire scoped resources for the duration of a single workflow. + * + * **Details** + * + * Finalizers for resources acquired inside the workflow run as soon as the + * workflow completes, whether by success, failure, or interruption. + * + * **Example** (Running a scoped acquisition) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -11931,8 +12682,8 @@ export const scope: Effect = internal.scope * // Output: "Releasing resource" * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const scoped: ( self: Effect @@ -11941,7 +12692,13 @@ export const scoped: ( /** * Creates a scoped effect by providing access to the scope. * - * @example + * **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 * import { Console, Effect, Scope } from "effect" * @@ -11973,27 +12730,32 @@ export const scoped: ( * // Manual finalizer * ``` * - * @since 2.0.0 - * @category Resource Management & Finalization + * @category resource management + * @since 3.11.0 */ export const scopedWith: ( f: (scope: Scope) => Effect ) => Effect = internal.scopedWith /** - * This function constructs a scoped resource from an `acquire` and `release` - * `Effect` value. + * Constructs a scoped resource from an acquisition effect and a release + * finalizer. + * + * **When to use** + * + * Use to acquire a scoped resource with an explicit release finalizer. + * + * **Details** + * + * If acquisition succeeds, the release finalizer is added to the current scope + * and is guaranteed to run when that scope closes. The finalizer receives the + * `Exit` value used to close the scope. * - * If the `acquire` `Effect` value successfully completes execution, then the - * `release` `Effect` value will be added to the finalizers associated with the - * scope of this `Effect` value, and it is guaranteed to be run when the scope - * is closed. + * By default, acquisition is protected by an uninterruptible region. Pass + * `{ interruptible: true }` to allow the acquisition effect to be interrupted. * - * The `acquire` and `release` `Effect` values will be run uninterruptibly. - * Additionally, the `release` `Effect` value may depend on the `Exit` value - * specified when the scope is closed. + * **Example** (Acquiring and releasing a resource) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12030,8 +12792,11 @@ export const scopedWith: ( * ) * ``` * + * @see {@link acquireDisposable} for resources that implement JavaScript disposal protocols + * @see {@link acquireUseRelease} for bracketing acquire, use, and release in one effect + * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const acquireRelease: ( acquire: Effect, @@ -12040,8 +12805,14 @@ export const acquireRelease: ( ) => Effect = internal.acquireRelease /** - * This function constructs a scoped resource from an Effect that acquires a - * disposable value. + * Acquires a scoped resource that implements JavaScript disposal protocols. + * + * **When to use** + * + * Use when you work with JavaScript `Disposable` or `AsyncDisposable` resources + * that should be closed with the surrounding scope. + * + * **Details** * * The resource is automatically disposed when the surrounding * {@link Scope} is closed, using {@link Symbol.dispose} for @@ -12049,15 +12820,15 @@ export const acquireRelease: ( * disposables. * * This is similar to {@link acquireRelease}, but uses the standard - * JavaScript disposal protocal instead of requiring an explicit release - * function. + * JavaScript disposal protocol instead of requiring an explicit release + * function. It works with JavaScript `Disposable` and `AsyncDisposable` + * resources. * - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using} + * **Example** (Acquiring a disposable resource) * - * @example * ```ts * import sqlite from "node:sqlite"; - * import { Effect } from "effect"; + * import { Effect } from "effect" * * const program = Effect.scoped( * Effect.gen(function* () { @@ -12073,18 +12844,23 @@ export const acquireRelease: ( * ) * ``` * + * @see {@link acquireRelease} for resources that need an explicit finalizer + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const acquireDisposable: ( acquire: Effect ) => Effect = internal.acquireDisposable /** - * This function is used to ensure that an `Effect` value that represents the - * acquisition of a resource (for example, opening a file, launching a thread, - * etc.) will not be interrupted, and that the resource will always be released - * when the `Effect` value completes execution. + * Runs resource acquisition, usage, and release as one bracketed effect. + * + * **When to use** + * + * Use to bracket acquire, use, and release logic in one effect. + * + * **Details** * * `acquireUseRelease` does the following: * @@ -12103,7 +12879,8 @@ export const acquireDisposable: ( * is not desired, errors produced by the `release` `Effect` value can be caught * and ignored. * - * @example + * **Example** (Using a resource with cleanup) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12148,8 +12925,10 @@ export const acquireDisposable: ( * // Closing connection to db://localhost:5432 (success) * ``` * + * @see {@link acquireRelease} for scoped resources whose use happens later + * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const acquireUseRelease: ( acquire: Effect, @@ -12158,15 +12937,19 @@ export const acquireUseRelease: ( ) => Effect = internal.acquireUseRelease /** - * This function adds a finalizer to the scope of the calling `Effect` value. - * The finalizer is guaranteed to be run when the scope is closed, and it may - * depend on the `Exit` value that the scope is closed with. + * Adds a finalizer to the current scope. + * + * **When to use** + * + * Use to register low-level cleanup in the current scope. * - * Finalizers are useful for cleanup operations that must run regardless of - * whether the effect succeeds or fails. They're commonly used for resource - * cleanup, logging, or other side effects that should always occur. + * **Details** + * + * The finalizer runs when the surrounding scope is closed and receives the + * `Exit` value used to close the scope. + * + * **Example** (Registering scope finalizers) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12195,8 +12978,11 @@ export const acquireUseRelease: ( * // operation result * ``` * + * @see {@link acquireRelease} for resource acquisition with a release finalizer + * @see {@link ensuring} for attaching a finalizer to one effect + * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const addFinalizer: ( finalizer: (exit: Exit.Exit) => Effect @@ -12207,13 +12993,16 @@ export const addFinalizer: ( * specified `finalizer` is guaranteed to be executed, whether this effect * succeeds, fails, or is interrupted. * + * **Details** + * * For use cases that need access to the effect's result, see `onExit`. * * Finalizers offer very powerful guarantees, but they are low-level, and * should generally not be used for releasing resources. For higher-level * logic built on `ensuring`, see the `acquireRelease` family of methods. * - * @example + * **Example** (Always running cleanup) + * * ```ts * import { Console, Effect } from "effect" * @@ -12238,8 +13027,8 @@ export const addFinalizer: ( * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const ensuring: { /** @@ -12247,13 +13036,16 @@ export const ensuring: { * specified `finalizer` is guaranteed to be executed, whether this effect * succeeds, fails, or is interrupted. * + * **Details** + * * For use cases that need access to the effect's result, see `onExit`. * * Finalizers offer very powerful guarantees, but they are low-level, and * should generally not be used for releasing resources. For higher-level * logic built on `ensuring`, see the `acquireRelease` family of methods. * - * @example + * **Example** (Always running cleanup) + * * ```ts * import { Console, Effect } from "effect" * @@ -12278,8 +13070,8 @@ export const ensuring: { * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (finalizer: Effect): (self: Effect) => Effect /** @@ -12287,13 +13079,16 @@ export const ensuring: { * specified `finalizer` is guaranteed to be executed, whether this effect * succeeds, fails, or is interrupted. * + * **Details** + * * For use cases that need access to the effect's result, see `onExit`. * * Finalizers offer very powerful guarantees, but they are low-level, and * should generally not be used for releasing resources. For higher-level * logic built on `ensuring`, see the `acquireRelease` family of methods. * - * @example + * **Example** (Always running cleanup) + * * ```ts * import { Console, Effect } from "effect" * @@ -12318,8 +13113,8 @@ export const ensuring: { * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (self: Effect, finalizer: Effect): Effect } = internal.ensuring @@ -12328,9 +13123,10 @@ export const ensuring: { * Runs the specified effect if this effect fails, providing the error to the * effect if it exists. The provided effect will not be interrupted. * - * @example + * **Example** (Running cleanup on failure) + * * ```ts - * import { Cause, Data, Console, Effect } from "effect" + * import { Cause, Console, Data, Effect } from "effect" * * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} * @@ -12347,17 +13143,18 @@ export const ensuring: { * // TaskError: Something went wrong * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const onError: { /** * Runs the specified effect if this effect fails, providing the error to the * effect if it exists. The provided effect will not be interrupted. * - * @example + * **Example** (Running cleanup on failure) + * * ```ts - * import { Cause, Data, Console, Effect } from "effect" + * import { Cause, Console, Data, Effect } from "effect" * * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} * @@ -12374,17 +13171,18 @@ export const onError: { * // TaskError: Something went wrong * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (cleanup: (cause: Cause.Cause) => Effect): (self: Effect) => Effect /** * Runs the specified effect if this effect fails, providing the error to the * effect if it exists. The provided effect will not be interrupted. * - * @example + * **Example** (Running cleanup on failure) + * * ```ts - * import { Cause, Data, Console, Effect } from "effect" + * import { Cause, Console, Data, Effect } from "effect" * * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} * @@ -12401,8 +13199,8 @@ export const onError: { * // TaskError: Something went wrong * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12414,7 +13212,8 @@ export const onError: { * Runs the finalizer only when this effect fails and the `Cause` matches the * provided predicate. * - * @example + * **Example** (Running cleanup for selected failures) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -12430,15 +13229,16 @@ export const onError: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const onErrorIf: { /** * Runs the finalizer only when this effect fails and the `Cause` matches the * provided predicate. * - * @example + * **Example** (Running cleanup for selected failures) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -12454,8 +13254,8 @@ export const onErrorIf: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( predicate: Predicate.Predicate>, @@ -12465,7 +13265,8 @@ export const onErrorIf: { * Runs the finalizer only when this effect fails and the `Cause` matches the * provided predicate. * - * @example + * **Example** (Running cleanup for selected failures) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -12481,8 +13282,8 @@ export const onErrorIf: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12494,15 +13295,35 @@ export const onErrorIf: { /** * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup or diagnostics should run only for failures whose full + * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the + * filter's pass value plus the original cause. + * + * @see {@link onError} for cleanup on every failure + * @see {@link onErrorIf} for selecting failures with a boolean predicate + * @see {@link onExitFilter} for selecting from every exit instead of only failures + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const onErrorFilter: { /** * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup or diagnostics should run only for failures whose full + * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the + * filter's pass value plus the original cause. + * + * @see {@link onError} for cleanup on every failure + * @see {@link onErrorIf} for selecting failures with a boolean predicate + * @see {@link onExitFilter} for selecting from every exit instead of only failures + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( filter: Filter.Filter, EB, X>, @@ -12511,8 +13332,18 @@ export const onErrorFilter: { /** * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup or diagnostics should run only for failures whose full + * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the + * filter's pass value plus the original cause. + * + * @see {@link onError} for cleanup on every failure + * @see {@link onErrorIf} for selecting failures with a boolean predicate + * @see {@link onExitFilter} for selecting from every exit instead of only failures + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12522,12 +13353,24 @@ export const onErrorFilter: { } = internal.onErrorFilter /** - * The low level primitive that powers `onExit`. - * function is used to run a finalizer when the effect exits, regardless of the - * exit status. + * Runs an optional finalizer with the effect's `Exit` value when the effect + * completes. * - * @since 2.0.0 - * @category Resource Management & Finalization + * **When to use** + * + * Use when you are building a low-level `Effect` operator that must inspect the + * source effect's `Exit`, may skip finalization by returning `undefined`, or + * must choose whether finalization is forced into an uninterruptible region. + * + * **Details** + * + * This low-level operator preserves the source effect's result unless the + * finalizer fails. Prefer `onExit` for normal cleanup logic. + * + * @see {@link onExit} for ordinary exit-aware cleanup whose finalizer always returns an effect + * + * @category resource management + * @since 4.0.0 */ export const onExitPrimitive: ( self: Effect, @@ -12536,10 +13379,11 @@ export const onExitPrimitive: ( ) => Effect = internal.onExitPrimitive /** - * Ensures that a cleanup functions runs, whether this effect succeeds, fails, - * or is interrupted. + * Ensures that a cleanup function runs whether this effect succeeds, fails, or + * is interrupted. + * + * **Example** (Observing every exit) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12558,15 +13402,16 @@ export const onExitPrimitive: ( * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const onExit: { /** - * Ensures that a cleanup functions runs, whether this effect succeeds, fails, - * or is interrupted. + * Ensures that a cleanup function runs whether this effect succeeds, fails, or + * is interrupted. + * + * **Example** (Observing every exit) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12585,15 +13430,16 @@ export const onExit: { * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (f: (exit: Exit.Exit) => Effect): (self: Effect) => Effect /** - * Ensures that a cleanup functions runs, whether this effect succeeds, fails, - * or is interrupted. + * Ensures that a cleanup function runs whether this effect succeeds, fails, or + * is interrupted. + * + * **Example** (Observing every exit) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12612,8 +13458,8 @@ export const onExit: { * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (self: Effect, f: (exit: Exit.Exit) => Effect): Effect } = internal.onExit @@ -12622,7 +13468,8 @@ export const onExit: { * Runs the cleanup effect only when the `Exit` satisfies the provided * predicate. * - * @example + * **Example** (Observing selected exits) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12636,15 +13483,16 @@ export const onExit: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const onExitIf: { /** * Runs the cleanup effect only when the `Exit` satisfies the provided * predicate. * - * @example + * **Example** (Observing selected exits) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12658,8 +13506,8 @@ export const onExitIf: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( predicate: Predicate.Predicate, NoInfer>>, @@ -12669,7 +13517,8 @@ export const onExitIf: { * Runs the cleanup effect only when the `Exit` satisfies the provided * predicate. * - * @example + * **Example** (Observing selected exits) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12683,8 +13532,8 @@ export const onExitIf: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12696,15 +13545,45 @@ export const onExitIf: { /** * Runs the cleanup effect only when the `Exit` matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup should run only for `Exit` values selected by a `Filter`, + * and the cleanup needs the extracted pass value together with the original + * `Exit`. + * + * **Details** + * + * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the + * selected value and the original `Exit`. + * + * @see {@link onExit} for cleanup on every exit + * @see {@link onExitIf} for selecting exits with a boolean predicate + * @see {@link onErrorFilter} for selecting only failure causes + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const onExitFilter: { /** * Runs the cleanup effect only when the `Exit` matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup should run only for `Exit` values selected by a `Filter`, + * and the cleanup needs the extracted pass value together with the original + * `Exit`. + * + * **Details** + * + * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the + * selected value and the original `Exit`. + * + * @see {@link onExit} for cleanup on every exit + * @see {@link onExitIf} for selecting exits with a boolean predicate + * @see {@link onErrorFilter} for selecting only failure causes + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( filter: Filter.Filter, NoInfer>, B, X>, @@ -12713,8 +13592,23 @@ export const onExitFilter: { /** * Runs the cleanup effect only when the `Exit` matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup should run only for `Exit` values selected by a `Filter`, + * and the cleanup needs the extracted pass value together with the original + * `Exit`. + * + * **Details** + * + * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the + * selected value and the original `Exit`. + * + * @see {@link onExit} for cleanup on every exit + * @see {@link onExitIf} for selecting exits with a boolean predicate + * @see {@link onErrorFilter} for selecting only failure causes + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12731,6 +13625,11 @@ export const onExitFilter: { * Returns an effect that lazily computes a result and caches it for subsequent * evaluations. * + * **When to use** + * + * Use when you need an expensive or time-consuming operation to be evaluated + * once and reused by later callers. + * * **Details** * * This function wraps an effect and ensures that its result is computed only @@ -12738,19 +13637,8 @@ export const onExitFilter: { * evaluations of the same effect will return the cached result without * re-executing the logic. * - * **When to Use** - * - * 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. + * **Example** (Memoizing an effect until invalidated) * - * @see {@link cachedWithTTL} for a similar function that includes a - * time-to-live duration for the cached value. - * @see {@link cachedInvalidateWithTTL} for a similar function that includes an - * additional effect for manually invalidating the cached value. - * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -12787,8 +13675,12 @@ export const onExitFilter: { * // result 3 * ``` * + * @see {@link cachedWithTTL} for a similar function that includes a + * time-to-live duration for the cached value. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching * @since 2.0.0 - * @category Caching */ export const cached: (self: Effect) => Effect> = internal.cached @@ -12796,6 +13688,11 @@ export const cached: (self: Effect) => Effect> * Returns an effect that caches its result for a specified `Duration`, * known as "timeToLive" (TTL). * + * **When to use** + * + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. + * * **Details** * * This function is used to cache the result of an effect for a specified amount @@ -12808,23 +13705,8 @@ export const cached: (self: Effect) => Effect> * After the specified duration has passed, the cache expires, and the effect * will be recomputed upon the next evaluation. * - * **When to Use** - * - * 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. - * - * 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. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedInvalidateWithTTL} for a similar function that includes an - * additional effect for manually invalidating the cached value. + * **Example** (Memoizing an effect with TTL) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -12855,14 +13737,23 @@ export const cached: (self: Effect) => Effect> * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching * @since 2.0.0 - * @category Caching */ export const cachedWithTTL: { /** * Returns an effect that caches its result for a specified `Duration`, * known as "timeToLive" (TTL). * + * **When to use** + * + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. + * * **Details** * * This function is used to cache the result of an effect for a specified amount @@ -12875,23 +13766,8 @@ export const cachedWithTTL: { * After the specified duration has passed, the cache expires, and the effect * will be recomputed upon the next evaluation. * - * **When to Use** - * - * 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. - * - * 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. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedInvalidateWithTTL} for a similar function that includes an - * additional effect for manually invalidating the cached value. + * **Example** (Memoizing an effect with TTL) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -12922,14 +13798,23 @@ export const cachedWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching * @since 2.0.0 - * @category Caching */ (timeToLive: Duration.Input): (self: Effect) => Effect> /** * Returns an effect that caches its result for a specified `Duration`, * known as "timeToLive" (TTL). * + * **When to use** + * + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. + * * **Details** * * This function is used to cache the result of an effect for a specified amount @@ -12942,23 +13827,8 @@ export const cachedWithTTL: { * After the specified duration has passed, the cache expires, and the effect * will be recomputed upon the next evaluation. * - * **When to Use** - * - * 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. + * **Example** (Memoizing an effect with TTL) * - * 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. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedInvalidateWithTTL} for a similar function that includes an - * additional effect for manually invalidating the cached value. - * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -12989,16 +13859,26 @@ export const cachedWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching * @since 2.0.0 - * @category Caching */ (self: Effect, timeToLive: Duration.Input): Effect> } = internal.cachedWithTTL /** - * Caches an effect's result for a specified duration and allows manual + * Creates a cached effect result for a specified duration and allows manual * invalidation before expiration. * + * **When to use** + * + * Use when an effect result should be cached for a bounded time and callers + * also need a manual invalidation effect to force recomputation before + * expiration. + * * **Details** * * This function behaves similarly to {@link cachedWithTTL} by caching the @@ -13012,22 +13892,8 @@ export const cachedWithTTL: { * Once the cache is invalidated, the next time the effect is evaluated, the * result will be recomputed, and the cache will be refreshed. * - * **When to Use** - * - * Use this function when you have an effect whose result needs to be cached for - * a certain period, but you also want the option to refresh the cache manually - * before the expiration time. - * - * This is useful when you need to ensure that the cached data remains valid for - * a certain period but still want to invalidate it if the underlying data - * changes or if you want to force a recomputation. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedWithTTL} for a similar function that caches the result for - * a specified duration but does not include an effect for manual invalidation. + * **Example** (Memoizing with TTL and invalidation) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -13061,14 +13927,24 @@ export const cachedWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedWithTTL} for a similar function that caches the result for + * a specified duration but does not include an effect for manual invalidation. + * @category caching * @since 2.0.0 - * @category Caching */ export const cachedInvalidateWithTTL: { /** - * Caches an effect's result for a specified duration and allows manual + * Creates a cached effect result for a specified duration and allows manual * invalidation before expiration. * + * **When to use** + * + * Use when an effect result should be cached for a bounded time and callers + * also need a manual invalidation effect to force recomputation before + * expiration. + * * **Details** * * This function behaves similarly to {@link cachedWithTTL} by caching the @@ -13082,22 +13958,8 @@ export const cachedInvalidateWithTTL: { * Once the cache is invalidated, the next time the effect is evaluated, the * result will be recomputed, and the cache will be refreshed. * - * **When to Use** - * - * Use this function when you have an effect whose result needs to be cached for - * a certain period, but you also want the option to refresh the cache manually - * before the expiration time. - * - * This is useful when you need to ensure that the cached data remains valid for - * a certain period but still want to invalidate it if the underlying data - * changes or if you want to force a recomputation. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedWithTTL} for a similar function that caches the result for - * a specified duration but does not include an effect for manual invalidation. + * **Example** (Memoizing with TTL and invalidation) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -13131,14 +13993,24 @@ export const cachedInvalidateWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedWithTTL} for a similar function that caches the result for + * a specified duration but does not include an effect for manual invalidation. + * @category caching * @since 2.0.0 - * @category Caching */ (timeToLive: Duration.Input): (self: Effect) => Effect<[Effect, Effect]> /** - * Caches an effect's result for a specified duration and allows manual + * Creates a cached effect result for a specified duration and allows manual * invalidation before expiration. * + * **When to use** + * + * Use when an effect result should be cached for a bounded time and callers + * also need a manual invalidation effect to force recomputation before + * expiration. + * * **Details** * * This function behaves similarly to {@link cachedWithTTL} by caching the @@ -13152,22 +14024,8 @@ export const cachedInvalidateWithTTL: { * Once the cache is invalidated, the next time the effect is evaluated, the * result will be recomputed, and the cache will be refreshed. * - * **When to Use** - * - * Use this function when you have an effect whose result needs to be cached for - * a certain period, but you also want the option to refresh the cache manually - * before the expiration time. + * **Example** (Memoizing with TTL and invalidation) * - * This is useful when you need to ensure that the cached data remains valid for - * a certain period but still want to invalidate it if the underlying data - * changes or if you want to force a recomputation. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedWithTTL} for a similar function that caches the result for - * a specified duration but does not include an effect for manual invalidation. - * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -13201,8 +14059,12 @@ export const cachedInvalidateWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedWithTTL} for a similar function that caches the result for + * a specified duration but does not include an effect for manual invalidation. + * @category caching * @since 2.0.0 - * @category Caching */ (self: Effect, timeToLive: Duration.Input): Effect<[Effect, Effect]> } = internal.cachedInvalidateWithTTL @@ -13214,7 +14076,8 @@ export const cachedInvalidateWithTTL: { /** * Returns an effect that is immediately interrupted. * - * @example + * **Example** (Creating an interrupted effect) + * * ```ts * import { Effect } from "effect" * @@ -13227,15 +14090,16 @@ export const cachedInvalidateWithTTL: { * // Throws: InterruptedException * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const interrupt: Effect = internal.interrupt /** * Returns a new effect that allows the effect to be interruptible. * - * @example + * **Example** (Allowing interruption) + * * ```ts * import { Effect } from "effect" * @@ -13248,8 +14112,8 @@ export const interrupt: Effect = internal.interrupt * // Later: fiber.interrupt() * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const interruptible: ( self: Effect @@ -13258,7 +14122,8 @@ export const interruptible: ( /** * Runs the specified finalizer effect if this effect is interrupted. * - * @example + * **Example** (Running cleanup on interruption) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13275,14 +14140,15 @@ export const interruptible: ( * // Output: Task was interrupted, cleaning up... * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const onInterrupt: { /** * Runs the specified finalizer effect if this effect is interrupted. * - * @example + * **Example** (Running cleanup on interruption) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13299,14 +14165,15 @@ export const onInterrupt: { * // Output: Task was interrupted, cleaning up... * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ (finalizer: (interruptors: ReadonlySet) => Effect): (self: Effect) => Effect /** * Runs the specified finalizer effect if this effect is interrupted. * - * @example + * **Example** (Running cleanup on interruption) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13323,8 +14190,8 @@ export const onInterrupt: { * // Output: Task was interrupted, cleaning up... * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ ( self: Effect, @@ -13335,7 +14202,8 @@ export const onInterrupt: { /** * Returns a new effect that disables interruption for the given effect. * - * @example + * **Example** (Preventing interruption) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13352,8 +14220,8 @@ export const onInterrupt: { * Effect.runPromise(Fiber.interrupt(fiber)) * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const uninterruptible: ( self: Effect @@ -13363,7 +14231,8 @@ export const uninterruptible: ( * Disables interruption and provides a restore function to restore the * interruptible state within the effect. * - * @example + * **Example** (Restoring interruption in protected regions) + * * ```ts * import { Console, Effect } from "effect" * @@ -13385,8 +14254,8 @@ export const uninterruptible: ( * ) * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const uninterruptibleMask: ( f: ( @@ -13395,11 +14264,11 @@ export const uninterruptibleMask: ( ) => Effect = internal.uninterruptibleMask /** - * This function behaves like {@link interruptible}, but it also provides a - * `restore` function. This function can be used to restore the interruptibility - * of any specific region of code. + * Runs an effect in an interruptible region while providing `restore` for + * locally restoring the previous interruptibility. + * + * **Example** (Controlling interruptibility locally) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -13421,8 +14290,8 @@ export const uninterruptibleMask: ( * ) * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const interruptibleMask: ( f: ( @@ -13433,8 +14302,26 @@ export const interruptibleMask: ( /** * Creates an AbortSignal that is managed by the provided scope. * + * **When to use** + * + * Use to obtain a scope-managed `AbortSignal` for APIs that accept cancellation + * through a signal. + * + * **Details** + * + * Each acquisition creates a fresh `AbortController`. Closing the owning scope + * runs a finalizer that aborts the controller and the effect succeeds with the + * controller's signal. + * + * **Gotchas** + * + * The signal is aborted when its owning scope closes, so avoid keeping it for + * work that outlives that scope. + * + * @see {@link scoped} for binding resource lifetime to a scope + * + * @category interruption * @since 4.0.0 - * @category Interruption */ export const abortSignal: Effect = internal.abortSignal @@ -13443,31 +14330,16 @@ export const abortSignal: Effect = internal.abortSign // ----------------------------------------------------------------------------- /** - * @since 2.0.0 - * @category Repetition / Recursion - * @example - * ```ts - * import type { Effect } from "effect" + * Type helpers for repeating effects. * - * // Repeat namespace contains types for repeating operations - * declare const effect: Effect.Effect - * declare const options: Effect.Repeat.Options - * // Use Effect.repeat with these types for repeating successful effects - * ``` + * @since 2.0.0 */ export declare namespace Repeat { /** - * @since 2.0.0 - * @category Repetition / Recursion - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the result type of `Effect.repeat` from the original effect and repeat options. * - * // Return type for repeat operations with specific options - * declare const options: Effect.Repeat.Options - * type RepeatResult = Effect.Repeat.Return - * // Result: Effect with repeated operation result types - * ``` + * @category repetition + * @since 2.0.0 */ export type Return> = Effect< O extends { until: Predicate.Refinement } ? B @@ -13495,20 +14367,10 @@ export declare namespace Repeat { : never /** - * @since 2.0.0 - * @category Repetition / Recursion - * @example - * ```ts - * import { Schedule } from "effect" - * import type { Effect } from "effect" + * Options that control whether and how an effect is repeated. * - * // Options for configuring repeat behavior - * const repeatOptions: Effect.Repeat.Options = { - * times: 5, - * schedule: Schedule.fixed("100 millis"), - * while: (result) => result < 10 - * } - * ``` + * @category repetition + * @since 2.0.0 */ export interface Options { while?: ((_: A) => boolean | Effect) | undefined @@ -13521,7 +14383,8 @@ export declare namespace Repeat { /** * Repeats this effect forever (until the first error). * - * @example + * **Example** (Repeating forever) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13544,8 +14407,8 @@ export declare namespace Repeat { * }) * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const forever: < Arg extends Effect | { @@ -13564,6 +14427,10 @@ export const forever: < /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13583,12 +14450,16 @@ export const forever: < * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13597,10 +14468,11 @@ export const forever: < * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13620,14 +14492,22 @@ export const forever: < * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const repeat: { /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13647,12 +14527,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13661,10 +14545,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13684,14 +14569,22 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ , A>(options: O): (self: Effect) => Repeat.Return /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13711,12 +14604,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13725,10 +14622,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13748,14 +14646,22 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ (schedule: Schedule, Error, Env>): (self: Effect) => Effect /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13775,12 +14681,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13789,10 +14699,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13812,9 +14723,13 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( builder: ( @@ -13824,6 +14739,10 @@ export const repeat: { /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13843,12 +14762,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13857,10 +14780,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13880,14 +14804,22 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ >(self: Effect, options: O): Repeat.Return /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13907,12 +14839,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13921,10 +14857,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13944,9 +14881,13 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( self: Effect, @@ -13955,6 +14896,10 @@ export const repeat: { /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13974,12 +14919,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13988,10 +14937,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -14011,9 +14961,13 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( self: Effect, @@ -14024,27 +14978,25 @@ export const repeat: { } = internalSchedule.repeat /** - * Repeats an effect with a schedule, handling failures using a custom handler. + * 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** * - * This function allows you to execute an effect repeatedly based on a specified - * schedule. If the effect fails at any point, a custom failure handler is - * invoked. The handler is provided with both the failure value and the output - * of the schedule at the time of failure. If the effect fails immediately, the - * schedule will never be executed and the output provided to the handler will - * be `None`. This enables advanced error recovery or alternative fallback logic - * while maintaining flexibility in how repetitions are handled. + * If the repeated effect or schedule step fails, `orElse` receives the failure + * and the latest schedule metadata when at least one schedule step has run; + * otherwise it receives `None`. If the schedule completes normally, the + * returned effect succeeds with the schedule's output. * - * For example, using a schedule with `recurs(2)` will allow for two additional - * repetitions after the initial execution, provided the effect succeeds. If a - * failure occurs during any iteration, the failure handler is invoked to handle - * the situation. + * **Example** (Recovering after repetition stops) * - * @example * ```ts - * import { Console, Effect, Schedule } from "effect" - * import * as Option from "effect/Option" + * import { Console, Effect, Option, Schedule } from "effect" * * let attempt = 0 * const task = Effect.gen(function*() { @@ -14069,32 +15021,30 @@ export const repeat: { * ) * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const repeatOrElse: { /** - * Repeats an effect with a schedule, handling failures using a custom handler. + * 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** * - * This function allows you to execute an effect repeatedly based on a specified - * schedule. If the effect fails at any point, a custom failure handler is - * invoked. The handler is provided with both the failure value and the output - * of the schedule at the time of failure. If the effect fails immediately, the - * schedule will never be executed and the output provided to the handler will - * be `None`. This enables advanced error recovery or alternative fallback logic - * while maintaining flexibility in how repetitions are handled. + * If the repeated effect or schedule step fails, `orElse` receives the failure + * and the latest schedule metadata when at least one schedule step has run; + * otherwise it receives `None`. If the schedule completes normally, the + * returned effect succeeds with the schedule's output. * - * For example, using a schedule with `recurs(2)` will allow for two additional - * repetitions after the initial execution, provided the effect succeeds. If a - * failure occurs during any iteration, the failure handler is invoked to handle - * the situation. + * **Example** (Recovering after repetition stops) * - * @example * ```ts - * import { Console, Effect, Schedule } from "effect" - * import * as Option from "effect/Option" + * import { Console, Effect, Option, Schedule } from "effect" * * let attempt = 0 * const task = Effect.gen(function*() { @@ -14119,35 +15069,33 @@ export const repeatOrElse: { * ) * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( schedule: Schedule, orElse: (error: E | E2, option: Option) => Effect ): (self: Effect) => Effect /** - * Repeats an effect with a schedule, handling failures using a custom handler. + * 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** * - * This function allows you to execute an effect repeatedly based on a specified - * schedule. If the effect fails at any point, a custom failure handler is - * invoked. The handler is provided with both the failure value and the output - * of the schedule at the time of failure. If the effect fails immediately, the - * schedule will never be executed and the output provided to the handler will - * be `None`. This enables advanced error recovery or alternative fallback logic - * while maintaining flexibility in how repetitions are handled. + * If the repeated effect or schedule step fails, `orElse` receives the failure + * and the latest schedule metadata when at least one schedule step has run; + * otherwise it receives `None`. If the schedule completes normally, the + * returned effect succeeds with the schedule's output. * - * For example, using a schedule with `recurs(2)` will allow for two additional - * repetitions after the initial execution, provided the effect succeeds. If a - * failure occurs during any iteration, the failure handler is invoked to handle - * the situation. + * **Example** (Recovering after repetition stops) * - * @example * ```ts - * import { Console, Effect, Schedule } from "effect" - * import * as Option from "effect/Option" + * import { Console, Effect, Option, Schedule } from "effect" * * let attempt = 0 * const task = Effect.gen(function*() { @@ -14172,8 +15120,8 @@ export const repeatOrElse: { * ) * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( self: Effect, @@ -14185,28 +15133,58 @@ export const repeatOrElse: { /** * Returns an array of `n` identical effects. * - * Use with `Effect.all` to run the replicated effects and collect results. + * **When to use** + * + * Use when you need an array of identical effect values without running them + * yet. + * + * **Details** + * + * This only creates the array of effects. It does not run or collect them. + * + * @see {@link all} for running the returned effects and collecting results + * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const replicate: { /** * Returns an array of `n` identical effects. * - * Use with `Effect.all` to run the replicated effects and collect results. + * **When to use** + * + * Use when you need an array of identical effect values without running them + * yet. + * + * **Details** + * + * This only creates the array of effects. It does not run or collect them. * + * @see {@link all} for running the returned effects and collecting results + * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options + * + * @category collecting * @since 2.0.0 - * @category Collecting */ (n: number): (self: Effect) => Array> /** * Returns an array of `n` identical effects. * - * Use with `Effect.all` to run the replicated effects and collect results. + * **When to use** + * + * Use when you need an array of identical effect values without running them + * yet. * + * **Details** + * + * This only creates the array of effects. It does not run or collect them. + * + * @see {@link all} for running the returned effects and collecting results + * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options + * + * @category collecting * @since 2.0.0 - * @category Collecting */ (self: Effect, n: number): Array> } = internal.replicate @@ -14214,9 +15192,17 @@ 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. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14226,16 +15212,24 @@ export const replicate: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const replicateEffect: { /** * 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. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14245,8 +15239,8 @@ export const replicateEffect: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( n: number, @@ -14255,9 +15249,17 @@ export const replicateEffect: { /** * 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. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14267,8 +15269,8 @@ export const replicateEffect: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( n: number, @@ -14277,9 +15279,17 @@ export const replicateEffect: { /** * 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. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14289,8 +15299,8 @@ export const replicateEffect: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( self: Effect, @@ -14300,9 +15310,17 @@ export const replicateEffect: { /** * 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. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14312,8 +15330,8 @@ export const replicateEffect: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( self: Effect, @@ -14323,22 +15341,24 @@ export const replicateEffect: { } = internal.replicateEffect /** - * Repeats an effect based on a specified schedule. + * Runs an effect repeatedly according to a schedule and returns the schedule's + * final output. + * + * **When to use** + * + * Use to rerun a successful effect according to a `Schedule` when the schedule + * does not need a custom initial input. * * **Details** * - * This function allows you to execute an effect repeatedly according to a given - * schedule. The schedule determines the timing and number of repetitions. Each - * repetition can also depend on the decision of the schedule, providing - * flexibility for complex workflows. This function does not modify the effect's - * success or failure; it only controls its repetition. + * The schedule is first stepped with `undefined`. After each successful + * execution, the effect's success value is fed to the schedule to decide + * whether to run again. The returned effect fails if the effect or schedule + * fails, and otherwise succeeds with the schedule output when the schedule + * completes. * - * For example, you can use a schedule that recurs a specific number of times, - * adds delays between repetitions, or customizes repetition behavior based on - * external inputs. The effect runs initially and is repeated according to the - * schedule. + * **Example** (Scheduling repeated execution) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14364,27 +15384,29 @@ export const replicateEffect: { * @see {@link scheduleFrom} for a variant that allows the schedule's decision * to depend on the result of this effect. * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const schedule: { /** - * Repeats an effect based on a specified schedule. + * Runs an effect repeatedly according to a schedule and returns the schedule's + * final output. + * + * **When to use** + * + * Use to rerun a successful effect according to a `Schedule` when the schedule + * does not need a custom initial input. * * **Details** * - * This function allows you to execute an effect repeatedly according to a given - * schedule. The schedule determines the timing and number of repetitions. Each - * repetition can also depend on the decision of the schedule, providing - * flexibility for complex workflows. This function does not modify the effect's - * success or failure; it only controls its repetition. + * The schedule is first stepped with `undefined`. After each successful + * execution, the effect's success value is fed to the schedule to decide + * whether to run again. The returned effect fails if the effect or schedule + * fails, and otherwise succeeds with the schedule output when the schedule + * completes. * - * For example, you can use a schedule that recurs a specific number of times, - * adds delays between repetitions, or customizes repetition behavior based on - * external inputs. The effect runs initially and is repeated according to the - * schedule. + * **Example** (Scheduling repeated execution) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14410,27 +15432,29 @@ export const schedule: { * @see {@link scheduleFrom} for a variant that allows the schedule's decision * to depend on the result of this effect. * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ (schedule: Schedule): (self: Effect) => Effect /** - * Repeats an effect based on a specified schedule. + * Runs an effect repeatedly according to a schedule and returns the schedule's + * final output. + * + * **When to use** + * + * Use to rerun a successful effect according to a `Schedule` when the schedule + * does not need a custom initial input. * * **Details** * - * This function allows you to execute an effect repeatedly according to a given - * schedule. The schedule determines the timing and number of repetitions. Each - * repetition can also depend on the decision of the schedule, providing - * flexibility for complex workflows. This function does not modify the effect's - * success or failure; it only controls its repetition. + * The schedule is first stepped with `undefined`. After each successful + * execution, the effect's success value is fed to the schedule to decide + * whether to run again. The returned effect fails if the effect or schedule + * fails, and otherwise succeeds with the schedule output when the schedule + * completes. * - * For example, you can use a schedule that recurs a specific number of times, - * adds delays between repetitions, or customizes repetition behavior based on - * external inputs. The effect runs initially and is repeated according to the - * schedule. + * **Example** (Scheduling repeated execution) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14456,8 +15480,8 @@ export const schedule: { * @see {@link scheduleFrom} for a variant that allows the schedule's decision * to depend on the result of this effect. * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ (self: Effect, schedule: Schedule): Effect } = dual(2, ( @@ -14466,21 +15490,19 @@ export const schedule: { ): Effect => scheduleFrom(self, undefined, schedule)) /** - * Runs an effect repeatedly according to a schedule, starting from a specified - * initial input value. + * Runs an effect repeatedly according to a schedule that is initialized with a + * specific schedule input. * * **Details** * - * This function allows you to repeatedly execute an effect based on a schedule. - * The schedule starts with the given `initial` input value, which is passed to - * the first execution. Subsequent executions of the effect are controlled by - * the schedule's rules, using the output of the previous iteration as the input - * for the next one. + * `initial` is passed to the schedule before the first execution, not to the + * effect itself. After each successful execution, the effect's success value is + * fed back into the schedule to decide whether to continue. The returned effect + * succeeds with the schedule output when the schedule completes and fails if + * the effect or schedule fails. * - * The returned effect will complete when the schedule ends or the effect fails, - * propagating the error. + * **Example** (Scheduling from an initial value) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14501,26 +15523,24 @@ export const schedule: { * // Returns the schedule count * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const scheduleFrom: { /** - * Runs an effect repeatedly according to a schedule, starting from a specified - * initial input value. + * Runs an effect repeatedly according to a schedule that is initialized with a + * specific schedule input. * * **Details** * - * This function allows you to repeatedly execute an effect based on a schedule. - * The schedule starts with the given `initial` input value, which is passed to - * the first execution. Subsequent executions of the effect are controlled by - * the schedule's rules, using the output of the previous iteration as the input - * for the next one. + * `initial` is passed to the schedule before the first execution, not to the + * effect itself. After each successful execution, the effect's success value is + * fed back into the schedule to decide whether to continue. The returned effect + * succeeds with the schedule output when the schedule completes and fails if + * the effect or schedule fails. * - * The returned effect will complete when the schedule ends or the effect fails, - * propagating the error. + * **Example** (Scheduling from an initial value) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14541,26 +15561,24 @@ export const scheduleFrom: { * // Returns the schedule count * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ (initial: Input, schedule: Schedule): (self: Effect) => Effect /** - * Runs an effect repeatedly according to a schedule, starting from a specified - * initial input value. + * Runs an effect repeatedly according to a schedule that is initialized with a + * specific schedule input. * * **Details** * - * This function allows you to repeatedly execute an effect based on a schedule. - * The schedule starts with the given `initial` input value, which is passed to - * the first execution. Subsequent executions of the effect are controlled by - * the schedule's rules, using the output of the previous iteration as the input - * for the next one. + * `initial` is passed to the schedule before the first execution, not to the + * effect itself. After each successful execution, the effect's success value is + * fed back into the schedule to decide whether to continue. The returned effect + * succeeds with the schedule output when the schedule completes and fails if + * the effect or schedule fails. * - * The returned effect will complete when the schedule ends or the effect fails, - * propagating the error. + * **Example** (Scheduling from an initial value) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14581,8 +15599,8 @@ export const scheduleFrom: { * // Returns the schedule count * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( self: Effect, @@ -14598,7 +15616,8 @@ export const scheduleFrom: { /** * Returns the current tracer from the context. * - * @example + * **Example** (Accessing the current tracer) + * * ```ts * import { Effect } from "effect" * @@ -14609,15 +15628,16 @@ export const scheduleFrom: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const tracer: Effect = internal.tracer /** * Provides a tracer to an effect. * - * @example + * **Example** (Providing a tracer) + * * ```ts * import { Effect } from "effect" * @@ -14630,14 +15650,15 @@ export const tracer: Effect = internal.tracer * // const traced = Effect.withTracer(program, customTracer) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withTracer: { /** * Provides a tracer to an effect. * - * @example + * **Example** (Providing a tracer) + * * ```ts * import { Effect } from "effect" * @@ -14650,14 +15671,15 @@ export const withTracer: { * // const traced = Effect.withTracer(program, customTracer) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (value: Tracer): (effect: Effect) => Effect /** * Provides a tracer to an effect. * - * @example + * **Example** (Providing a tracer) + * * ```ts * import { Effect } from "effect" * @@ -14670,16 +15692,22 @@ export const withTracer: { * // const traced = Effect.withTracer(program, customTracer) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, value: Tracer): Effect } = internal.withTracer /** - * Disable the tracer for the given Effect. + * Enables or disables tracing for spans created by the given effect. + * + * **Details** + * + * When `enabled` is `false`, spans created inside the effect are not registered + * with the current tracer and do not propagate as normal trace parents. + * + * **Example** (Enabling or disabling tracing) * - * @example * ```ts * import { Effect } from "effect" * @@ -14690,14 +15718,20 @@ export const withTracer: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withTracerEnabled: { /** - * Disable the tracer for the given Effect. + * Enables or disables tracing for spans created by the given effect. + * + * **Details** + * + * When `enabled` is `false`, spans created inside the effect are not registered + * with the current tracer and do not propagate as normal trace parents. + * + * **Example** (Enabling or disabling tracing) * - * @example * ```ts * import { Effect } from "effect" * @@ -14708,14 +15742,20 @@ export const withTracerEnabled: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (enabled: boolean): (effect: Effect) => Effect /** - * Disable the tracer for the given Effect. + * Enables or disables tracing for spans created by the given effect. + * + * **Details** + * + * When `enabled` is `false`, spans created inside the effect are not registered + * with the current tracer and do not propagate as normal trace parents. + * + * **Example** (Enabling or disabling tracing) * - * @example * ```ts * import { Effect } from "effect" * @@ -14726,8 +15766,8 @@ export const withTracerEnabled: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, enabled: boolean): Effect } = internal.withTracerEnabled @@ -14735,7 +15775,8 @@ export const withTracerEnabled: { /** * Enables or disables tracer timing for the given Effect. * - * @example + * **Example** (Enabling or disabling tracing timing) + * * ```ts * import { Effect } from "effect" * @@ -14746,14 +15787,15 @@ export const withTracerEnabled: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withTracerTiming: { /** * Enables or disables tracer timing for the given Effect. * - * @example + * **Example** (Enabling or disabling tracing timing) + * * ```ts * import { Effect } from "effect" * @@ -14764,14 +15806,15 @@ export const withTracerTiming: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (enabled: boolean): (effect: Effect) => Effect /** * Enables or disables tracer timing for the given Effect. * - * @example + * **Example** (Enabling or disabling tracing timing) + * * ```ts * import { Effect } from "effect" * @@ -14782,8 +15825,8 @@ export const withTracerTiming: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, enabled: boolean): Effect } = internal.withTracerTiming @@ -14791,7 +15834,8 @@ export const withTracerTiming: { /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14811,14 +15855,15 @@ export const withTracerTiming: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const annotateSpans: { /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14838,14 +15883,15 @@ export const annotateSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (key: string, value: unknown): (effect: Effect) => Effect /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14865,14 +15911,15 @@ export const annotateSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (values: Record): (effect: Effect) => Effect /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14892,14 +15939,15 @@ export const annotateSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, key: string, value: unknown): Effect /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14919,8 +15967,8 @@ export const annotateSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, values: Record): Effect } = internal.annotateSpans @@ -14928,7 +15976,8 @@ export const annotateSpans: { /** * Adds an annotation to the current span if available. * - * @example + * **Example** (Annotating the current span) + * * ```ts * import { Effect } from "effect" * @@ -14945,14 +15994,15 @@ export const annotateSpans: { * const traced = Effect.withSpan(program, "user-operation") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const annotateCurrentSpan: { /** * Adds an annotation to the current span if available. * - * @example + * **Example** (Annotating the current span) + * * ```ts * import { Effect } from "effect" * @@ -14969,14 +16019,15 @@ export const annotateCurrentSpan: { * const traced = Effect.withSpan(program, "user-operation") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (key: string, value: unknown): Effect /** * Adds an annotation to the current span if available. * - * @example + * **Example** (Annotating the current span) + * * ```ts * import { Effect } from "effect" * @@ -14993,16 +16044,22 @@ export const annotateCurrentSpan: { * const traced = Effect.withSpan(program, "user-operation") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (values: Record): Effect } = internal.annotateCurrentSpan /** - * Returns the current span from the context. + * Returns the currently active local tracing span. + * + * **Details** + * + * The effect fails with `NoSuchElementError` when there is no active local + * `Span`. + * + * **Example** (Reading the current span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15015,15 +16072,22 @@ export const annotateCurrentSpan: { * const traced = Effect.withSpan(program, "my-span") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const currentSpan: Effect = internal.currentSpan /** - * Returns the current parent span from the context. + * Returns the current parent span from the effect context. + * + * **Details** + * + * The effect succeeds with either a local span or external span when one is + * present, and fails with `NoSuchElementError` when no parent span is + * available. + * + * **Example** (Reading the parent span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15041,15 +16105,21 @@ export const currentSpan: Effect = internal.curr * const traced = Effect.withSpan(program, "parent-span") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const currentParentSpan: Effect = internal.currentParentSpan /** - * Returns the annotations of the current span. + * Returns the tracing span annotations currently carried in the effect context. + * + * **Details** + * + * These annotations are applied to spans created inside the context, such as + * spans created by `withSpan`, `useSpan`, or `makeSpan`. + * + * **Example** (Providing span annotations) * - * @example * ```ts * import { Effect } from "effect" * @@ -15069,19 +16139,21 @@ export const currentParentSpan: Effect = inte * // Output: Current span annotations: { userId: "123", operation: "data-processing" } * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const spanAnnotations: Effect>> = internal.spanAnnotations /** - * Retrieves the span links associated with the current span. + * Returns the tracing span links currently carried in the effect context. + * + * **Details** + * + * These links are attached to spans created inside the context. Span links + * connect related spans without making one span the parent of another. * - * Span links are connections between spans that are related but not in a - * parent-child relationship. They are useful for linking spans across different - * traces or connecting spans from parallel operations. + * **Example** (Providing span links) * - * @example * ```ts * import { Effect } from "effect" * @@ -15093,19 +16165,22 @@ export const spanAnnotations: Effect>> = intern * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const spanLinks: Effect> = internal.spanLinks /** - * For all spans in this effect, add a link with the provided span. + * Adds a link with the provided span to all spans in this effect. + * + * **Details** * * This is useful for connecting spans that are related but not in a direct * parent-child relationship. For example, you might want to link spans from * parallel operations or connect spans across different traces. * - * @example + * **Example** (Linking one span to another span) + * * ```ts * import { Effect } from "effect" * @@ -15127,7 +16202,8 @@ export const spanLinks: Effect> = internal.spanLinks * }) * ``` * - * @example + * **Example** (Linking multiple spans at once) + * * ```ts * import { Effect } from "effect" * @@ -15145,18 +16221,21 @@ export const spanLinks: Effect> = internal.spanLinks * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const linkSpans: { /** - * For all spans in this effect, add a link with the provided span. + * Adds a link with the provided span to all spans in this effect. + * + * **Details** * * This is useful for connecting spans that are related but not in a direct * parent-child relationship. For example, you might want to link spans from * parallel operations or connect spans across different traces. * - * @example + * **Example** (Linking one span to another span) + * * ```ts * import { Effect } from "effect" * @@ -15178,7 +16257,8 @@ export const linkSpans: { * }) * ``` * - * @example + * **Example** (Linking multiple spans at once) + * * ```ts * import { Effect } from "effect" * @@ -15196,21 +16276,24 @@ export const linkSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ ( span: AnySpan | ReadonlyArray, attributes?: Record ): (self: Effect) => Effect /** - * For all spans in this effect, add a link with the provided span. + * Adds a link with the provided span to all spans in this effect. + * + * **Details** * * This is useful for connecting spans that are related but not in a direct * parent-child relationship. For example, you might want to link spans from * parallel operations or connect spans across different traces. * - * @example + * **Example** (Linking one span to another span) + * * ```ts * import { Effect } from "effect" * @@ -15232,7 +16315,8 @@ export const linkSpans: { * }) * ``` * - * @example + * **Example** (Linking multiple spans at once) + * * ```ts * import { Effect } from "effect" * @@ -15250,8 +16334,8 @@ export const linkSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ ( self: Effect, @@ -15261,9 +16345,16 @@ export const linkSpans: { } = internal.linkSpans /** - * Create a new span for tracing. + * Creates a new tracing span and returns it without managing its lifetime. + * + * **Details** + * + * The span is not added to the current span stack and is not ended + * automatically. Use `withSpan`, `useSpan`, or `makeSpanScoped` when the span + * should be installed as context or closed automatically. + * + * **Example** (Creating a span manually) * - * @example * ```ts * import { Effect } from "effect" * @@ -15274,8 +16365,8 @@ export const linkSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const makeSpan: (name: string, options?: SpanOptionsNoTrace) => Effect = internal.makeSpan @@ -15283,10 +16374,13 @@ export const makeSpan: (name: string, options?: SpanOptionsNoTrace) => Effect Effect(name: string, evaluate: (span: Span) => Effect): Effect /** * Create a new span for tracing, and automatically close it when the effect * completes. * + * **Details** + * * The span is not added to the current span stack, so no child spans will be * created for it. * - * @example + * **Example** (Running an effect with a standalone span) + * * ```ts * import { Effect } from "effect" * @@ -15379,8 +16482,8 @@ export const useSpan: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ ( name: string, @@ -15390,9 +16493,10 @@ export const useSpan: { } = internal.useSpan /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a child span for tracing. + * + * **Example** (Wrapping an effect in a child span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15406,14 +16510,15 @@ export const useSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withSpan: { /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a child span for tracing. + * + * **Example** (Wrapping an effect in a child span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15427,8 +16532,8 @@ export const withSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ >( name: string, @@ -15439,9 +16544,10 @@ export const withSpan: { traceOptions?: TraceOptions | undefined ): (self: Effect, ...args: Args) => Effect> /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a child span for tracing. + * + * **Example** (Wrapping an effect in a child span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15455,18 +16561,21 @@ export const withSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (self: Effect, name: string, options?: SpanOptions | undefined): Effect> } = internal.withSpan /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a scoped child span for tracing. + * + * **Details** * * The span is ended when the Scope is finalized. * - * @example + * **Example** (Creating a scoped child span) + * * ```ts * import { Effect } from "effect" * @@ -15479,16 +16588,19 @@ export const withSpan: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withSpanScoped: { /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a scoped child span for tracing. + * + * **Details** * * The span is ended when the Scope is finalized. * - * @example + * **Example** (Creating a scoped child span) + * * ```ts * import { Effect } from "effect" * @@ -15501,18 +16613,21 @@ export const withSpanScoped: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (name: string, options?: SpanOptions): ( self: Effect ) => Effect | Scope> /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a scoped child span for tracing. + * + * **Details** * * The span is ended when the Scope is finalized. * - * @example + * **Example** (Creating a scoped child span) + * * ```ts * import { Effect } from "effect" * @@ -15525,8 +16640,8 @@ export const withSpanScoped: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (self: Effect, name: string, options?: SpanOptions): Effect | Scope> } = internal.withSpanScoped @@ -15534,7 +16649,8 @@ export const withSpanScoped: { /** * Adds the provided span to the current span stack. * - * @example + * **Example** (Setting a parent span) + * * ```ts * import { Effect } from "effect" * @@ -15546,14 +16662,15 @@ export const withSpanScoped: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withParentSpan: { /** * Adds the provided span to the current span stack. * - * @example + * **Example** (Setting a parent span) + * * ```ts * import { Effect } from "effect" * @@ -15565,14 +16682,15 @@ export const withParentSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (value: AnySpan, options?: TraceOptions): (self: Effect) => Effect> /** * Adds the provided span to the current span stack. * - * @example + * **Example** (Setting a parent span) + * * ```ts * import { Effect } from "effect" * @@ -15584,8 +16702,8 @@ export const withParentSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (self: Effect, value: AnySpan, options?: TraceOptions): Effect> } = internal.withParentSpan @@ -15597,10 +16715,12 @@ export const withParentSpan: { /** * Executes a request using the provided resolver. * - * @since 2.0.0 - * @category Requests & Batching + * **When to use** + * + * Use when you need resolver-driven batching for a typed `Request`. + * + * **Example** (Executing a request through a resolver) * - * @example * ```ts * import { Console, Effect, Exit, Request, RequestResolver } from "effect" * @@ -15623,6 +16743,11 @@ export const withParentSpan: { * yield* Console.log(name) * }) * ``` + * + * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect` + * + * @category requests & batching + * @since 2.0.0 */ export const request: { // ----------------------------------------------------------------------------- @@ -15632,10 +16757,12 @@ export const request: { /** * Executes a request using the provided resolver. * - * @since 2.0.0 - * @category Requests & Batching + * **When to use** + * + * Use when you need resolver-driven batching for a typed `Request`. + * + * **Example** (Executing a request through a resolver) * - * @example * ```ts * import { Console, Effect, Exit, Request, RequestResolver } from "effect" * @@ -15658,6 +16785,11 @@ export const request: { * yield* Console.log(name) * }) * ``` + * + * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect` + * + * @category requests & batching + * @since 2.0.0 */ (resolver: RequestResolver | Effect, EX, RX>): (self: A) => Effect, Request.Error | EX, Request.Services | RX> // ----------------------------------------------------------------------------- @@ -15667,10 +16799,12 @@ export const request: { /** * Executes a request using the provided resolver. * - * @since 2.0.0 - * @category Requests & Batching + * **When to use** + * + * Use when you need resolver-driven batching for a typed `Request`. + * + * **Example** (Executing a request through a resolver) * - * @example * ```ts * import { Console, Effect, Exit, Request, RequestResolver } from "effect" * @@ -15693,18 +16827,31 @@ export const request: { * yield* Console.log(name) * }) * ``` + * + * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect` + * + * @category requests & batching + * @since 2.0.0 */ (self: A, resolver: RequestResolver | Effect, EX, RX>): Effect, Request.Error | EX, Request.Services | RX> } = internalRequest.request /** - * Low-level entry point that registers a request with a resolver and delivers the exit value via `onExit`. - * Use this when you already have a `Context` and need to enqueue a request outside an `Effect`. + * Registers a request with a resolver and delivers the exit value via `onExit`. + * + * **When to use** + * + * Use when you already have a `Context` and need to enqueue a request outside + * an `Effect` while receiving completion through `onExit`. + * + * **Details** * * It returns a canceler that removes the pending request entry. * + * @see {@link request} for the `Effect`-returning API used for normal request execution + * + * @category requests & batching * @since 4.0.0 - * @category Requests & Batching */ export const requestUnsafe: ( self: A, @@ -15724,6 +16871,8 @@ export const requestUnsafe: ( * returning the fiber immediately, without waiting for it to begin executing * the effect. * + * **Details** + * * You can use the `forkChild` method whenever you want to execute an effect in a * new fiber, concurrently and without "blocking" the fiber executing other * effects. Using fibers can be tricky, so instead of using this method @@ -15740,7 +16889,8 @@ export const requestUnsafe: ( * fibers leak. This behavior is called "auto supervision", and if this * behavior is not desired, you may use the `forkDetach` or `forkIn` methods. * - * @example + * **Example** (Forking a child fiber) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -15762,8 +16912,8 @@ export const requestUnsafe: ( * }) * ``` * + * @category supervision & fibers * @since 4.0.0 - * @category Supervision & Fibers */ export const forkChild: < Arg extends Effect | { @@ -15786,7 +16936,8 @@ export const forkChild: < * Forks the effect in the specified scope. The fiber will be interrupted * when the scope is closed. * - * @example + * **Example** (Forking into a supplied scope) + * * ```ts * import { Effect } from "effect" * @@ -15806,15 +16957,16 @@ export const forkChild: < * ) * ``` * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ export const forkIn: { /** * Forks the effect in the specified scope. The fiber will be interrupted * when the scope is closed. * - * @example + * **Example** (Forking into a supplied scope) + * * ```ts * import { Effect } from "effect" * @@ -15834,8 +16986,8 @@ export const forkIn: { * ) * ``` * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ ( scope: Scope, @@ -15848,7 +17000,8 @@ export const forkIn: { * Forks the effect in the specified scope. The fiber will be interrupted * when the scope is closed. * - * @example + * **Example** (Forking into a supplied scope) + * * ```ts * import { Effect } from "effect" * @@ -15868,8 +17021,8 @@ export const forkIn: { * ) * ``` * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ ( self: Effect, @@ -15884,7 +17037,8 @@ export const forkIn: { /** * Forks the fiber in a `Scope`, interrupting it when the scope is closed. * - * @example + * **Example** (Forking into the current scope) + * * ```ts * import { Effect } from "effect" * @@ -15910,8 +17064,8 @@ export const forkIn: { * ) * ``` * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ export const forkScoped: < Arg extends Effect | { @@ -15935,7 +17089,8 @@ export const forkScoped: < * new fiber is attached to the global scope, when the fiber executing the * returned effect terminates, the forked fiber will continue running. * - * @example + * **Example** (Forking a detached fiber) + * * ```ts * import { Effect } from "effect" * @@ -15959,8 +17114,8 @@ export const forkScoped: < * }) * ``` * - * @since 2.0.0 - * @category Supervision & Fibers + * @category supervision & fibers + * @since 4.0.0 */ export const forkDetach: < Arg extends Effect | { @@ -15983,15 +17138,31 @@ export const forkDetach: < * Waits for all child fibers forked by this effect to complete before this * effect completes. * + * **When to use** + * + * Use to let an effect start child work concurrently while still delaying its + * own completion until that child work is done. + * + * **Gotchas** + * + * Child fibers that already exist before the wrapped effect starts are not + * awaited. + * + * @see {@link forkChild} for forking child fibers that are awaited by this operator + * @see {@link forkDetach} for forking fibers outside the child scope + * @see {@link forkIn} for forking into an explicit scope + * @see {@link forkScoped} for forking fibers tied to the current scope + * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ export const awaitAllChildren: (self: Effect) => Effect = internal.awaitAllChildren /** - * Access the fiber currently executing the effect. + * Accesses the fiber currently executing the effect. + * + * **Example** (Accessing the current fiber) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -16001,15 +17172,16 @@ export const awaitAllChildren: (self: Effect) => Effect> = internal.fiber /** - * Access the current fiber id executing the effect. + * Accesses the current fiber id executing the effect. + * + * **Example** (Accessing the current fiber id) * - * @example * ```ts * import { Effect } from "effect" * @@ -16024,8 +17196,8 @@ export const fiber: Effect> = internal.fiber * ) * ``` * - * @since 4.0.0 - * @category Supervision & Fibers + * @category supervision & fibers + * @since 2.0.0 */ export const fiberId: Effect = internal.fiberId @@ -16037,27 +17209,24 @@ export const fiberId: Effect = internal.fiberId * Configuration options for running Effect programs, providing control over * interruption and scheduling behavior. * - * @example - * ```ts - * import { Effect } from "effect" + * **When to use** * - * const program = Effect.gen(function*() { - * yield* Effect.sleep("2 seconds") - * return "completed" - * }) + * Use to pass cancellation, scheduler, interruptibility, and fiber-start hooks + * when running an `Effect` at a program boundary. * - * // Run with abort signal for cancellation - * const controller = new AbortController() - * const options: Effect.RunOptions = { - * signal: controller.signal - * } + * **Details** * - * const fiber = Effect.runFork(program, options) - * // Later: controller.abort() to cancel - * ``` + * `signal` interrupts the fiber, `scheduler` provides the scheduler service, + * `uninterruptible` starts the fiber uninterruptibly, and `onFiberStart` + * receives the created fiber. * + * @see {@link runFork} for starting a fiber with these options + * @see {@link runCallback} for callback-based running with these options + * @see {@link runPromise} for promise-based running with these options + * @see {@link runPromiseExit} for promise-based running that returns an `Exit` + * + * @category running * @since 4.0.0 - * @category Running Effects */ export interface RunOptions { readonly signal?: AbortSignal | undefined @@ -16067,25 +17236,17 @@ export interface RunOptions { } /** - * The foundational function for running effects, returning a "fiber" that can + * Runs an effect in the background, returning a fiber that can * be observed or interrupted. * - * **When to Use** + * **When to use** * - * `runFork` is used to run an effect in the background by creating a - * fiber. It is the base function for all other run functions. It starts a fiber - * that can be observed or interrupted. + * Use when you need to start an effect in the background and receive a fiber. * - * Unless you specifically need a `Promise` or synchronous operation, - * `runFork` is a good default choice. + * **Example** (Running an effect in the background) * - * @example * ```ts - * // Title: Running an Effect in the Background - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Fiber } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Fiber, Schedule } from "effect" * * // ┌─── Effect * // ▼ @@ -16103,8 +17264,8 @@ export interface RunOptions { * }, 500) * ``` * + * @category running * @since 2.0.0 - * @category Running Effects */ export const runFork: (effect: Effect, options?: RunOptions | undefined) => Fiber = internal.runFork @@ -16112,9 +17273,15 @@ export const runFork: (effect: Effect, options?: RunOptions | /** * Runs an effect in the background with the provided services. * - * @example + * **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 - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * interface Logger { * log: (message: string) => void @@ -16135,8 +17302,8 @@ export const runFork: (effect: Effect, options?: RunOptions | * const fiber = Effect.runForkWith(services)(program) * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runForkWith: ( context: Context.Context @@ -16145,11 +17312,19 @@ 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. * - * @example + * **Example** (Running with services and a callback) + * * ```ts - * import { Console, Effect, Exit, Context } from "effect" + * import { Console, Context, Effect, Exit } from "effect" * * interface Logger { * log: (message: string) => Effect.Effect @@ -16179,8 +17354,8 @@ export const runForkWith: ( * interrupt() * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runCallbackWith: ( context: Context.Context @@ -16193,10 +17368,13 @@ export const runCallbackWith: ( * Runs an effect asynchronously, registering `onExit` as a fiber observer and * returning an interruptor. * + * **Details** + * * The interruptor calls `fiber.interruptUnsafe` with the optional interruptor * id. * - * @example + * **Example** (Running with a callback) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -16223,8 +17401,8 @@ export const runCallbackWith: ( * // interrupt() to cancel the fiber if needed * ``` * - * @since 4.0.0 - * @category Running Effects + * @category running + * @since 2.0.0 */ export const runCallback: ( effect: Effect, @@ -16234,36 +17412,38 @@ export const runCallback: ( /** * Executes an effect and returns the result as a `Promise`. * - * **When to Use** + * **When to use** * - * Use `runPromise` when you need to execute an effect and work with the + * Use when you need to execute an effect and work with the * result using `Promise` syntax, typically for compatibility with other * promise-based code. * * If the effect succeeds, the promise will resolve with the result. If the * effect fails, the promise will reject with an error. * - * @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. + * **Example** (Running a successful effect as a Promise) * - * @example * ```ts - * // Title: Running a Successful Effect as a Promise * import { Effect } from "effect" * * Effect.runPromise(Effect.succeed(1)).then(console.log) * // Output: 1 * ``` * - * @example + * **Example** (Running effects as promises) + * + * ```ts * //Example: Handling a Failing Effect as a Rejected Promise * import { Effect } from "effect" * * Effect.runPromise(Effect.fail("my error")).catch(console.error) * // Output: * // (FiberFailure) Error: my error + * ``` * + * @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. + * @category running * @since 2.0.0 - * @category Running Effects */ export const runPromise: ( effect: Effect, @@ -16273,9 +17453,15 @@ export const runPromise: ( /** * Executes an effect as a Promise with the provided services. * - * @example + * **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 - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * interface Config { * apiUrl: string @@ -16295,8 +17481,8 @@ export const runPromise: ( * Effect.runPromiseWith(context)(program).then(console.log) * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runPromiseWith: ( context: Context.Context @@ -16306,21 +17492,20 @@ export const runPromiseWith: ( * Runs an effect and returns a `Promise` that resolves to an `Exit`, which * represents the outcome (success or failure) of the effect. * - * **When to Use** + * **When to use** * - * Use `runPromiseExit` when you need to determine if an effect succeeded + * Use when you need to determine if an effect succeeded * or failed, including any defects, and you want to work with a `Promise`. * * **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) * - * @example * ```ts - * // Title: Handling Results as Exit * import { Effect } from "effect" * * // Execute a successful effect and get the Exit result as a Promise @@ -16346,8 +17531,10 @@ export const runPromiseWith: ( * // } * ``` * + * @see {@link runPromise} for a version that rejects on failure. + * + * @category running * @since 2.0.0 - * @category Running Effects */ export const runPromiseExit: ( effect: Effect, @@ -16357,9 +17544,15 @@ export const runPromiseExit: ( /** * Runs an effect and returns a Promise of Exit with provided services. * - * @example + * **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 - * import { Effect, Exit, Context } from "effect" + * import { Context, Effect, Exit } from "effect" * * interface Database { * query: (sql: string) => string @@ -16383,8 +17576,8 @@ export const runPromiseExit: ( * }) * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runPromiseExitWith: ( context: Context.Context @@ -16392,23 +17585,22 @@ export const runPromiseExitWith: ( internal.runPromiseExitWith /** - * Executes an effect synchronously, running it immediately and returning the - * result. + * Executes an effect synchronously and returns its success value. * - * **When to Use** + * **When to use** * - * Use `runSync` to run an effect that does not fail and does not include - * any asynchronous operations. + * Use when you need to execute an effect that is guaranteed to complete + * synchronously. * - * If the effect fails or involves asynchronous work, it will throw an error, - * and execution will stop where the failure or async operation occurs. + * **Details** * - * @see {@link runSyncExit} for a version that returns an `Exit` type instead of - * throwing an error. + * If the effect fails, dies, is interrupted, or performs asynchronous work, + * `runSync` throws a `FiberFailure` instead of returning a value. Use + * `runSyncExit` when you want the failure captured as an `Exit`. + * + * **Example** (Running a synchronous effect) * - * @example * ```ts - * // Title: Synchronous Logging * import { Effect } from "effect" * * const program = Effect.sync(() => { @@ -16423,8 +17615,9 @@ export const runPromiseExitWith: ( * // Output: 1 * ``` * - * @example - * // Title: Incorrect Usage with Failing or Async Effects + * **Example** (Throwing for failed or async effects) + * + * ```ts * import { Effect } from "effect" * * try { @@ -16444,18 +17637,27 @@ export const runPromiseExitWith: ( * } * // Output: * // (FiberFailure) AsyncFiberException: Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work + * ``` * + * @see {@link runSyncExit} for a version that returns an `Exit` type instead of + * throwing an error. + * @category running * @since 2.0.0 - * @category Running Effects */ export const runSync: (effect: Effect) => A = internal.runSync /** * Executes an effect synchronously with provided services. * - * @example + * **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 - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * interface MathService { * add: (a: number, b: number) => number @@ -16476,36 +17678,35 @@ export const runSync: (effect: Effect) => A = internal.runSync * console.log(result) // 5 * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runSyncWith: ( context: Context.Context ) => (effect: Effect) => A = internal.runSyncWith /** - * Runs an effect synchronously and returns the result as an `Exit` type, which + * Runs an effect synchronously and captures the outcome safely as an `Exit` type, which * represents the outcome (success or failure) of the effect. * - * **When to Use** + * **When to use** * - * Use `runSyncExit` to find out whether an effect succeeded or failed, + * Use to find out whether an effect succeeded or failed, * including any defects, without dealing with asynchronous operations. * * **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 * resolved synchronously. * - * @example + * **Example** (Observing synchronous results as Exit) + * * ```ts - * // Title: Handling Results as Exit * import { Effect } from "effect" * * console.log(Effect.runSyncExit(Effect.succeed(1))) @@ -16529,8 +17730,9 @@ export const runSyncWith: ( * // } * ``` * - * @example - * // Title: Asynchronous Operation Resulting in Die + * **Example** (Capturing async work as a Die cause) + * + * ```ts * import { Effect } from "effect" * * console.log(Effect.runSyncExit(Effect.promise(() => Promise.resolve(1)))) @@ -16548,18 +17750,27 @@ export const runSyncWith: ( * // } * // } * // } + * ``` * + * @see {@link runSync} for a version that throws on failure. + * + * @category running * @since 2.0.0 - * @category Running Effects */ export const runSyncExit: (effect: Effect) => Exit.Exit = internal.runSyncExit /** - * Runs an effect synchronously with provided services, returning an Exit result. + * 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) * - * @example * ```ts - * import { Effect, Exit, Context } from "effect" + * import { Context, Effect, Exit } from "effect" * * // Define a logger service * const Logger = Context.Service<{ @@ -16589,8 +17800,8 @@ export const runSyncExit: (effect: Effect) => Exit.Exit = inte * // Success: 42 * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runSyncExitWith: ( context: Context.Context @@ -16603,102 +17814,144 @@ export const runSyncExitWith: ( /** * Type helpers for functions built with `Effect.fn` and `Effect.fnUntraced`. * + * **Details** + * * Use these to describe generator-based signatures and traced or untraced variants. * - * @since 3.12.0 - * @category Function + * @since 3.11.0 */ -export namespace fn { +export declare namespace fn { /** + * Generator return type accepted by {@link fn} and {@link fnUntraced}. + * + * **When to use** + * + * Use when you need to annotate the return type of a generator body while + * keeping the produced function's `Effect` return type inferred. + * + * **Example** (Annotating an Effect function) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: string + * ): Effect.fn.Return { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Annotating a parametric Effect function) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: A + * ): Effect.fn.Return { + * return yield* Effect.succeed(value) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * @category utility types * @since 3.19.0 - * @category Models */ - export type Return = Generator, A, any> + export type Return = Generator, A, any> /** + * Type of the untraced function builder used by `Effect.fnUntraced`. + * + * @category utility types * @since 3.11.0 - * @category Models */ export type Untraced = { - , AEff, Args extends Array>( + , AEff, Args extends Array>( body: (this: unassigned, ...args: Args) => Generator ): (...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array>( + , AEff, Args extends Array>( body: (this: Self, ...args: Args) => Generator ): (this: Self, ...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( body: (this: unassigned, ...args: Args) => Generator, a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (...args: Args) => A - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( body: (this: Self, ...args: Args) => Generator, a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (this: Self, ...args: Args) => A - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( body: (this: unassigned, ...args: Args) => Generator, a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A, b: (_: A, ...args: Args) => B ): (...args: Args) => B - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( body: (this: Self, ...args: Args) => Generator, a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16706,7 +17959,7 @@ export namespace fn { b: (_: A, ...args: Args) => B ): (this: Self, ...args: Args) => B < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16718,10 +17971,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16731,7 +17984,7 @@ export namespace fn { ): (...args: Args) => C < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16743,10 +17996,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16755,7 +18008,7 @@ export namespace fn { c: (_: B, ...args: Args) => C ): (this: Self, ...args: Args) => C < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16768,10 +18021,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16782,7 +18035,7 @@ export namespace fn { ): (...args: Args) => D < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16795,10 +18048,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16808,7 +18061,7 @@ export namespace fn { d: (_: C, ...args: Args) => D ): (this: Self, ...args: Args) => D < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16822,10 +18075,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16837,7 +18090,7 @@ export namespace fn { ): (...args: Args) => E < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16851,10 +18104,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16865,7 +18118,7 @@ export namespace fn { e: (_: D, ...args: Args) => E ): (this: Self, ...args: Args) => E < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16880,10 +18133,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16896,7 +18149,7 @@ export namespace fn { ): (...args: Args) => F < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16911,10 +18164,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16926,7 +18179,7 @@ export namespace fn { f: (_: E, ...args: Args) => F ): (this: Self, ...args: Args) => F < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16942,10 +18195,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16959,7 +18212,7 @@ export namespace fn { ): (...args: Args) => G < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16975,10 +18228,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16991,7 +18244,7 @@ export namespace fn { g: (_: F, ...args: Args) => G ): (this: Self, ...args: Args) => G < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17008,10 +18261,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17026,7 +18279,7 @@ export namespace fn { ): (...args: Args) => H < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17043,10 +18296,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17060,7 +18313,7 @@ export namespace fn { h: (_: G, ...args: Args) => H ): (this: Self, ...args: Args) => H < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17078,10 +18331,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17097,7 +18350,7 @@ export namespace fn { ): (...args: Args) => I < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17115,10 +18368,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17133,7 +18386,7 @@ export namespace fn { i: (_: H, ...args: Args) => I ): (this: Self, ...args: Args) => I < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17152,10 +18405,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17172,7 +18425,7 @@ export namespace fn { ): (...args: Args) => J < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17191,10 +18444,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17210,7 +18463,7 @@ export namespace fn { j: (_: I, ...args: Args) => J ): (this: Self, ...args: Args) => J < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17230,10 +18483,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17251,7 +18504,7 @@ export namespace fn { ): (...args: Args) => K < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17271,10 +18524,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17291,7 +18544,7 @@ export namespace fn { k: (_: J, ...args: Args) => K ): (this: Self, ...args: Args) => K < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17312,10 +18565,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17334,7 +18587,7 @@ export namespace fn { ): (...args: Args) => L < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17355,10 +18608,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17376,7 +18629,7 @@ export namespace fn { l: (_: K, ...args: Args) => L ): (this: Self, ...args: Args) => L < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17398,10 +18651,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17421,7 +18674,7 @@ export namespace fn { ): (...args: Args) => M < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17443,10 +18696,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17465,7 +18718,7 @@ export namespace fn { m: (_: L, ...args: Args) => M ): (this: Self, ...args: Args) => M < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17488,10 +18741,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17512,7 +18765,7 @@ export namespace fn { ): (...args: Args) => N < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17535,10 +18788,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17558,7 +18811,7 @@ export namespace fn { n: (_: M, ...args: Args) => N ): (this: Self, ...args: Args) => N < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17582,10 +18835,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17607,7 +18860,7 @@ export namespace fn { ): (...args: Args) => O < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17631,10 +18884,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17655,7 +18908,7 @@ export namespace fn { o: (_: N, ...args: Args) => O ): (this: Self, ...args: Args) => O < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17680,10 +18933,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17706,7 +18959,7 @@ export namespace fn { ): (...args: Args) => P < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17731,10 +18984,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17756,7 +19009,7 @@ export namespace fn { p: (_: O, ...args: Args) => P ): (this: Self, ...args: Args) => P < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17782,10 +19035,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17809,7 +19062,7 @@ export namespace fn { ): (...args: Args) => Q < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17835,10 +19088,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17861,7 +19114,7 @@ export namespace fn { q: (_: P, ...args: Args) => Q ): (this: Self, ...args: Args) => Q < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17888,10 +19141,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17916,7 +19169,7 @@ export namespace fn { ): (...args: Args) => R < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17943,10 +19196,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17970,7 +19223,7 @@ export namespace fn { r: (_: Q, ...args: Args) => R ): (this: Self, ...args: Args) => R < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17998,10 +19251,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18027,7 +19280,7 @@ export namespace fn { ): (...args: Args) => S < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18055,10 +19308,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18083,7 +19336,7 @@ export namespace fn { s: (_: R, ...args: Args) => S ): (this: Self, ...args: Args) => S < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18112,10 +19365,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18142,7 +19395,7 @@ export namespace fn { ): (...args: Args) => T < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18171,10 +19424,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18202,135 +19455,137 @@ export namespace fn { } /** - * @since 3.11.0 - * @category Models + * Type of the traced function builder used by `Effect.fn`. + * + * @category utility types + * @since 4.0.0 */ export type Traced = { - , AEff, Args extends Array>( + , AEff, Args extends Array>( body: (this: unassigned, ...args: Args) => Generator | (Eff & Effect) ): (...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array>( + , AEff, Args extends Array>( body: (this: Self, ...args: Args) => Generator | (Eff & Effect) ): (this: Self, ...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array>( + , AEff, Args extends Array>( options: { readonly self: Self }, body: (this: Self, ...args: Args) => Generator | (Eff & Effect) ): (...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( body: (this: unassigned, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (...args: Args) => A - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( body: (this: Self, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (this: Self, ...args: Args) => A - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( options: { readonly self: Self }, body: (this: Self, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (...args: Args) => A - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( body: (this: unassigned, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A, b: (_: A, ...args: Args) => B ): (...args: Args) => B - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( body: (this: Self, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A, b: (_: A, ...args: Args) => B ): (this: Self, ...args: Args) => B - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( options: { readonly self: Self }, body: (this: Self, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18339,7 +19594,7 @@ export namespace fn { ): (...args: Args) => B < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18351,10 +19606,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18364,7 +19619,7 @@ export namespace fn { ): (...args: Args) => C < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18376,10 +19631,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18389,7 +19644,7 @@ export namespace fn { ): (this: Self, ...args: Args) => C < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18402,10 +19657,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18415,7 +19670,7 @@ export namespace fn { ): (...args: Args) => C < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18428,10 +19683,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18442,7 +19697,7 @@ export namespace fn { ): (...args: Args) => D < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18455,10 +19710,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18470,7 +19725,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18484,10 +19739,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18498,7 +19753,7 @@ export namespace fn { ): (...args: Args) => D < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18512,10 +19767,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18527,7 +19782,7 @@ export namespace fn { ): (...args: Args) => E < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18541,10 +19796,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18557,7 +19812,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18572,10 +19827,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18587,7 +19842,7 @@ export namespace fn { ): (...args: Args) => E < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18602,10 +19857,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18618,7 +19873,7 @@ export namespace fn { ): (...args: Args) => F < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18633,10 +19888,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18650,7 +19905,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18666,10 +19921,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18682,7 +19937,7 @@ export namespace fn { ): (...args: Args) => F < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18698,10 +19953,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18715,7 +19970,7 @@ export namespace fn { ): (...args: Args) => G < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18731,10 +19986,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18749,7 +20004,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18766,10 +20021,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18783,7 +20038,7 @@ export namespace fn { ): (...args: Args) => G < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18800,10 +20055,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18818,7 +20073,7 @@ export namespace fn { ): (...args: Args) => H < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18835,10 +20090,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18854,7 +20109,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18872,10 +20127,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18890,7 +20145,7 @@ export namespace fn { ): (...args: Args) => H < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18908,10 +20163,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18927,7 +20182,7 @@ export namespace fn { ): (...args: Args) => I < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18945,10 +20200,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18965,7 +20220,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18984,10 +20239,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19003,7 +20258,7 @@ export namespace fn { ): (...args: Args) => I < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19022,10 +20277,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19042,7 +20297,7 @@ export namespace fn { ): (...args: Args) => J < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19061,10 +20316,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19082,7 +20337,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19102,10 +20357,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19122,7 +20377,7 @@ export namespace fn { ): (...args: Args) => J < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19142,10 +20397,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19163,7 +20418,7 @@ export namespace fn { ): (...args: Args) => K < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19183,10 +20438,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19205,7 +20460,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19226,10 +20481,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19247,7 +20502,7 @@ export namespace fn { ): (...args: Args) => K < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19268,10 +20523,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19290,7 +20545,7 @@ export namespace fn { ): (...args: Args) => L < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19311,10 +20566,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19334,7 +20589,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19356,10 +20611,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19378,7 +20633,7 @@ export namespace fn { ): (...args: Args) => L < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19400,10 +20655,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19423,7 +20678,7 @@ export namespace fn { ): (...args: Args) => M < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19445,10 +20700,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19469,7 +20724,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19492,10 +20747,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19515,7 +20770,7 @@ export namespace fn { ): (...args: Args) => M < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19538,10 +20793,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19562,7 +20817,7 @@ export namespace fn { ): (...args: Args) => N < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19585,10 +20840,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19610,7 +20865,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19634,10 +20889,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19658,7 +20913,7 @@ export namespace fn { ): (...args: Args) => N < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19682,10 +20937,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19707,7 +20962,7 @@ export namespace fn { ): (...args: Args) => O < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19731,10 +20986,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19757,7 +21012,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19782,10 +21037,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19807,7 +21062,7 @@ export namespace fn { ): (...args: Args) => O < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19832,10 +21087,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19858,7 +21113,7 @@ export namespace fn { ): (...args: Args) => P < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19883,10 +21138,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19910,7 +21165,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19936,10 +21191,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19962,7 +21217,7 @@ export namespace fn { ): (...args: Args) => P < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19988,10 +21243,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20015,7 +21270,7 @@ export namespace fn { ): (...args: Args) => Q < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20041,10 +21296,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20069,7 +21324,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20096,10 +21351,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20123,7 +21378,7 @@ export namespace fn { ): (...args: Args) => Q < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20150,10 +21405,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20178,7 +21433,7 @@ export namespace fn { ): (...args: Args) => R < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20205,10 +21460,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20234,7 +21489,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20262,10 +21517,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20290,7 +21545,7 @@ export namespace fn { ): (...args: Args) => R < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20318,10 +21573,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20347,7 +21602,7 @@ export namespace fn { ): (...args: Args) => S < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20375,10 +21630,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20405,7 +21660,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20434,10 +21689,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20463,7 +21718,7 @@ export namespace fn { ): (...args: Args) => S < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20492,10 +21747,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20522,7 +21777,7 @@ export namespace fn { ): (...args: Args) => T < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20551,10 +21806,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20582,7 +21837,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20612,10 +21867,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20646,51 +21901,211 @@ export namespace fn { /** * Creates an Effect-returning function without tracing. * - * `Effect.fnUntraced` also acts as a `pipe` function, so you can append transforms after the body. + * **When to use** + * + * Use when you are defining a reusable Effect function whose implementation + * would otherwise be a normal function returning {@link gen}, especially when + * tracing spans or stack-frame capture are not needed. + * + * **Details** + * + * Compared to a plain function that returns {@link gen}, `Effect.fnUntraced` + * reuses the generator body instead of allocating a fresh generator closure + * around the arguments on every call. It does not record an Effect stack-frame + * boundary and does not create tracing spans. Use {@link fn} when you need + * those stack frames or spans. Additional arguments after the generator body + * act like `pipe` transforms: each transform receives the previous result and + * the original function arguments. Annotate the generator return type with + * `Effect.fn.Return` when the produced `Effect` type needs to be + * stated explicitly. + * + * **Example** (Defining untraced effect functions) * - * @example * ```ts - * import { Console, Effect } from "effect" + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: string + * ) { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Transforming the returned Effect) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced( + * function*(value: string) { + * return yield* Effect.succeed(value.length) + * }, + * (effect, value) => + * effect.pipe(Effect.map((length) => `${value}: ${length}`)) + * ) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Annotating an untraced non-parametric function) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: string + * ): Effect.fn.Return { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Annotating an untraced parametric function) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: A + * ): Effect.fn.Return { + * return yield* Effect.succeed(value) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * @category functions + * @since 3.12.0 + */ +export const fnUntraced: fn.Untraced = internal.fnUntraced + +/** + * Creates a reusable traced function from an Effect body. + * + * **When to use** + * + * Use when you are defining a reusable Effect function whose implementation + * would otherwise be a normal function returning {@link gen}, and you want + * tracing spans or stack-frame capture. + * + * **Details** + * + * Compared to a plain function that returns {@link gen}, `Effect.fn` reuses the + * generator body instead of allocating a fresh generator closure around the + * arguments on every call. Call `Effect.fn(body, ...)` for a generic + * stack-frame boundary without creating a span. Call + * `Effect.fn("operationName", options?)(body, ...)` when that boundary should + * have a readable operation name and the returned `Effect` should create a + * tracing span when run. {@link SpanOptionsNoTrace} configures span metadata + * such as attributes, links, parent or root selection, kind, sampling, and log + * level. Additional arguments after the generator body act like `pipe` + * transforms: each transform receives the previous result and the original + * function arguments. When those transforms return an `Effect`, the returned + * effect includes stack-frame metadata and, for the named form, a tracing span. + * Generator bodies may declare a `this` parameter; pass `{ self }` before the + * body to bind `this` when the function is created. + * + * **Example** (Defining traced effect functions) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fn("calculateLength")(function*(value: string) { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Transforming the returned Effect) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fn("formatLength")( + * function*(value: string) { + * return yield* Effect.succeed(value.length) + * }, + * (effect, value) => + * effect.pipe(Effect.map((length) => `${value}: ${length}`)) + * ) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Binding this) + * + * ```ts + * import { Effect } from "effect" + * + * class Counter { + * count = 0 + * + * increment = Effect.fn("Counter.increment")( + * { self: this }, + * function*(this: Counter, by: number) { + * this.count += by + * return yield* Effect.succeed(this.count) + * } + * ) + * } + * + * const counter = new Counter() + * + * // ┌─── Effect.Effect + * // ▼ + * const program = counter.increment(1) + * ``` + * + * **Example** (Annotating a traced non-parametric function) + * + * ```ts + * import { Effect } from "effect" * - * const greet = Effect.fnUntraced(function* (name: string) { - * yield* Console.log(`Hello, ${name}`) - * return name.length + * const f = Effect.fn("calculateLength")(function*( + * value: string + * ): Effect.fn.Return { + * return yield* Effect.succeed(value.length) * }) * - * Effect.runFork(greet("Ada")) + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") * ``` * - * @since 3.12.0 - * @category Function - */ -export const fnUntraced: fn.Untraced = internal.fnUntraced - -/** - * Creates a traced function with an optional span name and `SpanOptionsNoTrace` that adds spans and stack frames, plus pipeable post-processing that receives the Effect and the original arguments. - * - * Pipeable functions run after the body and can transform the resulting Effect. + * **Example** (Annotating a traced parametric function) * - * @example * ```ts - * import { Console, Effect } from "effect" - * - * // Create a named span and post-process the returned Effect. - * const greet = Effect.fn("greet")( - * function*(name: string) { - * yield* Console.log(`Hello, ${name}`) - * return name.length - * }, - * Effect.map((length) => length + 1) - * ) + * import { Effect } from "effect" * - * const program = Effect.gen(function*() { - * const result = yield* greet("Ada") - * yield* Console.log(`Length: ${result}`) + * const f = Effect.fn("succeed")(function*( + * value: A + * ): Effect.fn.Return { + * return yield* Effect.succeed(value) * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") * ``` * - * @since 3.12.0 - * @category Function + * @category functions + * @since 3.11.0 */ export const fn: fn.Traced & { (name: string, options?: SpanOptionsNoTrace): fn.Traced @@ -20704,7 +22119,8 @@ export const fn: fn.Traced & { * Retrieves the `Clock` service from the context and provides it to the * specified effectful function. * - * @example + * **Example** (Accessing the Clock service) + * * ```ts * import { Console, Effect } from "effect" * @@ -20720,8 +22136,8 @@ export const fn: fn.Traced & { * // Current time is: 1735484929744 * ``` * + * @category clock * @since 2.0.0 - * @category Clock */ export const clockWith: ( f: (clock: Clock) => Effect @@ -20734,10 +22150,13 @@ export const clockWith: ( /** * Creates a logger function that logs at the specified level. * + * **Details** + * * If no level is provided, the logger uses the fiber's current log level and * extracts any `Cause` values from the message list. * - * @example + * **Example** (Logging at a dynamic level) + * * ```ts * import { Effect } from "effect" * @@ -20748,8 +22167,8 @@ export const clockWith: ( * }) * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logWithLevel: (level?: Severity) => (...message: ReadonlyArray) => Effect = internal.logWithLevel @@ -20757,7 +22176,8 @@ export const logWithLevel: (level?: Severity) => (...message: ReadonlyArray /** * Logs one or more messages using the default log level. * - * @example + * **Example** (Logging at the default level) + * * ```ts * import { Effect } from "effect" * @@ -20777,15 +22197,16 @@ export const logWithLevel: (level?: Severity) => (...message: ReadonlyArray * // 4 * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const log: (...message: ReadonlyArray) => Effect = internal.logWithLevel() /** * Logs one or more messages at the FATAL level. * - * @example + * **Example** (Logging fatal messages) + * * ```ts * import { Effect } from "effect" * @@ -20806,15 +22227,16 @@ export const log: (...message: ReadonlyArray) => Effect = internal.lo * // timestamp=2023-... level=FATAL message="System shutting down" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logFatal: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Fatal") /** * Logs one or more messages at the WARNING level. * - * @example + * **Example** (Logging warnings) + * * ```ts * import { Effect } from "effect" * @@ -20836,15 +22258,16 @@ export const logFatal: (...message: ReadonlyArray) => Effect = intern * // timestamp=2023-... level=WARN message="Using deprecated API endpoint" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logWarning: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Warn") /** * Logs one or more messages at the ERROR level. * - * @example + * **Example** (Logging errors) + * * ```ts * import { Effect } from "effect" * @@ -20869,15 +22292,16 @@ export const logWarning: (...message: ReadonlyArray) => Effect = inte * // timestamp=2023-... level=ERROR message="Caught error: Something went wrong" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logError: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Error") /** * Logs one or more messages at the INFO level. * - * @example + * **Example** (Logging information) + * * ```ts * import { Effect } from "effect" * @@ -20897,15 +22321,16 @@ export const logError: (...message: ReadonlyArray) => Effect = intern * // timestamp=2023-... level=INFO message="Application version: 1.2.3" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logInfo: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Info") /** * Logs one or more messages at the DEBUG level. * - * @example + * **Example** (Logging debug messages) + * * ```ts * import { Effect } from "effect" * @@ -20926,15 +22351,16 @@ export const logInfo: (...message: ReadonlyArray) => Effect = interna * // timestamp=2023-... level=DEBUG message="Variable state: x=10 y=20 z=30" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logDebug: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Debug") /** * Logs one or more messages at the TRACE level. * - * @example + * **Example** (Logging trace messages) + * * ```ts * import { Effect } from "effect" * @@ -20958,15 +22384,16 @@ export const logDebug: (...message: ReadonlyArray) => Effect = intern * // timestamp=2023-... level=TRACE message="Exiting function processData" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logTrace: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Trace") /** * Adds a logger to the set of loggers which will output logs for this effect. * - * @example + * **Example** (Adding a logger to an effect) + * * ```ts * import { Effect, Logger } from "effect" * @@ -20987,14 +22414,15 @@ export const logTrace: (...message: ReadonlyArray) => Effect = intern * // Output includes both default and custom log outputs * ``` * - * @since 2.0.0 - * @category Logging + * @category logging + * @since 4.0.0 */ export const withLogger = dual< /** * Adds a logger to the set of loggers which will output logs for this effect. * - * @example + * **Example** (Adding a logger to an effect) + * * ```ts * import { Effect, Logger } from "effect" * @@ -21015,14 +22443,15 @@ export const withLogger = dual< * // Output includes both default and custom log outputs * ``` * - * @since 2.0.0 - * @category Logging + * @category logging + * @since 4.0.0 */ (logger: Logger) => (effect: Effect) => Effect, /** * Adds a logger to the set of loggers which will output logs for this effect. * - * @example + * **Example** (Adding a logger to an effect) + * * ```ts * import { Effect, Logger } from "effect" * @@ -21043,8 +22472,8 @@ export const withLogger = dual< * // Output includes both default and custom log outputs * ``` * - * @since 2.0.0 - * @category Logging + * @category logging + * @since 4.0.0 */ (effect: Effect, logger: Logger) => Effect >(2, (effect, logger) => @@ -21057,7 +22486,8 @@ export const withLogger = dual< /** * Adds an annotation to each log line in this effect. * - * @example + * **Example** (Adding log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21080,14 +22510,15 @@ export const withLogger = dual< * // All log messages will include the userId and operation annotations * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const annotateLogs = dual< /** * Adds an annotation to each log line in this effect. * - * @example + * **Example** (Adding log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21110,8 +22541,8 @@ export const annotateLogs = dual< * // All log messages will include the userId and operation annotations * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ { ( @@ -21125,7 +22556,8 @@ export const annotateLogs = dual< /** * Adds an annotation to each log line in this effect. * - * @example + * **Example** (Adding log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21148,8 +22580,8 @@ export const annotateLogs = dual< * // All log messages will include the userId and operation annotations * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ { ( @@ -21182,11 +22614,18 @@ export const annotateLogs = dual< /** * Adds log annotations to the current scope. * + * **When to use** + * + * Use to attach log annotations that last until the current scope closes. + * + * **Details** + * * This differs from `annotateLogs`, which only annotates a specific effect. * `annotateLogsScoped` updates annotations for the entire current `Scope` and * restores the previous annotations when the scope closes. * - * @example + * **Example** (Adding scoped log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21201,18 +22640,27 @@ export const annotateLogs = dual< * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Logging + * @see {@link annotateLogs} for annotating one effect + * + * @category logging + * @since 3.1.0 */ export const annotateLogsScoped: { /** * Adds log annotations to the current scope. * + * **When to use** + * + * Use to attach log annotations that last until the current scope closes. + * + * **Details** + * * This differs from `annotateLogs`, which only annotates a specific effect. * `annotateLogsScoped` updates annotations for the entire current `Scope` and * restores the previous annotations when the scope closes. * - * @example + * **Example** (Adding scoped log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21227,18 +22675,27 @@ export const annotateLogsScoped: { * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Logging + * @see {@link annotateLogs} for annotating one effect + * + * @category logging + * @since 3.1.0 */ (key: string, value: unknown): Effect /** * Adds log annotations to the current scope. * + * **When to use** + * + * Use to attach log annotations that last until the current scope closes. + * + * **Details** + * * This differs from `annotateLogs`, which only annotates a specific effect. * `annotateLogsScoped` updates annotations for the entire current `Scope` and * restores the previous annotations when the scope closes. * - * @example + * **Example** (Adding scoped log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21253,8 +22710,10 @@ export const annotateLogsScoped: { * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Logging + * @see {@link annotateLogs} for annotating one effect + * + * @category logging + * @since 3.1.0 */ (values: Record): Effect } = internal.annotateLogsScoped @@ -21262,7 +22721,8 @@ export const annotateLogsScoped: { /** * Adds a span to each log line in this effect. * - * @example + * **Example** (Adding a log span) + * * ```ts * import { Effect } from "effect" * @@ -21286,14 +22746,15 @@ export const annotateLogsScoped: { * // All log messages will include span information showing the nested operation context * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const withLogSpan = dual< /** * Adds a span to each log line in this effect. * - * @example + * **Example** (Adding a log span) + * * ```ts * import { Effect } from "effect" * @@ -21317,14 +22778,15 @@ export const withLogSpan = dual< * // All log messages will include span information showing the nested operation context * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ (label: string) => (effect: Effect) => Effect, /** * Adds a span to each log line in this effect. * - * @example + * **Example** (Adding a log span) + * * ```ts * import { Effect } from "effect" * @@ -21348,8 +22810,8 @@ export const withLogSpan = dual< * // All log messages will include span information showing the nested operation context * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ (effect: Effect, label: string) => Effect >( @@ -21369,10 +22831,13 @@ export const withLogSpan = dual< /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21391,7 +22856,8 @@ export const withLogSpan = dual< * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21411,8 +22877,8 @@ export const withLogSpan = dual< * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const track: { // ----------------------------------------------------------------------------- @@ -21422,10 +22888,13 @@ export const track: { /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21444,7 +22913,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21464,8 +22934,8 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, f: (exit: Exit.Exit) => Input): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -21475,10 +22945,13 @@ export const track: { /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21497,7 +22970,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21517,8 +22991,8 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, NoInfer>, State>): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -21528,10 +23002,13 @@ export const track: { /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21550,7 +23027,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21570,8 +23048,8 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -21585,10 +23063,13 @@ export const track: { /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21607,7 +23088,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21627,8 +23109,8 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -21651,10 +23133,13 @@ export const track: { * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21672,7 +23157,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21689,18 +23175,21 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const trackSuccesses: { /** * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21718,7 +23207,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21735,18 +23225,21 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, f: (value: A) => Input): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21764,7 +23257,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21781,18 +23275,21 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, State>): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21810,7 +23307,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21827,8 +23325,8 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -21839,10 +23337,13 @@ export const trackSuccesses: { * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21860,7 +23361,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21877,8 +23379,8 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (self: Effect, metric: Metric.Metric, State>): Effect } = dual( @@ -21898,10 +23400,13 @@ export const trackSuccesses: { * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21919,7 +23424,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -21938,18 +23444,21 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const trackErrors: { /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21967,7 +23476,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -21986,18 +23496,21 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, f: (error: E) => Input): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22015,7 +23528,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -22034,18 +23548,21 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, State>): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22063,7 +23580,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -22082,8 +23600,8 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -22094,10 +23612,13 @@ export const trackErrors: { * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22115,7 +23636,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -22134,8 +23656,8 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (self: Effect, metric: Metric.Metric, State>): Effect } = dual( @@ -22155,10 +23677,13 @@ export const trackErrors: { * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22176,7 +23701,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22196,18 +23722,21 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const trackDefects: { /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22225,7 +23754,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22245,18 +23775,21 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, f: (defect: unknown) => Input): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22274,7 +23807,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22294,18 +23828,21 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22323,7 +23860,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22343,8 +23881,8 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -22355,10 +23893,13 @@ export const trackDefects: { * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22376,7 +23917,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22396,8 +23938,8 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (self: Effect, metric: Metric.Metric): Effect } = dual( @@ -22413,11 +23955,14 @@ export const trackDefects: { * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22433,7 +23978,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22450,19 +23996,22 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const trackDuration: { /** * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22478,7 +24027,8 @@ export const trackDuration: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22495,8 +24045,8 @@ export const trackDuration: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( metric: Metric.Metric, @@ -22506,11 +24056,14 @@ export const trackDuration: { * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22526,7 +24079,8 @@ export const trackDuration: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22543,19 +24097,22 @@ export const trackDuration: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric): (self: Effect) => Effect /** * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22571,7 +24128,8 @@ export const trackDuration: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22588,8 +24146,8 @@ export const trackDuration: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -22600,11 +24158,14 @@ export const trackDuration: { * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22620,7 +24181,8 @@ export const trackDuration: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22637,8 +24199,8 @@ export const trackDuration: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (self: Effect, metric: Metric.Metric): Effect } = dual( @@ -22667,12 +24229,15 @@ export const trackDuration: { // ----------------------------------------------------------------------------- /** - * Service that holds the current transaction state, it includes + * Service that holds the current transaction state. + * + * **Details** * - * - a journal that stores any non committed change to TxRef values - * - a retry flag to know if the transaction should be retried + * It includes a journal that stores non-committed changes to `TxRef` values and + * a retry flag that records whether the transaction should be retried. + * + * **Example** (Building transactions) * - * @example * ```ts * import { Effect } from "effect" * @@ -22684,8 +24249,8 @@ export const trackDuration: { * }) * ``` * + * @category transactions * @since 4.0.0 - * @category Transactions */ export class Transaction extends Context.Service< Transaction, @@ -22705,21 +24270,21 @@ export class Transaction extends Context.Service< * Defines a transaction boundary. Transactions are "all or nothing" with respect to changes * made to transactional values (i.e. TxRef) that occur within the transaction body. * + * **Details** + * * 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. * - * @example + * **Example** (Running a transaction) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -22740,8 +24305,8 @@ export class Transaction extends Context.Service< * }) * ``` * + * @category transactions * @since 4.0.0 - * @category Transactions */ export const tx = ( effect: Effect @@ -22833,14 +24398,13 @@ function clearTransaction(state: Transaction["Service"]) { } /** - * Signals that the current transaction needs to be retried. + * Retries the current transaction by signaling that it must be retried. * - * NOTE: the transaction retries on any change to transactional values (i.e. TxRef) accessed in its body. + * **Details** * - * @since 4.0.0 - * @category Transactions + * NOTE: the transaction retries on any change to transactional values (i.e. TxRef) accessed in its body. * - * @example + * **Example** (Retrying transactions) * * ```ts * import { Effect, TxRef } from "effect" @@ -22868,29 +24432,21 @@ function clearTransaction(state: Transaction["Service"]) { * * Effect.runPromise(program).catch(console.error) * ``` + * + * @category transactions + * @since 4.0.0 */ export const txRetry: Effect = flatMap( - Transaction.asEffect(), + Transaction, (state) => { state.retry = true return interrupt } ) /** - * @since 4.0.0 - * @category Effectify - * @example - * ```ts - * import { Effect } from "effect" + * Type helpers for converting callback-based functions into `Effect` functions. * - * // Effectify namespace contains utilities for converting callback-based APIs - * declare function readFile( - * path: string, - * cb: (err: Error | null, data?: string) => void - * ): void - * const effectReadFile = Effect.effectify(readFile) - * // Converts callback-based functions to Effect-based functions - * ``` + * @since 4.0.0 */ export declare namespace Effectify { interface Callback { @@ -22902,20 +24458,10 @@ export declare namespace Effectify { type WithoutNull = unknown extends A ? void : Exclude /** - * @since 4.0.0 - * @category Effectify - * @example - * ```ts - * import type { Effect } from "effect" + * Converts a callback-based function type into an `Effect`-returning function type. * - * // Effectify type converts callback-based function types to Effect-based types - * type CallbackFn = ( - * x: number, - * cb: (err: Error | null, result?: string) => void - * ) => void - * type EffectFn = Effect.Effectify.Effectify - * // Result: (x: number) => Effect - * ``` + * @category effectify + * @since 4.0.0 */ export type Effectify = T extends { (...args: ArgsWithCallback): infer _R1 @@ -23060,20 +24606,10 @@ export declare namespace Effectify { : never /** - * @category Util - * @since 4.0.0 - * @example - * ```ts - * import type { Effect } from "effect" + * Extracts the callback error type from a callback-based function type. * - * // EffectifyError extracts error types from callback-based function types - * type CallbackFn = ( - * x: number, - * cb: (err: Error | null, result?: string) => void - * ) => void - * type ErrorType = Effect.Effectify.EffectifyError - * // Result: Error | null - * ``` + * @category effectify + * @since 4.0.0 */ export type EffectifyError = T extends { (...args: ArgsWithCallback): infer _R1 @@ -23154,9 +24690,19 @@ export declare namespace Effectify { } /** - * Converts a callback-based function to a function that returns an `Effect`. + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) * - * @example Basic Usage * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23171,7 +24717,8 @@ export declare namespace Effectify { * // Output: contents of package.json * ``` * - * @example Custom Error Handling + * **Example** (Mapping callback errors to typed failures) + * * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23187,14 +24734,24 @@ export declare namespace Effectify { * // Output: Exit.failure with custom error message * ``` * + * @category effectify * @since 4.0.0 - * @category Effectify */ export const effectify: { /** - * Converts a callback-based function to a function that returns an `Effect`. + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) * - * @example Basic Usage * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23209,7 +24766,8 @@ export const effectify: { * // Output: contents of package.json * ``` * - * @example Custom Error Handling + * **Example** (Mapping callback errors to typed failures) + * * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23225,14 +24783,24 @@ export const effectify: { * // Output: Exit.failure with custom error message * ``` * + * @category effectify * @since 4.0.0 - * @category Effectify */ ) => any>(fn: F): Effectify.Effectify> /** - * Converts a callback-based function to a function that returns an `Effect`. + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) * - * @example Basic Usage * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23247,7 +24815,8 @@ export const effectify: { * // Output: contents of package.json * ``` * - * @example Custom Error Handling + * **Example** (Mapping callback errors to typed failures) + * * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23263,17 +24832,27 @@ export const effectify: { * // Output: Exit.failure with custom error message * ``` * + * @category effectify * @since 4.0.0 - * @category Effectify */ ) => any, E>( fn: F, onError: (error: Effectify.EffectifyError, args: Parameters) => E ): Effectify.Effectify /** - * Converts a callback-based function to a function that returns an `Effect`. + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) * - * @example Basic Usage * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23288,7 +24867,8 @@ export const effectify: { * // Output: contents of package.json * ``` * - * @example Custom Error Handling + * **Example** (Mapping callback errors to typed failures) + * * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23304,8 +24884,8 @@ export const effectify: { * // Output: Exit.failure with custom error message * ``` * + * @category effectify * @since 4.0.0 - * @category Effectify */ ) => any, E, E2>( fn: F, @@ -23336,10 +24916,13 @@ export const effectify: { /** * Ensures that an effect's success type extends a given type `A`. * - * This function provides compile-time type checking to ensure that the success - * value of an effect conforms to a specific type constraint. + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the success type) * - * @example * ```ts * import { Effect } from "effect" * @@ -23355,18 +24938,21 @@ export const effectify: { * // Type 'string' is not assignable to type 'number' * ``` * + * @category utility types * @since 4.0.0 - * @category Type Constraints */ export const satisfiesSuccessType = () => (effect: Effect): Effect => effect /** * Ensures that an effect's error type extends a given type `E`. * - * This function provides compile-time type checking to ensure that the error - * type of an effect conforms to a specific type constraint. + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the error type) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -23384,18 +24970,21 @@ export const satisfiesSuccessType = () => (effect: Effect * // Type 'string' is not assignable to type 'ValidationError' * ``` * + * @category utility types * @since 4.0.0 - * @category Type Constraints */ export const satisfiesErrorType = () => (effect: Effect): Effect => effect /** * Ensures that an effect's requirements type extends a given type `R`. * - * This function provides compile-time type checking to ensure that the - * requirements (context) type of an effect conforms to a specific type constraint. + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the services type) * - * @example * ```ts * import { Effect } from "effect" * @@ -23411,28 +25000,26 @@ export const satisfiesErrorType = () => (effect: Effect() => (effect: Effect): Effect => effect /** - * An optimized version of `map` that checks if an effect is already resolved - * and applies the mapping function eagerly when possible. + * Applies `map` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should apply a success transformation + * immediately while pending effects still use regular mapping. * - * `mapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` 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 + * **Example** (Mapping already completed effects) * - * @example * ```ts * import { Effect } from "effect" * @@ -23445,27 +25032,25 @@ export const satisfiesServicesType = () => (effect: Effec * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const mapEager: { /** - * An optimized version of `map` that checks if an effect is already resolved - * and applies the mapping function eagerly when possible. + * Applies `map` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should apply a success transformation + * immediately while pending effects still use regular mapping. * - * `mapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` 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 + * **Example** (Mapping already completed effects) * - * @example * ```ts * import { Effect } from "effect" * @@ -23478,27 +25063,25 @@ export const mapEager: { * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (f: (a: A) => B): (self: Effect) => Effect /** - * An optimized version of `map` that checks if an effect is already resolved - * and applies the mapping function eagerly when possible. + * Applies `map` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should apply a success transformation + * immediately while pending effects still use regular mapping. * - * `mapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` 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 + * **Example** (Mapping already completed effects) * - * @example * ```ts * import { Effect } from "effect" * @@ -23511,29 +25094,29 @@ export const mapEager: { * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (self: Effect, f: (a: A) => B): Effect } = internal.mapEager /** - * An optimized version of `mapError` that checks if an effect is already resolved - * and applies the error mapping function eagerly when possible. + * Applies `mapError` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should apply an error + * transformation immediately while pending effects still use regular error + * mapping. * - * `mapErrorEager` provides better performance for effects that are already resolved - * by applying the error transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **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. * - * - 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 + * **Example** (Mapping errors eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23549,27 +25132,27 @@ export const mapEager: { * ) // Uses regular mapError * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const mapErrorEager: { /** - * An optimized version of `mapError` that checks if an effect is already resolved - * and applies the error mapping function eagerly when possible. + * Applies `mapError` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should apply an error + * transformation immediately while pending effects still use regular error + * mapping. * - * `mapErrorEager` provides better performance for effects that are already resolved - * by applying the error transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **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. * - * - 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 + * **Example** (Mapping errors eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23585,27 +25168,27 @@ export const mapErrorEager: { * ) // Uses regular mapError * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (f: (e: E) => E2): (self: Effect) => Effect /** - * An optimized version of `mapError` that checks if an effect is already resolved - * and applies the error mapping function eagerly when possible. + * Applies `mapError` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should apply an error + * transformation immediately while pending effects still use regular error + * mapping. * - * `mapErrorEager` provides better performance for effects that are already resolved - * by applying the error transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **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. * - * - 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 + * **Example** (Mapping errors eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23621,29 +25204,28 @@ export const mapErrorEager: { * ) // Uses regular mapError * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (self: Effect, f: (e: E) => E2): Effect } = internal.mapErrorEager /** - * An optimized version of `mapBoth` that checks if an effect is already resolved - * and applies the appropriate mapping function eagerly when possible. + * Applies `mapBoth` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should transform either success or + * failure immediately while pending effects still use regular channel mapping. * - * `mapBothEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * 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 + * **Example** (Mapping both channels eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23661,27 +25243,26 @@ export const mapErrorEager: { * }) // onFailure applied eagerly * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const mapBothEager: { /** - * An optimized version of `mapBoth` that checks if an effect is already resolved - * and applies the appropriate mapping function eagerly when possible. + * Applies `mapBoth` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should transform either success or + * failure immediately while pending effects still use regular channel mapping. * - * `mapBothEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * 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 + * **Example** (Mapping both channels eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23699,29 +25280,28 @@ export const mapBothEager: { * }) // onFailure applied eagerly * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ ( options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 } ): (self: Effect) => Effect /** - * An optimized version of `mapBoth` that checks if an effect is already resolved - * and applies the appropriate mapping function eagerly when possible. + * Applies `mapBoth` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should transform either success or + * failure immediately while pending effects still use regular channel mapping. * - * `mapBothEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * 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 + * **Example** (Mapping both channels eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23739,8 +25319,8 @@ export const mapBothEager: { * }) // onFailure applied eagerly * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ ( self: Effect, @@ -23749,22 +25329,21 @@ export const mapBothEager: { } = internal.mapBothEager /** - * An optimized version of `flatMap` that checks if an effect is already resolved - * and applies the flatMap function eagerly when possible. + * Applies `flatMap` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved successful effect should bind immediately to the + * next effect while pending effects still use regular flat mapping. * - * `flatMapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * 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 + * **Example** (Flat mapping eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23780,27 +25359,26 @@ export const mapBothEager: { * ) // Uses regular flatMap * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const flatMapEager: { /** - * An optimized version of `flatMap` that checks if an effect is already resolved - * and applies the flatMap function eagerly when possible. + * Applies `flatMap` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved successful effect should bind immediately to the + * next effect while pending effects still use regular flat mapping. * - * `flatMapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * 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 + * **Example** (Flat mapping eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23816,27 +25394,26 @@ export const flatMapEager: { * ) // Uses regular flatMap * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (f: (a: A) => Effect): (self: Effect) => Effect /** - * An optimized version of `flatMap` that checks if an effect is already resolved - * and applies the flatMap function eagerly when possible. + * Applies `flatMap` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved successful effect should bind immediately to the + * next effect while pending effects still use regular flat mapping. * - * `flatMapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * 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 + * **Example** (Flat mapping eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23852,29 +25429,28 @@ export const flatMapEager: { * ) // Uses regular flatMap * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (self: Effect, f: (a: A) => Effect): Effect } = internal.flatMapEager /** - * An optimized version of `catch` that checks if an effect is already resolved - * and applies the catch function eagerly when possible. + * Applies `catch` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should recover immediately while + * pending effects still use regular error recovery. * - * `catchEager` provides better performance for effects that are already resolved - * by applying the error recovery immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **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. * - * - 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 + * **Example** (Catching failures eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23900,27 +25476,26 @@ export const flatMapEager: { * ) // Uses regular catch * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const catchEager: { /** - * An optimized version of `catch` that checks if an effect is already resolved - * and applies the catch function eagerly when possible. + * Applies `catch` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should recover immediately while + * pending effects still use regular error recovery. * - * `catchEager` provides better performance for effects that are already resolved - * by applying the error recovery immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **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. * - * - 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 + * **Example** (Catching failures eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23946,27 +25521,26 @@ export const catchEager: { * ) // Uses regular catch * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (f: (e: NoInfer) => Effect): (self: Effect) => Effect /** - * An optimized version of `catch` that checks if an effect is already resolved - * and applies the catch function eagerly when possible. + * Applies `catch` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should recover immediately while + * pending effects still use regular error recovery. * - * `catchEager` provides better performance for effects that are already resolved - * by applying the error recovery immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **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. * - * - 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 + * **Example** (Catching failures eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23992,8 +25566,8 @@ export const catchEager: { * ) // Uses regular catch * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (self: Effect, f: (e: NoInfer) => Effect): Effect } = internal.catchEager @@ -24001,10 +25575,13 @@ export const catchEager: { /** * Creates untraced function effects with eager evaluation optimization. * + * **Details** + * * Executes generator functions eagerly when all yielded effects are synchronous, * stopping at the first async effect and deferring to normal execution. * - * @example + * **Example** (Defining eager untraced effect functions) + * * ```ts * import { Effect } from "effect" * @@ -24017,7 +25594,7 @@ export const catchEager: { * const effect = computation() // Executed immediately if all effects are sync * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const fnUntracedEager: fn.Untraced = internal.fnUntracedEager