diff --git "a/.opencode/node_modules/effect/src/Layer.ts" "b/.opencode/node_modules/effect/src/Layer.ts" --- "a/.opencode/node_modules/effect/src/Layer.ts" +++ "b/.opencode/node_modules/effect/src/Layer.ts" @@ -1,19 +1,11 @@ /** - * A `Layer` describes how to build one or more services in your - * application. Services can be injected into effects via - * `Effect.provideService`. Effects can require services via `Effect.service`. + * Builds and wires services for Effect applications. * - * Layer can be thought of as recipes for producing bundles of services, given - * their dependencies (other services). - * - * Construction of services can be effectful and utilize resources that must be - * acquired and safely released when the services are done being utilized. - * - * By default layers are shared, meaning that if the same layer is used twice - * the layer will only be allocated a single time. - * - * Because of their excellent composition properties, layers are the idiomatic - * way in Effect-TS to create services that depend on other services. + * A `Layer` describes how to acquire one or more services, which + * services are required to build them, and which errors can occur during + * acquisition. Layers can manage scoped resources, memoize shared services, + * combine with other layers, provide services to effects or streams, and attach + * error handling, tracing, or lifecycle hooks. * * @since 2.0.0 */ @@ -42,15 +34,22 @@ import type * as Unify from "./Unify.ts" const TypeId = "~effect/Layer" /** - * A Layer describes how to build one or more services for dependency injection. + * A `Layer` describes how to build one or more services for dependency injection. * - * A Layer represents: - * - ROut: The services this layer provides - * - E: The possible errors during layer construction - * - RIn: The services this layer requires as dependencies + * **When to use** + * + * Use to model construction of application services for dependency injection, + * especially when services have dependencies, can fail during construction, or + * need scoped setup and release. + * + * **Details** + * + * A `Layer` represents `ROut` as the services this layer + * provides, `E` as the possible errors during layer construction, and `RIn` as + * the services this layer requires as dependencies. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Layer extends Variance, Pipeable { /** @internal */ @@ -61,8 +60,16 @@ export interface Layer extends Variance } /** - * @since 4.0.0 + * Type-level hook that allows `Layer` values to participate in `Unify` + * inference. + * + * **Details** + * + * This is used by Effect's pipe and unification machinery to preserve the + * provided services, error, and requirements of a `Layer`. + * * @category models + * @since 4.0.0 */ export interface LayerUnify { Layer?: () => A[Unify.typeSymbol] extends Layer | infer _ ? Layer< @@ -74,16 +81,19 @@ export interface LayerUnify { } /** - * @since 4.0.0 + * Type-level marker used by `Unify` for `Layer` types that should be ignored + * during unification. + * * @category models + * @since 4.0.0 */ export interface LayerUnifyIgnore {} /** * The variance interface for Layer type parameters. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Variance { readonly [TypeId]: { @@ -93,13 +103,26 @@ export interface Variance { } } /** - * A constraint interface for working with any Layer type. + * A type-level constraint for working with any `Layer` type. + * + * **When to use** + * + * Use to constrain generic parameters or layer collections to any `Layer` + * value while preserving its provided, error, and required service types for + * inference. + * + * **Details** * - * This interface is used to constrain generic types to Layer types - * without specifying exact type parameters. + * This interface is used to constrain generic types to `Layer` values without + * specifying exact type parameters. * + * @see {@link Layer} for the concrete layer interface + * @see {@link Services} for extracting required services from a layer type + * @see {@link Error} for extracting construction errors from a layer type + * @see {@link Success} for extracting provided services from a layer type + * + * @category utility types * @since 3.9.0 - * @category type-level */ export interface Any { readonly [TypeId]: { @@ -109,40 +132,68 @@ export interface Any { } } /** - * Extracts the service dependencies (RIn) from a Layer type. + * Extracts the service requirements (`RIn`) from a `Layer` type. * - * @since 2.0.0 - * @category type-level + * **When to use** + * + * Use to derive the dependency requirements of a generic or inferred `Layer` + * without restating its `RIn` type parameter. + * + * @see {@link Success} for extracting the services provided by the same `Layer` + * @see {@link Error} for extracting the construction failure type from the same `Layer` + * + * @category utility types + * @since 4.0.0 */ export type Services = T extends infer L ? L extends Layer ? _RIn : never : never /** - * Extracts the error type (E) from a Layer type. + * Extracts the error type (`E`) from a `Layer` type. + * + * **When to use** + * + * Use to derive a layer construction error type for helper types, wrappers, or + * APIs that preserve a layer failure channel. * + * @see {@link Success} for extracting the services provided by the same `Layer` + * @see {@link Services} for extracting the dependency requirements of the same `Layer` + * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Error = T extends Layer ? _E : never /** - * Extracts the service output type (ROut) from a Layer type. + * Extracts the service output type (`ROut`) from a `Layer` type. + * + * **When to use** + * + * Use to derive the services provided by an existing or generic `Layer` without + * restating its `ROut` type parameter. + * + * @see {@link Error} for extracting the layer construction error type instead + * @see {@link Services} for extracting the layer input service requirements instead * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Success = T extends Layer ? _ROut : never const MemoMapTypeId = "~effect/Layer/MemoMap" /** - * A MemoMap is used to memoize layer construction and ensure sharing of layers. + * A `MemoMap` is used to memoize layer construction and ensure sharing of + * layers. * - * The MemoMap prevents duplicate construction of the same layer instance, + * **Details** + * + * The `MemoMap` prevents duplicate construction of the same layer instance, * enabling efficient resource sharing across layer dependencies. * - * @example + * **Example** (Sharing layer construction with a memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -153,7 +204,7 @@ const MemoMapTypeId = "~effect/Layer/MemoMap" * const memoMap = yield* Layer.makeMemoMap * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) @@ -162,11 +213,15 @@ const MemoMapTypeId = "~effect/Layer/MemoMap" * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface MemoMap { readonly [MemoMapTypeId]: typeof MemoMapTypeId + readonly get: ( + layer: Layer, + scope: Scope.Scope + ) => Effect, E, RIn> | undefined readonly getOrElseMemoize: ( layer: Layer, scope: Scope.Scope, @@ -174,18 +229,36 @@ export interface MemoMap { ) => Effect, E, RIn> } +type MemoMapEntry = { + observers: number + effect: Effect, any> + readonly finalizer: (exit: Exit.Exit) => Effect +} + +const memoMapReuse = ( + entry: MemoMapEntry, + scope: Scope.Scope +): Effect, E, RIn> => { + entry.observers++ + return internalEffect.andThen( + internalEffect.scopeAddFinalizerExit(scope, (exit) => entry.finalizer(exit)), + entry.effect + ) +} + /** * Returns `true` if the specified value is a `Layer`, `false` otherwise. * - * @example + * **Example** (Checking whether a value is a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const notALayer = { someProperty: "value" } @@ -194,8 +267,8 @@ export interface MemoMap { * console.log(Layer.isLayer(notALayer)) // false * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const isLayer = (u: unknown): u is Layer => hasProperty(u, TypeId) @@ -222,14 +295,18 @@ const fromBuildUnsafe = ( } /** - * Constructs a Layer from a function that uses a `MemoMap` and `Scope` to build the layer. + * Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to + * build the layer. + * + * **Details** * * The function receives a `MemoMap` for memoization and a `Scope` for resource management. * A child scope is created, and if the build fails, the child scope is closed. * - * @example + * **Example** (Constructing a layer from a build function) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -244,8 +321,8 @@ const fromBuildUnsafe = ( * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromBuild = ( build: ( @@ -262,15 +339,18 @@ export const fromBuild = ( }) /** - * Constructs a Layer from a function that uses a `MemoMap` and `Scope` to build the layer, - * with automatic memoization. + * Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to + * build the layer, with automatic memoization. + * + * **Details** * * This is similar to `fromBuild` but provides automatic memoization of the layer construction. * The layer will be memoized based on the provided `MemoMap`. * - * @example + * **Example** (Memoizing layer construction) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -285,8 +365,8 @@ export const fromBuild = ( * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromBuildMemo = ( build: ( @@ -298,62 +378,81 @@ export const fromBuildMemo = ( return self } +const memoMapBuild = ( + memoMap: MemoMapImpl, + layer: Layer, + scope: Scope.Scope, + build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn> +): Effect, E, RIn> => { + const layerScope = Scope.makeUnsafe() + const deferred = Deferred.makeUnsafe, E>() + const entry: MemoMapEntry = { + observers: 1, + effect: Deferred.await(deferred), + finalizer: (exit: Exit.Exit) => + internalEffect.suspend(() => { + entry.observers-- + if (entry.observers === 0) { + memoMap.map.delete(layer) + return Scope.close(layerScope, exit) + } + return internalEffect.void + }) + } + memoMap.map.set(layer, entry) + return internalEffect.scopeAddFinalizerExit(scope, entry.finalizer).pipe( + internalEffect.flatMap(() => build(memoMap, layerScope)), + internalEffect.onExit((exit) => { + entry.effect = exit + return Deferred.done(deferred, exit) + }) + ) +} + class MemoMapImpl implements MemoMap { get [MemoMapTypeId](): typeof MemoMapTypeId { return MemoMapTypeId } - readonly map = new Map, { - observers: number - effect: Effect, any> - readonly finalizer: (exit: Exit.Exit) => Effect - }>() + readonly parent: MemoMap | undefined + + constructor(parent?: MemoMap) { + this.parent = parent + } + + readonly map = new Map, MemoMapEntry>() + + get( + layer: Layer, + scope: Scope.Scope + ): Effect, E, RIn> | undefined { + const local = this.map.get(layer) + if (local) { + return memoMapReuse(local, scope) + } + return this.parent?.get(layer, scope) + } getOrElseMemoize( layer: Layer, scope: Scope.Scope, build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn> ): Effect, E, RIn> { - if (this.map.has(layer)) { - const entry = this.map.get(layer)! - entry.observers++ - return internalEffect.andThen( - internalEffect.scopeAddFinalizerExit(scope, (exit) => entry.finalizer(exit)), - entry.effect - ) - } - const layerScope = Scope.makeUnsafe() - const deferred = Deferred.makeUnsafe, E>() - const entry = { - observers: 1, - effect: Deferred.await(deferred), - finalizer: (exit: Exit.Exit) => - internalEffect.suspend(() => { - entry.observers-- - if (entry.observers === 0) { - this.map.delete(layer) - return Scope.close(layerScope, exit) - } - return internalEffect.void - }) + const existing = this.get(layer, scope) + if (existing) { + return existing } - this.map.set(layer, entry) - return internalEffect.scopeAddFinalizerExit(scope, entry.finalizer).pipe( - internalEffect.flatMap(() => build(this, layerScope)), - internalEffect.onExit((exit) => { - entry.effect = exit - return Deferred.done(deferred, exit) - }) - ) + return memoMapBuild(this, layer, scope, build) } } /** - * Constructs a `MemoMap` that can be used to build additional layers. + * Constructs a `MemoMap` synchronously so it can be used to build additional layers. + * + * **Example** (Creating a memo map unsafely) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -364,7 +463,7 @@ class MemoMapImpl implements MemoMap { * const memoMap = Layer.makeMemoMapUnsafe() * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) @@ -373,17 +472,37 @@ class MemoMapImpl implements MemoMap { * }) * ``` * - * @since 4.0.0 * @category memo map + * @since 4.0.0 */ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() /** - * Constructs a `MemoMap` that can be used to build additional layers. + * Constructs a child `MemoMap` synchronously, allowing it to reuse layers + * already memoized in the parent while isolating any new layer allocations to + * the child map. + * + * **When to use** + * + * Use to synchronously fork a memo map for manual layer building when child + * builds should see parent memoized layers without writing newly built layers + * back to the parent. + * + * @see {@link forkMemoMap} for allocating the child memo map inside `Effect` + * @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent + * + * @category memo map + * @since 4.0.0 + */ +export const forkMemoMapUnsafe = (parent: MemoMap): MemoMap => new MemoMapImpl(parent) + +/** + * Constructs a `MemoMap` effectfully so it can be used to build additional layers. + * + * **Example** (Creating a memo map in an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -394,7 +513,7 @@ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() * const memoMap = yield* Layer.makeMemoMap * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) @@ -403,19 +522,47 @@ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ export const makeMemoMap: Effect = internalEffect.sync(makeMemoMapUnsafe) /** - * A service reference for the current `MemoMap` used in layer construction. + * Constructs a child `MemoMap` effectfully, allowing it to reuse layers already + * memoized in the parent while isolating any new layer allocations to the child + * map. * - * This service provides access to the current memoization map during layer building, - * allowing layers to share memoized results. + * **When to use** + * + * Use when a layer build should inherit already memoized layers from an + * existing `MemoMap` while keeping newly memoized layers out of the parent map. + * + * @see {@link makeMemoMap} for creating a root memo map in an `Effect` + * @see {@link forkMemoMapUnsafe} for the synchronous constructor variant + * @see {@link buildWithMemoMap} for building layers with an explicit memo map + * + * @category memo map + * @since 4.0.0 + */ +export const forkMemoMap = (parent: MemoMap): Effect => internalEffect.sync(() => forkMemoMapUnsafe(parent)) + +/** + * Context service for the current `MemoMap` used in layer construction. + * + * **When to use** + * + * Use when building custom layer operations that need to access the current + * memoization map from the fiber context. + * + * **Details** + * + * This service wraps a `MemoMap` as a `Context.Service`, making it available + * for dependency injection during layer construction. + * + * @see {@link MemoMap} the memoization map type wrapped by this service * - * @since 3.13.0 * @category models + * @since 3.13.0 */ export class CurrentMemoMap extends Context.Service()("effect/Layer/CurrentMemoMap") { static getOrCreate: (self: Context.Context) => MemoMap = Context.getOrElse( @@ -428,9 +575,10 @@ export class CurrentMemoMap extends Context.Service()(" * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * - * @example + * **Example** (Building layers with an explicit memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -446,13 +594,13 @@ export class CurrentMemoMap extends Context.Service()(" * const scope = yield* Effect.scope * * // Build database layer with memoization - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * // Build logger layer with same memoization (reuses memo if same layer) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * const loggerContext = yield* Layer.buildWithMemoMap( @@ -468,17 +616,18 @@ export class CurrentMemoMap extends Context.Service()(" * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ export const buildWithMemoMap: { /** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * - * @example + * **Example** (Building layers with an explicit memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -494,13 +643,13 @@ export const buildWithMemoMap: { * const scope = yield* Effect.scope * * // Build database layer with memoization - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * // Build logger layer with same memoization (reuses memo if same layer) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * const loggerContext = yield* Layer.buildWithMemoMap( @@ -516,17 +665,18 @@ export const buildWithMemoMap: { * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ (memoMap: MemoMap, scope: Scope.Scope): (self: Layer) => Effect, E, RIn> /** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * - * @example + * **Example** (Building layers with an explicit memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -542,13 +692,13 @@ export const buildWithMemoMap: { * const scope = yield* Effect.scope * * // Build database layer with memoization - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * // Build logger layer with same memoization (reuses memo if same layer) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * const loggerContext = yield* Layer.buildWithMemoMap( @@ -564,8 +714,8 @@ export const buildWithMemoMap: { * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ (self: Layer, memoMap: MemoMap, scope: Scope.Scope): Effect, E, RIn> } = dual(3, ( @@ -582,9 +732,10 @@ export const buildWithMemoMap: { /** * Builds a layer into a scoped value. * - * @example + * **Example** (Building a layer into a context) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -592,7 +743,7 @@ export const buildWithMemoMap: { * * // Build a layer to get its services * const program = Effect.gen(function*() { - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * @@ -606,8 +757,8 @@ export const buildWithMemoMap: { * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ export const build = ( self: Layer @@ -621,15 +772,22 @@ export const build = ( ) /** - * Builds a layer into an `Effect` value. Any resources associated with this - * layer will be released when the specified scope is closed unless their scope - * has been extended. This allows building layers where the lifetime of some of - * the services output by the layer exceed the lifetime of the effect the - * layer is provided to. + * Builds a layer using an explicit scope. + * + * **When to use** + * + * Use to control the lifetime of layer resources with a scope supplied by the + * caller. + * + * **Details** + * + * Resources created by the layer are released when the supplied scope is + * closed, unless a resource extends its own scope. + * + * **Example** (Building a layer with an explicit scope) * - * @example * ```ts - * import { Effect, Layer, Scope, Context } from "effect" + * import { Context, Effect, Layer, Scope } from "effect" * * class Database extends Context.Service Effect.Effect @@ -639,7 +797,7 @@ export const build = ( * const program = Effect.gen(function*() { * const scope = yield* Effect.scope * - * const dbLayer = Layer.effect(Database)(Effect.gen(function*() { + * const dbLayer = Layer.effect(Database, Effect.gen(function*() { * console.log("Initializing database...") * yield* Scope.addFinalizer( * scope, @@ -657,20 +815,27 @@ export const build = ( * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ export const buildWithScope: { /** - * Builds a layer into an `Effect` value. Any resources associated with this - * layer will be released when the specified scope is closed unless their scope - * has been extended. This allows building layers where the lifetime of some of - * the services output by the layer exceed the lifetime of the effect the - * layer is provided to. + * Builds a layer using an explicit scope. + * + * **When to use** + * + * Use to control the lifetime of layer resources with a scope supplied by the + * caller. + * + * **Details** + * + * Resources created by the layer are released when the supplied scope is + * closed, unless a resource extends its own scope. + * + * **Example** (Building a layer with an explicit scope) * - * @example * ```ts - * import { Effect, Layer, Scope, Context } from "effect" + * import { Context, Effect, Layer, Scope } from "effect" * * class Database extends Context.Service Effect.Effect @@ -680,7 +845,7 @@ export const buildWithScope: { * const program = Effect.gen(function*() { * const scope = yield* Effect.scope * - * const dbLayer = Layer.effect(Database)(Effect.gen(function*() { + * const dbLayer = Layer.effect(Database, Effect.gen(function*() { * console.log("Initializing database...") * yield* Scope.addFinalizer( * scope, @@ -698,20 +863,27 @@ export const buildWithScope: { * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ (scope: Scope.Scope): (self: Layer) => Effect, E, RIn> /** - * Builds a layer into an `Effect` value. Any resources associated with this - * layer will be released when the specified scope is closed unless their scope - * has been extended. This allows building layers where the lifetime of some of - * the services output by the layer exceed the lifetime of the effect the - * layer is provided to. + * Builds a layer using an explicit scope. + * + * **When to use** + * + * Use to control the lifetime of layer resources with a scope supplied by the + * caller. + * + * **Details** + * + * Resources created by the layer are released when the supplied scope is + * closed, unless a resource extends its own scope. + * + * **Example** (Building a layer with an explicit scope) * - * @example * ```ts - * import { Effect, Layer, Scope, Context } from "effect" + * import { Context, Effect, Layer, Scope } from "effect" * * class Database extends Context.Service Effect.Effect @@ -721,7 +893,7 @@ export const buildWithScope: { * const program = Effect.gen(function*() { * const scope = yield* Effect.scope * - * const dbLayer = Layer.effect(Database)(Effect.gen(function*() { + * const dbLayer = Layer.effect(Database, Effect.gen(function*() { * console.log("Initializing database...") * yield* Scope.addFinalizer( * scope, @@ -739,8 +911,8 @@ export const buildWithScope: { * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ (self: Layer, scope: Scope.Scope): Effect, E, RIn> } = dual(2, ( @@ -756,132 +928,90 @@ export const buildWithScope: { )) /** - * Constructs a layer from the specified value. + * Constructs a layer that provides a single service from an already available + * value. + * + * **When to use** + * + * Use when you need a `Layer` that provides a service from an already + * constructed implementation without effectful acquisition. + * + * **Example** (Creating a layer from a service implementation) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Create layers from concrete service implementations - * const databaseLayer = Layer.succeed(Database)({ + * const DatabaseLive = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) * }) - * - * const loggerLayer = Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) - * }) - * - * // Use the layers in a program - * const program = Effect.gen(function*() { - * const database = yield* Database - * const logger = yield* Logger - * - * yield* logger.log("Starting database query") - * const result = yield* database.query("SELECT * FROM users") - * yield* logger.log(`Query completed: ${result}`) - * - * return result - * }).pipe( - * Effect.provide(Layer.mergeAll(databaseLayer, loggerLayer)) - * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for constructing layers from lazy values + * * @category constructors + * @since 2.0.0 */ export const succeed: { /** - * Constructs a layer from the specified value. + * Constructs a layer that provides a single service from an already available + * value. + * + * **When to use** + * + * Use when you need a `Layer` that provides a service from an already + * constructed implementation without effectful acquisition. + * + * **Example** (Creating a layer from a service implementation) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Create layers from concrete service implementations - * const databaseLayer = Layer.succeed(Database)({ + * const DatabaseLive = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) * }) - * - * const loggerLayer = Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) - * }) - * - * // Use the layers in a program - * const program = Effect.gen(function*() { - * const database = yield* Database - * const logger = yield* Logger - * - * yield* logger.log("Starting database query") - * const result = yield* database.query("SELECT * FROM users") - * yield* logger.log(`Query completed: ${result}`) - * - * return result - * }).pipe( - * Effect.provide(Layer.mergeAll(databaseLayer, loggerLayer)) - * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for constructing layers from lazy values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key): (resource: S) => Layer /** - * Constructs a layer from the specified value. + * Constructs a layer that provides a single service from an already available + * value. + * + * **When to use** + * + * Use when you need a `Layer` that provides a service from an already + * constructed implementation without effectful acquisition. + * + * **Example** (Creating a layer from a service implementation) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Create layers from concrete service implementations - * const databaseLayer = Layer.succeed(Database)({ + * const DatabaseLive = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) * }) - * - * const loggerLayer = Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) - * }) - * - * // Use the layers in a program - * const program = Effect.gen(function*() { - * const database = yield* Database - * const logger = yield* Logger - * - * yield* logger.log("Starting database query") - * const result = yield* database.query("SELECT * FROM users") - * yield* logger.log(`Query completed: ${result}`) - * - * return result - * }).pipe( - * Effect.provide(Layer.mergeAll(databaseLayer, loggerLayer)) - * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for constructing layers from lazy values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key, resource: Types.NoInfer): Layer } = function() { @@ -892,15 +1022,23 @@ export const succeed: { } as any /** - * Constructs a layer from the specified value, which must return one or more - * services. + * Constructs a layer that provides all services in an already available + * `Context`. * - * This is a more general version of `succeed` that allows you to provide multiple - * services at once through a `Context`. + * **When to use** + * + * Use when you need a `Layer` built from an existing `Context`, including when + * you need to provide multiple services at once. + * + * **Details** + * + * This is a more general version of `succeed` that allows you to provide + * multiple services at once through a `Context`. + * + * **Example** (Providing multiple services from a context) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -921,97 +1059,138 @@ export const succeed: { * const layer = Layer.succeedContext(context) * ``` * - * @since 2.0.0 + * @see {@link succeed} for providing a single service from a value + * * @category constructors + * @since 2.0.0 */ export const succeedContext = (context: Context.Context): Layer => fromBuildUnsafe(constant(internalEffect.succeed(context))) /** - * A Layer that constructs an empty Context. + * An empty layer that provides no services, cannot fail, has no requirements, + * and performs no construction or finalization work. * - * This layer provides no services and can be used as a neutral element - * in layer composition or as a starting point for building layers. + * **When to use** + * + * Use as the no-op branch when conditionally composing layers. + * + * **Example** (Disabling optional lifecycle work) * - * @example * ```ts - * import { Layer } from "effect" + * import { Console, Layer } from "effect" + * + * declare const flag: boolean * - * const emptyLayer = Layer.empty + * const StartupLogLive = flag + * ? Layer.effectDiscard(Console.log("application starting")) + * : Layer.empty * ``` * - * @since 2.0.0 + * @see {@link effectDiscard} for running an effect while providing no services + * * @category constructors + * @since 2.0.0 */ export const empty: Layer = succeedContext(Context.empty()) /** - * Lazily constructs a layer from the specified value. + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** * * This is a lazy version of `succeed` where the service value is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a service) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.sync(Database)(() => ({ + * const layer = Layer.sync(Database, () => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ``` * - * @since 2.0.0 + * @see {@link succeed} for constructing layers from static values + * * @category constructors + * @since 2.0.0 */ export const sync: { /** - * Lazily constructs a layer from the specified value. + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** * * This is a lazy version of `succeed` where the service value is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a service) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.sync(Database)(() => ({ + * const layer = Layer.sync(Database, () => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ``` * - * @since 2.0.0 + * @see {@link succeed} for constructing layers from static values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key): (evaluate: LazyArg) => Layer /** - * Lazily constructs a layer from the specified value. + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** * * This is a lazy version of `succeed` where the service value is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a service) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.sync(Database)(() => ({ + * const layer = Layer.sync(Database, () => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ``` * - * @since 2.0.0 + * @see {@link succeed} for constructing layers from static values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key, evaluate: LazyArg>): Layer } = function() { @@ -1022,15 +1201,22 @@ export const sync: { } as any /** - * Lazily constructs a layer from the specified value, which must return one or more - * services. + * Constructs a layer lazily that provides all services in a `Context`. + * + * **When to use** + * + * Use when you need a `Layer` that creates multiple services synchronously but + * defers that work until the layer is built. + * + * **Details** * - * This is a lazy version of `succeedContext` where the Context is computed + * This is a lazy version of `succeedContext` where the `Context` is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a context) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1043,108 +1229,126 @@ export const sync: { * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for lazily providing a single service + * @see {@link succeedContext} for providing an already available context + * * @category constructors + * @since 2.0.0 */ export const syncContext = (evaluate: LazyArg>): Layer => fromBuildMemo(constant(internalEffect.sync(evaluate))) /** - * Constructs a layer from the specified scoped effect. + * Constructs a layer from an effect that produces a single service. * - * This allows you to create a Layer from an Effect that produces a service. - * The Effect is executed in the scope of the layer, allowing for proper - * resource management. + * **When to use** * - * **Previously Known As** + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. + * + * **Details** * - * This API replaces the following from Effect 3.x: + * This allows you to create a `Layer` from an `Effect` that produces a service. + * The `Effect` is executed in the scope of the layer, allowing for proper + * resource management. * - * - `Layer.scoped` + * **Example** (Creating a layer from an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.effect(Database)( + * const layer = Layer.effect(Database, * Effect.sync(() => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ) * ``` * - * @since 2.0.0 + * @see {@link effectContext} for effectfully providing multiple services + * @see {@link effectDiscard} for running construction work without providing services + * * @category constructors + * @since 2.0.0 */ export const effect: { /** - * Constructs a layer from the specified scoped effect. + * Constructs a layer from an effect that produces a single service. * - * This allows you to create a Layer from an Effect that produces a service. - * The Effect is executed in the scope of the layer, allowing for proper - * resource management. + * **When to use** + * + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * This allows you to create a `Layer` from an `Effect` that produces a service. + * The `Effect` is executed in the scope of the layer, allowing for proper + * resource management. * - * - `Layer.scoped` + * **Example** (Creating a layer from an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.effect(Database)( + * const layer = Layer.effect(Database, * Effect.sync(() => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ) * ``` * - * @since 2.0.0 + * @see {@link effectContext} for effectfully providing multiple services + * @see {@link effectDiscard} for running construction work without providing services + * * @category constructors + * @since 2.0.0 */ (service: Context.Key): ( effect: Effect ) => Layer> /** - * Constructs a layer from the specified scoped effect. + * Constructs a layer from an effect that produces a single service. * - * This allows you to create a Layer from an Effect that produces a service. - * The Effect is executed in the scope of the layer, allowing for proper - * resource management. + * **When to use** * - * **Previously Known As** + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. * - * This API replaces the following from Effect 3.x: + * **Details** + * + * This allows you to create a `Layer` from an `Effect` that produces a service. + * The `Effect` is executed in the scope of the layer, allowing for proper + * resource management. * - * - `Layer.scoped` + * **Example** (Creating a layer from an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.effect(Database)( + * const layer = Layer.effect(Database, * Effect.sync(() => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ) * ``` * - * @since 2.0.0 + * @see {@link effectContext} for effectfully providing multiple services + * @see {@link effectDiscard} for running construction work without providing services + * * @category constructors + * @since 2.0.0 */ (service: Context.Key, effect: Effect, E, R>): Layer> } = function() { @@ -1161,15 +1365,23 @@ const effectImpl = ( effectContext(internalEffect.map(effect, (value) => Context.make(service, value))) /** - * Constructs a layer from the specified scoped effect, which must return one - * or more services. + * Constructs a layer from an effect that produces all services in a `Context`. + * + * **When to use** + * + * Use when you need a `Layer` that effectfully constructs a `Context` with + * multiple services. * - * This allows you to create a Layer from an effectful computation that returns - * multiple services. The Effect is executed in the scope of the layer. + * **Details** + * + * This allows you to create a `Layer` from an effectful computation that + * returns multiple services. The `Effect` is executed in the scope of the + * layer. + * + * **Example** (Creating a layer from an effectful context) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service< * Database, @@ -1183,26 +1395,26 @@ const effectImpl = ( * ) * ``` * - * @since 2.0.0 + * @see {@link effect} for effectfully providing a single service + * * @category constructors + * @since 2.0.0 */ export const effectContext = ( effect: Effect, E, R> ): Layer> => fromBuildMemo((_, scope) => Scope.provide(effect, scope)) /** - * Constructs a layer from the specified scoped effect. - * - * This is useful when you want to run an Effect for its side effects during - * layer construction, but don't need to provide any services. + * Constructs a layer from an effect, discarding its value and providing no + * services. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when layer construction should run an Effect for its side effects while providing no + * services. * - * - `Layer.scopedDiscard` + * **Example** (Running an effect during layer construction) * - * @example * ```ts * import { Effect, Layer } from "effect" * @@ -1213,21 +1425,26 @@ export const effectContext = ( * ) * ``` * - * @since 2.0.0 + * @see {@link empty} for a no-op layer that performs no construction work + * * @category constructors + * @since 2.0.0 */ export const effectDiscard = (effect: Effect): Layer> => effectContext(internalEffect.as(effect, Context.empty())) /** - * Lazily constructs a layer using the specified factory. + * Constructs a layer lazily using the specified factory. + * + * **Details** * * The factory is evaluated only when the suspended layer is first built, and * the result is memoized with normal layer sharing semantics. * - * @example + * **Example** (Choosing a layer lazily) + * * ```ts - * import { Layer, Context } from "effect" + * import { Context, Layer } from "effect" * * class Config extends Context.Service()("Config") {} * @@ -1235,41 +1452,48 @@ export const effectDiscard = (effect: Effect): Layer * useProd - * ? Layer.succeed(Config)("https://api.example.com") - * : Layer.succeed(Config)("http://localhost:3000") + * ? Layer.succeed(Config, "https://api.example.com") + * : Layer.succeed(Config, "http://localhost:3000") * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const suspend = (evaluate: LazyArg>): Layer => fromBuildMemo((memoMap, scope) => internalEffect.suspend(() => evaluate().build(memoMap, scope))) /** - * Unwraps a Layer from an Effect, flattening the nested structure. + * Unwraps a `Layer` from an `Effect`, flattening the nested structure. + * + * **When to use** * - * This is useful when you have an Effect that produces a Layer, and you want to - * use that Layer directly. The resulting Layer will have the combined error and - * dependency types from both the outer Effect and the inner Layer. + * Use when you have an `Effect` that produces a `Layer` and you want to + * use that layer directly. + * + * **Details** + * + * The resulting Layer will have the combined error and dependency types from + * both the outer Effect and the inner Layer. + * + * **Example** (Unwrapping an effectful layer) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * * const layerEffect = Effect.succeed( - * Layer.succeed(Database)({ query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) }) + * Layer.succeed(Database, { query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) }) * ) * * const unwrappedLayer = Layer.unwrap(layerEffect) * ``` * + * @category converting * @since 4.0.0 - * @category utils */ export const unwrap = ( self: Effect, E, R> @@ -1296,14 +1520,25 @@ const mergeAllEffect = , ...Array Effect.Effect @@ -1313,18 +1548,20 @@ const mergeAllEffect = , ...Array Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link merge} for merging one layer with another layer or array + * * @category zipping + * @since 2.0.0 */ export const mergeAll = , ...Array>]>( ...layers: Layers @@ -1335,14 +1572,24 @@ export const mergeAll = , ...Array => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)) /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1352,29 +1599,41 @@ export const mergeAll = , ...Array Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ export const merge: { /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1384,29 +1643,41 @@ export const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ (that: Layer): (self: Layer) => Layer /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1416,18 +1687,20 @@ export const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ ]>(that: Layers): ( self: Layer @@ -1438,14 +1711,24 @@ export const merge: { | R > /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1455,29 +1738,41 @@ export const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ (self: Layer, that: Layer): Layer /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1487,18 +1782,20 @@ export const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ ]>(self: Layer, that: Layers): Layer< A | Success, @@ -1533,13 +1830,22 @@ const provideWith = ( ) /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1557,16 +1863,16 @@ const provideWith = ( * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1595,18 +1901,29 @@ const provideWith = ( * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ export const provide: { /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1624,16 +1941,16 @@ export const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1662,18 +1979,29 @@ export const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ (that: Layer): (self: Layer) => Layer> /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1691,16 +2019,16 @@ export const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1729,8 +2057,10 @@ export const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(that: Layers): ( self: Layer @@ -1741,13 +2071,22 @@ export const provide: { | Exclude> > /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1765,16 +2104,16 @@ export const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1803,18 +2142,29 @@ export const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ (self: Layer, that: Layer): Layer> /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1832,16 +2182,16 @@ export const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1870,8 +2220,10 @@ export const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(self: Layer, that: Layers): Layer< A, @@ -1885,13 +2237,22 @@ export const provide: { ) => provideWith(self, that, identity)) /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1909,16 +2270,16 @@ export const provide: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1953,18 +2314,29 @@ export const provide: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ export const provideMerge: { /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1982,16 +2354,16 @@ export const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -2026,18 +2398,29 @@ export const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ (that: Layer): (self: Layer) => Layer> /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -2055,16 +2438,16 @@ export const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -2099,8 +2482,10 @@ export const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(that: Layers): ( self: Layer @@ -2111,13 +2496,22 @@ export const provideMerge: { | Exclude> > /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -2135,16 +2529,16 @@ export const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -2179,18 +2573,29 @@ export const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ (self: Layer, that: Layer): Layer> /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -2208,16 +2613,16 @@ export const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -2252,8 +2657,10 @@ export const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(self: Layer, that: Layers): Layer< A | Success, @@ -2274,9 +2681,10 @@ export const provideMerge: { /** * Constructs a layer dynamically based on the output of this layer. * - * @example + * **Example** (Creating services from layer output) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Config extends Context.Service()("Logger") {} * * // Base config layer - * const configLayer = Layer.succeed(Config)({ + * const configLayer = Layer.succeed(Config, { * dbUrl: "postgres://localhost:5432/mydb", * logLevel: "debug" * }) @@ -2303,7 +2711,7 @@ export const provideMerge: { * const config = Context.get(context, Config) * * // Create database layer based on config - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => * Effect.succeed( * `Querying ${config.dbUrl}: ${sql}` @@ -2311,7 +2719,7 @@ export const provideMerge: { * }) * * // Create logger layer based on config - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => * config.logLevel === "debug" * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) @@ -2338,16 +2746,17 @@ export const provideMerge: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const flatMap: { /** * Constructs a layer dynamically based on the output of this layer. * - * @example + * **Example** (Creating services from layer output) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Config extends Context.Service()("Logger") {} * * // Base config layer - * const configLayer = Layer.succeed(Config)({ + * const configLayer = Layer.succeed(Config, { * dbUrl: "postgres://localhost:5432/mydb", * logLevel: "debug" * }) @@ -2374,7 +2783,7 @@ export const flatMap: { * const config = Context.get(context, Config) * * // Create database layer based on config - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => * Effect.succeed( * `Querying ${config.dbUrl}: ${sql}` @@ -2382,7 +2791,7 @@ export const flatMap: { * }) * * // Create logger layer based on config - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => * config.logLevel === "debug" * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) @@ -2409,16 +2818,17 @@ export const flatMap: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (f: (context: Context.Context) => Layer): (self: Layer) => Layer /** * Constructs a layer dynamically based on the output of this layer. * - * @example + * **Example** (Creating services from layer output) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Config extends Context.Service()("Logger") {} * * // Base config layer - * const configLayer = Layer.succeed(Config)({ + * const configLayer = Layer.succeed(Config, { * dbUrl: "postgres://localhost:5432/mydb", * logLevel: "debug" * }) @@ -2445,7 +2855,7 @@ export const flatMap: { * const config = Context.get(context, Config) * * // Create database layer based on config - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => * Effect.succeed( * `Querying ${config.dbUrl}: ${sql}` @@ -2453,7 +2863,7 @@ export const flatMap: { * }) * * // Create logger layer based on config - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => * config.logLevel === "debug" * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) @@ -2480,8 +2890,8 @@ export const flatMap: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( self: Layer, @@ -2501,22 +2911,64 @@ export const flatMap: { /** * Performs the specified effect if this layer succeeds. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * * @category sequencing + * @since 2.0.0 */ export const tap: { /** * Performs the specified effect if this layer succeeds. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * * @category sequencing + * @since 2.0.0 */ (f: (context: Context.Context) => Effect): (self: Layer) => Layer> /** * Performs the specified effect if this layer succeeds. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * * @category sequencing + * @since 2.0.0 */ ( self: Layer, @@ -2536,22 +2988,64 @@ export const tap: { /** * Performs the specified effect if this layer fails. * - * @since 4.0.0 + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * * @category sequencing + * @since 2.0.0 */ export const tapError: { /** * Performs the specified effect if this layer fails. * - * @since 4.0.0 + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * * @category sequencing + * @since 2.0.0 */ (f: (e: XE) => Effect): (self: Layer) => Layer> /** * Performs the specified effect if this layer fails. * - * @since 4.0.0 + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * * @category sequencing + * @since 2.0.0 */ (self: Layer, f: (e: XE) => Effect): Layer> } = dual(2, ( @@ -2566,42 +3060,69 @@ export const tapError: { )) /** - * Performs the specified effect if this layer fails. + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** * - * **Previously Known As** + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.tapErrorCause` + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ export const tapCause: { /** - * Performs the specified effect if this layer fails. + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** * - * **Previously Known As** + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.tapErrorCause` + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ (f: (cause: Cause.Cause) => Effect): (self: Layer) => Layer> /** - * Performs the specified effect if this layer fails. + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** * - * **Previously Known As** + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.tapErrorCause` + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ ( self: Layer, @@ -2620,12 +3141,18 @@ export const tapCause: { )) /** - * Translates effect failure into death of the fiber, making all failures - * unchecked and not a part of the type of the layer. + * Converts layer construction failures into defects, removing them from the + * layer's error type. + * + * **Details** + * + * Use this only when failures should be treated as unrecoverable defects rather + * than typed errors that callers can handle. + * + * **Example** (Converting layer failures to defects) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string @@ -2636,14 +3163,9 @@ export const tapCause: { * }>()("Database") {} * * // Layer that can fail during construction - * const flakyDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * // Simulate a database connection that might fail - * const shouldFail = Math.random() > 0.5 - * if (shouldFail) { - * return yield* new DatabaseError({ message: "Connection failed" }) - * } - * - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } + * const flakyDatabaseLayer = Layer.effect(Database, Effect.gen(function*() { + * console.log("connecting") + * return yield* new DatabaseError({ message: "Connection failed" }) * })) * * // Convert failures to fiber death - removes error from type @@ -2657,12 +3179,12 @@ export const tapCause: { * Effect.provide(reliableDatabaseLayer) * ) * - * // If the database layer fails, the entire fiber will die - * // instead of the effect failing with DatabaseError + * // Running the program prints "connecting", then the DatabaseError is + * // converted into a fiber defect instead of remaining a typed error. * ``` * - * @since 2.0.0 * @category error handling + * @since 2.0.0 */ export const orDie = (self: Layer): Layer => fromBuildUnsafe((memoMap, scope) => internalEffect.orDie(self.build(memoMap, scope))) @@ -2688,10 +3210,18 @@ const catch_: { export { /** - * Recovers from all errors. + * Recovers from all typed errors by switching to another layer. + * + * **When to use** + * + * Use when every typed `Layer` construction error should use the same + * recovery path. + * + * @see {@link catchTag} for recovering from specific tagged errors + * @see {@link catchCause} for recovering with access to the full cause * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ catch_ as catch } @@ -2699,9 +3229,14 @@ export { /** * Recovers from specific tagged errors. * - * @example + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class ConfigError extends Data.TaggedError("ConfigError") {} * @@ -2709,25 +3244,32 @@ export { * readonly apiUrl: string * }>()("Config") {} * - * const configLayer = Layer.effect(Config)(Effect.fail(new ConfigError())) + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) * - * const fallbackLayer = Layer.succeed(Config)({ apiUrl: "http://localhost" }) + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) * * const recovered = configLayer.pipe( * Layer.catchTag("ConfigError", () => fallbackLayer) * ) * ``` * - * @since 4.0.0 + * @see {@link catchCause} for recovering with access to the full cause + * * @category error handling + * @since 4.0.0 */ export const catchTag: { /** * Recovers from specific tagged errors. * - * @example + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class ConfigError extends Data.TaggedError("ConfigError") {} * @@ -2735,17 +3277,19 @@ export const catchTag: { * readonly apiUrl: string * }>()("Config") {} * - * const configLayer = Layer.effect(Config)(Effect.fail(new ConfigError())) + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) * - * const fallbackLayer = Layer.succeed(Config)({ apiUrl: "http://localhost" }) + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) * * const recovered = configLayer.pipe( * Layer.catchTag("ConfigError", () => fallbackLayer) * ) * ``` * - * @since 4.0.0 + * @see {@link catchCause} for recovering with access to the full cause + * * @category error handling + * @since 4.0.0 */ | NonEmptyReadonlyArray>, E, RIn2, E2, ROut2>( k: K, @@ -2762,9 +3306,14 @@ export const catchTag: { /** * Recovers from specific tagged errors. * - * @example + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class ConfigError extends Data.TaggedError("ConfigError") {} * @@ -2772,17 +3321,19 @@ export const catchTag: { * readonly apiUrl: string * }>()("Config") {} * - * const configLayer = Layer.effect(Config)(Effect.fail(new ConfigError())) + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) * - * const fallbackLayer = Layer.succeed(Config)({ apiUrl: "http://localhost" }) + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) * * const recovered = configLayer.pipe( * Layer.catchTag("ConfigError", () => fallbackLayer) * ) * ``` * - * @since 4.0.0 + * @see {@link catchCause} for recovering with access to the full cause + * * @category error handling + * @since 4.0.0 */ < RIn, @@ -2823,177 +3374,177 @@ export const catchTag: { )) /** - * Recovers from all errors. + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string * }> {} * - * class NetworkError extends Data.TaggedError("NetworkError")<{ - * reason: string - * }> {} - * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * return yield* new DatabaseError({ message: "Primary DB unreachable" }) - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Primary: ${sql}`)) } - * })) + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) * - * // Fallback layers for different error causes * const databaseWithFallback = primaryDatabaseLayer.pipe( * Layer.catchCause(() => { - * // For any cause/error, fallback to in-memory database - * return Layer.mergeAll( - * Layer.succeed(Database)({ - * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) - * }), - * Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => - * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) - * ) - * }) - * ) + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) * }) * ) * * const program = Effect.gen(function*() { * const database = yield* Database - * return yield* database.query("SELECT * FROM users") + * const result = yield* database.query("SELECT * FROM users") + * console.log(result) * }).pipe( * Effect.provide(databaseWithFallback) * ) + * + * Effect.runPromise(program) + * // Memory: SELECT * FROM users * ``` * - * @since 2.0.0 + * @see {@link catchTag} for recovering from specific tagged errors + * * @category error handling + * @since 4.0.0 */ export const catchCause: { /** - * Recovers from all errors. + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string * }> {} * - * class NetworkError extends Data.TaggedError("NetworkError")<{ - * reason: string - * }> {} - * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * return yield* new DatabaseError({ message: "Primary DB unreachable" }) - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Primary: ${sql}`)) } - * })) + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) * - * // Fallback layers for different error causes * const databaseWithFallback = primaryDatabaseLayer.pipe( * Layer.catchCause(() => { - * // For any cause/error, fallback to in-memory database - * return Layer.mergeAll( - * Layer.succeed(Database)({ - * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) - * }), - * Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => - * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) - * ) - * }) - * ) + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) * }) * ) * * const program = Effect.gen(function*() { * const database = yield* Database - * return yield* database.query("SELECT * FROM users") + * const result = yield* database.query("SELECT * FROM users") + * console.log(result) * }).pipe( * Effect.provide(databaseWithFallback) * ) + * + * Effect.runPromise(program) + * // Memory: SELECT * FROM users * ``` * - * @since 2.0.0 + * @see {@link catchTag} for recovering from specific tagged errors + * * @category error handling + * @since 4.0.0 */ (onError: (cause: Cause.Cause) => Layer): (self: Layer) => Layer /** - * Recovers from all errors. + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string * }> {} * - * class NetworkError extends Data.TaggedError("NetworkError")<{ - * reason: string - * }> {} - * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * return yield* new DatabaseError({ message: "Primary DB unreachable" }) - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Primary: ${sql}`)) } - * })) + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) * - * // Fallback layers for different error causes * const databaseWithFallback = primaryDatabaseLayer.pipe( * Layer.catchCause(() => { - * // For any cause/error, fallback to in-memory database - * return Layer.mergeAll( - * Layer.succeed(Database)({ - * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) - * }), - * Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => - * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) - * ) - * }) - * ) + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) * }) * ) * * const program = Effect.gen(function*() { * const database = yield* Database - * return yield* database.query("SELECT * FROM users") + * const result = yield* database.query("SELECT * FROM users") + * console.log(result) * }).pipe( * Effect.provide(databaseWithFallback) * ) + * + * Effect.runPromise(program) + * // Memory: SELECT * FROM users * ``` * - * @since 2.0.0 + * @see {@link catchTag} for recovering from specific tagged errors + * * @category error handling + * @since 4.0.0 */ ( self: Layer, @@ -3013,6 +3564,11 @@ export const catchCause: { /** * Updates a service in the context with a new implementation. * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * * **Details** * * This function modifies the existing implementation of a service in the @@ -3020,18 +3576,18 @@ export const catchCause: { * transformation function `f`, and replaces the old service with the * transformed one. * - * **When to Use** - * - * This is useful for adapting or extending a service's behavior during the - * creation of a layer. - * + * @category providing services * @since 3.13.0 - * @category utils */ export const updateService: { /** * Updates a service in the context with a new implementation. * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * * **Details** * * This function modifies the existing implementation of a service in the @@ -3039,18 +3595,18 @@ export const updateService: { * transformation function `f`, and replaces the old service with the * transformed one. * - * **When to Use** - * - * This is useful for adapting or extending a service's behavior during the - * creation of a layer. - * + * @category providing services * @since 3.13.0 - * @category utils */ (service: Context.Key, f: (a: Types.NoInfer) => A): (layer: Layer) => Layer /** * Updates a service in the context with a new implementation. * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * * **Details** * * This function modifies the existing implementation of a service in the @@ -3058,13 +3614,8 @@ export const updateService: { * transformation function `f`, and replaces the old service with the * transformed one. * - * **When to Use** - * - * This is useful for adapting or extending a service's behavior during the - * creation of a layer. - * + * @category providing services * @since 3.13.0 - * @category utils */ ( layer: Layer, @@ -3077,70 +3628,111 @@ export const updateService: { layer: Layer, service: Context.Key, f: (a: Types.NoInfer) => A - ): Layer => provide(layer, effect(service, internalEffect.map(service.asEffect(), f))) + ): Layer => provide(layer, effect(service, internalEffect.map(service, f))) ) /** * Creates a fresh version of this layer that will not be shared. * - * @example + * **When to use** + * + * Use when you need two parts of an application to receive separate instances + * of a resource, such as two independent client sessions. + * + * **Gotchas** + * + * Do not use it just to work around confusing composition. By default, sharing + * the same layer value is usually the desired behavior. + * + * **Example** (Creating non-shared layer instances) + * * ```ts - * import { Effect, Layer, Ref, Context } from "effect" + * import { Context, Effect, Layer, Ref } from "effect" * * class Counter extends Context.Service Effect.Effect + * readonly id: number * }>()("Counter") {} * - * // Layer that creates a counter with shared state - * const counterLayer = Layer.effect(Counter)(Effect.gen(function*() { - * const ref = yield* Ref.make(0) - * return { - * count: 0, - * increment: Effect.fn("Counter.increment")(() => - * Ref.update(ref, (n) => n + 1).pipe( - * Effect.flatMap(() => Ref.get(ref)) - * ) - * ) - * } + * class Left extends Context.Service()("Left") {} + * + * class Right extends Context.Service()("Right") {} + * + * const leftLayer = Layer.effect(Left, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } + * })) + * + * const rightLayer = Layer.effect(Right, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } * })) * - * // By default, layers are shared - same instance used everywhere - * const sharedProgram = Effect.gen(function*() { - * const counter1 = yield* Counter - * const counter2 = yield* Counter + * const showIds = Effect.gen(function*() { + * const left = yield* Left + * const right = yield* Right + * console.log(`same Counter: ${left.counterId === right.counterId}`) + * }) * - * // Both counter1 and counter2 refer to the same instance - * console.log("Shared layer - same instance") - * }).pipe( - * Effect.provide(counterLayer) - * ) + * const program = Effect.gen(function*() { + * const nextId = yield* Ref.make(0) * - * // Fresh layer creates a new instance each time - * const freshProgram = Effect.gen(function*() { - * const counter1 = yield* Counter - * const counter2 = yield* Counter + * const counterLayer = Layer.effect(Counter, Effect.gen(function*() { + * const id = yield* Ref.updateAndGet(nextId, (n) => n + 1) + * console.log("constructed Counter") + * return { id } + * })) * - * // counter1 and counter2 are different instances - * console.log("Fresh layer - different instances") - * }).pipe( - * Effect.provide(Layer.fresh(counterLayer)) - * ) + * const shared = Layer.merge( + * Layer.provide(leftLayer, counterLayer), + * Layer.provide(rightLayer, counterLayer) + * ) + * + * yield* Effect.provide(showIds, shared) + * + * const freshCounterLayer = Layer.fresh(counterLayer) + * const fresh = Layer.merge( + * Layer.provide(leftLayer, freshCounterLayer), + * Layer.provide(rightLayer, freshCounterLayer) + * ) + * + * yield* Effect.provide(showIds, fresh) + * }) + * + * Effect.runPromise(program) + * // constructed Counter + * // same Counter: true + * // constructed Counter + * // constructed Counter + * // same Counter: false * ``` * + * @category layers * @since 2.0.0 - * @category utils */ export const fresh = (self: Layer): Layer => fromBuildUnsafe((_, scope) => self.build(makeMemoMapUnsafe(), scope)) /** - * Builds this layer and uses it until it is interrupted. This is useful when - * your entire application is a layer, such as an HTTP server. + * Builds this layer and keeps it alive until the returned effect is interrupted. + * + * **When to use** + * + * Use when you model your entire application as a layer, such as an HTTP + * server. + * + * **Details** + * + * When the returned effect is interrupted, the layer scope is closed and all + * finalizers registered during layer acquisition are run. + * + * **Example** (Launching an application layer) * - * @example * ```ts - * import { Console, Effect, Layer, Context } from "effect" + * import { Console, Context, Effect, Layer } from "effect" * * class HttpServer extends Context.Service Effect.Effect @@ -3152,7 +3744,7 @@ export const fresh = (self: Layer): Layer => * }>()("Logger") {} * * // Server layer that starts an HTTP server - * const serverLayer = Layer.effect(HttpServer)(Effect.gen(function*() { + * const serverLayer = Layer.effect(HttpServer, Effect.gen(function*() { * yield* Console.log("Starting HTTP server...") * * return { @@ -3167,7 +3759,7 @@ export const fresh = (self: Layer): Layer => * } * })) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Console.log(`[LOG] ${msg}`)) * }) * @@ -3185,8 +3777,8 @@ export const fresh = (self: Layer): Layer => * // Effect.runFork(application) * ``` * + * @category converting * @since 2.0.0 - * @category conversions */ export const launch = (self: Layer): Effect => internalEffect.scoped(internalEffect.andThen(build(self), internalEffect.never)) @@ -3194,12 +3786,22 @@ export const launch = (self: Layer): Effect = Types.Simplify< & { @@ -3220,12 +3822,21 @@ type AnyEffectOrStream = /** * Creates a mock layer for testing purposes. You can provide a partial - * implementation of the service, and any methods not provided will - * throw an unimplemented defect when called. + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class UserService extends Context.Service(service: Context.Key): (implementation: PartialEffectful) => Layer /** * Creates a mock layer for testing purposes. You can provide a partial - * implementation of the service, and any methods not provided will - * throw an unimplemented defect when called. + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class UserService extends Context.Service( service: Context.Key, @@ -3417,12 +4046,15 @@ const ChannelTypeId: Channel.TypeId = "~effect/Channel" // ----------------------------------------------------------------------------- /** - * Ensures that an layer's success type extends a given type `ROut`. + * Ensures that a layer's success type extends a given type `ROut`. + * + * **Details** * * This function provides compile-time type checking to ensure that the success - * value of an layer conforms to a specific type constraint. + * value of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer success types) * - * @example * ```ts * import { Layer } from "effect" * @@ -3438,22 +4070,25 @@ const ChannelTypeId: Channel.TypeId = "~effect/Channel" * // This would cause a TypeScript compilation error: * // const invalidLayer = satisfiesNumber(StringLayer) * // ^^^^^^^^^^^ - * // Type 'number' is not assignable to type 'string' + * // Type 'string' is not assignable to type 'number' * ``` * + * @category utility types * @since 4.0.0 - * @category Type constraints */ export const satisfiesSuccessType = () => (layer: Layer): Layer => layer /** - * Ensures that an layer's error type extends a given type `E`. + * Ensures that a layer's error type extends a given type `E`. + * + * **Details** * * This function provides compile-time type checking to ensure that the error - * type of an layer conforms to a specific type constraint. + * type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer error types) * - * @example * ```ts * import { Layer } from "effect" * @@ -3473,26 +4108,29 @@ export const satisfiesSuccessType = * // Type 'string' is not assignable to type 'Error' * ``` * + * @category utility types * @since 4.0.0 - * @category Type constraints */ export const satisfiesErrorType = () => (layer: Layer): Layer => layer /** - * Ensures that an layer's requirements type extends a given type `R`. + * Ensures that a layer's requirements type extends a given type `R`. + * + * **Details** * * This function provides compile-time type checking to ensure that the - * requirements (context) type of an layer conforms to a specific type constraint. + * requirements type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer service requirements) * - * @example * ```ts * import { Layer } from "effect" * * declare const FortyTwoLayer: Layer.Layer * declare const StringLayer: Layer.Layer * - * // Define a constraint that the success type must be a number + * // Define a constraint that the service requirements must be numbers * const satisfiesNumber = Layer.satisfiesServicesType() * * // This works - Layer extends Layer @@ -3504,8 +4142,8 @@ export const satisfiesErrorType = * // Type 'string' is not assignable to type 'number' * ``` * + * @category utility types * @since 4.0.0 - * @category Type constraints */ export const satisfiesServicesType = () => (layer: Layer): Layer => layer @@ -3518,13 +4156,27 @@ export const satisfiesServicesType = * Represents options that can be used to control the behavior of spans created * for layers. * + * **When to use** + * + * Use to configure tracing metadata, stack trace capture, and `onEnd` + * finalization for spans created by `Layer.span` and `Layer.withSpan` during + * layer construction. + * + * **Details** + * + * Extends `Tracer.SpanOptions` with `onEnd`, which runs when the layer span + * ends as the layer scope closes. + * + * @see {@link span} for creating a layer span + * @see {@link withSpan} for wrapping layer construction in a span + * + * @category options * @since 4.0.0 - * @category Models */ export interface SpanOptions extends Tracer.SpanOptions { /** - * A function that will be called when the span associated with the layer is - * ending (i.e. when the `Scope` that the span is associated with is closed). + * Runs when the span associated with the layer ends, which happens when the + * layer scope is closed. */ readonly onEnd?: | ((span: Tracer.Span, exit: Exit.Exit) => Effect) @@ -3535,13 +4187,19 @@ export interface SpanOptions extends Tracer.SpanOptions { * Constructs a new `Layer` which creates a span and registers it as the current * parent span. * + * **Details** + * * This allows you to create a traced scope for layer construction, making all * operations within the layer constructor part of the same trace span. The span - * is automatically closed when the layer's scope is closed. + * is automatically ended when the layer's scope is closed. If `onEnd` is + * provided, it receives the span and the layer scope's exit value when the span + * ends. + * + * **Example** (Tracing layer construction with a span) * - * @example * ```ts - * import { Console, Effect, Layer, Context, type Tracer } from "effect" + * import { Console, Context, Effect, Layer } from "effect" + * import type { Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3573,8 +4231,8 @@ export interface SpanOptions extends Tracer.SpanOptions { * }) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export const span = ( name: string, @@ -3593,16 +4251,18 @@ export const span = ( } /** - * Constructs a new `Layer` which takes an existing span and registers it as the - * current parent span. + * Constructs a layer that provides an existing span as the current parent span. * - * This allows you to create a traced scope for layer construction, making all - * operations within the layer constructor part of the same trace span. The span - * is automatically closed when the layer's scope is closed. + * **Details** + * + * The supplied span is made available through `Tracer.ParentSpan` for layers + * that are built with this layer. This API does not create, end, or close the + * span; the caller remains responsible for the span's lifetime. + * + * **Example** (Using an existing parent span) * - * @example * ```ts - * import { Console, Effect, Layer, Context, Tracer } from "effect" + * import { Console, Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3627,23 +4287,26 @@ export const span = ( * })))) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export const parentSpan = (span: Tracer.AnySpan): Layer => succeedContext(Tracer.ParentSpan.context(span)) /** - * Wraps a Layer with a new tracing span, making all operations in the layer + * Wraps a `Layer` with a new tracing span, making all operations in the layer * constructor part of the named trace span. * + * **Details** + * * This creates a new span for the layer's construction and execution. The span * is automatically ended when the layer's scope is closed. This is useful for * tracking the lifecycle and performance of layer initialization. * - * @example + * **Example** (Wrapping a layer with a span) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3684,25 +4347,27 @@ export const parentSpan = (span: Tracer.AnySpan): Layer => * * yield* logger.log("Application ready") * return yield* database.query("SELECT * FROM users") - * }).pipe(Effect.provide(appLayer) - * ) + * }).pipe(Effect.provide(appLayer)) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export const withSpan: { /** - * Wraps a Layer with a new tracing span, making all operations in the layer + * Wraps a `Layer` with a new tracing span, making all operations in the layer * constructor part of the named trace span. * + * **Details** + * * This creates a new span for the layer's construction and execution. The span * is automatically ended when the layer's scope is closed. This is useful for * tracking the lifecycle and performance of layer initialization. * - * @example + * **Example** (Wrapping a layer with a span) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3743,27 +4408,29 @@ export const withSpan: { * * yield* logger.log("Application ready") * return yield* database.query("SELECT * FROM users") - * }).pipe(Effect.provide(appLayer) - * ) + * }).pipe(Effect.provide(appLayer)) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (name: string, options?: SpanOptions): ( self: Layer ) => Layer> /** - * Wraps a Layer with a new tracing span, making all operations in the layer + * Wraps a `Layer` with a new tracing span, making all operations in the layer * constructor part of the named trace span. * + * **Details** + * * This creates a new span for the layer's construction and execution. The span * is automatically ended when the layer's scope is closed. This is useful for * tracking the lifecycle and performance of layer initialization. * - * @example + * **Example** (Wrapping a layer with a span) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3804,12 +4471,11 @@ export const withSpan: { * * yield* logger.log("Application ready") * return yield* database.query("SELECT * FROM users") - * }).pipe(Effect.provide(appLayer) - * ) + * }).pipe(Effect.provide(appLayer)) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (self: Layer, name: string, options?: SpanOptions): Layer> } = function() { @@ -3845,15 +4511,23 @@ export const withSpan: { } as any /** - * Wraps a `Layer` with a new tracing span and sets the span as the parent span. + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** * - * This attaches a layer to an existing trace span, making all operations within - * the layer children of the provided parent span. This is useful for integrating - * layer construction into an existing trace hierarchy. + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. + * + * **Example** (Attaching layers to an existing parent span) * - * @example * ```ts - * import { Effect, Layer, Context, Tracer } from "effect" + * import { Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3900,20 +4574,28 @@ export const withSpan: { * ) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export const withParentSpan: { /** - * Wraps a `Layer` with a new tracing span and sets the span as the parent span. + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** + * + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. * - * This attaches a layer to an existing trace span, making all operations within - * the layer children of the provided parent span. This is useful for integrating - * layer construction into an existing trace hierarchy. + * **Example** (Attaching layers to an existing parent span) * - * @example * ```ts - * import { Effect, Layer, Context, Tracer } from "effect" + * import { Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3960,22 +4642,30 @@ export const withParentSpan: { * ) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (span: Tracer.AnySpan, options?: Tracer.TraceOptions): ( self: Layer ) => Layer> /** - * Wraps a `Layer` with a new tracing span and sets the span as the parent span. + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** * - * This attaches a layer to an existing trace span, making all operations within - * the layer children of the provided parent span. This is useful for integrating - * layer construction into an existing trace hierarchy. + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. + * + * **Example** (Attaching layers to an existing parent span) * - * @example * ```ts - * import { Effect, Layer, Context, Tracer } from "effect" + * import { Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -4022,8 +4712,8 @@ export const withParentSpan: { * ) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (self: Layer, span: Tracer.AnySpan, options?: Tracer.TraceOptions): Layer> } = function() {