diff --git "a/.opencode/node_modules/effect/dist/Channel.js" "b/.opencode/node_modules/effect/dist/Channel.js" --- "a/.opencode/node_modules/effect/dist/Channel.js" +++ "b/.opencode/node_modules/effect/dist/Channel.js" @@ -1,58 +1,11 @@ /** - * The `Channel` module provides a powerful abstraction for bi-directional communication - * and streaming operations. A `Channel` is a nexus of I/O operations that supports both - * reading and writing, forming the foundation for Effect's Stream and Sink abstractions. + * Provides low-level building blocks for streaming data through Effect. * - * ## What is a Channel? - * - * A `Channel` represents: - * - **OutElem**: The type of elements the channel outputs - * - **OutErr**: The type of errors the channel can produce - * - **OutDone**: The type of the final value when the channel completes - * - **InElem**: The type of elements the channel reads - * - **InErr**: The type of errors the channel can receive - * - **InDone**: The type of the final value from upstream - * - **Env**: The environment/context required by the channel - * - * ## Key Features - * - * - **Bi-directional**: Channels can both read and write - * - **Composable**: Channels can be piped, sequenced, and concatenated - * - **Resource-safe**: Automatic cleanup and resource management - * - **Error-handling**: Built-in error propagation and handling - * - **Concurrent**: Support for concurrent operations - * - * ## Composition Patterns - * - * 1. **Piping**: Connect channels where output of one becomes input of another - * 2. **Sequencing**: Use the result of one channel to create another - * 3. **Concatenating**: Combine multiple channels into a single channel - * - * @example - * ```ts - * import { Channel } from "effect" - * - * // Simple channel that outputs numbers - * const numberChannel = Channel.succeed(42) - * - * // Transform channel that doubles values - * const doubleChannel = Channel.map(numberChannel, (n) => n * 2) - * - * // Running the channel would output: 84 - * ``` - * - * @example - * ```ts - * import { Channel } from "effect" - * - * // Channel from an array of values - * const arrayChannel = Channel.fromArray([1, 2, 3, 4, 5]) - * - * // Transform the channel by mapping over values - * const transformedChannel = Channel.map(arrayChannel, (n) => n * 2) - * - * // This channel will output: 2, 4, 6, 8, 10 - * ``` + * A `Channel` can read input elements, write output elements, fail with a typed + * error, and finish with a typed result while managing resources safely. + * Streams and sinks are built on channels, so most application code uses those + * higher-level modules instead. This module is useful when implementing stream + * operators or specialized streaming workflows. * * @since 2.0.0 */ @@ -85,14 +38,18 @@ import * as String from "./String.js"; import * as Take from "./Take.js"; import { ParentSpan } from "./Tracer.js"; /** + * Runtime identifier stored on `Channel` values and used by `isChannel` to + * recognize them. + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export const TypeId = "~effect/Channel"; /** - * Tests if a value is a `Channel`. + * Checks whether a value is a `Channel`. + * + * **Example** (Checking for channels) * - * @example * ```ts * import { Channel } from "effect" * @@ -123,7 +80,8 @@ const ChannelProto = { /** * Creates a `Channel` from a transformation function that operates on upstream pulls. * - * @example + * **Example** (Creating channels from transforms) + * * ```ts * import { Channel, Effect } from "effect" * @@ -143,7 +101,8 @@ export const fromTransform = transform => { /** * Transforms a Channel by applying a function to its Pull implementation. * - * @example + * **Example** (Transforming pull behavior) + * * ```ts * import { Channel, Effect } from "effect" * @@ -167,7 +126,8 @@ export const transformPull = (self, f) => fromTransform((upstream, scope) => Eff /** * Creates a `Channel` from an `Effect` that produces a `Pull`. * - * @example + * **Example** (Creating channels from pulls) + * * ```ts * import { Channel, Effect } from "effect" * @@ -185,8 +145,15 @@ export const fromPull = effect => fromTransform((_, __) => effect); * pulls, but also provides a forked scope that closes when the resulting * Channel completes. * - * @since 4.0.0 + * **When to use** + * + * Use when building channels that require scoped resource lifecycle management, + * providing both the channel scope and a forked scope that automatically closes + * when the channel completes. + * + * @see {@link fromTransform} for a simpler transformation without a forked scope * @category constructors + * @since 4.0.0 */ export const fromTransformBracket = f => fromTransform(Effect.fnUntraced(function* (upstream, scope) { const closableScope = Scope.forkUnsafe(scope); @@ -197,7 +164,8 @@ export const fromTransformBracket = f => fromTransform(Effect.fnUntraced(functio /** * Converts a `Channel` back to its underlying transformation function. * - * @example + * **Example** (Extracting channel transforms) + * * ```ts * import { Channel } from "effect" * @@ -213,7 +181,8 @@ export const toTransform = channel => channel.transform; /** * The default chunk size used by channels for batching operations. * - * @example + * **Example** (Reading the default chunk size) + * * ```ts * import { Channel } from "effect" * @@ -221,7 +190,7 @@ export const toTransform = channel => channel.transform; * ``` * * @category constants - * @since 2.0.0 + * @since 4.0.0 */ export const DefaultChunkSize = 4096; const asyncQueue = (scope, f, options) => Queue.make({ @@ -231,7 +200,8 @@ const asyncQueue = (scope, f, options) => Queue.make({ /** * Creates a `Channel` that interacts with a callback function using a queue. * - * @example + * **Example** (Creating channels from callbacks) + * * ```ts * import { Channel, Effect, Queue } from "effect" * @@ -245,13 +215,14 @@ const asyncQueue = (scope, f, options) => Queue.make({ * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const callback = (f, options) => fromTransform((_, scope) => Effect.map(asyncQueue(scope, f, options), Queue.take)); /** * Creates a `Channel` that interacts with a callback function using a queue, emitting arrays. * - * @example + * **Example** (Creating array channels from callbacks) + * * ```ts * import { Channel, Effect, Queue } from "effect" * @@ -269,7 +240,8 @@ export const callbackArray = (f, options) => fromTransform((_, scope) => Effect. /** * Creates a `Channel` that lazily evaluates to another channel. * - * @example + * **Example** (Suspending channel creation) + * * ```ts * import { Channel } from "effect" * @@ -282,9 +254,17 @@ export const callbackArray = (f, options) => fromTransform((_, scope) => Effect. */ export const suspend = evaluate => fromTransform((upstream, scope) => Effect.suspend(() => toTransform(evaluate())(upstream, scope))); /** - * Creates a `Channel` with resource management using acquire-use-release pattern. + * Acquires a resource, uses it to build a `Channel`, and guarantees that + * `release` runs with the channel's `Exit` when the channel completes, fails, + * or is interrupted. + * + * **Details** + * + * Acquisition is uninterruptible. If acquisition fails, `use` is not run and + * `release` is not registered. + * + * **Example** (Managing resources with acquire-use-release) * - * @example * ```ts * import { Channel, Effect } from "effect" * @@ -306,9 +286,17 @@ export const acquireUseRelease = (acquire, use, release) => fromTransformBracket return yield* toTransform(use(value))(upstream, scope); })); /** - * Creates a `Channel` with resource management using acquire-release pattern. + * Acquires a resource, emits the acquired value as a single channel element, + * and registers `release` in the channel scope. + * + * **Details** + * + * The release action runs when the channel scope closes and receives the scope + * exit. If acquisition fails, no element is emitted and `release` is not + * registered. + * + * **Example** (Managing resources with acquire-release) * - * @example * ```ts * import { Channel, Effect } from "effect" * @@ -319,13 +307,14 @@ export const acquireUseRelease = (acquire, use, release) => fromTransformBracket * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const acquireRelease = /*#__PURE__*/dual(2, (self, release) => unwrap(Effect.map(Effect.acquireRelease(self, release), succeed))); /** * Creates a `Channel` from an iterator. * - * @example + * **Example** (Creating channels from iterators) + * * ```ts * import { Channel } from "effect" * @@ -335,7 +324,7 @@ export const acquireRelease = /*#__PURE__*/dual(2, (self, release) => unwrap(Eff * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const fromIterator = iterator => fromPull(Effect.sync(() => { const iter = iterator(); @@ -347,7 +336,8 @@ export const fromIterator = iterator => fromPull(Effect.sync(() => { /** * Creates a `Channel` that emits all elements from an array. * - * @example + * **Example** (Creating channels from arrays) + * * ```ts * import { Channel } from "effect" * @@ -356,7 +346,7 @@ export const fromIterator = iterator => fromPull(Effect.sync(() => { * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const fromArray = array => fromPull(Effect.sync(() => { let index = 0; @@ -365,7 +355,8 @@ export const fromArray = array => fromPull(Effect.sync(() => { /** * Creates a `Channel` that emits all elements from a chunk. * - * @example + * **Example** (Creating channels from chunks) + * * ```ts * import { Channel, Chunk } from "effect" * @@ -375,13 +366,14 @@ export const fromArray = array => fromPull(Effect.sync(() => { * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const fromChunk = chunk => fromArray(Chunk.toReadonlyArray(chunk)); /** * Creates a `Channel` from an iterator that emits arrays of elements. * - * @example + * **Example** (Batching iterator output) + * * ```ts * import { Channel } from "effect" * @@ -402,7 +394,8 @@ export const fromChunk = chunk => fromArray(Chunk.toReadonlyArray(chunk)); * // This will emit arrays: [0, 1], [2], then complete with "finished" * ``` * - * @example + * **Example** (Batching generator output) + * * ```ts * import { Channel } from "effect" * @@ -419,8 +412,8 @@ export const fromChunk = chunk => fromArray(Chunk.toReadonlyArray(chunk)); * // Emits: [0, 1, 1], [2, 3], then completes * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const fromIteratorArray = (iterator, chunkSize = DefaultChunkSize) => fromPull(Effect.sync(() => { const iter = iterator(); @@ -445,7 +438,8 @@ export const fromIteratorArray = (iterator, chunkSize = DefaultChunkSize) => fro /** * Creates a `Channel` that emits all elements from an iterable. * - * @example + * **Example** (Creating channels from iterables) + * * ```ts * import { Channel } from "effect" * @@ -455,13 +449,14 @@ export const fromIteratorArray = (iterator, chunkSize = DefaultChunkSize) => fro * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const fromIterable = iterable => fromIterator(() => iterable[Symbol.iterator]()); /** * Creates a `Channel` that emits arrays of elements from an iterable. * - * @example + * **Example** (Batching iterable output) + * * ```ts * import { Channel } from "effect" * @@ -471,13 +466,14 @@ export const fromIterable = iterable => fromIterator(() => iterable[Symbol.itera * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const fromIterableArray = (iterable, chunkSize = DefaultChunkSize) => fromIteratorArray(() => iterable[Symbol.iterator](), chunkSize); /** * Creates a `Channel` that emits a single value and then ends. * - * @example + * **Example** (Creating channels that succeed) + * * ```ts * import { Channel } from "effect" * @@ -492,7 +488,8 @@ export const succeed = value => fromEffect(Effect.succeed(value)); /** * Creates a `Channel` that immediately ends with the specified value. * - * @example + * **Example** (Ending with a value) + * * ```ts * import { Channel } from "effect" * @@ -514,12 +511,18 @@ export const endSync = evaluate => fromPull(Effect.sync(() => Cause.done(evaluat /** * Creates a `Channel` that emits a single value computed by a lazy evaluation. * - * @example + * **Example** (Computing values lazily) + * * ```ts * import { Channel } from "effect" * - * const channel = Channel.sync(() => Math.random()) - * // Emits a random number computed when the channel runs + * let requests = 0 + * + * const channel = Channel.sync(() => { + * requests += 1 + * return `request-${requests}` + * }) + * // Emits "request-1" when the channel runs for the first time * ``` * * @category constructors @@ -527,9 +530,10 @@ export const endSync = evaluate => fromPull(Effect.sync(() => Cause.done(evaluat */ export const sync = evaluate => fromEffect(Effect.sync(evaluate)); /** - * Represents an Channel that emits no elements + * Represents a `Channel` that emits no elements. + * + * **Example** (Using empty channels) * - * @example * ```ts * import { Channel } from "effect" * @@ -545,14 +549,15 @@ export const sync = evaluate => fromEffect(Effect.sync(evaluate)); * shouldEmit ? Channel.succeed("data") : Channel.empty * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const empty = /*#__PURE__*/fromPull(/*#__PURE__*/Effect.succeed(/*#__PURE__*/Cause.done())); /** - * Represents an Channel that never completes + * Represents a `Channel` that never completes. + * + * **Example** (Using non-terminating channels) * - * @example * ```ts * import { Channel } from "effect" * @@ -570,14 +575,15 @@ export const empty = /*#__PURE__*/fromPull(/*#__PURE__*/Effect.succeed(/*#__PURE * shouldComplete ? Channel.succeed("done") : Channel.never * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const never = /*#__PURE__*/fromPull(/*#__PURE__*/Effect.succeed(Effect.never)); /** * Constructs a channel that fails immediately with the specified error. * - * @example + * **Example** (Failing with an error) + * * ```ts * import { Channel } from "effect" * @@ -600,15 +606,21 @@ export const never = /*#__PURE__*/fromPull(/*#__PURE__*/Effect.succeed(Effect.ne * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fail = error => fromPull(Effect.succeed(Effect.fail(error))); /** * Constructs a channel that fails immediately with the specified lazily * evaluated error. * - * @example + * **When to use** + * + * Use when the error value should be computed each time the channel runs instead + * of when the channel is constructed. + * + * **Example** (Failing with a lazy error) + * * ```ts * import { Channel } from "effect" * @@ -619,25 +631,33 @@ export const fail = error => fromPull(Effect.succeed(Effect.fail(error))); * }) * * // The error computation is deferred until the channel runs - * const conditionalError = Channel.failSync(() => - * Math.random() > 0.5 ? "Error A" : "Error B" - * ) + * let attempts = 0 + * const conditionalError = Channel.failSync(() => { + * attempts += 1 + * return `Error after attempt ${attempts}` + * }) * * // Use with expensive error construction * const expensiveError = Channel.failSync(() => { - * const timestamp = Date.now() - * return new Error(`Failed at: ${timestamp}`) + * const requestId = "request-123" + * return new Error(`Failed while processing ${requestId}`) * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const failSync = evaluate => fromPull(Effect.failSync(evaluate)); /** * Constructs a channel that fails immediately with the specified `Cause`. * - * @example + * **When to use** + * + * Use when the channel failure must preserve a full `Cause`, such as defects, + * interruptions, or combined failures. + * + * **Example** (Failing with causes) + * * ```ts * import { Cause, Channel } from "effect" * @@ -654,39 +674,42 @@ export const failSync = evaluate => fromPull(Effect.failSync(evaluate)); * const simpleFail = Channel.failCause(failCause) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const failCause = cause => fromPull(Effect.failCause(cause)); /** * Constructs a channel that fails immediately with the specified lazily * evaluated `Cause`. * - * @example + * **Example** (Failing with lazy causes) + * * ```ts * import { Cause, Channel } from "effect" * * // Create a channel that fails with a lazily computed cause + * let attempts = 0 * const failedChannel = Channel.failCauseSync(() => { - * const errorType = Math.random() > 0.5 ? "A" : "B" - * return Cause.fail(`Runtime error ${errorType}`) + * attempts += 1 + * return Cause.fail(`Runtime error after attempt ${attempts}`) * }) * * // Create a channel with die cause computation * const dieCauseChannel = Channel.failCauseSync(() => { - * const timestamp = Date.now() - * return Cause.die(`Error at ${timestamp}`) + * const operation = "load-profile" + * return Cause.die(`Unexpected defect during ${operation}`) * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const failCauseSync = evaluate => fromPull(Effect.failCauseSync(evaluate)); /** * Constructs a channel that fails immediately with the specified defect. * - * @example + * **Example** (Dying with defects) + * * ```ts * import { Channel } from "effect" * @@ -703,14 +726,15 @@ export const failCauseSync = evaluate => fromPull(Effect.failCauseSync(evaluate) * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const die = defect => failCause(Cause.die(defect)); /** - * Use an effect to write a single value to the channel. + * Uses an effect to write a single value to the channel. + * + * **Example** (Creating channels from effects) * - * @example * ```ts * import { Channel, Data, Effect } from "effect" * @@ -740,8 +764,8 @@ export const die = defect => failCause(Cause.die(defect)); * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromEffect = effect => fromPull(Effect.sync(() => { let done = false; @@ -752,26 +776,42 @@ export const fromEffect = effect => fromPull(Effect.sync(() => { }); })); /** - * @since 4.0.0 + * Creates a channel that evaluates an effect and uses its successful value as + * the channel's done value without emitting any output elements. + * + * **Details** + * + * If the effect fails, the channel fails with the effect's error. + * * @category constructors + * @since 4.0.0 */ export const fromEffectDone = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Cause.done))); /** - * Use an effect and discard its result. + * Uses an effect and discards its result. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromEffectDrain = effect => fromPull(Effect.flatMap(effect, () => Cause.done())); /** - * @since 4.0.0 + * Creates a channel from an effect that produces a `Take`. + * + * **Details** + * + * A successful `Take` emits a non-empty array of output elements. A failed + * `Take` fails the channel. A done `Take` completes the channel with its done + * value. + * * @category constructors + * @since 4.0.0 */ export const fromEffectTake = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Take.toPull))); /** - * Create a channel from a queue + * Creates a channel from a queue. + * + * **Example** (Creating channels from queues) * - * @example * ```ts * import { Channel, Data, Effect, Queue } from "effect" * @@ -803,14 +843,15 @@ export const fromEffectTake = effect => fromPull(Effect.succeed(Effect.flatMap(e * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const fromQueue = queue => fromPull(Effect.succeed(Queue.take(queue))); /** - * Create a channel from a queue that emits arrays of elements + * Creates a channel from a queue that emits arrays of elements. + * + * **Example** (Creating batched channels from queues) * - * @example * ```ts * import { Channel, Data, Effect, Queue } from "effect" * @@ -846,19 +887,23 @@ export const fromQueue = queue => fromPull(Effect.succeed(Queue.take(queue))); * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromQueueArray = queue => fromPull(Effect.succeed(Queue.takeAll(queue))); /** + * Creates a channel that forwards upstream input elements, input errors, and + * the upstream done value unchanged. + * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const identity = () => fromTransform((upstream, _scope) => Effect.succeed(upstream)); /** - * Create a channel from a PubSub subscription + * Creates a channel from a PubSub subscription. + * + * **Example** (Creating channels from subscriptions) * - * @example * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -895,21 +940,21 @@ export const identity = () => fromTransform((upstream, _scope) => Effect.succeed * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromSubscription = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.take(subscription), () => Cause.done()))); /** - * Create a channel from a PubSub subscription that outputs arrays of values. + * Creates a channel from a PubSub subscription that outputs arrays of values. + * + * **Details** * * This constructor creates a channel that reads from a PubSub subscription and outputs * arrays of values in chunks. It's useful when you want to process multiple values at once * for better performance. * - * @param subscription - The PubSub subscription to read from - * @param chunkSize - The maximum number of elements to read in each chunk (default: 4096) + * **Example** (Batching subscription values) * - * @example * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -935,7 +980,8 @@ export const fromSubscription = subscription => fromPull(Effect.succeed(Effect.o * }) * ``` * - * @example + * **Example** (Processing subscription values in batches) + * * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -960,13 +1006,10 @@ export const fromSubscription = subscription => fromPull(Effect.succeed(Effect.o * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Aggregating subscription metrics) * - * class MetricsError extends Data.TaggedError("MetricsError")<{ - * readonly cause: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * const metricsAggregator = Effect.gen(function*() { * const metricsPubSub = yield* PubSub.bounded< @@ -991,7 +1034,8 @@ export const fromSubscription = subscription => fromPull(Effect.succeed(Effect.o * average: avg, * min, * max, - * timestamp: Date.now() + * firstTimestamp: Math.min(...metrics.map((m) => m.timestamp)), + * lastTimestamp: Math.max(...metrics.map((m) => m.timestamp)) * } * }) * @@ -999,20 +1043,21 @@ export const fromSubscription = subscription => fromPull(Effect.succeed(Effect.o * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromSubscriptionArray = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.takeAll(subscription), () => Cause.done()))); /** - * Create a channel from a PubSub that outputs individual values. + * Creates a channel from a PubSub that outputs individual values. + * + * **Details** * * This constructor creates a channel that reads from a PubSub by automatically * subscribing to it. The channel outputs individual values as they are published * to the PubSub, making it ideal for real-time streaming scenarios. * - * @param pubsub - The PubSub to read from + * **Example** (Creating channels from PubSubs) * - * @example * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -1036,13 +1081,10 @@ export const fromSubscriptionArray = subscription => fromPull(Effect.succeed(Eff * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Streaming PubSub notifications) * - * class NotificationError extends Data.TaggedError("NotificationError")<{ - * readonly reason: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * const notificationService = Effect.gen(function*() { * const notificationPubSub = yield* PubSub.bounded(50) @@ -1051,24 +1093,21 @@ export const fromSubscriptionArray = subscription => fromPull(Effect.succeed(Eff * const notificationChannel = Channel.fromPubSub(notificationPubSub) * * // Transform notifications to add timestamps + * const receivedAt = "2024-01-01T00:00:00.000Z" * const timestampedChannel = Channel.map(notificationChannel, (message) => ({ * message, - * timestamp: new Date().toISOString(), - * id: Math.random().toString(36).substr(2, 9) + * receivedAt, + * id: `notification:${message}` * })) * * return timestampedChannel * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Processing PubSub events) * - * class EventProcessingError extends Data.TaggedError("EventProcessingError")<{ - * readonly eventType: string - * readonly cause: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * interface DomainEvent { * readonly type: string @@ -1088,7 +1127,7 @@ export const fromSubscriptionArray = subscription => fromPull(Effect.succeed(Eff * return { * ...event, * processed: true, - * processedAt: Date.now() + * processedAt: event.timestamp + 1 * } * } * return event @@ -1098,21 +1137,21 @@ export const fromSubscriptionArray = subscription => fromPull(Effect.succeed(Eff * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscription)); /** - * Create a channel from a PubSub that outputs arrays of values. + * Creates a channel from a PubSub that outputs arrays of values. + * + * **Details** * * This constructor creates a channel that reads from a PubSub by automatically * subscribing to it and collecting values into arrays. The channel outputs * arrays of values in chunks, making it ideal for batch processing scenarios. * - * @param pubsub - The PubSub to read from - * @param chunkSize - The maximum number of elements to collect in each array (default: 4096) + * **Example** (Batching PubSub values) * - * @example * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -1137,20 +1176,17 @@ export const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Processing PubSub orders in batches) * - * class OrderProcessingError extends Data.TaggedError("OrderProcessingError")<{ - * readonly orderId: string - * readonly reason: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * interface Order { * readonly id: string * readonly customerId: string * readonly items: ReadonlyArray * readonly total: number + * readonly submittedAt: number * } * * const orderBatchProcessor = Effect.gen(function*() { @@ -1170,7 +1206,7 @@ export const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), * batchSize: orderBatch.length, * totalRevenue, * uniqueCustomers: customerCount, - * processedAt: Date.now(), + * firstSubmittedAt: Math.min(...orderBatch.map((order) => order.submittedAt)), * orders: orderBatch * } * }) @@ -1179,14 +1215,10 @@ export const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Processing PubSub logs in batches) * - * class LogProcessingError extends Data.TaggedError("LogProcessingError")<{ - * readonly batchId: string - * readonly cause: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * interface LogEntry { * readonly timestamp: number @@ -1213,7 +1245,7 @@ export const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), * } * * return { - * batchId: Math.random().toString(36).substr(2, 9), + * batchId: `${timeRange.start}-${timeRange.end}`, * totalEntries: logBatch.length, * errorCount, * warnCount, @@ -1227,27 +1259,41 @@ export const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromPubSubArray = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscriptionArray)); /** - * @since 4.0.0 + * Subscribes to a `PubSub` of `Take` values and exposes them as a channel. + * + * **Details** + * + * Output `Take` values are emitted as non-empty arrays. Failed `Take` values + * fail the channel. Done `Take` values complete the channel. + * * @category constructors + * @since 4.0.0 */ export const fromPubSubTake = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), sub => fromEffectTake(PubSub.take(sub)))); /** * Creates a Channel from a Schedule. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => step(void 0))); /** - * Creates a Channel from a AsyncIterable. + * Creates a channel that pulls values from an `AsyncIterable`. + * + * **Details** + * + * Each yielded value is emitted as an output element. The iterator's return + * value becomes the channel's done value. Thrown or rejected iterator errors + * are converted with `onError`. If the channel scope closes early and the + * iterator has a `return` method, that method is called. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromAsyncIterable = (iterable, onError) => fromTransform(Effect.fnUntraced(function* (_, scope) { const iter = iterable[Symbol.asyncIterator](); @@ -1260,16 +1306,24 @@ export const fromAsyncIterable = (iterable, onError) => fromTransform(Effect.fnU }), result => result.done ? Cause.done(result.value) : Effect.succeed(result.value)); })); /** - * Creates a Channel from a AsyncIterable that emits arrays of elements. + * Creates a channel from an `AsyncIterable`, emitting each yielded value as a + * single-element non-empty array. + * + * **Details** + * + * The iterator's return value becomes the channel's done value. Thrown or + * rejected iterator errors are converted with `onError`. If the channel scope + * closes early and the iterator has a `return` method, that method is called. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromAsyncIterableArray = (iterable, onError) => map(fromAsyncIterable(iterable, onError), Arr.of); /** * Maps the output of this channel using the specified function. * - * @example + * **Example** (Mapping channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -1301,8 +1355,8 @@ export const fromAsyncIterableArray = (iterable, onError) => map(fromAsyncIterab * })) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const map = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => Effect.sync(() => { let i = 0; @@ -1311,26 +1365,41 @@ export const map = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => /** * Maps the done value of this channel using the specified function. * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const mapDone = /*#__PURE__*/dual(2, (self, f) => mapDoneEffect(self, o => Effect.succeed(f(o)))); /** * Maps the done value of this channel using the specified effectful function. * - * @since 2.0.0 - * @category Sequencing + * **When to use** + * + * Use when the terminal done value transformation needs services or can fail, + * while emitted elements should pass through unchanged. + * + * @category sequencing + * @since 4.0.0 */ export const mapDoneEffect = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, done => Effect.flatMap(f(done), Cause.done))))); const concurrencyIsSequential = concurrency => concurrency === undefined || concurrency !== "unbounded" && concurrency <= 1; /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element with an effectful function, preserving the source + * channel's done value. + * + * **When to use** + * + * Use when transforming each channel output needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Details** + * + * The mapping function receives the output element and its zero-based index. + * By default elements are mapped sequentially. Use `options.concurrency` to + * map multiple elements concurrently, and `options.unordered` to allow + * concurrently mapped outputs to be emitted as soon as they complete. + * + * **Example** (Mapping channel output with effects) * - * @example * ```ts * import { Channel, Data, Effect } from "effect" * @@ -1367,8 +1436,8 @@ const concurrencyIsSequential = concurrency => concurrency === undefined || conc * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const mapEffect = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? mapEffectSequential(self, f) : mapEffectConcurrent(self, f, options)); const mapEffectSequential = (self, f) => fromTransform((upstream, scope) => { @@ -1427,16 +1496,16 @@ const mapEffectConcurrent = (self, f, options) => fromTransformBracket(Effect.fn * Returns a new channel which is the same as this one but applies the given * function to the input channel’s input elements. * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const mapInput = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.flatMap(upstream, el => f(el)), scope))); /** * Returns a new channel which is the same as this one but applies the given * function to the input errors. * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const mapInputError = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.catch(upstream, err => { if (Cause.isDone(err)) return Effect.fail(err); @@ -1446,11 +1515,14 @@ export const mapInputError = /*#__PURE__*/dual(2, (self, f) => fromTransform((up * Applies a side effect function to each output element of the channel, * returning a new channel that emits the same elements. * + * **Details** + * * The `tap` function allows you to perform side effects (like logging or * debugging) on each element emitted by a channel without modifying the * elements themselves. * - * @example + * **Example** (Tapping channel output) + * * ```ts * import { Channel, Console, Data } from "effect" * @@ -1471,18 +1543,23 @@ export const mapInputError = /*#__PURE__*/dual(2, (self, f) => fromTransform((up * // Outputs: 1, 2, 3 (while logging each) * ``` * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ export const tap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => mapEffect(self, a => Effect.as(f(a), a), options)); /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element to a channel and flattens the child channel + * outputs. + * + * **Details** + * + * The source channel's done value is preserved. Child channel done values are + * used only for child-channel completion. By default child channels are run + * sequentially. Use `options.concurrency` and `options.bufferSize` to run child + * channels concurrently. + * + * **Example** (FlatMapping channel output) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -1504,8 +1581,8 @@ export const tap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, optio * // Outputs: "item-1-0", "item-2-0", "item-2-1", "item-3-0", "item-3-1", "item-3-2" * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const flatMap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? flatMapSequential(self, f) : flatMapConcurrent(self, f, options)); const flatMapSequential = (self, f) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => { @@ -1535,7 +1612,8 @@ const flatMapConcurrent = (self, f, options) => self.pipe(map(f), mergeAll(optio * Concatenates this channel with another channel created from the terminal value * of this channel. The new channel is created using the provided function. * - * @example + * **Example** (Concatenating with completion values) + * * ```ts * import { Channel, Data } from "effect" * @@ -1552,8 +1630,8 @@ const flatMapConcurrent = (self, f, options) => self.pipe(map(f), mergeAll(optio * // Outputs: 1, 2, 3, then "Completed processing" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ export const concatWith = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => { let currentPull; @@ -1573,7 +1651,8 @@ export const concatWith = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstr * Concatenates this channel with another channel, so that the second channel * starts emitting values after the first channel has completed. * - * @example + * **Example** (Concatenating channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -1591,19 +1670,26 @@ export const concatWith = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstr * // Outputs: 1, 2, 3, "a", "b", "c" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ export const concat = /*#__PURE__*/dual(2, (self, that) => concatWith(self, _ => that)); /** - * Combines the elements from this channel and the specified channel by - * repeatedly applying the function `f` to extract an element using both sides - * and conceptually "offer" it to the destination channel. `f` can maintain - * some internal state to control the combining process, with the initial - * state being specified by `s`. + * Combines two channels with a stateful pull function. + * + * **When to use** + * + * Use to coordinate pulling from two channels when each output element depends + * on both sides and local state. + * + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right channels. It returns the next output element together with the + * next state. * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ export const combine = /*#__PURE__*/dual(4, (self, that, s, f) => fromTransform(Effect.fnUntraced(function* (upstream, scope) { const leftPull = yield* toTransform(self)(upstream, scope); @@ -1618,8 +1704,17 @@ export const combine = /*#__PURE__*/dual(4, (self, that, s, f) => fromTransform( }); }))); /** - * @since 2.0.0 + * Runs a fallback channel if this channel completes without emitting any + * output elements. + * + * **Details** + * + * If the source emits at least one element, the source is used unchanged. If + * the source completes before emitting an element, the fallback function + * receives the source done value and returns the replacement channel. + * * @category sequencing + * @since 4.0.0 */ export const orElseIfEmpty = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => { let currentPull; @@ -1638,9 +1733,10 @@ export const orElseIfEmpty = /*#__PURE__*/dual(2, (self, f) => fromTransform((up return Effect.suspend(() => currentPull ?? makePull); }))); /** - * Flatten a channel of channels. + * Flattens a channel of channels. + * + * **Example** (Flattening nested channels) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -1661,14 +1757,15 @@ export const orElseIfEmpty = /*#__PURE__*/dual(2, (self, f) => fromTransform((up * // Outputs: 1, 2, 3, 4, 5, 6 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const flatten = channels => flatMap(channels, identity_); /** * Flattens a channel that outputs arrays into a channel that outputs individual elements. * - * @example + * **Example** (Flattening arrays of channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -1689,8 +1786,8 @@ export const flatten = channels => flatMap(channels, identity_); * // Outputs: 1, 2, 3, 4, 5, 6, 7, 8, 9 * ``` * + * @category transforming * @since 4.0.0 - * @category utils */ export const flattenArray = self => transformPull(self, pull => { let array; @@ -1721,15 +1818,24 @@ export const flattenArray = self => transformPull(self, pull => { return Effect.succeed(pump); }); /** + * Flattens a channel that emits `Take` values into a channel that emits the + * `Take` outputs directly. + * + * **Details** + * + * Output `Take` values are emitted as non-empty arrays. Failed `Take` values + * fail the returned channel. Done `Take` values complete the returned channel. + * + * @category transforming * @since 4.0.0 - * @category utils */ export const flattenTake = self => mapEffectSequential(self, Take.toPull); /** * Creates a new channel that consumes all output from the source channel * but emits nothing, preserving only the completion value. * - * @example + * **Example** (Draining channel output) + * * ```ts * import { Channel } from "effect" * @@ -1743,8 +1849,8 @@ export const flattenTake = self => mapEffectSequential(self, Take.toPull); * // Useful for consuming side effects without collecting output * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const drain = self => transformPull(self, pull => Effect.succeed(Effect.forever(pull, { disableYield: true @@ -1752,8 +1858,8 @@ export const drain = self => transformPull(self, pull => Effect.succeed(Effect.f /** * Repeats this channel according to the provided schedule. * + * @category repetition * @since 4.0.0 - * @category utils */ export const repeat = /*#__PURE__*/dual(2, (self, schedule) => Schedule.toStepWithMetadata(typeof schedule === "function" ? schedule(identity_) : schedule).pipe(Effect.map(step => { let meta = Schedule.CurrentMetadata.defaultValue(); @@ -1766,13 +1872,23 @@ export const repeat = /*#__PURE__*/dual(2, (self, schedule) => Schedule.toStepWi /** * Repeats this channel forever. * + * @category repetition * @since 4.0.0 - * @category utils */ export const forever = self => concatWith(self, () => forever(self)); /** + * Runs a schedule step for each output element while preserving the emitted + * elements. + * + * **Details** + * + * The schedule receives each output element as input. Schedule delays are + * applied between emitted elements. If the schedule fails, the returned channel + * fails. If the schedule finishes, the returned channel completes with the + * schedule output. + * + * @category sequencing * @since 4.0.0 - * @category utils */ export const schedule = /*#__PURE__*/dual(2, (self, schedule) => transformPull(self, (pull, _scope) => Effect.map(Schedule.toStepWithSleep(schedule), step => { const pullWithStep = Effect.tap(pull, step); @@ -1782,7 +1898,8 @@ export const schedule = /*#__PURE__*/dual(2, (self, schedule) => transformPull(s * Filters the output elements of a channel using a predicate function. * Elements that don't match the predicate are discarded. * - * @example + * **Example** (Filtering channel output) + * * ```ts * import { Channel } from "effect" * @@ -1802,30 +1919,78 @@ export const schedule = /*#__PURE__*/dual(2, (self, schedule) => transformPull(s * // Outputs: 1, 2, 3 (all typed as numbers) * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ export const filter = /*#__PURE__*/dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { return predicate(elem) ? Effect.succeed(elem) : Effect.flatMap(pull, loop); })))); /** + * Filters and maps output elements using a `Filter`. + * + * **When to use** + * + * Use to keep only channel output elements accepted by a `Filter` and emit + * each filter success value. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. The source channel's errors and done value are + * preserved. + * + * @see {@link filter} for keeping original output elements with a predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * @see {@link filterMapArray} for filtering arrays of output elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMap = /*#__PURE__*/dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { const result = filter(elem); return Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success); })))); /** + * Filters output elements with an effectful predicate. + * + * **When to use** + * + * Use when the keep/discard decision depends on an Effect or service and + * predicate failures should fail the returned channel. + * + * **Details** + * + * Elements for which the predicate succeeds with `true` are emitted. Elements + * for which the predicate succeeds with `false` are discarded. Predicate + * failures fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterEffect = /*#__PURE__*/dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { return Effect.flatMap(predicate(elem), passes => passes ? Effect.succeed(elem) : Effect.flatMap(pull, loop)); })))); /** + * Filters and maps output elements using an effectful `Filter`. + * + * **When to use** + * + * Use to apply effectful logic that can discard channel output elements and + * emit transformed values for the elements that pass. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. Failures from the effectful filter fail the returned + * channel. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filterEffect} for effectfully keeping original output elements + * @see {@link mapEffect} for effectfully transforming every output element + * @see {@link filterMapArrayEffect} for effectful filtering of array outputs + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { return Effect.flatMap(filter(elem), result => Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success)); @@ -1834,7 +1999,8 @@ export const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromTransf * Filters arrays of elements emitted by a channel, applying the filter * to each element within the arrays and only emitting non-empty filtered arrays. * - * @example + * **Example** (Filtering array output) + * * ```ts * import { Array, Channel } from "effect" * @@ -1862,8 +2028,8 @@ export const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromTransf * // Outputs: [2, 4] (the arrays [1,3,5] and [7,9] are discarded) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterArray = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) { const passes = []; @@ -1875,8 +2041,16 @@ export const filterArray = /*#__PURE__*/dual(2, (self, predicate) => transformPu return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop); })))); /** - * @since 4.0.0 - * @category Filtering + * Filters and maps each element inside emitted non-empty arrays using a + * `Filter`. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. + * + * @category filtering + * @since 4.0.0 */ export const filterMapArray = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) { const passes = []; @@ -1889,8 +2063,22 @@ export const filterMapArray = /*#__PURE__*/dual(2, (self, filter) => transformPu return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop); })))); /** + * Filters each element inside emitted non-empty arrays with an effectful + * predicate. + * + * **When to use** + * + * Use when filtering array-valued channel outputs requires Effects or services, + * and arrays that become empty should be skipped. + * + * **Details** + * + * The predicate receives the element and its index within the array. Elements + * for which the predicate succeeds with `true` are kept. Arrays that become + * empty are discarded. Predicate failures fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterArrayEffect = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, pull => { const f = Effect.flatMap(pull, arr => Effect.filter(arr, predicate)); @@ -1899,16 +2087,31 @@ export const filterArrayEffect = /*#__PURE__*/dual(2, (self, predicate) => trans })); })); /** + * Filters and maps each element inside emitted non-empty arrays using an + * effectful `Filter`. + * + * **When to use** + * + * Use when array-valued channel outputs need an effectful filter-map that can + * fail and can discard arrays that become empty. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. Failures + * from the effectful filter fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapArrayEffect = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) { return Effect.flatMap(Effect.filterMapEffect(arr, filter), passes => Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop)); })))); /** - * Statefully maps over a channel with an accumulator, where each element can produce multiple output values. + * Maps over a channel statefully with an accumulator, where each element can produce multiple output values. + * + * **Example** (Mapping with accumulated state) * - * @example * ```ts * import { Channel, Effect } from "effect" * @@ -1939,8 +2142,8 @@ export const filterMapArrayEffect = /*#__PURE__*/dual(2, (self, filter) => trans * ) * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const mapAccum = /*#__PURE__*/dual(args => isChannel(args[0]), (self, initial, f, options) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => { let state = initial(); @@ -1982,10 +2185,11 @@ export const mapAccum = /*#__PURE__*/dual(args => isChannel(args[0]), (self, ini return pump; }))); /** - * Statefully transforms a channel by scanning over its output with an accumulator function. + * Transforms a channel statefully by scanning over its output with an accumulator function. * Emits the intermediate results of the scan operation. * - * @example + * **Example** (Scanning channel output) + * * ```ts * import { Channel } from "effect" * @@ -2007,15 +2211,21 @@ export const mapAccum = /*#__PURE__*/dual(args => isChannel(args[0]), (self, ini * // Outputs: "", "hello", "hello world", "hello world from", "hello world from effect" * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const scan = /*#__PURE__*/dual(3, (self, initial, f) => scanEffect(self, initial, (s, a) => Effect.succeed(f(s, a)))); /** - * Statefully transforms a channel by scanning over its output with an effectful accumulator function. + * Transforms a channel statefully by scanning over its output with an effectful accumulator function. * Emits the intermediate results of the scan operation. * - * @example + * **When to use** + * + * Use when maintaining accumulated state over channel output requires Effects + * or can fail, while still emitting each intermediate state. + * + * **Example** (Scanning channel output with effects) + * * ```ts * import { Channel, Data, Effect } from "effect" * @@ -2052,8 +2262,8 @@ export const scan = /*#__PURE__*/dual(3, (self, initial, f) => scanEffect(self, * ) * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const scanEffect = /*#__PURE__*/dual(3, (self, initial, f) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => { let state = initial; @@ -2073,7 +2283,8 @@ export const scanEffect = /*#__PURE__*/dual(3, (self, initial, f) => fromTransfo * Catches any cause of failure from the channel and allows recovery by * creating a new channel based on the caught cause. * - * @example + * **Example** (Recovering from failure causes) + * * ```ts * import { Cause, Channel, Data } from "effect" * @@ -2101,8 +2312,8 @@ export const scanEffect = /*#__PURE__*/dual(3, (self, initial, f) => fromTransfo * // The channel recovers gracefully from errors * ``` * - * @since 4.0.0 - * @category Error handling + * @category error handling + * @since 2.0.0 */ export const catchCause = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => { let forkedScope = Scope.forkUnsafe(scope); @@ -2122,23 +2333,69 @@ export const catchCause = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstr }); })); /** + * Runs an effect with the full failure `Cause` when the channel fails, then + * fails the returned channel with the original cause. + * + * **When to use** + * + * Use when observing the full channel failure `Cause` is needed without + * changing successful output or replacing the original cause. + * + * **Details** + * + * Use this for observing failures, such as logging or metrics. If the observer + * effect fails, that failure can fail the returned channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const tapCause = /*#__PURE__*/dual(2, (self, f) => catchCause(self, cause => fromEffectDrain(Effect.flatMap(f(cause), _ => Effect.failCause(cause))))); /** * Catches causes of failure that match a specific filter, allowing * conditional error recovery based on the type of failure. * + * **When to use** + * + * Use to recover a channel only when its full `Cause` satisfies a boolean + * predicate. + * + * **Details** + * + * When the predicate matches, the recovery function receives the original + * cause. When it does not match, the returned channel fails with the original + * cause. + * + * @see {@link catchCauseFilter} for selecting causes with a `Filter` + * @see {@link catchCause} for recovering from every cause + * @see {@link catchIf} for recovering from typed channel errors + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchCauseIf = /*#__PURE__*/dual(3, (self, predicate, f) => catchCause(self, cause => { return predicate(cause) ? f(cause) : failCause(cause); })); /** + * Recovers from channel failures whose full `Cause` is selected by a `Filter`. + * + * **When to use** + * + * Use when you need to recover a channel only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * When the filter succeeds, the recovery function receives the selected value + * and the original cause. When the filter fails, the returned channel fails + * with the residual cause produced by the filter. + * + * @see {@link catchCauseIf} for selecting causes with a predicate + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchCause} for recovering from every cause + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchCauseFilter = /*#__PURE__*/dual(3, (self, filter, f) => catchCause(self, cause => { const result = filter(cause); @@ -2147,33 +2404,86 @@ export const catchCauseFilter = /*#__PURE__*/dual(3, (self, filter, f) => catchC const catch_ = /*#__PURE__*/dual(2, (self, f) => catchCauseFilter(self, Cause.findError, e => f(e))); export { /** + * Recovers from typed channel errors by running a fallback channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ catch_ as catch }; /** + * Runs an effect when the channel fails with a typed error, then preserves the + * original channel failure. + * + * **Details** + * + * The effect is not run for normal channel completion. If the observer effect + * fails, that failure can fail the returned channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const tapError = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => Effect.succeed(Effect.tapError(pull, err => Cause.isDone(err) ? Effect.void : Effect.asVoid(f(err)))))); /** + * Recovers from typed channel errors that match a predicate or refinement. + * + * **When to use** + * + * Use to recover from typed channel errors when a predicate or refinement + * selects the failures that should switch to a recovery channel. + * + * **Details** + * + * Matching errors are handled by the recovery function. Non-matching errors + * are handled by `orElse` when provided. Without `orElse`, non-matching errors + * are re-failed. + * + * @see {@link catch_ catch} for recovering from every typed channel error + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchIf = /*#__PURE__*/dual(args => isChannel(args[0]), (self, predicate, f, orElse) => catch_(self, err => { return predicate(err) ? f(err) : orElse ? orElse(err) : fail(err); })); /** + * Recovers from typed channel errors selected by a `Filter`. + * + * **When to use** + * + * Use to recover from channel errors with a reusable `Filter` when matching + * can also narrow or transform the error before choosing the recovery channel. + * + * **Details** + * + * Successful filter results are handled by the recovery function. Failed + * filter results are handled by `orElse` when provided. Without `orElse`, + * failed filter results are re-failed. + * + * @see {@link catchIf} for selecting typed errors with a predicate + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchFilter = /*#__PURE__*/dual(args => isChannel(args[0]), (self, filter, f, orElse) => catch_(self, err => { const result = filter(err); return Result.isFailure(result) ? orElse ? orElse(result.failure) : fail(result.failure) : f(result.success); })); /** + * Recovers from tagged channel errors whose `_tag` matches one or more tags. + * + * **Details** + * + * Matching tagged errors are handled by the recovery function. Non-matching + * errors are handled by `orElse` when provided. Without `orElse`, + * non-matching errors are re-failed. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchTag = /*#__PURE__*/dual(args => isChannel(args[0]), (self, k, f, orElse) => { const pred = Array.isArray(k) ? e => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); @@ -2182,7 +2492,8 @@ export const catchTag = /*#__PURE__*/dual(args => isChannel(args[0]), (self, k, /** * Catches a specific reason within a tagged error. * - * @example + * **Example** (Recovering from nested reasons) + * * ```ts * import { Channel, Data } from "effect" * @@ -2209,8 +2520,8 @@ export const catchTag = /*#__PURE__*/dual(args => isChannel(args[0]), (self, k, * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchReason = /*#__PURE__*/dual(args => isChannel(args[0]), (self, errorTag, reasonTag, f, orElse) => catch_(self, error => { if (isTagged(error, errorTag) && hasProperty(error, "reason")) { @@ -2225,8 +2536,8 @@ export const catchReason = /*#__PURE__*/dual(args => isChannel(args[0]), (self, /** * Catches multiple reasons within a tagged error using an object of handlers. * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchReasons = /*#__PURE__*/dual(args => isChannel(args[0]), (self, errorTag, cases, orElse) => { let keys; @@ -2245,7 +2556,8 @@ export const catchReasons = /*#__PURE__*/dual(args => isChannel(args[0]), (self, /** * Promotes nested reason errors into the channel error, replacing the parent error. * - * @example + * **Example** (Promoting nested reasons) + * * ```ts * import { Channel, Data } from "effect" * @@ -2268,8 +2580,8 @@ export const catchReasons = /*#__PURE__*/dual(args => isChannel(args[0]), (self, * const unwrapped = channel.pipe(Channel.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const unwrapReason = /*#__PURE__*/dual(2, (self, errorTag) => catchFilter(self, error => isTagged(error, errorTag) && hasProperty(error, "reason") ? Result.succeed(error.reason) : Result.fail(error), fail)); /** @@ -2277,15 +2589,16 @@ export const unwrapReason = /*#__PURE__*/dual(2, (self, errorTag) => catchFilter * value of the returned channel is created by applying the specified function * to the failure value of this channel. * + * @category error handling * @since 2.0.0 - * @category Error handling */ export const mapError = /*#__PURE__*/dual(2, (self, f) => catch_(self, err => fail(f(err)))); /** * Converts all errors in the channel to defects (unrecoverable failures). * This is useful when you want to treat errors as programming errors. * - * @example + * **Example** (Converting failures to defects) + * * ```ts * import { Channel, Data } from "effect" * @@ -2302,17 +2615,19 @@ export const mapError = /*#__PURE__*/dual(2, (self, f) => catch_(self, err => fa * // Any failure will now become a defect (uncaught exception) * ``` * - * @since 4.0.0 - * @category Error handling + * @category error handling + * @since 2.0.0 */ export const orDie = self => catch_(self, die); /** * Ignores all errors in the channel, converting them to an empty channel. * + * **Details** + * * Use the `log` option to emit the full {@link Cause} when the channel fails. * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const ignore = /*#__PURE__*/dual(args => isChannel(args[0]), (self, options) => { if (!options?.log) { @@ -2325,10 +2640,17 @@ const ignoreCause_ = self => catchCause(self, () => empty); /** * Ignores all errors in the channel including defects, converting them to an empty channel. * + * **When to use** + * + * Use when a channel should become best-effort and all failure causes, including + * defects and interruptions, can be converted to empty output. + * + * **Details** + * * Use the `log` option to emit the full {@link Cause} when the channel fails. * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const ignoreCause = /*#__PURE__*/dual(args => isChannel(args[0]), (self, options) => { if (!options?.log) return ignoreCause_(self); @@ -2339,8 +2661,8 @@ export const ignoreCause = /*#__PURE__*/dual(args => isChannel(args[0]), (self, * Returns a new channel that retries this channel according to the specified * schedule whenever it fails. * + * @category error handling * @since 4.0.0 - * @category utils */ export const retry = /*#__PURE__*/dual(2, (self, schedule) => suspend(() => { let step = undefined; @@ -2361,13 +2683,17 @@ export const retry = /*#__PURE__*/dual(2, (self, schedule) => suspend(() => { return loop; })); /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element to a channel and emits values from the most recent + * active child channels. + * + * **Details** + * + * With the default concurrency of `1`, starting a new child channel interrupts + * the previous child channel. Use `options.concurrency` to allow more active + * child channels. The source channel's done value is preserved. + * + * **Example** (Switching mapped channels) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -2387,8 +2713,8 @@ export const retry = /*#__PURE__*/dual(2, (self, schedule) => suspend(() => { * // Outputs: "value-1", "value-2", "value-3" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ export const switchMap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => self.pipe(map(f), mergeAll({ ...options, @@ -2398,7 +2724,13 @@ export const switchMap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, /** * Merges multiple channels with specified concurrency and buffering options. * - * @example + * **When to use** + * + * Use when channel outputs are themselves channels and multiple inner channels + * should run with configured concurrency and buffering. + * + * **Example** (Merging nested channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -2422,8 +2754,8 @@ export const switchMap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, * // Outputs: 1, 2, 3, 4, 5, 6 (order may vary due to concurrency) * ``` * + * @category combining * @since 2.0.0 - * @category utils */ export const mergeAll = /*#__PURE__*/dual(2, (channels, { bufferSize = 16, @@ -2471,7 +2803,8 @@ export const mergeAll = /*#__PURE__*/dual(2, (channels, { * Returns a new channel, which is the merge of this channel and the specified * channel. * - * @example + * **Example** (Merging channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -2492,8 +2825,8 @@ export const mergeAll = /*#__PURE__*/dual(2, (channels, { * // Order may vary: 1, "a", 2, "b", 3, "c" * ``` * - * @since 2.0.0 - * @category utils + * @category combining + * @since 4.0.0 */ export const merge = /*#__PURE__*/dual(args => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(Effect.fnUntraced(function* (upstream, _scope, forkedScope) { const strategy = options?.haltStrategy ?? "both"; @@ -2527,8 +2860,21 @@ export const merge = /*#__PURE__*/dual(args => isChannel(args[0]) && isChannel(a return Queue.take(queue); }))); /** + * Runs an effect concurrently with a channel while emitting only the channel's + * output elements. + * + * **When to use** + * + * Use when a side effect should run for the lifetime of a channel and only the + * channel's output elements should be emitted. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails while the + * channel is running, the returned channel fails with that error. + * + * @category combining * @since 4.0.0 - * @category utils */ export const mergeEffect = /*#__PURE__*/dual(2, (self, effect) => merge(self, fromEffectDrain(effect), { haltStrategy: "left" @@ -2538,12 +2884,14 @@ export const mergeEffect = /*#__PURE__*/dual(2, (self, effect) => merge(self, fr * standalone `\r` as line terminators. The behavior matches * `String.linesIterator` regardless of how the input is chunked. * + * **Details** + * * A line terminator at the very end of the stream does **not** produce a * trailing empty line (consistent with `String.linesIterator`). Conversely, * if the stream ends without a terminator the final partial line is still * emitted. * - * **Example** + * **Example** (Splitting string chunks into lines) * * ```ts * import { Effect, Stream } from "effect" @@ -2557,8 +2905,8 @@ export const mergeEffect = /*#__PURE__*/dual(2, (self, effect) => merge(self, fr * })) * ``` * - * @since 2.0.0 * @category String manipulation + * @since 2.0.0 */ export const splitLines = () => fromTransform((upstream, _scope) => Effect.sync(() => { // Accumulates text that has not yet been terminated by a line break. @@ -2646,16 +2994,33 @@ export const splitLines = () => fromTransform((upstream, _scope) => Effect.sync( return pullOrFlush; })); /** - * @since 4.0.0 + * Decodes incoming `Uint8Array` chunks into strings using `TextDecoder`. + * + * **Details** + * + * Input chunks are decoded with streaming enabled so multi-byte characters may + * span `Uint8Array` boundaries. The optional `encoding` and `options` are + * passed to `TextDecoder`. + * * @category String manipulation + * @since 4.0.0 */ export const decodeText = (encoding, options) => fromTransform((upstream, _scope) => Effect.sync(() => { const decoder = new TextDecoder(encoding, options); - return Effect.map(upstream, Arr.map(line => decoder.decode(line))); + const streamOptions = { + stream: true + }; + return Effect.map(upstream, Arr.map(line => decoder.decode(line, streamOptions))); })); /** - * @since 4.0.0 + * Encodes incoming string chunks into `Uint8Array` values using `TextEncoder`. + * + * **Details** + * + * Each string inside an emitted array is encoded independently. + * * @category String manipulation + * @since 4.0.0 */ export const encodeText = () => fromTransform((upstream, _scope) => Effect.sync(() => { const encoder = new TextEncoder(); @@ -2667,7 +3032,8 @@ export const encodeText = () => fromTransform((upstream, _scope) => Effect.sync( * and the output type of the specified channel, terminating with the value of * the specified channel. * - * @example + * **Example** (Piping one channel into another) + * * ```ts * import { Channel, Data } from "effect" * @@ -2685,8 +3051,8 @@ export const encodeText = () => fromTransform((upstream, _scope) => Effect.sync( * // Outputs: 2, 4, 6 * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ export const pipeTo = /*#__PURE__*/dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => toTransform(that)(upstream, scope)))); /** @@ -2694,7 +3060,8 @@ export const pipeTo = /*#__PURE__*/dual(2, (self, that) => fromTransform((upstre * specified channel and preserves this channel's failures without providing * them to the other channel for observation. * - * @example + * **Example** (Piping while preserving failures) + * * ```ts * import { Channel, Data } from "effect" * @@ -2712,8 +3079,8 @@ export const pipeTo = /*#__PURE__*/dual(2, (self, that) => fromTransform((upstre * // Source errors are preserved and not sent to transform channel * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ export const pipeToOrFail = /*#__PURE__*/dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => { const upstreamPull = Effect.catchCause(upstream, cause => Pull.isDoneCause(cause) ? Effect.failCause(cause) : Effect.die(Cause.Done(cause))); @@ -2723,7 +3090,8 @@ export const pipeToOrFail = /*#__PURE__*/dual(2, (self, that) => fromTransform(( * Constructs a `Channel` from a scoped effect that will result in a * `Channel` if successful. * - * @example + * **Example** (Unwrapping channel effects) + * * ```ts * import { Channel, Data, Effect } from "effect" * @@ -2742,8 +3110,8 @@ export const pipeToOrFail = /*#__PURE__*/dual(2, (self, that) => fromTransform(( * // The resulting channel outputs: 1, 2, 3 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const unwrap = channel => fromTransform((upstream, scope) => { let pull; @@ -2753,41 +3121,72 @@ export const unwrap = channel => fromTransform((upstream, scope) => { })); }); /** + * Runs a channel with a scope provided for the duration of the channel + * execution, removing the channel's `Scope` requirement. + * + * @category resource management * @since 2.0.0 - * @category utils */ -export const scoped = self => fromTransformBracket((upstream, scope, forkedScope) => Scope.provide(toTransform(self)(upstream, scope), forkedScope)); +export const scoped = self => fromTransformBracket((upstream, scope, forkedScope) => Effect.map(Scope.provide(toTransform(self)(upstream, scope), forkedScope), Scope.provide(forkedScope))); /** - * Returns a new channel which embeds the given input handler into a Channel. + * Runs an input handler against the upstream pull while the wrapped channel + * runs without receiving upstream input directly. * - * @example - * ```ts - * import { Channel, Data, Effect } from "effect" + * **Details** * - * class EmbedError extends Data.TaggedError("EmbedError")<{ - * readonly stage: string - * }> {} + * The input handler is forked in the channel scope. The wrapped channel is run + * with an already-completed input. + * + * **Example** (Embedding custom input handling) + * + * ```ts + * import { Channel, Effect } from "effect" * * // Create a base channel * const baseChannel = Channel.fromIterable([1, 2, 3]) * - * // Embed input handling - simplified example + * // Drain the embedded input while the base channel runs * const embeddedChannel = Channel.embedInput( * baseChannel, - * (_upstream) => Effect.void + * (upstream) => + * upstream.pipe( + * Effect.tap((message) => + * Effect.sync(() => console.log(message)) + * ), + * Effect.forever, + * Effect.ignore + * ) * ) * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ export const embedInput = /*#__PURE__*/dual(2, (self, input) => fromTransformBracket((upstream, scope, forkedScope) => Effect.andThen(Effect.forkIn(input(upstream), forkedScope), toTransform(self)(Cause.done(), scope)))); /** - * Allows a faster producer to progress independently of a slower consumer by - * buffering up to `capacity` elements in a queue. + * Buffers individual output elements in a queue with the configured `capacity` + * so a faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when output elements can be decoupled from downstream demand and the + * configured backpressure or loss strategy is acceptable. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Dropping and sliding strategies can lose output elements under backpressure. + * + * @see {@link bufferArray} for buffering elements from array outputs * - * @since 2.0.0 * @category Buffering + * @since 2.0.0 */ export const buffer = /*#__PURE__*/dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) { const pull = yield* toTransform(self)(upstream, scope); @@ -2802,11 +3201,31 @@ export const buffer = /*#__PURE__*/dual(2, (self, options) => fromTransform(Effe return Queue.take(queue); }))); /** - * Allows a faster producer to progress independently of a slower consumer by - * buffering up to `capacity` elements in a queue. + * Buffers array output elements in a queue with the configured `capacity` so a + * faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when emitted arrays are batches of elements and it is acceptable for + * buffering to flatten and rebuild those batches. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Input arrays are offered to the queue element-by-element and outputs are + * rebuilt from the currently available queued elements, so upstream array + * boundaries are not preserved. + * + * @see {@link buffer} for buffering output elements without flattening arrays * - * @since 2.0.0 * @category Buffering + * @since 4.0.0 */ export const bufferArray = /*#__PURE__*/dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) { const pull = yield* toTransform(self)(upstream, scope); @@ -2821,23 +3240,37 @@ export const bufferArray = /*#__PURE__*/dual(2, (self, options) => fromTransform return Queue.takeAll(queue); }))); /** - * Returns a new channel, which is the same as this one, except it will be - * interrupted when the specified effect completes. If the effect completes - * successfully before the underlying channel is done, then the returned - * channel will yield the success value of the effect as its terminal value. - * On the other hand, if the underlying channel finishes first, then the - * returned channel will yield the success value of the underlying channel as - * its terminal value. + * Interrupts a channel when another effect completes. + * + * **When to use** * + * Use to race channel execution against an external effect whose success can + * become the channel's done value. + * + * **Details** + * + * If the effect completes first, its success value becomes the returned + * channel's done value. If the channel completes first, the original channel's + * done value is preserved. + * + * @category interruption * @since 2.0.0 - * @category utils */ export const interruptWhen = /*#__PURE__*/dual(2, (self, effect) => merge(self, fromPull(Effect.succeed(Effect.flatMap(effect, Cause.done))), { haltStrategy: "either" })); /** + * Stops a channel when the specified effect completes or fails. + * + * **Details** + * + * If the effect completes before the channel is done, its success value becomes + * the returned channel's done value. If the effect fails, the returned channel + * fails with that error. If the channel completes first, the channel's done + * value is preserved. + * + * @category interruption * @since 4.0.0 - * @category utils */ export const haltWhen = /*#__PURE__*/dual(2, (self, effect) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) { const pull = yield* toTransform(self)(upstream, scope); @@ -2849,16 +3282,23 @@ export const haltWhen = /*#__PURE__*/dual(2, (self, effect) => fromTransformBrac return Effect.suspend(() => haltCause ? Effect.failCause(haltCause) : pull); }))); /** + * Attaches a finalizer that runs only when the channel exits with failure. + * + * **Details** + * + * The finalizer receives the failure `Cause`. The original channel failure is + * preserved. The finalizer itself must not fail. + * + * @category error handling * @since 4.0.0 - * @category utils */ export const onError = /*#__PURE__*/dual(2, (self, finalizer) => onExit(self, exit => Exit.isFailure(exit) ? finalizer(exit.cause) : Effect.void)); /** - * Returns a new channel with an attached finalizer. The finalizer is - * guaranteed to be executed so long as the channel begins execution (and - * regardless of whether or not it completes). + * Returns a channel with an exit-aware finalizer that is guaranteed to run once + * the channel begins execution, whether it succeeds or fails. + * + * **Example** (Running exit finalizers) * - * @example * ```ts * import { Channel, Console, Data, Exit } from "effect" * @@ -2879,18 +3319,38 @@ export const onError = /*#__PURE__*/dual(2, (self, finalizer) => onExit(self, ex * }) * ``` * + * @category resource management * @since 4.0.0 - * @category utils */ export const onExit = /*#__PURE__*/dual(2, (self, finalizer) => fromTransformBracket((upstream, scope, forkedScope) => Scope.addFinalizerExit(forkedScope, finalizer).pipe(Effect.andThen(toTransform(self)(upstream, scope))))); /** + * Runs an effect before the channel starts. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails, the returned + * channel fails before running the source channel. + * + * @category hooks * @since 4.0.0 - * @category utils */ export const onStart = /*#__PURE__*/dual(2, (self, onStart) => unwrap(Effect.as(onStart, self))); /** + * Runs an effect the first time the channel emits an output element. + * + * **When to use** + * + * Use when initialization depends on the first output element rather than only + * on channel startup. + * + * **Details** + * + * The effect receives the first emitted element. The first element is still + * emitted unchanged. The effect is not run if the channel completes without + * emitting an element. + * + * @category hooks * @since 4.0.0 - * @category utils */ export const onFirst = /*#__PURE__*/dual(2, (self, onFirst) => transformPull(self, pull => Effect.sync(() => { let isFirst = true; @@ -2901,16 +3361,24 @@ export const onFirst = /*#__PURE__*/dual(2, (self, onFirst) => transformPull(sel return Effect.suspend(() => isFirst ? pullFirst : pull); }))); /** + * Runs an effect when the channel completes successfully. + * + * **Details** + * + * The effect runs before the original done value is propagated. The effect is + * not run when the channel fails. If the effect fails, the returned channel + * fails with that error. + * + * @category hooks * @since 4.0.0 - * @category utils */ export const onEnd = /*#__PURE__*/dual(2, (self, onEnd) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, leftover => Effect.flatMap(onEnd, () => Cause.done(leftover)))))); /** - * Returns a new channel with an attached finalizer. The finalizer is - * guaranteed to be executed so long as the channel begins execution (and - * regardless of whether or not it completes). + * Returns a channel with a finalizer effect that is guaranteed to run once the + * channel begins execution, whether it succeeds or fails. + * + * **Example** (Ensuring cleanup runs) * - * @example * ```ts * import { Channel, Console, Data } from "effect" * @@ -2928,8 +3396,8 @@ export const onEnd = /*#__PURE__*/dual(2, (self, onEnd) => transformPull(self, p * ) * ``` * + * @category resource management * @since 2.0.0 - * @category utils */ export const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => onExit(self, _ => finalizer)); const runWith = (self, f, onHalt) => Effect.suspend(() => { @@ -2938,52 +3406,97 @@ const runWith = (self, f, onHalt) => Effect.suspend(() => { return Pull.catchDone(Effect.flatMap(makePull, f), onHalt ? onHalt : Effect.succeed).pipe(Effect.onExit(exit => Scope.close(scope, exit))); }); /** - * Create a channel from the specified services. + * Creates a channel from the specified services. * + * @category services * @since 2.0.0 - * @category Services */ export const contextWith = f => fromTransform((upstream, scope) => Effect.contextWith(context => toTransform(f(context))(upstream, scope))); /** - * Provides a layer or context to the channel, removing the corresponding - * service requirements. Use `options.local` to build the layer every time; by - * default, layers are shared between provide calls. + * Provides a `Context` to the channel, removing the corresponding service + * requirements from the returned channel. * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ export const provideContext = /*#__PURE__*/dual(2, (self, context) => fromTransform((upstream, scope) => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context)))); /** - * @since 4.0.0 - * @category Services + * Provides a concrete service for a context key, removing that service + * requirement from the returned channel. + * + * @category services + * @since 2.0.0 */ export const provideService = /*#__PURE__*/dual(3, (self, key, service) => fromTransform((upstream, scope) => Effect.map(Effect.provideService(toTransform(self)(upstream, scope), key, service), Effect.provideService(key, service)))); /** + * Provides a service to the channel after obtaining it from an effect. + * + * **When to use** + * + * Use to supply a channel dependency when constructing the service itself is + * effectful or can fail. + * + * **Details** + * + * If the service effect fails, the returned channel fails. The provided service + * removes the corresponding service requirement from the returned channel. + * + * @category services * @since 4.0.0 - * @category Services */ export const provideServiceEffect = /*#__PURE__*/dual(3, (self, key, service) => fromTransform((upstream, scope) => Effect.flatMap(service, s => toTransform(provideService(self, key, s))(upstream, scope)))); /** + * Provides a `Layer` or `Context` to the channel, removing the corresponding + * service requirements. + * + * **Details** + * + * Providing a `Context` delegates to `provideContext`. Providing a `Layer` + * builds the layer in the channel scope. Use `options.local` to build a fresh + * layer instance for this provision. + * + * @category services * @since 4.0.0 - * @category Services */ export const provide = /*#__PURE__*/dual(args => isChannel(args[0]), (self, layer, options) => Context.isContext(layer) ? provideContext(self, layer) : fromTransform((upstream, scope) => Effect.flatMap(options?.local ? Layer.buildWithMemoMap(layer, Layer.makeMemoMapUnsafe(), scope) : Layer.buildWithScope(layer, scope), context => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context))))); /** - * @since 2.0.0 - * @category Services + * Transforms the current context before running the channel. + * + * **Details** + * + * The function receives the surrounding context and returns the context to + * provide to the channel. The returned channel requires the services needed to + * build that context. + * + * @category services + * @since 4.0.0 */ export const updateContext = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.contextWith(context => { const toProvide = f(context); return toTransform(provideContext(self, toProvide))(upstream, scope); }))); /** + * Updates a service in the current context before running the channel. + * + * **Details** + * + * The existing service is read from the context. The updated service is + * provided to the channel under the same key. + * + * @category services * @since 2.0.0 - * @category Services */ export const updateService = /*#__PURE__*/dual(3, (self, service, f) => updateContext(self, context => Context.add(context, service, f(Context.get(context, service))))); /** - * @since 4.0.0 - * @category Tracing + * Runs the channel inside a tracing span with the specified name and options. + * + * **Details** + * + * The created span is provided as the current parent span while the channel + * runs. The span is ended with the channel's exit value. + * + * @category tracing + * @since 2.0.0 */ export const withSpan = function () { const dataFirst = isChannel(arguments[0]); @@ -3001,8 +3514,10 @@ const withSpanImpl = (self, name, options) => acquireUseRelease(Effect.makeSpan( return endSpan(span, exit, clock, timingEnabled); })); /** + * The starting channel for Do notation, emitting an empty object. + * + * @category do notation * @since 4.0.0 - * @category Do notation */ export const Do = /*#__PURE__*/succeed({}); const let_ = /*#__PURE__*/dual(3, (self, name, f) => map(self, elem => ({ @@ -3011,21 +3526,43 @@ const let_ = /*#__PURE__*/dual(3, (self, name, f) => map(self, elem => ({ }))); export { /** + * Adds a computed field to each object emitted by a channel. + * + * @category do notation * @since 4.0.0 - * @category Do notation */ let_ as let }; /** + * Adds a field to each object emitted by a channel by running another channel + * derived from that object. + * + * **Details** + * + * The field name must not already exist on the emitted object. The derived + * channel's output becomes the value of the new field. `options.concurrency` + * and `options.bufferSize` control how derived channels are flattened. + * + * @category do notation * @since 4.0.0 - * @category Do notation */ export const bind = /*#__PURE__*/dual(args => isChannel(args[0]), (self, name, f, options) => flatMap(self, elem => map(f(elem), b => ({ ...elem, [name]: b })), options)); /** + * Wraps each output element in an object under the specified field name. + * + * **When to use** + * + * Use when you need to start a Channel Do-notation chain from an existing + * output value by assigning that value to a field name. + * + * @see {@link Do} for starting Do notation from an empty object + * @see {@link bind} for adding a field produced by another channel + * @see {@link let_ let} for adding a computed field + * + * @category do notation * @since 4.0.0 - * @category Do notation */ export const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, elem => ({ [name]: elem @@ -3033,7 +3570,8 @@ export const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, elem => ({ /** * Runs a channel and counts the number of elements it outputs. * - * @example + * **Example** (Counting channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -3050,14 +3588,15 @@ export const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, elem => ({ * // Effect.runSync(countEffect) // Returns: 5 * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ export const runCount = self => runFold(self, () => 0, acc => acc + 1); /** * Runs a channel and discards all output elements, returning only the final result. * - * @example + * **Example** (Draining channel output at runtime) + * * ```ts * import { Channel, Data } from "effect" * @@ -3078,8 +3617,8 @@ export const runCount = self => runFold(self, () => 0, acc => acc + 1); * // Effect.runSync(drainEffect) // Returns: "completed" * ``` * - * @since 2.0.0 * @category execution + * @since 2.0.0 */ export const runDrain = self => runWith(self, pull => Effect.forever(pull, { disableYield: true @@ -3087,7 +3626,8 @@ export const runDrain = self => runWith(self, pull => Effect.forever(pull, { /** * Runs a channel and applies an effect to each output element. * - * @example + * **Example** (Running effects for each output) + * * ```ts * import { Channel, Console, Data } from "effect" * @@ -3107,15 +3647,23 @@ export const runDrain = self => runWith(self, pull => Effect.forever(pull, { * // Logs: "Processing: 1", "Processing: 2", "Processing: 3" * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ export const runForEach = /*#__PURE__*/dual(2, (self, f) => runWith(self, pull => Effect.forever(Effect.flatMap(pull, f), { disableYield: true }))); /** - * @since 2.0.0 + * Runs a channel and applies an effectful predicate to each output element + * until the predicate returns `false`. + * + * **Details** + * + * Returning `true` continues consuming the channel. Returning `false` stops + * consumption early. The returned effect completes with `void`. + * * @category execution + * @since 4.0.0 */ export const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => runWith(self, pull => pull.pipe(Effect.flatMap(f), Effect.flatMap(cont => cont ? Effect.void : Cause.done()), Effect.forever({ disableYield: true @@ -3123,7 +3671,8 @@ export const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => runWith(self, p /** * Runs a channel and collects all output elements into an array. * - * @example + * **Example** (Collecting channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -3140,8 +3689,8 @@ export const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => runWith(self, p * // Effect.runSync(collectEffect) // Returns: [1, 2, 3, 4, 5] * ``` * - * @since 2.0.0 * @category execution + * @since 2.0.0 */ export const runCollect = self => runFold(self, () => [], (acc, o) => { acc.push(o); @@ -3150,13 +3699,21 @@ export const runCollect = self => runFold(self, () => [], (acc, o) => { /** * Runs a channel and outputs the done value. * - * @since 4.0.0 * @category execution + * @since 4.0.0 */ export const runDone = self => runWith(self, identity_, Effect.succeed); /** - * @since 2.0.0 + * Runs a channel until the first output element is available, returning it in + * an `Option`. + * + * **Details** + * + * Returns `Option.some` with the first output element, or `Option.none` if the + * channel completes without emitting output. + * * @category execution + * @since 4.0.0 */ export const runHead = self => Effect.suspend(() => { let head = Option.none(); @@ -3166,8 +3723,16 @@ export const runHead = self => Effect.suspend(() => { })), () => Effect.succeed(head)); }); /** - * @since 2.0.0 + * Runs a channel to completion and returns the last output element in an + * `Option`. + * + * **Details** + * + * Returns `Option.some` with the last emitted element, or `Option.none` if the + * channel completes without emitting output. + * * @category execution + * @since 4.0.0 */ export const runLast = self => Effect.suspend(() => { const absent = Symbol(); // Prevent boxing @@ -3182,7 +3747,8 @@ export const runLast = self => Effect.suspend(() => { /** * Runs a channel and folds over all output elements with an accumulator. * - * @example + * **Example** (Folding channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -3199,8 +3765,8 @@ export const runLast = self => Effect.suspend(() => { * // Effect.runSync(sumEffect) // Returns: 15 * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ export const runFold = /*#__PURE__*/dual(3, (self, initial, f) => Effect.suspend(() => { let state = initial(); @@ -3213,8 +3779,21 @@ export const runFold = /*#__PURE__*/dual(3, (self, initial, f) => Effect.suspend }), () => Effect.succeed(state)); })); /** - * @since 2.0.0 + * Runs a channel and effectfully folds all output elements with an accumulator. + * + * **When to use** + * + * Use when folding channel output needs effects, services, or an additional + * failure channel during accumulation. + * + * **Details** + * + * The initial accumulator is evaluated lazily. Each output element is passed to + * the effectful accumulator function. The returned effect succeeds with the + * final accumulator value. + * * @category execution + * @since 4.0.0 */ export const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Effect.suspend(() => { let state = initial(); @@ -3227,9 +3806,16 @@ export const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Effect.s }), () => Effect.succeed(state)); })); /** - * Converts a channel to a Pull data structure for low-level consumption. + * Converts a channel to a scoped `Pull` for low-level consumption. + * + * **Details** + * + * The effect requires a `Scope`. The returned pull should be consumed only + * while that scope remains open. Pulls are serialized so only one pull is + * evaluated at a time. + * + * **Example** (Converting channels to pulls) * - * @example * ```ts * import { Channel, Data, Effect } from "effect" * @@ -3248,8 +3834,8 @@ export const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Effect.s * // Use the Pull to manually consume elements * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toPull = /*#__PURE__*/Effect.fnUntraced(function* (self) { const semaphore = Semaphore.makeUnsafe(1); @@ -3264,7 +3850,8 @@ Effect.catchCause(cause => Effect.succeed(Effect.failCause(cause)))); /** * Converts a channel to a Pull within an existing scope. * - * @example + * **Example** (Converting channels to scoped pulls) + * * ```ts * import { Channel, Data, Effect, Scope } from "effect" * @@ -3283,13 +3870,21 @@ Effect.catchCause(cause => Effect.succeed(Effect.failCause(cause)))); * }) * ``` * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toPullScoped = (self, scope) => toTransform(self)(Cause.done(), scope); /** + * Runs a channel and offers each output element into a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const runIntoQueue = /*#__PURE__*/dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offer(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => { if (Exit.isSuccess(exit)) { @@ -3300,8 +3895,17 @@ export const runIntoQueue = /*#__PURE__*/dual(args => isChannel(args[0]), (self, return Effect.void; })))); /** + * Runs a channel that emits non-empty arrays and offers each array element into + * a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const runIntoQueueArray = /*#__PURE__*/dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offerAll(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => { if (Exit.isSuccess(exit)) { @@ -3312,9 +3916,17 @@ export const runIntoQueueArray = /*#__PURE__*/dual(args => isChannel(args[0]), ( return Effect.void; })))); /** - * Converts a channel to a queue for concurrent consumption. + * Creates a scoped queue and forks the channel to feed it for concurrent + * consumption. + * + * **Details** + * + * Output elements are offered to the queue. Channel completion and failure are + * signaled through the queue. The queue is shut down when the surrounding scope + * closes. + * + * **Example** (Converting channels to queues) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -3332,8 +3944,8 @@ export const runIntoQueueArray = /*#__PURE__*/dual(args => isChannel(args[0]), ( * // Multiple consumers can read from the queue * ``` * - * @since 4.0.0 - * @category Destructors + * @category destructors + * @since 2.0.0 */ export const toQueue = /*#__PURE__*/dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) { const scope = yield* Effect.scope; @@ -3346,8 +3958,16 @@ export const toQueue = /*#__PURE__*/dual(args => isChannel(args[0]), /*#__PURE__ return queue; })); /** + * Creates a scoped queue and forks an array-emitting channel to feed it. + * + * **Details** + * + * Each element inside emitted non-empty arrays is offered to the queue. Channel + * completion and failure are signaled through the queue. The queue is shut down + * when the surrounding scope closes. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toQueueArray = /*#__PURE__*/dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) { const scope = yield* Effect.scope; @@ -3362,11 +3982,13 @@ export const toQueueArray = /*#__PURE__*/dual(args => isChannel(args[0]), /*#__P /** * Converts a channel to a PubSub for concurrent consumption. * + * **Details** + * * `shutdownOnEnd` indicates whether the PubSub should be shut down when the * channel ends. By default this is `true`. * - * @since 4.0.0 - * @category Destructors + * @category destructors + * @since 2.0.0 */ export const toPubSub = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { const pubsub = yield* makePubSub(options); @@ -3376,19 +3998,30 @@ export const toPubSub = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(func return pubsub; })); /** + * Runs a channel and publishes each output element to a `PubSub`. + * + * **Details** + * + * The channel's output values are published as individual PubSub messages. Use + * `options.shutdownOnEnd` to shut down the PubSub when channel execution ends. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const runIntoPubSub = /*#__PURE__*/dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publish(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_)); const makePubSub = options => Effect.acquireRelease(options.capacity === "unbounded" ? PubSub.unbounded(options) : options.strategy === "dropping" ? PubSub.dropping(options) : options.strategy === "sliding" ? PubSub.sliding(options) : PubSub.bounded(options), PubSub.shutdown); /** - * Converts a channel to a PubSub for concurrent consumption. + * Converts an array-emitting channel to a scoped `PubSub` for concurrent + * consumption. * - * `shutdownOnEnd` indicates whether the PubSub should be shut down when the - * channel ends. By default this is `true`. + * **Details** * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. `shutdownOnEnd` indicates whether the PubSub should be shut + * down when the channel ends. By default this is `true`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toPubSubArray = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { const pubsub = yield* makePubSub(options); @@ -3398,15 +4031,30 @@ export const toPubSubArray = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced return pubsub; })); /** + * Runs an array-emitting channel and publishes each array element to a + * `PubSub`. + * + * **Details** + * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. Use `options.shutdownOnEnd` to shut down the PubSub when + * channel execution ends. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const runIntoPubSubArray = /*#__PURE__*/dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publishAll(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_)); /** - * Converts a channel to a PubSub for concurrent consumption. + * Converts a channel to a scoped `PubSub` of `Take` values. + * + * **Details** * + * Emitted non-empty arrays are published as output `Take` values. When the + * channel ends, its final `Exit` is published so subscribers can observe + * completion or failure. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toPubSubTake = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { const pubsub = yield* makePubSub(options);