diff --git "a/.opencode/node_modules/effect/dist/Stream.js" "b/.opencode/node_modules/effect/dist/Stream.js" --- "a/.opencode/node_modules/effect/dist/Stream.js" +++ "b/.opencode/node_modules/effect/dist/Stream.js" @@ -1,4 +1,13 @@ /** + * Describes effectful sources that emit values over time. + * + * A `Stream` can emit many `A` values, fail with `E`, and require + * services `R` while it is being consumed. Streams are useful for data that is + * pulled in steps, such as values from collections, queues, pubsubs, schedules, + * callbacks, async iterables, or platform streams. The APIs here cover the full + * stream lifecycle: create a stream, transform or combine it, control buffering + * and timing, handle failures, and finally consume it. + * * @since 2.0.0 */ // @effect-diagnostics returnEffectInGen:off @@ -23,6 +32,7 @@ import * as MutableHashMap from "./MutableHashMap.js"; import * as MutableList from "./MutableList.js"; import * as Option from "./Option.js"; import { hasProperty, isNotUndefined, isTagged } from "./Predicate.js"; +import * as PubSub from "./PubSub.js"; import * as Pull from "./Pull.js"; import * as Queue from "./Queue.js"; import * as RcMap from "./RcMap.js"; @@ -33,14 +43,25 @@ import * as Scope from "./Scope.js"; import * as Sink from "./Sink.js"; import { isString } from "./String.js"; /** + * Runtime identifier stored on `Stream` values and used by `isStream` to + * recognize them. + * + * **Details** + * + * This marker is part of the runtime representation of `Stream` values. Prefer + * `isStream` when narrowing unknown values. + * + * @see {@link isStream} for the public guard that checks this identifier + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export const TypeId = "~effect/Stream"; /** * Checks whether a value is a Stream. * - * @example + * **Example** (Checking whether a value is a Stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -57,14 +78,15 @@ export const TypeId = "~effect/Stream"; * Effect.runPromise(program) * ``` * - * @since 2.0.0 - * @category Guards + * @category guards + * @since 4.0.0 */ export const isStream = u => hasProperty(u, TypeId); /** * The default chunk size used by Stream constructors and combinators. * - * @example + * **Example** (Reading the default chunk size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -76,14 +98,15 @@ export const isStream = u => hasProperty(u, TypeId); * // Output: 4096 * ``` * - * @category Constants + * @category constants * @since 2.0.0 */ export const DefaultChunkSize = Channel.DefaultChunkSize; /** * Creates a stream from a array-emitting `Channel`. * - * @example + * **Example** (Creating a stream from an array-emitting channel) + * * ```ts * import { Channel, Console, Effect, Stream } from "effect" * @@ -97,15 +120,15 @@ export const DefaultChunkSize = Channel.DefaultChunkSize; * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromChannel = internal.fromChannel; /** - * Either emits the success value of this effect or terminates the stream - * with the failure value of this effect. + * Creates a stream from an effect. + * + * **Example** (Creating a stream from an effect) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -119,16 +142,17 @@ export const fromChannel = internal.fromChannel; * // Output: [ 42 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromEffect = effect => fromChannel(Channel.fromEffect(Effect.map(effect, Arr.of))); /** * Accesses a service from the context and emits it as a single element. * - * @example + * **Example** (Accessing a service as a stream) + * * ```ts - * import { Effect, Context, Stream } from "effect" + * import { Context, Effect, Stream } from "effect" * * class Greeter extends Context.Service string @@ -151,17 +175,23 @@ export const fromEffect = effect => fromChannel(Channel.fromEffect(Effect.map(ef * // Output: [ "Hello, World!" ] * ``` * + * @category context * @since 4.0.0 - * @category Context */ export const service = service => fromEffect(Effect.service(service)); /** * Optionally accesses a service from the context and emits the result as a * single element. * - * @example + * **When to use** + * + * Use when you need a stream that emits an optional service from the context + * without requiring that service to be present. + * + * **Example** (Accessing an optional service as a stream) + * * ```ts - * import { Effect, Option, Context, Stream } from "effect" + * import { Context, Effect, Option, Stream } from "effect" * * class Greeter extends Context.Service string @@ -189,14 +219,15 @@ export const service = service => fromEffect(Effect.service(service)); * // Output: [ "Hello, World!" ] * ``` * + * @category context * @since 4.0.0 - * @category Context */ export const serviceOption = service => fromEffect(Effect.serviceOption(service)); /** * Creates a stream that runs the effect and emits no elements. * - * @example + * **Example** (Draining an effect into a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -210,20 +241,15 @@ export const serviceOption = service => fromEffect(Effect.serviceOption(service) * // Output: Draining side effect * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromEffectDrain = effect => fromPull(Effect.succeed(Effect.flatMap(effect, () => Cause.done()))); /** * Creates a stream from an effect producing a value of type `A` which repeats forever. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Repeating an effect forever) * - * - `Stream.repeatEffect` - * - * @example * ```ts * import { Console, Effect, Random, Stream } from "effect" * @@ -239,21 +265,16 @@ export const fromEffectDrain = effect => fromPull(Effect.succeed(Effect.flatMap( * // Output: [ 3891571149, 4239494205, 2352981603, 2339111046, 1488052210 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromEffectRepeat = effect => fromPull(Effect.succeed(Effect.map(effect, Arr.of))); /** * Creates a stream from an effect producing a value of type `A`, which is * repeated using the specified schedule. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Repeating an effect with a schedule) * - * - `Stream.repeatEffectWithSchedule` - * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -270,8 +291,8 @@ export const fromEffectRepeat = effect => fromPull(Effect.succeed(Effect.map(eff * // Output: [ "ping", "ping", "ping" ] * ``` * - * @since 2.0.0 - * @category Constructors + * @category constructors + * @since 4.0.0 */ export const fromEffectSchedule = (effect, schedule) => fromPull(Effect.gen(function* () { const step = yield* Schedule.toStepWithMetadata(schedule); @@ -290,9 +311,11 @@ export const fromEffectSchedule = (effect, schedule) => fromPull(Effect.gen(func }); })); /** - * Creates a stream that emits void values spaced by the specified duration. + * Creates a stream that emits `void` immediately once, then emits another + * `void` after each specified interval. + * + * **Example** (Emitting ticks on an interval) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -308,8 +331,8 @@ export const fromEffectSchedule = (effect, schedule) => fromPull(Effect.gen(func * // Output: [ undefined, undefined, undefined ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const tick = interval => fromPull(Effect.sync(() => { let first = true; @@ -326,10 +349,13 @@ export const tick = interval => fromPull(Effect.sync(() => { /** * Creates a stream from a pull effect, such as one produced by `Stream.toPull`. * + * **Details** + * * A pull effect yields chunks on demand and completes when the upstream stream ends. * See `Stream.toPull` for a matching producer. * - * @example + * **Example** (Creating a stream from a pull effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -347,14 +373,15 @@ export const tick = interval => fromPull(Effect.sync(() => { * // Output: [1, 2, 3] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromPull = pull => fromChannel(Channel.fromPull(pull)); /** - * Derive a stream by transforming its pull effect. + * Derives a stream by transforming its pull effect. + * + * **Example** (Transforming a pull effect) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -371,17 +398,20 @@ export const fromPull = pull => fromChannel(Channel.fromPull(pull)); * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const transformPull = (self, f) => fromChannel(Channel.fromTransform((_, scope) => Effect.flatMap(Channel.toPullScoped(self.channel, scope), pull => f(pull, scope)))); /** * Transforms a stream by effectfully transforming its pull effect. * + * **Details** + * * A forked scope is also provided to the transformation function, which is * closed once the resulting stream has finished processing. * - * @example + * **Example** (Transforming a stream by effectfully transforming its pull effect) + * * ```ts * import { Console, Effect, Scope, Stream } from "effect" * @@ -406,14 +436,15 @@ export const transformPull = (self, f) => fromChannel(Channel.fromTransform((_, * // Releasing scope * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const transformPullBracket = (self, f) => fromChannel(Channel.fromTransformBracket((_, scope, forkedScope) => Effect.flatMap(Channel.toPullScoped(self.channel, scope), pull => f(pull, scope, forkedScope)))); /** * Creates a channel from a stream. * - * @example + * **Example** (Converting a stream to a channel) + * * ```ts * import { Channel, Console, Effect, Stream } from "effect" * @@ -428,30 +459,24 @@ export const transformPullBracket = (self, f) => fromChannel(Channel.fromTransfo * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const toChannel = stream => stream.channel; /** * Creates a stream from a callback that can emit values into a queue. * - * You can use the `Queue` with the apis from the `Queue` module to emit - * values to the stream or to signal the stream ending. + * **When to use** + * + * Use when you need callback-based code to emit stream values by offering to a + * `Queue`, or signal stream completion through the `Queue` module APIs. * * By default it uses an "unbounded" buffer size. * You can customize the buffer size and strategy by passing an object as the * second argument with the `bufferSize` and `strategy` fields. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Creating a stream from a callback that can emit values into a queue) * - * - `Stream.async` - * - `Stream.asyncEffect` - * - `Stream.asyncPush` - * - `Stream.asyncScoped` - * - * @example * ```ts * import { Console, Effect, Queue, Stream } from "effect" * @@ -475,14 +500,15 @@ export const toChannel = stream => stream.channel; * Effect.runPromise(program) * ``` * - * @since 2.0.0 - * @category Constructors + * @category constructors + * @since 4.0.0 */ export const callback = (f, options) => fromChannel(Channel.callbackArray(f, options)); /** * Creates an empty stream. * - * @example + * **Example** (Creating an empty stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -495,14 +521,15 @@ export const callback = (f, options) => fromChannel(Channel.callbackArray(f, opt * // [] * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const empty = /*#__PURE__*/fromChannel(Channel.empty); /** * Creates a single-valued pure stream. * - * @example + * **Example** (Creating a single-valued pure stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -515,14 +542,15 @@ export const empty = /*#__PURE__*/fromChannel(Channel.empty); * // [ 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const succeed = value => fromChannel(Channel.succeed(Arr.of(value))); /** * Creates a stream from a sequence of values. * - * @example + * **Example** (Creating a stream from a sequence of values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -536,16 +564,19 @@ export const succeed = value => fromChannel(Channel.succeed(Arr.of(value))); * Effect.runPromise(program) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const make = (...values) => fromArray(values); /** * Creates a stream that synchronously evaluates a function and emits the result as a single value. * + * **Details** + * * The function is evaluated each time the stream is run. * - * @example + * **Example** (Evaluating a value synchronously) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -558,16 +589,19 @@ export const make = (...values) => fromArray(values); * // Output: [ 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const sync = evaluate => fromChannel(Channel.sync(() => Arr.of(evaluate()))); /** * Creates a lazily constructed stream. * + * **Details** + * * The stream factory is evaluated each time the stream is run. * - * @example + * **Example** (Creating a lazily constructed stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -580,14 +614,15 @@ export const sync = evaluate => fromChannel(Channel.sync(() => Arr.of(evaluate() * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const suspend = stream => fromChannel(Channel.suspend(() => stream().channel)); /** * Terminates with the specified error. * - * @example + * **Example** (Failing a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -601,14 +636,15 @@ export const suspend = stream => fromChannel(Channel.suspend(() => stream().chan * Effect.runPromise(program) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fail = error => fromChannel(Channel.fail(error)); /** * Terminates with the specified lazily evaluated error. * - * @example + * **Example** (Failing a stream lazily) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -624,14 +660,15 @@ export const fail = error => fromChannel(Channel.fail(error)); * // { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Fail', failure: 'Uh oh!' } } * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const failSync = evaluate => fromChannel(Channel.failSync(evaluate)); /** * Creates a stream that fails with the specified `Cause`. * - * @example + * **Example** (Failing with a cause) + * * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -648,14 +685,15 @@ export const failSync = evaluate => fromChannel(Channel.failSync(evaluate)); * Effect.runPromise(program) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const failCause = cause => fromChannel(Channel.failCause(cause)); /** * The stream that dies with the specified defect. * - * @example + * **Example** (Dying with a defect) + * * ```ts * import { Cause, Console, Effect, Exit, Stream } from "effect" * @@ -679,14 +717,15 @@ export const failCause = cause => fromChannel(Channel.failCause(cause)); * // Output: Exit.Failure(Error: Boom) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const die = defect => fromChannel(Channel.die(defect)); /** * The stream that always fails with the specified lazily evaluated `Cause`. * - * @example + * **Example** (Failing with a lazy cause) + * * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -704,16 +743,19 @@ export const die = defect => fromChannel(Channel.die(defect)); * // { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Fail', failure: 'Connection timeout after retries' } } * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const failCauseSync = evaluate => fromChannel(Channel.failCauseSync(evaluate)); /** * Creates a stream that consumes values from an iterator. * + * **Details** + * * The `maxChunkSize` parameter controls how many values are pulled per chunk. * - * @example + * **Example** (Consuming values from an iterator) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -734,18 +776,19 @@ export const failCauseSync = evaluate => fromChannel(Channel.failCauseSync(evalu * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromIteratorSucceed = (iterator, maxChunkSize) => fromChannel(Channel.fromIteratorArray(() => iterator, maxChunkSize)); /** * Creates a new `Stream` from an iterable collection of values. * - * **Options** + * **Details** * * - `chunkSize`: Maximum number of values emitted per chunk. * - * @example + * **Example** (Creating a stream from an iterable) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -761,16 +804,22 @@ export const fromIteratorSucceed = (iterator, maxChunkSize) => fromChannel(Chann * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromIterable = (iterable, options) => Array.isArray(iterable) && options?.chunkSize === undefined ? fromArray(iterable) : fromChannel(Channel.fromIterableArray(iterable, options?.chunkSize)); /** * Creates a stream from an effect producing an iterable of values. * - * @example + * **When to use** + * + * Use when the iterable must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * + * **Example** (Creating a stream from an iterable effect) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class UserRepo extends Context.Service> @@ -796,20 +845,15 @@ export const fromIterable = (iterable, options) => Array.isArray(iterable) && op * // Output: [ "user1", "user2" ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromIterableEffect = iterable => unwrap(Effect.map(iterable, fromIterable)); /** * Creates a stream by repeatedly running an effect that yields an iterable of values. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Repeating an iterable effect) * - * - `Stream.repeatEffectChunk` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -825,20 +869,15 @@ export const fromIterableEffect = iterable => unwrap(Effect.map(iterable, fromIt * // Output: [ 1, 2, 1, 2, 1 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromIterableEffectRepeat = iterable => flatMap(fromEffectRepeat(iterable), fromIterable); /** * Creates a stream from an array of values. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Creating a stream from an array of values) * - * - `Stream.fromChunk` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -852,14 +891,20 @@ export const fromIterableEffectRepeat = iterable => flatMap(fromEffectRepeat(ite * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromArray = array => Arr.isReadonlyArrayNonEmpty(array) ? fromChannel(Channel.succeed(array)) : empty; /** * Creates a stream from an effect that produces an array of values. * - * @example + * **When to use** + * + * Use when the array must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * + * **Example** (Creating a stream from an effect that produces an array of values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -873,20 +918,15 @@ export const fromArray = array => Arr.isReadonlyArrayNonEmpty(array) ? fromChann * // Output: [ "Ada", "Grace" ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromArrayEffect = effect => unwrap(Effect.map(effect, fromArray)); /** * Creates a stream from an arbitrary number of arrays. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Stream.fromChunks` + * **Example** (Creating a stream from an arbitrary number of arrays) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -900,19 +940,20 @@ export const fromArrayEffect = effect => unwrap(Effect.map(effect, fromArray)); * // Output: [ 1, 2, 3, 4 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromArrays = (...arrays) => fromChannel(Channel.fromArray(Arr.filter(arrays, Arr.isReadonlyArrayNonEmpty))); /** - * Creates a stream from a queue of values. + * Creates a stream that pulls values from a `Queue.Dequeue`. * - * **Options** + * **Details** * - * - `maxChunkSize`: The maximum number of queued elements to put in one chunk in the stream - * - `shutdown`: If `true`, the queue will be shutdown after the stream is evaluated (defaults to `false`) + * The stream emits non-empty batches of queued values and ends when the queue + * fails with `Cause.Done`; other queue failures are propagated. + * + * **Example** (Creating a stream from a queue of values) * - * @example * ```ts * import { Console, Effect, Queue, Stream } from "effect" * @@ -932,14 +973,15 @@ export const fromArrays = (...arrays) => fromChannel(Channel.fromArray(Arr.filte * // Output: [ 1, 2, 3 ] * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const fromQueue = queue => fromChannel(Channel.fromQueueArray(queue)); /** * Creates a stream from a subscription to a `PubSub`. * - * @example + * **Example** (Creating a stream from a subscription to a PubSub) + * * ```ts * import { Console, Effect, Fiber, PubSub, Stream } from "effect" * @@ -964,16 +1006,19 @@ export const fromQueue = queue => fromChannel(Channel.fromQueueArray(queue)); * // Output: [ 1, 2, 3 ] * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const fromPubSub = pubsub => fromChannel(Channel.fromPubSubArray(pubsub)); /** * Creates a stream from a PubSub of `Take` values. * + * **Details** + * * `Take` values include end and failure signals. * - * @example + * **Example** (Creating a stream from PubSub takes) + * * ```ts * import { Console, Effect, Exit, PubSub, Stream, Take } from "effect" * @@ -994,16 +1039,21 @@ export const fromPubSub = pubsub => fromChannel(Channel.fromPubSubArray(pubsub)) * // Output: [ 1, 2 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromPubSubTake = pubsub => fromChannel(Channel.fromPubSubTake(pubsub)); /** - * Creates a stream from a `ReadableStream`. + * Creates a stream from a lazily supplied Web `ReadableStream`. * - * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * **Details** + * + * The stream reads from a `ReadableStreamDefaultReader`, maps read failures + * with `onError`, and closes the reader when the stream finalizes. By default + * the reader is canceled; set `releaseLockOnEnd` to release the lock instead. + * + * **Example** (Creating a stream from a ReadableStream) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -1031,12 +1081,12 @@ export const fromPubSubTake = pubsub => fromChannel(Channel.fromPubSubTake(pubsu * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromReadableStream = options => fromChannel(Channel.fromTransform(Effect.fnUntraced(function* (_, scope) { const reader = options.evaluate().getReader(); - yield* Scope.addFinalizer(scope, options.releaseLockOnEnd ? Effect.sync(() => reader.releaseLock()) : Effect.promise(() => reader.cancel())); + yield* Scope.addFinalizer(scope, options.releaseLockOnEnd ? Effect.sync(() => reader.releaseLock()) : Effect.promise(() => reader.cancel().catch(constVoid))); return Effect.flatMap(Effect.tryPromise({ try: () => reader.read(), catch: reason => options.onError(reason) @@ -1048,9 +1098,10 @@ export const fromReadableStream = options => fromChannel(Channel.fromTransform(E /** * Creates a stream from an AsyncIterable. * - * @example + * **Example** (Creating a stream from an AsyncIterable) + * * ```ts - * import { Console, Data, Effect, Stream } from "effect" + * import { Data, Effect, Stream } from "effect" * * class StreamError extends Data.TaggedError("StreamError")<{ readonly cause: unknown }> {} * @@ -1060,25 +1111,25 @@ export const fromReadableStream = options => fromChannel(Channel.fromTransform(E * yield 3 * })() * - * const program = Effect.gen(function*() { + * Effect.runPromise(Effect.gen(function*() { * const stream = Stream.fromAsyncIterable(iterable, (cause) => new StreamError({ cause })) * const values = yield* Stream.runCollect(stream) - * yield* Console.log(values) - * }) + * yield* Effect.sync(() => console.log(values)) + * })) * - * Effect.runPromise(program) - * // Output: [ 1, 2, 3 ] + * // [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromAsyncIterable = (iterable, onError) => fromChannel(Channel.fromAsyncIterableArray(iterable, onError)); /** * Creates a stream that emits each output of a schedule that does not require input, * for as long as the schedule continues. * - * @example + * **Example** (Creating a stream from a schedule) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -1095,17 +1146,21 @@ export const fromAsyncIterable = (iterable, onError) => fromChannel(Channel.from * // Output: [ 0, 1, 2 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => Pull.catchDone(Effect.map(step(void 0), Arr.of), () => Cause.done()))); /** * Creates a stream from a PubSub subscription. * - * Use `PubSub.subscribe` to create the subscription and `Stream.take` or - * cancellation to control how many values are consumed. + * **When to use** + * + * Use when you already have a `PubSub.Subscription` and want to expose its + * messages as a `Stream`, with `Stream.take` or cancellation controlling how + * many values are consumed. + * + * **Example** (Creating a stream from a PubSub subscription) * - * @example * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -1125,33 +1180,42 @@ export const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithS * // Output: [ 1, 2 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromSubscription = pubsub => fromChannel(Channel.fromSubscriptionArray(pubsub)); /** * Creates a stream from an event listener. * - * @example + * **Example** (Creating a stream from an event listener) + * * ```ts - * import { Console, Effect, Stream } from "effect" + * import { Effect, Stream } from "effect" * - * declare const target: Stream.EventListener + * class NumberTarget implements Stream.EventListener { + * addEventListener(event: string, f: (event: number) => void) { + * if (event === "data") { + * f(1) + * f(2) + * f(3) + * } + * } + * removeEventListener(_event: string, _f: (event: number) => void) {} + * } * - * const program = Effect.gen(function*() { - * const stream = Stream.fromEventListener(target, "data").pipe( + * Effect.runPromise(Effect.gen(function*() { + * const stream = Stream.fromEventListener(new NumberTarget(), "data").pipe( * Stream.take(3) * ) * const values = yield* Stream.runCollect(stream) - * yield* Console.log(values) - * }) + * yield* Effect.sync(() => console.log(values)) + * })) * - * Effect.runPromise(program) - * // Output: [ 1, 2, 3 ] + * // [ 1, 2, 3 ] * ``` * + * @category constructors * @since 3.1.0 - * @category Constructors */ export const fromEventListener = (target, type, options) => callback(queue => { function emit(event) { @@ -1162,9 +1226,16 @@ export const fromEventListener = (target, type, options) => callback(queue => { bufferSize: typeof options === "object" ? options.bufferSize : undefined }); /** - * Creates a stream by peeling off successive layers of a state value. + * Creates a stream by repeatedly applying an effectful step function to a + * state. + * + * **Details** + * + * Each `readonly [value, nextState]` result emits `value` and continues with + * `nextState`; returning `undefined` ends the stream. + * + * **Example** (Unfolding stream state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1178,8 +1249,8 @@ export const fromEventListener = (target, type, options) => callback(queue => { * // Output: [ 1, 2, 3, 4, 5 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const unfold = (s, f) => fromPull(Effect.sync(() => { let state = s; @@ -1190,14 +1261,22 @@ export const unfold = (s, f) => fromPull(Effect.sync(() => { }); })); /** - * Like `Stream.unfold`, but allows the emission of values to end one step further - * than the unfolding of the state. This is useful for embedding paginated APIs, - * hence the name. + * Creates a stream by repeatedly evaluating an effectful page function. + * + * **When to use** + * + * Use to consume paginated APIs where each step returns a batch of values + * together with an optional next state. + * + * **Details** + * + * This is similar to {@link unfold}, but each step can emit zero or more values + * and independently decide whether another state should be requested. + * + * **Example** (Paginating stream state) * - * @example * ```ts - * import { Console, Effect, Stream } from "effect" - * import * as Option from "effect/Option" + * import { Console, Effect, Option, Stream } from "effect" * * const stream = Stream.paginate(0, (n: number) => * Effect.succeed( @@ -1211,8 +1290,8 @@ export const unfold = (s, f) => fromPull(Effect.sync(() => { * // Output: [ 0, 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const paginate = (s, f) => fromPull(Effect.sync(() => { let state = s; @@ -1233,7 +1312,8 @@ export const paginate = (s, f) => fromPull(Effect.sync(() => { /** * Creates an infinite stream by repeatedly applying a function to a seed value. * - * @example + * **Example** (Iterating from a seed value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1248,17 +1328,20 @@ export const paginate = (s, f) => fromPull(Effect.sync(() => { * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const iterate = (value, next) => unfold(value, a => Effect.succeed([a, next(a)])); /** * Constructs a stream from a range of integers, including both endpoints. * + * **Details** + * * If the provided `min` is greater than `max`, the stream will not emit any * values. * - * @example + * **Example** (Creating a numeric range) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1270,8 +1353,9 @@ export const iterate = (value, next) => unfold(value, a => Effect.succeed([a, ne * Effect.runPromise(program) * // Output: [ 1, 2, 3, 4, 5 ] * ``` - * @since 4.0.0 - * @category Constructors + * + * @category constructors + * @since 2.0.0 */ export const range = (min, max, chunkSize = Channel.DefaultChunkSize) => min > max ? empty : fromPull(Effect.sync(() => { let start = min; @@ -1292,7 +1376,8 @@ export const range = (min, max, chunkSize = Channel.DefaultChunkSize) => min > m /** * The stream that never produces any value or fails with any error. * - * @example + * **Example** (Creating a never-ending stream) + * * ```ts * import { Effect, Stream } from "effect" * @@ -1305,14 +1390,15 @@ export const range = (min, max, chunkSize = Channel.DefaultChunkSize) => min > m * // [] * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const never = /*#__PURE__*/fromChannel(Channel.never); /** * Creates a stream produced from an `Effect`. * - * @example + * **Example** (Unwrapping a stream effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1327,15 +1413,16 @@ export const never = /*#__PURE__*/fromChannel(Channel.never); * // [1, 2, 3] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const unwrap = effect => fromChannel(Channel.unwrap(Effect.map(effect, toChannel))); /** * Runs a stream that requires `Scope` in a managed scope, ensuring its * finalizers are run when the stream completes. * - * @example + * **Example** (Scoping a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1354,14 +1441,15 @@ export const unwrap = effect => fromChannel(Channel.unwrap(Effect.map(effect, to * // [ "resource" ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const scoped = self => fromChannel(Channel.scoped(self.channel)); /** * Transforms the elements of this stream using the supplied function. * - * @example + * **Example** (Mapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1374,8 +1462,8 @@ export const scoped = self => fromChannel(Channel.scoped(self.channel)); * // [ 1, 3, 5 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const map = /*#__PURE__*/dual(2, (self, f) => suspend(() => { let i = 0; @@ -1384,7 +1472,8 @@ export const map = /*#__PURE__*/dual(2, (self, f) => suspend(() => { /** * Maps both the failure and success channels of a stream. * - * @example + * **Example** (Mapping both the failure and success channels of a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1413,20 +1502,15 @@ export const map = /*#__PURE__*/dual(2, (self, f) => suspend(() => { * // Output: [ "error: boom" ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapBoth = /*#__PURE__*/dual(2, (self, options) => self.pipe(map(options.onSuccess), mapError(options.onFailure))); /** * Transforms each emitted chunk using the provided function, which receives the chunk and its index. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Mapping stream chunks) * - * - `Stream.mapChunks` - * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -1443,14 +1527,20 @@ export const mapBoth = /*#__PURE__*/dual(2, (self, options) => self.pipe(map(opt * // Output: [ 1, 2, 4, 5 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ export const mapArray = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.map(self.channel, f))); /** * Maps over elements of the stream with the specified effectful function. * - * @example + * **When to use** + * + * Use when each stream element transformation needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Example** (Effectfully mapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1478,14 +1568,20 @@ export const mapArray = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.ma * // [2, 4, 6] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.mapEffect(f, options), Channel.map(Arr.of), fromChannel)); /** * Flattens a stream of `Effect` values into a stream of their results. * - * @example + * **When to use** + * + * Use when stream elements already are effects and their successes should become + * stream elements while their failures enter the stream error channel. + * + * **Example** (Flattening a stream of Effect values into a stream of their results) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1500,20 +1596,20 @@ export const mapEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, * // Output: [1, 2, 3] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const flattenEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => mapEffect(self, identity, options)); /** - * Effectfully maps over non-empty array chunks emitted by the stream. + * Maps over non-empty array chunks emitted by the stream effectfully. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when transformation needs to see and replace each non-empty emitted chunk + * effectfully instead of mapping individual stream elements. * - * - `Stream.mapChunksEffect` + * **Example** (Effectfully mapping stream chunks) * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -1532,22 +1628,19 @@ export const flattenEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, * // Output: [1, 2, 13, 14] * ``` * + * @category mapping * @since 4.0.0 - * @category Mapping */ export const mapArrayEffect = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.mapEffect(self.channel, f))); /** * Lifts failures and successes into a `Result`, yielding a stream that cannot fail. * - * The stream ends after the first failure, emitting a `Result.fail` value. - * - * **Previously Known As:** + * **Details** * - * This API replaces the following from Effect 3.x: + * The stream ends after the first failure, emitting a `Result.fail` value. * - * - `Stream.either` + * **Example** (Converting failures to results) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -1568,14 +1661,15 @@ export const mapArrayEffect = /*#__PURE__*/dual(2, (self, f) => fromChannel(Chan * // Output: [ "success: 1", "success: 2", "failure: boom" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const result = self => self.pipe(map(Result.succeed), catch_(e => succeed(Result.fail(e)))); /** * Runs the provided effect for each element while preserving the elements. * - * @example + * **Example** (Tapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1601,14 +1695,15 @@ export const result = self => self.pipe(map(Result.succeed), catch_(e => succeed * // [ 2, 4, 6 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => mapEffect(self, a => Effect.as(f(a), a), options)); /** * Returns a stream that effectfully "peeks" at elements and failures. * - * @example + * **Example** (Tapping values and errors) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1633,17 +1728,17 @@ export const tap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, option * // [ 1, 2, 3 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapBoth = /*#__PURE__*/dual(2, (self, options) => self.pipe(tapError(options.onError), tap(options.onElement, { concurrency: options.concurrency }))); /** - * Sends all elements emitted by this stream to the specified sink in addition - * to emitting them. + * Runs a sink for all stream elements while still emitting them downstream. + * + * **Example** (Tapping values with a sink) * - * @example * ```ts * import { Console, Effect, Ref, Sink, Stream } from "effect" * @@ -1666,8 +1761,8 @@ export const tapBoth = /*#__PURE__*/dual(2, (self, options) => self.pipe(tapErro * // Output: [1, 2, 3] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapSink = /*#__PURE__*/dual(2, (self, sink) => transformPullBracket(self, Effect.fnUntraced(function* (pull, _, scope) { const upstreamLatch = Latch.makeUnsafe(); @@ -1713,9 +1808,17 @@ export const tapSink = /*#__PURE__*/dual(2, (self, sink) => transformPullBracket }); }))); /** - * Maps each element to a stream and concatenates the results in order. + * Maps each element to a stream and flattens the resulting streams. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * input order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (FlatMapping stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1731,15 +1834,16 @@ export const tapSink = /*#__PURE__*/dual(2, (self, sink) => transformPullBracket * // Output: [ 1, 2, 2, 4, 3, 6 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const flatMap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.flatMap(a => f(a).channel, options), fromChannel)); /** * Switches to the latest stream produced by the mapping function, interrupting * the previous stream when a new element arrives. * - * @example + * **Example** (Switching to the latest stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1755,15 +1859,22 @@ export const flatMap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, op * }) * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const switchMap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.switchMap(a => f(a).channel, options), fromChannel)); /** - * Flattens a stream of streams into a single stream by concatenating the - * inner streams in strict order. + * Flattens a stream of streams into a single stream. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * strict order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (Flattening nested streams) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1782,20 +1893,15 @@ export const switchMap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, * // Output: [ 1, 2, 3, 4, 5, 6 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const flatten = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => flatMap(self, identity, options)); /** * Flattens a stream of non-empty arrays into a stream of elements. * - * **Previously Known As** + * **Example** (Flattening a stream of non-empty arrays into a stream of elements) * - * This API replaces the following from Effect 3.x: - * - * - `Stream.flattenChunks` - * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -1810,14 +1916,15 @@ export const flatten = /*#__PURE__*/dual(args => isStream(args[0]), (self, optio * // Output: [ 1, 2, 3 ] * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const flattenArray = self => fromChannel(Channel.flattenArray(self.channel)); /** * Converts this stream to one that runs its effects but emits no elements. * - * @example + * **Example** (Draining stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1830,15 +1937,16 @@ export const flattenArray = self => fromChannel(Channel.flattenArray(self.channe * // Output: [] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const drain = self => fromChannel(Channel.drain(self.channel)); /** * Runs the provided stream in the background while this stream runs, interrupting it * when this stream completes and failing if the background stream fails or defects. * - * @example + * **Example** (Draining a stream in the background) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1858,14 +1966,15 @@ export const drain = self => fromChannel(Channel.drain(self.channel)); * // Output: [ 1, 2 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const drainFork = /*#__PURE__*/dual(2, (self, that) => mergeEffect(self, runDrain(that))); /** * Repeats the entire stream according to the provided schedule. * - * @example + * **Example** (Repeating a stream on a schedule) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -1882,14 +1991,15 @@ export const drainFork = /*#__PURE__*/dual(2, (self, that) => mergeEffect(self, * // Output: [ 1, 1, 1, 1, 1 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const repeat = /*#__PURE__*/dual(2, (self, schedule) => fromChannel(Channel.repeat(self.channel, schedule))); /** - * Spaces the stream's elements according to the provided `schedule`. + * Schedules the stream's elements according to the provided schedule. + * + * **Example** (Scheduling stream elements) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -1906,14 +2016,15 @@ export const repeat = /*#__PURE__*/dual(2, (self, schedule) => fromChannel(Chann * // Output: [ 1, 2, 3 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const schedule = /*#__PURE__*/dual(2, (self, schedule) => self.channel.pipe(Channel.flattenArray, Channel.schedule(schedule), Channel.map(Arr.of), fromChannel)); /** * Ends the stream if it does not produce a value within the specified duration. * - * @example + * **Example** (Timing out a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1930,16 +2041,36 @@ export const schedule = /*#__PURE__*/dual(2, (self, schedule) => self.channel.pi * // Output: [ 1 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const timeout = /*#__PURE__*/dual(2, (self, duration) => timeoutOrElse(self, { duration, orElse: () => empty })); /** - * @since 2.0.0 - * @category Rate Limiting + * Switches to a fallback stream if this stream does not emit a value within + * the specified duration. + * + * **When to use** + * + * Use when a stream should continue with another stream if an upstream pull + * waits longer than the allowed duration. + * + * **Details** + * + * The timeout is checked for each pull. A zero duration uses `orElse` + * immediately, while an infinite duration leaves the original stream + * unchanged. + * + * **Gotchas** + * + * The fallback stream is not timed after the switch. + * + * @see {@link timeout} for ending the stream instead of switching to a fallback stream + * + * @category rate limiting + * @since 4.0.0 */ export const timeoutOrElse = /*#__PURE__*/dual(2, (self, options) => { const duration = Duration.fromInputUnsafe(options.duration); @@ -1983,9 +2114,8 @@ export const timeoutOrElse = /*#__PURE__*/dual(2, (self, options) => { * Repeats each element of the stream according to the provided schedule, * including the original emission. * - * @since 2.0.0 - * @category Sequencing - * @example + * **Example** (Repeating stream elements) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -2000,6 +2130,9 @@ export const timeoutOrElse = /*#__PURE__*/dual(2, (self, options) => { * Effect.runPromise(program) * // Output: [ "A", "A", "B", "B", "C", "C" ] * ``` + * + * @category sequencing + * @since 2.0.0 */ export const repeatElements = /*#__PURE__*/dual(2, (self, schedule) => fromChannel(Channel.fromTransform((upstream, scope) => Effect.map(Channel.toTransform(Channel.flattenArray(self.channel))(upstream, scope), pullElement => { let pullRepeat = undefined; @@ -2018,7 +2151,8 @@ export const repeatElements = /*#__PURE__*/dual(2, (self, schedule) => fromChann /** * Repeats this stream forever. * - * @example + * **Example** (Repeating a stream forever) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2036,20 +2170,15 @@ export const repeatElements = /*#__PURE__*/dual(2, (self, schedule) => fromChann * // Output: [ "A", "B", "A", "B", "A" ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const forever = self => fromChannel(Channel.forever(self.channel)); /** - * Submerges the iterables emitted by this stream into the stream's structure. - * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * Flattens the iterables emitted by this stream into the stream's structure. * - * - `Stream.flattenIterables` + * **Example** (Flattening iterable values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2063,15 +2192,16 @@ export const forever = self => fromChannel(Channel.forever(self.channel)); * // Output: [ 1, 2, 3, 4 ] * ``` * + * @category mapping * @since 4.0.0 - * @category Mapping */ export const flattenIterable = self => flatMap(self, fromIterable); /** * Unwraps `Take` values, emitting elements from non-empty arrays and ending or * failing when the `Exit` signals completion. * - * @example + * **Example** (Flattening Take values) + * * ```ts * import { Array, Console, Effect, Exit, Stream } from "effect" * @@ -2090,15 +2220,16 @@ export const flattenIterable = self => flatMap(self, fromIterable); * // Output: [ 1, 2, 3 ] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 2.0.0 */ export const flattenTake = self => self.channel.pipe(Channel.flattenArray, Channel.flattenTake, fromChannel); /** * Concatenates two streams, emitting all elements from the first stream * followed by all elements from the second stream. * - * @example + * **Example** (Concatenating streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2111,14 +2242,15 @@ export const flattenTake = self => self.channel.pipe(Channel.flattenArray, Chann * // Output: [ 1, 2, 3, 4, 5, 6 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const concat = /*#__PURE__*/dual(2, (self, that) => flatten(fromArray([self, that]))); /** * Prepends the values from the provided iterable before the stream's elements. * - * @example + * **Example** (Prepending values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2135,17 +2267,20 @@ export const concat = /*#__PURE__*/dual(2, (self, that) => flatten(fromArray([se * Effect.runPromise(program) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const prepend = /*#__PURE__*/dual(2, (self, values) => concat(fromIterable(values), self)); /** * Merges two streams, emitting elements from both as they arrive. * + * **Details** + * * By default, the merged stream ends when both streams end. Use * `haltStrategy` to change the termination behavior. * - * @example + * **Example** (Merging stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2161,19 +2296,25 @@ export const prepend = /*#__PURE__*/dual(2, (self, values) => concat(fromIterabl * // Output: [ 1, 2, 3, 4 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const merge = /*#__PURE__*/dual(args => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel(Channel.merge(toChannel(self), toChannel(that), options))); /** * Merges this stream with a background effect, keeping the stream's elements. * + * **When to use** + * + * Use when an effect should run concurrently for the lifetime of a stream while + * only the stream's elements remain in the output. + * + * **Details** + * * The effect runs concurrently, fails the stream if it fails, and is interrupted * when the stream completes. * - * @since 4.0.0 - * @category Merging - * @example + * **Example** (Merging with a background effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2190,19 +2331,23 @@ export const merge = /*#__PURE__*/dual(args => isStream(args[0]) && isStream(arg * // Output: side task * // Output: [ 1, 2, 3 ] * ``` + * + * @category merging + * @since 4.0.0 */ export const mergeEffect = /*#__PURE__*/dual(2, (self, effect) => self.channel.pipe(Channel.mergeEffect(effect), fromChannel)); /** * Merges this stream and the specified stream together, tagging values from the * left stream as `Result.succeed` and values from the right stream as `Result.fail`. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when values from both streams should be emitted and downstream code needs + * left values wrapped as successful `Result` values and right values wrapped as + * failed `Result` values. * - * - `Stream.mergeEither` + * **Example** (Merging streams into results) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -2228,18 +2373,26 @@ export const mergeEffect = /*#__PURE__*/dual(2, (self, effect) => self.channel.p * // Output: [ "left:left", "right:right" ] * ``` * - * @since 2.0.0 - * @category Merging + * @category merging + * @since 4.0.0 */ export const mergeResult = /*#__PURE__*/dual(2, (self, that) => merge(map(self, Result.succeed), map(that, Result.fail))); /** * Merges two streams while emitting only the values from the left stream. * + * **When to use** + * + * Use when the right stream is needed for its effects or failures, but downstream + * consumers should only receive values from the left stream. + * + * **Details** + * * The right stream still runs for its effects, and any failures from the right * stream are propagated. The merged stream completes when the left stream * completes, interrupting the right stream. * - * @example + * **Example** (Merging streams while keeping left values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2254,18 +2407,26 @@ export const mergeResult = /*#__PURE__*/dual(2, (self, that) => merge(map(self, * // Output: [ 1, 2 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const mergeLeft = /*#__PURE__*/dual(2, (left, right) => mergeEffect(left, runDrain(right))); /** * Merges this stream and the specified stream together, emitting only the * values from the right stream while the left stream runs for its effects. * + * **When to use** + * + * Use when the left stream is needed for its effects or failures, but downstream + * consumers should only receive values from the right stream. + * + * **Details** + * * The merged stream ends when the right stream completes, interrupting the * left stream. Failures from the left stream still fail the merged stream. * - * @example + * **Example** (Merging streams while keeping right values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2285,17 +2446,26 @@ export const mergeLeft = /*#__PURE__*/dual(2, (left, right) => mergeEffect(left, * // Output: [ 1, 2 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const mergeRight = /*#__PURE__*/dual(2, (left, right) => mergeEffect(right, runDrain(left))); /** * Merges a collection of streams, running up to the specified number concurrently. * - * @since 2.0.0 - * @category Merging + * **When to use** + * + * Use to merge an iterable of already-created streams while bounding how many + * inner streams may run at the same time. + * + * **Details** + * + * The `concurrency` option is required and may be a number or `"unbounded"`. + * `bufferSize` controls buffering between inner streams, and outputs are + * emitted as they arrive under concurrent merging. + * + * **Example** (Merging streams with bounded concurrency) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2314,15 +2484,24 @@ export const mergeRight = /*#__PURE__*/dual(2, (left, right) => mergeEffect(righ * Effect.runPromise(program) * // Output: [ "B", "A" ] * ``` + * + * @see {@link merge} for merging exactly two streams and choosing a halt strategy + * @see {@link flatten} for flattening a stream that already emits streams + * + * @category merging + * @since 2.0.0 */ export const mergeAll = /*#__PURE__*/dual(2, (streams, options) => flatten(fromIterable(streams), options)); /** * Creates the cartesian product of two streams, running the `right` stream for * each element in the `left` stream. * + * **Details** + * * See also `Stream.zip` for the more common point-wise variant. * - * @example + * **Example** (Computing cartesian products) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2337,18 +2516,21 @@ export const mergeAll = /*#__PURE__*/dual(2, (streams, options) => flatten(fromI * // Output: [ [ 1, "a" ], [ 1, "b" ], [ 2, "a" ], [ 2, "b" ] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const cross = /*#__PURE__*/dual(2, (left, right) => crossWith(left, right, (l, r) => [l, r])); /** * Creates a cartesian product of elements from two streams using a function. * + * **Details** + * * The `right` stream is rerun for every element in the `left` stream. * * See also `Stream.zipWith` for the more common point-wise variant. * - * @example + * **Example** (Combining cartesian products) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2364,14 +2546,15 @@ export const cross = /*#__PURE__*/dual(2, (left, right) => crossWith(left, right * // Output: [ "1-a", "1-b", "2-a", "2-b" ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const crossWith = /*#__PURE__*/dual(3, (left, right, f) => flatMap(left, l => map(right, r => f(l, r)))); /** * Zips two streams point-wise with a combining function, ending when either stream ends. * - * @example + * **Example** (Zipping streams with a function) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2389,8 +2572,8 @@ export const crossWith = /*#__PURE__*/dual(3, (left, right, f) => flatMap(left, * // Output: [ "1-a", "2-b", "3-c" ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWith = /*#__PURE__*/dual(3, (left, right, f) => zipWithArray(left, right, zipArrays(f))); const zipArrays = f => (leftArr, rightArr) => { @@ -2404,15 +2587,12 @@ const zipArrays = f => (leftArr, rightArr) => { /** * Zips two streams by applying a function to non-empty arrays of elements. * - * The function returns output plus leftover arrays that carry into the next pull. - * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * The function returns output plus leftover arrays that carry into the next pull. * - * - `Stream.zipWithChunks` + * **Example** (Zipping stream chunks) * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -2435,8 +2615,8 @@ const zipArrays = f => (leftArr, rightArr) => { * // Output: [[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]] * ``` * - * @since 2.0.0 - * @category Zipping + * @category zipping + * @since 4.0.0 */ export const zipWithArray = /*#__PURE__*/dual(3, (left, right, f) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_, scope) { const pullLeft = yield* Channel.toPullScoped(left.channel, scope); @@ -2475,7 +2655,8 @@ export const zipWithArray = /*#__PURE__*/dual(3, (left, right, f) => fromChannel * Zips this stream with another point-wise and emits tuples of elements from * both streams. The new stream ends when either stream ends. * - * @example + * **Example** (Zipping streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2493,17 +2674,20 @@ export const zipWithArray = /*#__PURE__*/dual(3, (left, right, f) => fromChannel * // Output: [[1, "a"], [2, "b"], [3, "c"]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zip = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, (a, a2) => [a, a2])); /** * Zips this stream with another point-wise and keeps only the values from * the left stream. * + * **Details** + * * The resulting stream ends when either side ends. * - * @example + * **Example** (Zipping streams while keeping left values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2519,8 +2703,8 @@ export const zip = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, (a, * // Output: [1, 2] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipLeft = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => { const minLength = Math.min(leftArr.length, rightArr.length); @@ -2532,7 +2716,8 @@ export const zipLeft = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, /** * Zips this stream with another point-wise, keeping only right values and ending when either stream ends. * - * @example + * **Example** (Zipping streams while keeping right values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2548,8 +2733,8 @@ export const zipLeft = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, * // Output: ["a", "b"] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipRight = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => { const minLength = Math.min(leftArr.length, rightArr.length); @@ -2562,9 +2747,12 @@ export const zipRight = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, * Zips this stream with another point-wise and emits tuples of elements from * both streams, flattening the left tuple. * + * **Details** + * * The new stream will end when one of the sides ends. * - * @example + * **Example** (Zipping and flattening tuples) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2584,14 +2772,15 @@ export const zipRight = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, * // Output: [[1, "a", "x"], [2, "b", "y"], [3, "c", "z"]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipFlatten = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, (a, a2) => [...a, a2])); /** * Zips this stream together with the index of elements. * - * @example + * **Example** (Zipping elements with indices) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2607,15 +2796,16 @@ export const zipFlatten = /*#__PURE__*/dual(2, (self, that) => zipWith(self, tha * // Output: [["a", 0], ["b", 1], ["c", 2], ["d", 3]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWithIndex = self => map(self, (a, i) => [a, i]); /** * Zips each element with the next element, pairing the final element with * `Option.none()`. * - * @example + * **Example** (Zipping elements with next values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2633,8 +2823,8 @@ export const zipWithIndex = self => map(self, (a, i) => [a, i]); * // ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWithNext = self => mapAccumArray(self, Option.none, (acc, arr) => { let i = 0; @@ -2657,7 +2847,8 @@ export const zipWithNext = self => mapAccumArray(self, Option.none, (acc, arr) = /** * Zips each element with its previous element, starting with `None`. * - * @example + * **Example** (Zipping elements with previous values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2677,8 +2868,8 @@ export const zipWithNext = self => mapAccumArray(self, Option.none, (acc, arr) = * // ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWithPrevious = self => mapAccumArray(self, Option.none, (acc, arr) => { const pairs = Arr.empty(); @@ -2692,7 +2883,8 @@ export const zipWithPrevious = self => mapAccumArray(self, Option.none, (acc, ar /** * Zips each element with its previous and next values. * - * @example + * **Example** (Zipping elements with neighbors) + * * ```ts * import { Console, Effect, Option, Stream } from "effect" * @@ -2708,8 +2900,8 @@ export const zipWithPrevious = self => mapAccumArray(self, Option.none, (acc, ar * // Output: [ [Option.none(), 1, Option.some(2)], [Option.some(1), 2, Option.some(3)], [Option.some(2), 3, Option.none()] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWithPreviousAndNext = self => mapAccumArray(self, () => ({ prev: Option.none(), @@ -2742,11 +2934,19 @@ export const zipWithPreviousAndNext = self => mapAccumArray(self, () => ({ * Zips multiple streams so that when a value is emitted by any stream, it is * combined with the latest values from the other streams to produce a result. * + * **When to use** + * + * Use when each stream should contribute its latest value after all streams have + * emitted at least once. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values from many streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2765,8 +2965,8 @@ export const zipWithPreviousAndNext = self => mapAccumArray(self, () => ({ * // Output: [ [ 1, "a", true ], [ 2, "a", true ], [ 3, "a", true ], [ 3, "b", true ], [ 3, "c", true ], [ 3, "c", false ], [ 3, "c", true ] ] * ``` * - * @since 2.0.0 - * @category Zipping + * @category zipping + * @since 3.3.0 */ export const zipLatestAll = (...streams) => fromChannel(Channel.suspend(() => { const latest = []; @@ -2790,11 +2990,19 @@ export const zipLatestAll = (...streams) => fromChannel(Channel.suspend(() => { /** * Combines two streams by emitting each new element with the latest value from the other stream. * + * **When to use** + * + * Use when two streams should start emitting combined pairs after both have + * produced at least one value. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2809,19 +3017,27 @@ export const zipLatestAll = (...streams) => fromChannel(Channel.suspend(() => { * // Output: [ [1, "a"] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipLatest = /*#__PURE__*/dual(2, (left, right) => zipLatestAll(left, right)); /** * Combines the latest values from both streams whenever either emits, using * the provided function. * + * **When to use** + * + * Use when two streams should start emitting custom combined values after both + * have produced at least one value. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values with a function) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2840,17 +3056,22 @@ export const zipLatest = /*#__PURE__*/dual(2, (left, right) => zipLatestAll(left * }) * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipLatestWith = /*#__PURE__*/dual(3, (left, right, f) => map(zipLatestAll(left, right), ([a, a2]) => f(a, a2))); /** - * Races multiple streams and emits values from the first stream to produce a value, interrupting the rest. + * Runs all streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the rest. * - * @since 3.7.0 - * @category Racing + * **Details** + * + * Failures or completion from losing streams before a winner is chosen are + * ignored unless every stream fails or completes before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing multiple streams) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -2865,6 +3086,9 @@ export const zipLatestWith = /*#__PURE__*/dual(3, (left, right, f) => map(zipLat * Effect.runPromise(program) * // Output: [ 0, 1, 2 ] * ``` + * + * @category racing + * @since 3.5.0 */ export const raceAll = (...streams) => fromChannel(Channel.fromTransform((_, scope) => Effect.sync(() => { let winner; @@ -2884,10 +3108,17 @@ export const raceAll = (...streams) => fromChannel(Channel.fromTransform((_, sco return Effect.suspend(() => winner ?? race); }))); /** - * Returns a stream that mirrors the first upstream to emit an item. - * As soon as one stream emits, the other is interrupted and failures propagate. + * Runs both streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the other. + * + * **Details** + * + * A failure or completion from one side before the other side emits does not + * win the race unless both sides fail or complete before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing two streams) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -2905,14 +3136,15 @@ export const raceAll = (...streams) => fromChannel(Channel.fromTransform((_, sco * // Output: [ 0, 1, 2 ] * ``` * + * @category racing * @since 3.7.0 - * @category Racing */ export const race = /*#__PURE__*/dual(2, (left, right) => raceAll(left, right)); /** * Filters a stream to the elements that satisfy a predicate. * - * @example + * **Example** (Filtering stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2928,21 +3160,35 @@ export const race = /*#__PURE__*/dual(2, (left, right) => raceAll(left, right)); * // Output: [ 2, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filter = /*#__PURE__*/dual(2, (self, predicate) => fromChannel(Channel.filterArray(toChannel(self), predicate))); /** * Filters and maps stream elements in one pass using a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use to keep only stream elements accepted by a `Filter` and emit each filter + * success value. + * + * **Details** + * + * `Result.succeed` values are emitted and `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMapEffect} for an effectful `Filter` + * @see {@link partition} for consuming both filter success and failure values + * + * @category filtering + * @since 2.0.0 */ export const filterMap = /*#__PURE__*/dual(2, (self, filter) => fromChannel(Channel.filterMapArray(toChannel(self), filter))); /** - * Effectfully filters elements in a single pass. + * Filters elements in a single pass effectfully. + * + * **Example** (Effectfully filtering stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2957,23 +3203,43 @@ export const filterMap = /*#__PURE__*/dual(2, (self, filter) => fromChannel(Chan * // Output: [ 3, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filterEffect = /*#__PURE__*/dual(2, (self, predicate) => fromChannel(Channel.filterArrayEffect(toChannel(self), predicate))); /** - * Effectfully filters and maps elements in a single pass. + * Filters and maps elements in one pass effectfully using a `FilterEffect`. * - * @since 4.0.0 - * @category Filtering - */ -export const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromChannel(Channel.filterMapArrayEffect(toChannel(self), filter))); + * **When to use** + * + * Use to apply effectful logic that can reject stream elements or emit + * transformed values before they continue downstream. + * + * **Details** + * + * `Result.succeed` values are emitted, `Result.fail` values are skipped, and + * effect failures fail the stream. + * + * @see {@link filterMap} for the synchronous `Filter` variant + * @see {@link filterEffect} for effectfully keeping original elements + * @see {@link mapEffect} for effectfully transforming every element + * + * @category filtering + * @since 2.0.0 + */ +export const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromChannel(Channel.filterMapArrayEffect(toChannel(self), filter))); /** - * Partitions a stream using a `Filter` and exposes passing and failing values as queues. + * Partitions a stream using a `Filter` and exposes passing and failing values + * as scoped queues. + * + * **Details** + * + * The queues are backed by a fiber in the current scope and should be consumed + * while that scope remains open. Each queue fails with the stream error or + * `Cause.Done` when the source ends. * - * Each queue fails with the stream error or `Cause.Done` when the source ends. + * **Example** (Partitioning a stream into queues) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -2994,8 +3260,8 @@ export const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromChanne * Effect.runPromise(Effect.scoped(program)) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const partitionQueue = /*#__PURE__*/dual(args => isStream(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, filter, options) { const scope = yield* Effect.scope; @@ -3043,22 +3309,40 @@ export const partitionQueue = /*#__PURE__*/dual(args => isStream(args[0]), /*#__ return [passes, fails]; })); /** - * Splits a stream using an effectful `Filter`, producing pass and fail streams. + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** + * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. + * + * **Details** * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. + * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const partitionEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, filter, options) => Effect.map(partitionQueue(mapEffect(self, a => filter(a), options), result => result, options), ([passes, fails]) => [fromQueue(passes), fromQueue(fails)])); /** - * Splits a stream into excluded and satisfying substreams using a `Filter`. + * Splits a stream into scoped excluded and satisfying substreams using a + * `Filter`. * - * The faster stream may advance up to `bufferSize` elements ahead of the slower - * one. + * **Details** * - * @since 4.0.0 - * @category Filtering + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The faster stream may advance up to + * `bufferSize` elements ahead of the slower one. + * + * **Example** (Partitioning a stream) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -3075,6 +3359,9 @@ export const partitionEffect = /*#__PURE__*/dual(args => isStream(args[0]), (sel * // Output: [ 2, 4 ] * }) * ``` + * + * @category filtering + * @since 2.0.0 */ export const partition = /*#__PURE__*/dual(args => isStream(args[0]), (self, filter, options) => Effect.map(partitionQueue(self, filter, { capacity: options?.bufferSize ?? 16 @@ -3083,7 +3370,8 @@ export const partition = /*#__PURE__*/dual(args => isStream(args[0]), (self, fil * Returns the specified stream if the given condition is satisfied, otherwise * returns an empty stream. * - * @example + * **Example** (Conditionally keeping a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3098,17 +3386,20 @@ export const partition = /*#__PURE__*/dual(args => isStream(args[0]), (self, fil * // Output: [] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const when = /*#__PURE__*/dual(2, (self, test) => test.pipe(Effect.map(pass => pass ? self : empty), unwrap)); /** * Runs a sink to peel off enough elements to produce a value and returns that * value with the remaining stream in a scope. * + * **Details** + * * The returned stream is only valid within the scope. * - * @example + * **Example** (Peeling a stream with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -3127,8 +3418,8 @@ export const when = /*#__PURE__*/dual(2, (self, test) => test.pipe(Effect.map(pa * // Output: [ [1, 2, 3], [4, 5, 6] ] * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const peel = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, sink) { let cause = undefined; @@ -3147,10 +3438,15 @@ export const peel = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function * Buffers up to `capacity` elements so a faster producer can progress * independently of a slower consumer. * - * Note: This combinator destroys chunking. Use `Stream.rechunk` afterwards if - * you need fixed chunk sizes. + * **Details** + * + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard elements when + * the buffer is full. This combinator destroys chunking; use `Stream.rechunk` + * afterward if you need fixed chunk sizes. + * + * **Example** (Buffering stream elements) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3166,23 +3462,23 @@ export const peel = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function * // Output: [ 1, 2, 3 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const buffer = /*#__PURE__*/dual(2, (self, options) => fromChannel(Channel.bufferArray(self.channel, options))); /** * Allows a faster producer to progress independently of a slower consumer by * buffering up to `capacity` chunks in a queue. * - * This combinator preserves chunking and is best with power-of-2 capacities. - * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard chunks when the + * buffer is full. This combinator preserves chunking and is best with + * power-of-2 capacities. * - * - `Stream.bufferChunks` + * **Example** (Buffering stream chunks) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3197,8 +3493,8 @@ export const buffer = /*#__PURE__*/dual(2, (self, options) => fromChannel(Channe * // Output: [ 1, 2, 3, 4 ] * ``` * - * @since 2.0.0 - * @category Rate Limiting + * @category rate limiting + * @since 4.0.0 */ export const bufferArray = /*#__PURE__*/dual(2, (self, options) => fromChannel(Channel.buffer(self.channel, options))); /** @@ -3206,13 +3502,8 @@ export const bufferArray = /*#__PURE__*/dual(2, (self, options) => fromChannel(C * one fails. Allows recovery from all causes of failure, including * interruption if the stream is uninterruptible. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching stream causes) * - * - `Stream.catchAllCause` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3234,21 +3525,16 @@ export const bufferArray = /*#__PURE__*/dual(2, (self, options) => fromChannel(C * // Output: [ 1, 2, 999 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const catchCause = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.catchCause(cause => f(cause).channel), fromChannel)); /** * Runs an effect when the stream fails without changing its values or error, * unless the tap effect itself fails. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Stream.tapErrorCause` + * **Example** (Tapping stream causes) * - * @example * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -3268,8 +3554,8 @@ export const catchCause = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Ch * // Output: [ 1, 2, 0 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const tapCause = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.tapCause(f), fromChannel)); const catch_ = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.catch(self.channel, error => f(error).channel))); @@ -3277,13 +3563,8 @@ export { /** * Switches over to the stream produced by the provided function if this one fails. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching stream failures) * - * - `Stream.catchAll` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3301,14 +3582,15 @@ export { * // Output: [ 1, 2, 999 ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ catch_ as catch }; /** - * Effectfully peeks at errors without changing the stream unless the tap fails. + * Peeks at errors effectfully without changing the stream unless the tap fails. + * + * **Example** (Effectfully peeking at errors) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3329,24 +3611,21 @@ catch_ as catch }; * // [ 1, 2, 999 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const tapError = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.tapError(f), fromChannel)); /** * Recovers from errors that match a predicate by switching to a recovery stream. * + * **Details** + * * When a failure matches the filter, the stream switches to the recovery * stream. Non-matching failures propagate downstream, so the error type is * preserved unless the filter narrows it. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching matching failures) * - * - `Stream.catchSome` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3367,28 +3646,44 @@ export const tapError = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Chan * Effect.runPromise(program) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchIf = /*#__PURE__*/dual(args => isStream(args[0]), (self, predicate, f, orElse) => fromChannel(Channel.catchIf(toChannel(self), predicate, e => f(e).channel, orElse && (e => orElse(e).channel)))); /** * Recovers from errors that match a `Filter` by switching to a recovery * stream. * + * **When to use** + * + * Use to recover from stream errors with a reusable `Filter` when matching can + * also narrow or transform the error before choosing the recovery stream. + * + * **Details** + * + * Successful filter results are passed to `f`. Failed filter results go to + * `orElse` when provided; otherwise the filter failure is re-failed. + * + * @see {@link catchIf} for predicate or refinement based recovery + * @see {@link catchTag} for `_tag` based recovery from one tagged error + * @see {@link catchTags} for `_tag` based recovery from multiple tagged errors + * @see {@link catchCauseFilter} for filtering full causes + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchFilter = /*#__PURE__*/dual(args => isStream(args[0]), (self, filter, f, orElse) => fromChannel(Channel.catchFilter(toChannel(self), filter, e => f(e).channel, orElse && (e => orElse(e).channel)))); /** * Recovers from failures whose `_tag` matches the provided value by switching to * the stream returned by `f`. * - * **When to Use** + * **When to use** * - * Use `catchTag` when your error type is a tagged union with a readonly `_tag` - * field and you want to handle a specific error case. + * Use when you need to handle a specific error case from a stream whose error + * type is a tagged union with a readonly `_tag` field. + * + * **Example** (Catching tagged failures) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -3409,8 +3704,8 @@ export const catchFilter = /*#__PURE__*/dual(args => isStream(args[0]), (self, f * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const catchTag = /*#__PURE__*/dual(args => isStream(args[0]), (self, k, f, orElse) => { const pred = Array.isArray(k) ? e => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); @@ -3419,7 +3714,8 @@ export const catchTag = /*#__PURE__*/dual(args => isStream(args[0]), (self, k, f /** * Switches to a recovery stream based on matching `_tag` handlers. * - * @example + * **Example** (Catching tagged failures with handlers) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3449,8 +3745,8 @@ export const catchTag = /*#__PURE__*/dual(args => isStream(args[0]), (self, k, f * // Output: [ "fallback" ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const catchTags = /*#__PURE__*/dual(args => isStream(args[0]), (self, cases, orElse) => { let keys; @@ -3462,10 +3758,17 @@ export const catchTags = /*#__PURE__*/dual(args => isStream(args[0]), (self, cas /** * Catches a specific reason within a tagged error. * - * Use this to handle nested error causes without removing the parent error - * from the error channel. The handler receives the unwrapped reason. + * **When to use** + * + * Use to handle nested error causes without removing the parent error + * from the error channel. + * + * **Details** + * + * The handler receives the unwrapped reason. + * + * **Example** (Catching a tagged error reason) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -3499,14 +3802,15 @@ export const catchTags = /*#__PURE__*/dual(args => isStream(args[0]), (self, cas * // Output: [ "retry: 60" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchReason = /*#__PURE__*/dual(args => isStream(args[0]), (self, errorTag, reasonTag, f, orElse) => fromChannel(Channel.catchReason(toChannel(self), errorTag, reasonTag, (reason, error) => f(reason, error).channel, orElse && ((reason, error) => orElse(reason, error).channel)))); /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Catching tagged error reasons) + * * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -3541,8 +3845,8 @@ export const catchReason = /*#__PURE__*/dual(args => isStream(args[0]), (self, e * // Output: [ "retry: 60" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchReasons = /*#__PURE__*/dual(args => isStream(args[0]), (self, errorTag, cases, orElse) => { const handlers = {}; @@ -3556,7 +3860,8 @@ export const catchReasons = /*#__PURE__*/dual(args => isStream(args[0]), (self, /** * Transforms the errors emitted by this stream using `f`. * - * @example + * **Example** (Mapping stream errors) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3573,21 +3878,16 @@ export const catchReasons = /*#__PURE__*/dual(args => isStream(args[0]), (self, * // Output: [ "recovered from mapped: bad" ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const mapError = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.mapError(self.channel, f))); /** * Recovers from stream failures by filtering the `Cause` and switching to a recovery stream. * Non-matching causes are re-emitted as failures. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching matching causes) * - * - `Stream.catchSomeCause` - * - * @example * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -3607,22 +3907,39 @@ export const mapError = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.ma * // Output: [ "Recovered: NetworkError" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCauseIf = /*#__PURE__*/dual(3, (self, predicate, f) => fromChannel(Channel.catchCauseIf(self.channel, predicate, cause => f(cause).channel))); /** * Recovers from stream failures by filtering the `Cause` and switching to a * recovery stream. * + * **When to use** + * + * Use when you need to recover a stream only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. A successful filter result is + * passed to `f` together with the original cause; a failed filter result + * re-fails with the residual cause. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCauseFilter = /*#__PURE__*/dual(3, (self, filter, f) => fromChannel(Channel.catchCauseFilter(self.channel, filter, (failure, cause) => f(failure, cause).channel))); /** * Switches to a fallback stream if this stream is empty. * - * @example + * **Example** (Switching on empty streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3638,14 +3955,15 @@ export const catchCauseFilter = /*#__PURE__*/dual(3, (self, filter, f) => fromCh * // Output: [ 1, 2 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const orElseIfEmpty = /*#__PURE__*/dual(2, (self, orElse) => fromChannel(Channel.orElseIfEmpty(self.channel, _ => toChannel(orElse())))); /** * Returns a stream that emits a fallback value when this stream fails. * - * @example + * **Example** (Recovering with a fallback value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3662,14 +3980,15 @@ export const orElseIfEmpty = /*#__PURE__*/dual(2, (self, orElse) => fromChannel( * // Output: [ "Recovered: NetworkError" ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const orElseSucceed = /*#__PURE__*/dual(2, (self, f) => catch_(self, e => succeed(f(e)))); /** * Turns typed failures into defects, making the stream infallible. * - * @example + * **Example** (Turning failures into defects) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3686,16 +4005,25 @@ export const orElseSucceed = /*#__PURE__*/dual(2, (self, f) => catch_(self, e => * // Output: [ 1, 2, 3 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const orDie = self => fromChannel(Channel.orDie(self.channel)); /** * Ignores failures and ends the stream on error. * - * Use the `log` option to emit the full {@link Cause} when the stream fails. + * **When to use** + * + * Use when you want a failing stream to end gracefully rather than propagate + * the error. + * + * **Details** + * + * The `log` option controls whether the failure is logged before the stream + * terminates. + * + * **Example** (Ignoring stream failures) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3712,42 +4040,63 @@ export const orDie = self => fromChannel(Channel.orDie(self.channel)); * // Output: [ 1, 2, 3 ] * ``` * - * @example + * **Example** (Configuring ignore logging) + * * ```ts - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * - * const stream = Stream.fail("boom") + * Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.fail("boom").pipe( + * Stream.ignore({ log: false }), + * Stream.runCollect + * ) + * yield* Effect.sync(() => console.log(values)) + * })) * - * const program = stream.pipe(Stream.ignore({ log: "Error" })) + * // [] * ``` * + * @see {@link ignoreCause} for a variant that also ignores defects, not just typed failures + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const ignore = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignore(self.channel, options))); /** * Ignores the stream's failure cause, including defects, and ends the stream. * - * Use the `log` option to emit the full {@link Cause} when the stream fails. + * **When to use** + * + * Use when you need to silently suppress a stream's entire failure cause, + * including both typed errors and defects, rather than propagate it downstream. + * + * **Example** (Ignoring stream failure causes) * - * @example * ```ts * import { Effect, Stream } from "effect" * - * const stream = Stream.make(1, 2).pipe( - * Stream.concat(Stream.fail("boom")), - * Stream.ignoreCause({ log: "Error" }) - * ) + * Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.make(1, 2).pipe( + * Stream.concat(Stream.die("boom")), + * Stream.ignoreCause({ log: false }), + * Stream.runCollect + * ) + * yield* Effect.sync(() => console.log(values)) + * })) * - * const program = Stream.runCollect(stream) + * // [ 1, 2 ] * ``` * + * @see {@link ignore} to ignore only typed failures without suppressing defects + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const ignoreCause = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignoreCause(self.channel, options))); /** - * When the stream fails, retry it according to the given schedule. + * Retries the stream according to the given schedule when it fails. + * + * **Details** * * This retries the entire stream, so will re-execute all of the stream's * acquire operations. @@ -3755,7 +4104,8 @@ export const ignoreCause = /*#__PURE__*/dual(args => isStream(args[0]), (self, o * The schedule is reset as soon as the first element passes through the * stream again. * - * @example + * **Example** (Retrying stream failures) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3774,21 +4124,24 @@ export const ignoreCause = /*#__PURE__*/dual(args => isStream(args[0]), (self, o * // Output: [ 1, 1 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const retry = /*#__PURE__*/dual(2, (self, policy) => fromChannel(Channel.retry(self.channel, policy))); /** - * Apply an `ExecutionPlan` to a stream, retrying with step-provided resources + * Applies an `ExecutionPlan` to a stream, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * By default, a failing step can fallback even after emitting elements; set * `preventFallbackOnPartialStream` to fail instead of mixing partial output with * a later fallback. * - * @example + * **Example** (Applying an execution plan) + * * ```ts - * import { Console, Effect, ExecutionPlan, Layer, Context, Stream } from "effect" + * import { Console, Context, Effect, ExecutionPlan, Layer, Stream } from "effect" * * class Service extends Context.Service()("Service", { * make: Effect.succeed({ @@ -3804,7 +4157,7 @@ export const retry = /*#__PURE__*/dual(2, (self, policy) => fromChannel(Channel. * { provide: Service.Good } * ) * - * const stream = Stream.unwrap(Effect.map(Service.asEffect(), (_) => _.stream)) + * const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream)) * * const program = Effect.gen(function*() { * const items = yield* stream.pipe(Stream.withExecutionPlan(plan), Stream.runCollect) @@ -3815,9 +4168,8 @@ export const retry = /*#__PURE__*/dual(2, (self, policy) => fromChannel(Channel. * // Output: [ 1, 2, 3 ] * ``` * + * @category error handling * @since 3.16.0 - * @category Error Handling - * @experimental */ export const withExecutionPlan = /*#__PURE__*/dual(args => isStream(args[0]), (self, policy, options) => suspend(() => { const preventFallbackOnPartialStream = options?.preventFallbackOnPartialStream ?? false; @@ -3873,7 +4225,8 @@ export const withExecutionPlan = /*#__PURE__*/dual(args => isStream(args[0]), (s /** * Takes the first `n` elements from this stream, returning `Stream.empty` when `n < 1`. * - * @example + * **Example** (Taking values from the left) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3889,14 +4242,15 @@ export const withExecutionPlan = /*#__PURE__*/dual(args => isStream(args[0]), (s * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const take = /*#__PURE__*/dual(2, (self, n) => n < 1 ? empty : takeUntil(self, (_, i) => i === n - 1)); /** * Keeps the last `n` elements from this stream. * - * @example + * **Example** (Taking elements from the right) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3912,8 +4266,8 @@ export const take = /*#__PURE__*/dual(2, (self, n) => n < 1 ? empty : takeUntil( * // Output: [ 4, 5, 6 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const takeRight = /*#__PURE__*/dual(2, (self, n) => mapAccumArray(self, MutableList.make, (list, arr) => { MutableList.appendAll(list, arr); @@ -3929,9 +4283,12 @@ export const takeRight = /*#__PURE__*/dual(2, (self, n) => mapAccumArray(self, M /** * Takes elements until the predicate matches. * + * **Details** + * * When `excludeLast` is `true`, the matching element is dropped. * - * @example + * **Example** (Taking until a predicate matches) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3954,8 +4311,8 @@ export const takeRight = /*#__PURE__*/dual(2, (self, n) => mapAccumArray(self, M * }) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const takeUntil = /*#__PURE__*/dual(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => Effect.sync(() => { let i = 0; @@ -3972,9 +4329,15 @@ export const takeUntil = /*#__PURE__*/dual(args => isStream(args[0]), (self, pre return pump; }))); /** - * Effectful predicate version of `takeUntil`. + * Takes stream elements until an effectful predicate returns `true`. + * + * **When to use** + * + * Use when the stopping condition needs an Effect or service and predicate + * failure should fail the stream. + * + * **Example** (Taking until an effectful predicate matches) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3990,8 +4353,8 @@ export const takeUntil = /*#__PURE__*/dual(args => isStream(args[0]), (self, pre * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const takeUntilEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => Effect.sync(() => { let i = 0; @@ -4012,7 +4375,8 @@ export const takeUntilEffect = /*#__PURE__*/dual(args => isStream(args[0]), (sel /** * Takes the longest initial prefix of elements that satisfy the predicate. * - * @example + * **Example** (Taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4029,8 +4393,8 @@ export const takeUntilEffect = /*#__PURE__*/dual(args => isStream(args[0]), (sel * // Output: [ 1, 2 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const takeWhile = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => { let i = 0; @@ -4049,10 +4413,24 @@ export const takeWhile = /*#__PURE__*/dual(2, (self, predicate) => transformPull return pump; }))); /** - * Takes the longest initial prefix of elements that satisfy the filter. + * Takes the longest initial prefix accepted by a `Filter` and emits the + * filter's success values. + * + * **When to use** + * + * Use to keep the leading stream elements that a `Filter` accepts, emit the + * filter's success values, and stop at the first filter failure. + * + * **Details** + * + * The stream stops at the first `Result.fail` returned by the filter. * + * @see {@link takeWhile} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMap} for filtering across the whole stream instead of only the leading prefix + * @see {@link dropWhileFilter} for dropping the accepted prefix and keeping the remaining original elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const takeWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => { let done = false; @@ -4073,7 +4451,13 @@ export const takeWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformP /** * Takes elements from the stream while the effectful predicate is `true`. * - * @example + * **When to use** + * + * Use when the leading-prefix predicate needs an Effect or service and the + * stream should stop before the first false result. + * + * **Example** (Effectfully taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4089,8 +4473,8 @@ export const takeWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformP * // Output: [ 1, 2 ] * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ export const takeWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => takeUntilEffect(self, (a, n) => Effect.map(predicate(a, n), b => !b), { excludeLast: true @@ -4098,7 +4482,8 @@ export const takeWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => takeUnt /** * Drops the first `n` elements from this stream. * - * @example + * **Example** (Dropping values from the left) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4114,8 +4499,8 @@ export const takeWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => takeUnt * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const drop = /*#__PURE__*/dual(2, (self, n) => transformPull(self, (pull, _scope) => Effect.sync(() => { let dropped = 0; @@ -4131,7 +4516,8 @@ export const drop = /*#__PURE__*/dual(2, (self, n) => transformPull(self, (pull, * Drops elements until the specified predicate evaluates to `true`, then drops * that matching element. * - * @example + * **Example** (Dropping until a predicate matches) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4144,17 +4530,21 @@ export const drop = /*#__PURE__*/dual(2, (self, n) => transformPull(self, (pull, * }) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropUntil = /*#__PURE__*/dual(2, (self, predicate) => drop(dropWhile(self, (a, i) => !predicate(a, i)), 1)); /** * Drops all elements of the stream until the specified effectful predicate * evaluates to `true`. * - * The first element that satisfies the predicate is also dropped. + * **When to use** + * + * Use when dropping the leading prefix requires an Effect or service and the + * first matching element should also be dropped. + * + * **Example** (Dropping until an effectful predicate matches) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4170,14 +4560,15 @@ export const dropUntil = /*#__PURE__*/dual(2, (self, predicate) => drop(dropWhil * // Output: [ 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropUntilEffect = /*#__PURE__*/dual(2, (self, predicate) => drop(dropWhileEffect(self, (a, i) => Effect.map(predicate(a, i), b => !b)), 1)); /** * Drops elements from the stream while the specified predicate evaluates to `true`. * - * @example + * **Example** (Dropping while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4193,8 +4584,8 @@ export const dropUntilEffect = /*#__PURE__*/dual(2, (self, predicate) => drop(dr * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropWhile = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => { let dropping = true; @@ -4210,8 +4601,23 @@ export const dropWhile = /*#__PURE__*/dual(2, (self, predicate) => transformPull /** * Drops elements while the filter succeeds. * + * **When to use** + * + * Use when you need to remove a leading stream prefix based on a synchronous + * `Filter` result while preserving the remaining original stream elements. + * + * **Details** + * + * `Result.succeed` drops the current element. The first `Result.fail` stops + * dropping, emits that original element, and the rest of the source stream is + * emitted without further filtering. + * + * @see {@link dropWhile} for boolean predicate prefix dropping + * @see {@link takeWhileFilter} for keeping the accepted prefix as filter success values + * @see {@link dropWhileEffect} for effectful predicate prefix dropping + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const dropWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => { let dropping = true; @@ -4226,7 +4632,8 @@ export const dropWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformP /** * Drops elements while the specified effectful predicate evaluates to `true`. * - * @example + * **Example** (Effectfully dropping while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4242,8 +4649,8 @@ export const dropWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformP * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => { let dropping = true; @@ -4264,9 +4671,12 @@ export const dropWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => transfo /** * Drops the last specified number of elements from this stream. * + * **Details** + * * Keeps the last `n` elements in memory to drop them on completion. * - * @example + * **Example** (Dropping values from the right) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4282,8 +4692,8 @@ export const dropWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => transfo * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropRight = /*#__PURE__*/dual(2, (self, n) => { if (n <= 0) return self; @@ -4301,7 +4711,8 @@ export const dropRight = /*#__PURE__*/dual(2, (self, n) => { /** * Exposes the underlying chunks as a stream of non-empty arrays. * - * @example + * **Example** (Exposing stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4318,16 +4729,19 @@ export const dropRight = /*#__PURE__*/dual(2, (self, n) => { * // Output: [ [ 1, 2 ], [ 3, 4 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const chunks = self => self.channel.pipe(Channel.map(Arr.of), fromChannel); /** - * Re-chunks the stream into arrays of the specified size, preserving element order. + * Groups the stream into arrays of the specified size, preserving element order. + * + * **Details** * * The size is clamped to at least 1. * - * @example + * **Example** (Rechunking stream elements) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4344,8 +4758,8 @@ export const chunks = self => self.channel.pipe(Channel.map(Arr.of), fromChannel * // Output: [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const rechunk = /*#__PURE__*/dual(2, (self, target) => { target = Math.max(1, target); @@ -4390,9 +4804,10 @@ export const rechunk = /*#__PURE__*/dual(2, (self, target) => { /** * Emits a sliding window of `n` elements. * - * @example + * **Example** (Emitting sliding windows) + * * ```ts - * import { Console, Effect, Stream, pipe } from "effect" + * import { Console, Effect, pipe, Stream } from "effect" * * Effect.gen(function*() { * const result = yield* pipe( @@ -4405,13 +4820,15 @@ export const rechunk = /*#__PURE__*/dual(2, (self, target) => { * // Output: [ [1, 2], [2, 3], [3, 4], [4, 5] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const sliding = /*#__PURE__*/dual(2, (self, chunkSize) => slidingSize(self, chunkSize, 1)); /** * Emits sliding windows of `chunkSize` elements, advancing by `stepSize`. * + * **Example** (Emitting sliding windows with a step size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4427,8 +4844,8 @@ export const sliding = /*#__PURE__*/dual(2, (self, chunkSize) => slidingSize(sel * // Output: [ [ 1, 2, 3 ], [ 3, 4, 5 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const slidingSize = /*#__PURE__*/dual(3, (self, chunkSize, stepSize) => transformPull(self, (upstream, _scope) => Effect.sync(() => { let cause = null; @@ -4466,9 +4883,12 @@ export const slidingSize = /*#__PURE__*/dual(3, (self, chunkSize, stepSize) => t /** * Splits the stream into non-empty groups whenever the predicate matches. * + * **Details** + * * Matching elements act as delimiters and are not included in the output. * - * @example + * **Example** (Splitting on matching values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4484,8 +4904,8 @@ export const slidingSize = /*#__PURE__*/dual(3, (self, chunkSize, stepSize) => t * // Output: [ [1, 2, 3], [5, 6, 7], [9] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const split = /*#__PURE__*/dual(2, (self, predicate) => mapAccumArray(self, Arr.empty, (acc, arr) => { const out = Arr.empty(); @@ -4509,10 +4929,13 @@ export const split = /*#__PURE__*/dual(2, (self, predicate) => mapAccumArray(sel * Combines elements from this stream and the specified stream by repeatedly * applying a stateful function that can pull from either side. * + * **Details** + * * Where possible, prefer `Stream.combineArray` for a more efficient * implementation. * - * @example + * **Example** (Combining streams with state) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4535,24 +4958,26 @@ export const split = /*#__PURE__*/dual(2, (self, predicate) => mapAccumArray(sel * // Output: [ "L:A", "R:1", "L:B", "R:2", "L:C", "R:3" ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const combine = /*#__PURE__*/dual(4, (self, that, s, f) => Channel.combine(Channel.flattenArray(self.channel), Channel.flattenArray(that.channel), s, f).pipe(Channel.map(Arr.of), fromChannel)); /** - * Combines the arrays (chunks) from this stream and the specified stream by - * repeatedly applying the function `f` to extract an array using both sides and - * conceptually "offer" it to the destination stream. `f` can maintain some - * internal state to control the combining process, with the initial state - * being specified by `s`. + * Combines two streams chunk-by-chunk with a stateful pull function. + * + * **When to use** * - * **Previously Known As** + * Use to coordinate pulling chunks from two streams when each emitted chunk + * depends on both sides and local state. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Stream.combineChunks` + * The combining function receives the current state and pull functions for the + * left and right streams. It returns the next non-empty chunk together with the + * next state. + * + * **Example** (Combining stream chunks with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4577,14 +5002,15 @@ export const combine = /*#__PURE__*/dual(4, (self, that, s, f) => Channel.combin * // Output: [ 1, 2, 10, 20 ] * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const combineArray = /*#__PURE__*/dual(4, (self, that, s, f) => fromChannel(Channel.combine(self.channel, that.channel, s, f))); /** - * Statefully maps elements, emitting zero or more outputs per input. + * Maps elements statefully, emitting zero or more outputs per input. + * + * **Example** (Statefully mapping stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4604,8 +5030,8 @@ export const combineArray = /*#__PURE__*/dual(4, (self, that, s, f) => fromChann * // Output: [ 0, 1, 3, 6, 10, 15, 21 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapAccum = /*#__PURE__*/dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => { const acc = Arr.empty(); @@ -4622,11 +5048,14 @@ export const mapAccum = /*#__PURE__*/dual(args => isStream(args[0]), (self, init } } : undefined))); /** - * Statefully maps over non-empty chunk arrays, emitting zero or more values per chunk. + * Maps over non-empty chunk arrays statefully, emitting zero or more values per chunk. + * + * **Details** * * The mapping function runs once per chunk and the state is threaded across chunks. * - * @example + * **Example** (Statefully mapping stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4646,8 +5075,8 @@ export const mapAccum = /*#__PURE__*/dual(args => isStream(args[0]), (self, init * // Output: [ 3, 10, 21 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ export const mapAccumArray = /*#__PURE__*/dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => { const [newState, values] = f(state, arr); @@ -4661,9 +5090,22 @@ export const mapAccumArray = /*#__PURE__*/dual(args => isStream(args[0]), (self, } : undefined))); const emptyArr = /*#__PURE__*/Arr.empty(); /** - * Statefully and effectfully maps over the elements of this stream to produce new elements. + * Maps each element statefully and effectfully, emitting zero or more output + * values per input. + * + * **When to use** + * + * Use when stateful element mapping needs Effects or can fail while emitting + * zero or more values per input element. + * + * **Details** + * + * The mapping effect receives the current state and element, then returns the + * next state plus the values to emit. The state is threaded through the + * stream. + * + * **Example** (Effectfully mapping stream values with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4682,8 +5124,8 @@ const emptyArr = /*#__PURE__*/Arr.empty(); * // Output: [ 1, 2, 3 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapAccumEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, initial, f, options) => self.channel.pipe(Channel.flattenArray, Channel.mapAccum(initial, (state, a) => Effect.map(f(state, a), ([state, values]) => [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : Arr.empty()]), options?.onHalt ? { onHalt(state) { @@ -4692,9 +5134,21 @@ export const mapAccumEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self } } : undefined), fromChannel)); /** - * Statefully and effectfully maps over chunks of this stream to emit new values. + * Maps each non-empty input chunk statefully and effectfully, emitting zero or + * more output values per chunk. + * + * **When to use** + * + * Use when stateful mapping should process each emitted non-empty chunk with an + * Effect instead of each element separately. + * + * **Details** + * + * The mapping effect receives the current state and chunk, then returns the + * next state plus the values to emit. The state is threaded across chunks. + * + * **Example** (Effectfully mapping stream chunks with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4716,8 +5170,8 @@ export const mapAccumEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self * // Output: [ 3, 10 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ export const mapAccumArrayEffect = /*#__PURE__*/dual(args => isStream(args), (self, initial, f, options) => self.channel.pipe(Channel.mapAccum(initial, (state, a) => Effect.map(f(state, a), ([state, values]) => [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : emptyArr]), options?.onHalt ? { onHalt(state) { @@ -4728,7 +5182,8 @@ export const mapAccumArrayEffect = /*#__PURE__*/dual(args => isStream(args), (se /** * Accumulates state across the stream, emitting the initial state and each updated state. * - * @example + * **Example** (Scanning stream state) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4744,8 +5199,8 @@ export const mapAccumArrayEffect = /*#__PURE__*/dual(args => isStream(args), (se * // Output: [ 0, 1, 3, 6 ] * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ export const scan = /*#__PURE__*/dual(3, (self, initial, f) => suspend(() => { let isFirst = true; @@ -4763,9 +5218,10 @@ export const scan = /*#__PURE__*/dual(3, (self, initial, f) => suspend(() => { })); })); /** - * Effectfully accumulates state and emits the initial state plus each accumulated state. + * Accumulates state effectfully and emits the initial state plus each accumulated state. + * + * **Example** (Effectfully scanning stream state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4779,14 +5235,15 @@ export const scan = /*#__PURE__*/dual(3, (self, initial, f) => suspend(() => { * }) * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ export const scanEffect = /*#__PURE__*/dual(3, (self, initial, f) => self.channel.pipe(Channel.flattenArray, Channel.scanEffect(initial, f), Channel.map(Arr.of), fromChannel)); /** * Drops earlier elements within the debounce window and emits only the latest element after the pause. * - * @example + * **Example** (Debouncing stream elements) + * * ```ts * import { Console, Duration, Effect, Stream } from "effect" * @@ -4803,8 +5260,8 @@ export const scanEffect = /*#__PURE__*/dual(3, (self, initial, f) => self.channe * }) * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const debounce = /*#__PURE__*/dual(2, (self, duration) => transformPull(self, Effect.fnUntraced(function* (pull, scope) { const clock = yield* Clock; @@ -4862,10 +5319,16 @@ export const debounce = /*#__PURE__*/dual(2, (self, duration) => transformPull(s }); }))); /** - * Delays the arrays of this stream according to the given bandwidth - * parameters using the token bucket algorithm. Allows for burst processing by - * allowing the bucket to accumulate tokens up to a `units + burst` threshold. - * The weight of each array is determined by the effectful `cost` function. + * Rate-limits stream chunks with an effectful cost function. + * + * **When to use** + * + * Use to throttle chunks when computing each chunk's cost requires an effect. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by the effectful `cost` function. * * If using the "enforce" strategy, arrays that do not meet the bandwidth * constraints are dropped. If using the "shape" strategy, arrays are delayed @@ -4873,7 +5336,8 @@ export const debounce = /*#__PURE__*/dual(2, (self, duration) => transformPull(s * * Defaults to the "shape" strategy. * - * @example + * **Example** (Throttling stream chunks effectfully) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -4894,8 +5358,8 @@ export const debounce = /*#__PURE__*/dual(2, (self, duration) => transformPull(s * // Output: [0, 1, 2, 3, 4, 5] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const throttleEffect = /*#__PURE__*/dual(2, (self, options) => { const burst = options.burst ?? 0; @@ -4959,9 +5423,16 @@ const throttleShapeEffect = (self, cost, units, duration, burst) => transformPul }))); })); /** - * Delays the arrays of this stream using a token bucket and a per-array cost. - * Allows bursts by letting the bucket accumulate up to a `units + burst` - * threshold. The weight of each array is determined by the `cost` function. + * Rate-limits stream chunks with a synchronous cost function. + * + * **When to use** + * + * Use to throttle chunks when each chunk's cost can be computed synchronously. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by `cost`. * * If using the "enforce" strategy, arrays that do not meet the bandwidth * constraints are dropped. If using the "shape" strategy, arrays are delayed @@ -4969,7 +5440,8 @@ const throttleShapeEffect = (self, cost, units, duration, burst) => transformPul * * Defaults to the "shape" strategy. * - * @example + * **Example** (Throttling stream chunks) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -4990,8 +5462,8 @@ const throttleShapeEffect = (self, cost, units, duration, burst) => transformPul * }) * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const throttle = /*#__PURE__*/dual(2, (self, options) => throttleEffect(self, { ...options, @@ -5000,9 +5472,12 @@ export const throttle = /*#__PURE__*/dual(2, (self, options) => throttleEffect(s /** * Partitions the stream into non-empty arrays of the specified size. * + * **Details** + * * The final array may be smaller if there are not enough elements to fill it. * - * @example + * **Example** (Grouping elements by size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5018,15 +5493,16 @@ export const throttle = /*#__PURE__*/dual(2, (self, options) => throttleEffect(s * // Output: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const grouped = /*#__PURE__*/dual(2, (self, n) => chunks(rechunk(self, n))); /** * Partitions the stream into arrays, emitting when the chunk size is reached * or the duration passes. * - * @example + * **Example** (Grouping elements by size or time) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5042,14 +5518,15 @@ export const grouped = /*#__PURE__*/dual(2, (self, n) => chunks(rechunk(self, n) * // Output: [ [ 1, 2 ], [ 3 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const groupedWithin = /*#__PURE__*/dual(3, (self, chunkSize, duration) => aggregateWithin(self, Sink.take(chunkSize), Schedule.spaced(duration))); /** * Groups elements into keyed substreams using an effectful classifier. * - * @example + * **Example** (Grouping elements into keyed substreams using an effectful classifier) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5074,8 +5551,8 @@ export const groupedWithin = /*#__PURE__*/dual(3, (self, chunkSize, duration) => * // Output: [ [ "odd", [ 1, 3, 5 ] ], [ "even", [ 2, 4 ] ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const groupBy = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => groupByImpl(self, Effect.fnUntraced(function* (arr, queues, queueMap) { for (let i = 0; i < arr.length; i++) { @@ -5089,7 +5566,8 @@ export const groupBy = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, op /** * Groups elements by a key and emits a stream per key. * - * @example + * **Example** (Grouping elements by key) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5112,8 +5590,8 @@ export const groupBy = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, op * // Output: [ [ "odd", [ 1, 3, 5 ] ], [ "even", [ 2, 4 ] ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const groupByKey = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => suspend(() => { const batch = MutableHashMap.empty(); @@ -5160,8 +5638,25 @@ const groupByImpl = (self, f, options) => transformPullBracket(self, Effect.fnUn return Queue.takeAll(out); })); /** + * Groups consecutive elements that have equal keys into non-empty arrays. + * + * **When to use** + * + * Use when you already have a stream ordered by the grouping key and want to + * emit each consecutive run as a non-empty array while keeping later + * non-adjacent runs separate. + * + * **Details** + * + * The key is computed with `f`; adjacent elements whose keys are equal by + * `Equal.equals` are emitted as one `[key, group]`. Later non-adjacent runs + * with the same key are emitted separately. + * + * @see {@link groupByKey} for grouping all elements with the same key across the stream + * @see {@link groupBy} for custom grouped stream construction + * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const groupAdjacentBy = /*#__PURE__*/dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => { let currentKey = undefined; @@ -5201,7 +5696,8 @@ export const groupAdjacentBy = /*#__PURE__*/dual(2, (self, f) => transformPull(s /** * Applies a sink transducer to the stream and emits each sink result. * - * @example + * **Example** (Transducing with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -5216,8 +5712,8 @@ export const groupAdjacentBy = /*#__PURE__*/dual(2, (self, f) => transformPull(s * }) * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ export const transduce = /*#__PURE__*/dual(2, (self, sink) => transformPull(self, (upstream, scope) => Effect.sync(() => { let done; @@ -5242,10 +5738,13 @@ export const transduce = /*#__PURE__*/dual(2, (self, sink) => transformPull(self /** * Aggregates elements using the provided sink and emits each sink result as a stream element. * + * **Details** + * * The stream runs the upstream and downstream in separate fibers, so the sink can keep * consuming input while downstream is busy processing the previous output. * - * @example + * **Example** (Aggregating with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -5262,16 +5761,19 @@ export const transduce = /*#__PURE__*/dual(2, (self, sink) => transformPull(self * // [ 6, 15 ] * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ export const aggregate = /*#__PURE__*/dual(2, (self, sink) => aggregateWithin(self, sink, Schedule.forever)); /** * Aggregates elements with a sink, emitting each result when the sink completes or the schedule triggers. * + * **Details** + * * The schedule can flush the current aggregation even if the sink has not finished. * - * @example + * **Example** (Aggregating with a sink and schedule) + * * ```ts * import { Console, Effect, Schedule, Sink, Stream } from "effect" * @@ -5289,8 +5791,8 @@ export const aggregate = /*#__PURE__*/dual(2, (self, sink) => aggregateWithin(se * // Output: [ 6, 15 ] * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ export const aggregateWithin = /*#__PURE__*/dual(3, (self, sink, schedule) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_upstream, _, scope) { const pull = yield* Channel.toPullScoped(self.channel, _); @@ -5348,12 +5850,67 @@ export const aggregateWithin = /*#__PURE__*/dual(3, (self, sink, schedule) => fr return Effect.succeed(Effect.suspend(() => sink.transform(sinkUpstream, scope))); }).pipe(Effect.flatMap(pull => Effect.raceFirst(catchSinkHalt(pull), stepToBuffer))); })))); +/** + * Creates a fixed-size tuple of streams that each emit + * the same elements as the source stream. + * + * **Details** + * + * The source stream starts after all downstream streams have been subscribed. + * With the default suspend strategy, the source can only advance `capacity` + * chunks ahead of the slowest downstream stream. If a downstream stream is + * interrupted, it unsubscribes from the broadcast so it no longer contributes + * backpressure. + * + * **Example** (Broadcasting to two consumers) + * + * ```ts + * import { Console, Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const [left, right] = yield* Stream.make(1, 2, 3).pipe( + * Stream.broadcastN({ n: 2, capacity: 8 }) + * ) + * + * const values = yield* Effect.all([ + * Stream.runCollect(left), + * Stream.runCollect(right) + * ], { concurrency: "unbounded" }) + * + * yield* Console.log(values) + * }) + * ) + * + * Effect.runPromise(program) + * // Output: [[1, 2, 3], [1, 2, 3]] + * ``` + * + * @category Broadcast + * @since 4.0.0 + */ +export const broadcastN = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const pubsub = yield* makePubSub(options); + const streams = new Array(options.n); + const parentScope = yield* Scope.Scope; + for (let i = 0; i < options.n; i++) { + const scope = Scope.forkUnsafe(parentScope); + const subscription = yield* PubSub.subscribe(pubsub).pipe(Effect.provideService(Scope.Scope, scope)); + streams[i] = Channel.fromEffectTake(PubSub.take(subscription)).pipe(Channel.onExit(exit => Scope.close(scope, exit)), fromChannel); + } + yield* Channel.runForEach(self.channel, value => PubSub.publish(pubsub, value)).pipe(Effect.onExit(exit => PubSub.publish(pubsub, exit)), Effect.forkScoped); + return streams; +})); +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); /** * Creates a PubSub-backed stream that multicasts the source to all subscribers. * + * **Details** + * * The returned stream is scoped and uses the provided PubSub capacity and replay settings. * - * @example + * **Example** (Broadcasting a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5377,18 +5934,21 @@ export const aggregateWithin = /*#__PURE__*/dual(3, (self, sink, schedule) => fr * // Output: [[1, 2, 3], [1, 2, 3]] * ``` * - * @since 2.0.0 * @category Broadcast + * @since 2.0.0 */ export const broadcast = /*#__PURE__*/dual(2, (self, options) => Effect.map(toPubSubTake(self, options), fromPubSubTake)); /** * Returns a new Stream that multicasts the original stream, subscribing when the first consumer starts. * + * **Details** + * * The upstream continues running while there is at least one consumer and is finalized after the last one exits. * If `idleTimeToLive` is set, the upstream is kept alive for that duration so a later subscriber can continue from * the next element instead of restarting. * - * @example + * **Example** (Sharing a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5409,8 +5969,8 @@ export const broadcast = /*#__PURE__*/dual(2, (self, options) => Effect.map(toPu * // output: [[1], [1]] * ``` * - * @since 2.0.0 * @category Broadcast + * @since 3.8.0 */ export const share = /*#__PURE__*/dual(2, (self, options) => Effect.map(RcRef.make({ acquire: broadcast(self, options), @@ -5419,10 +5979,13 @@ export const share = /*#__PURE__*/dual(2, (self, options) => Effect.map(RcRef.ma /** * Pipes this stream through a channel that consumes and emits chunked elements. * + * **Details** + * * The channel receives `NonEmptyReadonlyArray` chunks and can transform both the * output elements and error type. * - * @example + * **Example** (Piping through a channel) + * * ```ts * import { Array, Channel, Console, Effect, Stream } from "effect" * @@ -5445,54 +6008,55 @@ export const share = /*#__PURE__*/dual(2, (self, options) => Effect.map(RcRef.ma * // => [2, 4, 6] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ export const pipeThroughChannel = /*#__PURE__*/dual(2, (self, channel) => fromChannel(Channel.pipeTo(self.channel, channel))); /** * Pipes values through the provided channel while preserving this stream's * failures alongside any channel failures. * + * **Details** + * * Upstream failures are not passed to the channel, so the resulting stream can * fail with either the original stream error or the channel error. * - * @example + * **Example** (Piping through a channel with failures) + * * ```ts - * import type { Channel } from "effect" - * import { Console, Effect, Stream } from "effect" + * import { Array, Channel, Effect, Stream } from "effect" + * + * type NumberChunk = readonly [number, ...Array] * - * declare const transformChannel: Channel.Channel< - * readonly [string, ...Array], - * "ChannelError", - * unknown, - * readonly [number, ...Array], - * "StreamError", - * unknown, - * never - * > + * const stringifyChunks = Channel.identity().pipe( + * Channel.map((chunk) => Array.map(chunk, String)) + * ) * * Effect.runPromise(Effect.gen(function*() { * const result = yield* Stream.make(1, 2, 3).pipe( - * Stream.pipeThroughChannelOrFail(transformChannel), + * Stream.rechunk(2), + * Stream.pipeThroughChannelOrFail(stringifyChunks), * Stream.runCollect * ) * - * yield* Console.log(result) + * yield* Effect.sync(() => console.log(result)) * })) - * // Output: - * // ["1", "2", "3"] + * // [ "1", "2", "3" ] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ export const pipeThroughChannelOrFail = /*#__PURE__*/dual(2, (self, channel) => fromChannel(Channel.pipeToOrFail(self.channel, channel))); /** * Pipes the stream through `Sink.toChannel`, emitting only the sink leftovers. * + * **Details** + * * If the sink completes mid-chunk, the remaining elements become the output stream. * - * @example + * **Example** (Piping through a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -5509,14 +6073,15 @@ export const pipeThroughChannelOrFail = /*#__PURE__*/dual(2, (self, channel) => * //=> [ 3, 4 ] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ export const pipeThrough = /*#__PURE__*/dual(2, (self, sink) => self.channel.pipe(Channel.pipeToOrFail(Sink.toChannel(sink)), Channel.concatWith(([_, leftover]) => leftover ? Channel.succeed(leftover) : Channel.empty), fromChannel)); /** * Collects all elements into an array and emits it as a single element. * - * @example + * **Example** (Collecting values into a stream element) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5531,14 +6096,15 @@ export const pipeThrough = /*#__PURE__*/dual(2, (self, sink) => self.channel.pip * // [1, 2, 3] * ``` * - * @since 2.0.0 * @category Accumulation + * @since 4.0.0 */ export const collect = self => fromEffect(runCollect(self)); /** * Accumulates elements into a growing array, emitting the cumulative array for each input chunk. * - * @example + * **Example** (Accumulating stream elements) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5556,8 +6122,8 @@ export const collect = self => fromEffect(runCollect(self)); * //=> { _id: 'Chunk', values: [ [ 1 ], [ 1, 2 ], [ 1, 2, 3 ] ] } * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ export const accumulate = self => mapAccumArray(self, Arr.empty, (acc, as) => { const combined = Arr.appendAll(acc, as); @@ -5566,7 +6132,8 @@ export const accumulate = self => mapAccumArray(self, Arr.empty, (acc, as) => { /** * Emits only elements that differ from the previous one. * - * @example + * **Example** (Emitting changed values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5583,14 +6150,15 @@ export const accumulate = self => mapAccumArray(self, Arr.empty, (acc, as) => { * // [1, 2, 3] * ``` * - * @since 2.0.0 * @category Deduplication + * @since 2.0.0 */ export const changes = self => changesWith(self, Equal.equals); /** * Returns a stream that only emits elements that are not equal to the previously emitted element, as determined by the specified predicate. * - * @example + * **Example** (Emitting values that changed by equivalence) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5607,8 +6175,8 @@ export const changes = self => changesWith(self, Equal.equals); * // ["A", "B"] * ``` * - * @since 2.0.0 * @category Deduplication + * @since 2.0.0 */ export const changesWith = /*#__PURE__*/dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => { let first = true; @@ -5634,9 +6202,12 @@ export const changesWith = /*#__PURE__*/dual(2, (self, f) => transformPull(self, /** * Emits only elements that differ from the previous element, using an effectful equality check. * + * **Details** + * * The predicate runs for each element after the first; returning `true` treats it as equal and skips it. * - * @example + * **Example** (Effectfully emitting changed values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5652,8 +6223,8 @@ export const changesWith = /*#__PURE__*/dual(2, (self, f) => transformPull(self, * // { _id: "Chunk", values: [ 1, 2, 3 ] } * ``` * - * @since 2.0.0 * @category Deduplication + * @since 2.0.0 */ export const changesWithEffect = /*#__PURE__*/dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => { let first = true; @@ -5679,7 +6250,8 @@ export const changesWithEffect = /*#__PURE__*/dual(2, (self, f) => transformPull /** * Decodes Uint8Array chunks into strings using TextDecoder with an optional encoding. * - * @example + * **Example** (Decoding Uint8Array chunks into strings using TextDecoder with an optional encoding) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5701,8 +6273,8 @@ export const changesWithEffect = /*#__PURE__*/dual(2, (self, f) => transformPull * // ["Hello", " World"] * ``` * + * @category encoding * @since 2.0.0 - * @category Encoding */ export const decodeText = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => suspend(() => { const decoder = new TextDecoder(options?.encoding); @@ -5713,7 +6285,8 @@ export const decodeText = /*#__PURE__*/dual(args => isStream(args[0]), (self, op /** * Encodes a stream of strings into UTF-8 `Uint8Array` chunks. * - * @example + * **Example** (Encoding a stream of strings into UTF-8 Uint8Array chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5729,8 +6302,8 @@ export const decodeText = /*#__PURE__*/dual(args => isStream(args[0]), (self, op * // [[72, 101, 108, 108, 111], [32], [87, 111, 114, 108, 100]] * ``` * + * @category encoding * @since 2.0.0 - * @category Encoding */ export const encodeText = self => suspend(() => { const encoder = new TextEncoder(); @@ -5739,7 +6312,8 @@ export const encodeText = self => suspend(() => { /** * Splits a stream of strings into lines, handling `\n`, `\r`, and `\r\n` delimiters across chunks. * - * @example + * **Example** (Splitting streamed text into lines) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5752,14 +6326,15 @@ export const encodeText = self => suspend(() => { * // ["a", "b", "c"] * ``` * + * @category encoding * @since 2.0.0 - * @category Encoding */ export const splitLines = self => self.channel.pipe(Channel.pipeTo(Channel.splitLines()), fromChannel); /** * Inserts the provided element between emitted elements. * - * @example + * **Example** (Interspersing stream elements) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5773,8 +6348,8 @@ export const splitLines = self => self.channel.pipe(Channel.pipeTo(Channel.split * // [1, 0, 2, 0, 3, 0, 4] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const intersperse = /*#__PURE__*/dual(2, (self, element) => mapArray(self, (arr, i) => { const out = i === 0 ? [] : [element]; @@ -5789,11 +6364,14 @@ export const intersperse = /*#__PURE__*/dual(2, (self, element) => mapArray(self return out; })); /** - * Intersperse stream elements with a middle value, adding a start and end value. + * Adds a start value, middle value, and end value around stream elements. + * + * **Details** * * The start and end values are always emitted, even when the stream is empty. * - * @example + * **Example** (Interspersing stream affixes) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5810,8 +6388,8 @@ export const intersperse = /*#__PURE__*/dual(2, (self, element) => mapArray(self * // [ "[", "a", ",", "b", ",", "c", "]" ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const intersperseAffixes = /*#__PURE__*/dual(2, (self, options) => succeed(options.start).pipe(concat(intersperse(self, options.middle)), concat(succeed(options.end)))); /** @@ -5819,7 +6397,8 @@ export const intersperseAffixes = /*#__PURE__*/dual(2, (self, options) => succee * each stream; when one ends, the remaining values from the other stream are * emitted. * - * @example + * **Example** (Interleaving streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5836,17 +6415,21 @@ export const intersperseAffixes = /*#__PURE__*/dual(2, (self, options) => succee * Effect.runPromise(program) * // [2, 5, 3, 6, 7] * ``` + * + * @category merging * @since 2.0.0 - * @category Merging */ export const interleave = /*#__PURE__*/dual(2, (self, that) => interleaveWith(self, that, fromIterable(Iterable.forever([true, false])))); /** * Interleaves two streams deterministically by following a boolean decider stream. * + * **Details** + * * The decider controls how many elements are pulled; if one side ends, pulls for * that side are ignored. * - * @example + * **Example** (Interleaving two streams deterministically by following a boolean decider stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5866,8 +6449,8 @@ export const interleave = /*#__PURE__*/dual(2, (self, that) => interleaveWith(se * // [ 1, 2, 4, 3, 5 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const interleaveWith = /*#__PURE__*/dual(3, (self, that, decider) => fromChannel(Channel.fromTransform(Effect.fnUntraced(function* (upstream, scope) { const pullDecider = yield* Channel.toTransform(Channel.flattenArray(decider.channel))(upstream, scope); @@ -5902,10 +6485,13 @@ export const interleaveWith = /*#__PURE__*/dual(3, (self, that, decider) => from * success will be discarded. This combinator will also interrupt any * in-progress element being pulled from upstream. * + * **Details** + * * If the effect completes with a failure before the stream completes, the * returned stream will emit that failure. * - * @example + * **Example** (Interrupting when an effect completes) + * * ```ts * import { Console, Deferred, Effect, Stream } from "effect" * @@ -5928,14 +6514,29 @@ export const interleaveWith = /*#__PURE__*/dual(3, (self, that, decider) => from * // => [1, 2] * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const interruptWhen = /*#__PURE__*/dual(2, (self, effect) => fromChannel(Channel.interruptWhen(self.channel, effect))); /** - * Halts evaluation after the current element once the provided effect completes; the effect is forked, its success is discarded, failures fail the stream, and it does not interrupt an in-progress pull (use `interruptWhen` for that). + * Stops a stream after the current element when an effect completes. + * + * **When to use** + * + * Use to stop before the next pull after an external signal completes. + * + * **Details** + * + * The effect is forked, its success value is discarded, and its failure fails + * the stream. + * + * **Gotchas** + * + * This does not interrupt an in-progress pull. Use {@link interruptWhen} when + * the stream should be interrupted immediately. + * + * **Example** (Halting a stream after an effect completes) * - * @example * ```ts * import { Console, Deferred, Effect, Stream } from "effect" * @@ -5954,14 +6555,15 @@ export const interruptWhen = /*#__PURE__*/dual(2, (self, effect) => fromChannel( * // [1, 2] * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const haltWhen = /*#__PURE__*/dual(2, (self, effect) => fromChannel(Channel.haltWhen(self.channel, effect))); /** * Runs the provided finalizer when the stream exits, passing the exit value. * - * @example + * **Example** (Running a finalizer on exit) + * * ```ts * import { Console, Effect, Exit, Stream } from "effect" * @@ -5980,17 +6582,20 @@ export const haltWhen = /*#__PURE__*/dual(2, (self, effect) => fromChannel(Chann * // Stream completed successfully * ``` * - * @since 4.0.0 * @category Finalization + * @since 4.0.0 */ export const onExit = /*#__PURE__*/dual(2, (self, finalizer) => fromChannel(Channel.onExit(self.channel, finalizer))); /** * Runs the provided effect when the stream fails, passing the failure cause. * + * **Gotchas** + * * Note: Unlike `Effect.onError` there is no guarantee that the provided * effect will not be interrupted. * - * @example + * **Example** (Running an effect on errors) + * * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -6008,14 +6613,15 @@ export const onExit = /*#__PURE__*/dual(2, (self, finalizer) => fromChannel(Chan * // Stream failed: boom * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const onError = /*#__PURE__*/dual(2, (self, cleanup) => fromChannel(Channel.onError(self.channel, cleanup))); /** * Runs the provided effect before this stream starts. * - * @example + * **Example** (Running an effect on start) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6034,14 +6640,15 @@ export const onError = /*#__PURE__*/dual(2, (self, cleanup) => fromChannel(Chann * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 3.6.0 */ export const onStart = /*#__PURE__*/dual(2, (self, onStart) => fromChannel(Channel.onStart(self.channel, onStart))); /** * Runs the provided effect with the first element emitted by the stream. * - * @example + * **Example** (Running an effect on the first value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6054,14 +6661,15 @@ export const onStart = /*#__PURE__*/dual(2, (self, onStart) => fromChannel(Chann * // Output: first=1 * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const onFirst = /*#__PURE__*/dual(2, (self, onFirst) => fromChannel(Channel.onFirst(self.channel, arr => onFirst(arr[0])))); /** * Runs the provided effect when the stream ends successfully. * - * @example + * **Example** (Running an effect on end) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6078,14 +6686,15 @@ export const onFirst = /*#__PURE__*/dual(2, (self, onFirst) => fromChannel(Chann * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 3.6.0 */ export const onEnd = /*#__PURE__*/dual(2, (self, onEnd) => fromChannel(Channel.onEnd(self.channel, onEnd))); /** * Executes the provided finalizer after this stream's finalizers run. * - * @example + * **Example** (Ensuring finalization) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6103,8 +6712,8 @@ export const onEnd = /*#__PURE__*/dual(2, (self, onEnd) => fromChannel(Channel.o * //=> [1, 2] * ``` * - * @since 4.0.0 * @category Finalization + * @since 2.0.0 */ export const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => fromChannel(Channel.ensuring(self.channel, finalizer))); /** @@ -6112,11 +6721,10 @@ export const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => fromChannel(Ch * service requirements. Use `options.local` to build the layer every time; by * default, layers are shared between provide calls. * - * **Previously Known As:** `provideSomeLayer`, `provideSomeContext`. + * **Example** (Providing stream requirements) * - * @example * ```ts - * import { Console, Effect, Layer, Context, Stream } from "effect" + * import { Console, Context, Effect, Layer, Stream } from "effect" * * class Env extends Context.Service()("Env") {} * @@ -6140,16 +6748,17 @@ export const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => fromChannel(Ch * // ["Hello, Ada"] * ``` * + * @category services * @since 4.0.0 - * @category Services */ export const provide = /*#__PURE__*/dual(args => isStream(args[0]), (self, layer, options) => fromChannel(Channel.provide(self.channel, layer, options))); /** * Provides multiple services to the stream using a context. * - * @example + * **Example** (Providing multiple services to the stream using a context) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Config extends Context.Service()("Config") {} * class Greeter extends Context.Service string }>()("Greeter") {} @@ -6175,17 +6784,18 @@ export const provide = /*#__PURE__*/dual(args => isStream(args[0]), (self, layer * // ["Hello!"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ export const provideContext = /*#__PURE__*/dual(2, (self, context) => fromChannel(Channel.provideContext(self.channel, context))); /** * Provides the stream with a single required service, eliminating that * requirement from its environment. * - * @example + * **Example** (Providing a stream service) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Greeter extends Context.Service string @@ -6212,16 +6822,17 @@ export const provideContext = /*#__PURE__*/dual(2, (self, context) => fromChanne * //=> ["Hello, Ada"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ export const provideService = /*#__PURE__*/dual(3, (self, key, service) => fromChannel(Channel.provideService(self.channel, key, service))); /** * Provides a service to the stream using an effect, removing the requirement and adding the effect's error and environment. * - * @example + * **Example** (Providing a stream service effectfully) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class ApiConfig extends Context.Service()("ApiConfig") {} * @@ -6251,17 +6862,18 @@ export const provideService = /*#__PURE__*/dual(3, (self, key, service) => fromC * // ["https://example.com"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ export const provideServiceEffect = /*#__PURE__*/dual(3, (self, key, service) => fromChannel(Channel.provideServiceEffect(self.channel, key, service))); /** * Transforms the stream's required services by mapping the current context * to a new one. * - * @example + * **Example** (Updating the stream context) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Logger extends Context.Service()("Logger") {} * class Config extends Context.Service()("Config") {} @@ -6291,16 +6903,17 @@ export const provideServiceEffect = /*#__PURE__*/dual(3, (self, key, service) => * //=> [ "Hello World" ] * ``` * - * @since 2.0.0 - * @category Services + * @category services + * @since 4.0.0 */ export const updateContext = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.updateContext(self.channel, f))); /** * Updates a single service in the stream environment by applying a function. * - * @example + * **Example** (Updating a stream service) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Counter extends Context.Service()("Counter") {} * @@ -6317,14 +6930,15 @@ export const updateContext = /*#__PURE__*/dual(2, (self, f) => fromChannel(Chann * // Output: Updated count: 1 * ``` * + * @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))))); /** * Wraps the stream with a new span for tracing. * - * @example + * **Example** (Wrapping a stream in a span) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6339,8 +6953,8 @@ export const updateService = /*#__PURE__*/dual(3, (self, service, f) => updateCo * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Tracing + * @category tracing + * @since 2.0.0 */ export const withSpan = function () { const dataFirst = isStream(arguments[0]); @@ -6355,9 +6969,10 @@ export const withSpan = function () { /** * Provides the entry point for do-notation style stream composition. * - * @example + * **Example** (Starting stream do notation) + * * ```ts - * import { Console, Effect, Stream, pipe } from "effect" + * import { Console, Effect, pipe, Stream } from "effect" * * const program = pipe( * Stream.Do, @@ -6374,8 +6989,8 @@ export const withSpan = function () { * //=> [{ value: 1, next: 2 }, { value: 2, next: 3 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ export const Do = /*#__PURE__*/succeed({}); const let_ = /*#__PURE__*/dual(3, (self, name, f) => map(self, a => ({ @@ -6386,7 +7001,8 @@ export { /** * Adds a computed field to the current Do-notation record. * - * @example + * **Example** (Adding a computed field) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6404,14 +7020,15 @@ export { * // [{ x: 2, y: 6 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ let_ as let }; /** * Binds the result of a stream to a field in the do-notation record. * - * @example + * **Example** (Binding a stream value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6426,8 +7043,8 @@ let_ as let }; * // [{ a: 1, b: 2 }, { a: 2, b: 3 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ export const bind = /*#__PURE__*/dual(args => isStream(args[0]), (self, tag, f, options) => flatMap(self, a => map(f(a), b => ({ ...a, @@ -6436,7 +7053,8 @@ export const bind = /*#__PURE__*/dual(args => isStream(args[0]), (self, tag, f, /** * Binds an Effect-produced value into the do-notation record for each stream element. * - * @example + * **Example** (Binding an effect value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6454,8 +7072,8 @@ export const bind = /*#__PURE__*/dual(args => isStream(args[0]), (self, tag, f, * // [{ value: 1, double: 2 }, { value: 2, double: 4 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ export const bindEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, tag, f, options) => mapEffect(self, a => Effect.map(f(a), b => ({ ...a, @@ -6464,7 +7082,8 @@ export const bindEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, ta /** * Maps each element into a record keyed by the provided name. * - * @example + * **Example** (Binding values to a record key) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6476,8 +7095,8 @@ export const bindEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, ta * // [{ value: 1 }, { value: 2 }, { value: 3 }] * ``` * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ export const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, a => ({ [name]: a @@ -6485,7 +7104,8 @@ export const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, a => ({ /** * Runs a stream with a sink and returns the sink result. * - * @example + * **Example** (Running a stream with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -6495,14 +7115,15 @@ export const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, a => ({ * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const run = /*#__PURE__*/dual(2, (self, sink) => Effect.scopedWith(scope => Channel.toPullScoped(self.channel, scope).pipe(Effect.flatMap(upstream => sink.transform(upstream, scope)), Effect.map(([a]) => a)))); /** * Runs the stream and collects all elements into an array. * - * @example + * **Example** (Collecting stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6517,8 +7138,8 @@ export const run = /*#__PURE__*/dual(2, (self, sink) => Effect.scopedWith(scope * // [1, 2, 3, 4, 5] * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runCollect = self => Channel.runFold(self.channel, () => [], (acc, chunk) => { for (let i = 0; i < chunk.length; i++) { @@ -6529,7 +7150,8 @@ export const runCollect = self => Channel.runFold(self.channel, () => [], (acc, /** * Runs the stream and returns the number of elements emitted. * - * @example + * **Example** (Counting stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6544,14 +7166,15 @@ export const runCollect = self => Channel.runFold(self.channel, () => [], (acc, * // 5 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runCount = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => acc + chunk.length); /** * Runs the stream and returns the numeric sum of its elements. * - * @example + * **Example** (Summing stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6564,8 +7187,8 @@ export const runCount = self => Channel.runFold(self.channel, () => 0, (acc, chu * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runSum = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => { for (let i = 0; i < chunk.length; i++) { @@ -6576,7 +7199,8 @@ export const runSum = self => Channel.runFold(self.channel, () => 0, (acc, chunk /** * Runs the stream and folds elements using a pure reducer. * - * @example + * **Example** (Folding stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6593,8 +7217,8 @@ export const runSum = self => Channel.runFold(self.channel, () => 0, (acc, chunk * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runFold = /*#__PURE__*/dual(3, (self, initial, f) => Channel.runFold(self.channel, initial, (acc, arr) => { for (let i = 0; i < arr.length; i++) { @@ -6605,7 +7229,13 @@ export const runFold = /*#__PURE__*/dual(3, (self, initial, f) => Channel.runFol /** * Runs the stream and folds elements using an effectful reducer. * - * @example + * **When to use** + * + * Use when reducing stream elements needs Effects, services, or failures in the + * reducer. + * + * **Example** (Effectfully folding stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6622,8 +7252,8 @@ export const runFold = /*#__PURE__*/dual(3, (self, initial, f) => Channel.runFol * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Channel.runFoldEffect(self.channel, initial, (acc, arr) => { let i = 0; @@ -6640,7 +7270,8 @@ export const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Channel. /** * Runs the stream and returns the first element as an `Option`. * - * @example + * **Example** (Getting the first stream value) + * * ```ts * import { Console, Effect, Option, Stream } from "effect" * @@ -6653,21 +7284,40 @@ export const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Channel. * // 1 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runHead = self => Effect.map(Channel.runHead(self.channel), Option.map(Arr.getUnsafe(0))); /** * Runs the stream and returns the last element as an `Option`. * + * **When to use** + * + * Use to consume a finite stream when only the final emitted element matters. + * + * **Details** + * + * `Option.some` contains the last emitted element. `Option.none` means the + * stream completed without emitting. + * + * **Gotchas** + * + * The returned effect waits for the stream to complete before it can produce a + * value. + * + * @see {@link runHead} for consuming only the first emitted element + * @see {@link runCollect} for collecting every emitted element + * @see {@link runDrain} for consuming the stream while discarding emitted elements + * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runLast = self => Effect.map(Channel.runLast(self.channel), Option.map(Arr.lastNonEmpty)); /** * Runs the provided effectful callback for each element of the stream. * - * @example + * **Example** (Running an effect for each value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6683,8 +7333,8 @@ export const runLast = self => Effect.map(Channel.runLast(self.channel), Option. * // Processing: 3 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runForEach = /*#__PURE__*/dual(2, (self, f) => Channel.runForEach(self.channel, arr => { let i = 0; @@ -6698,7 +7348,8 @@ export const runForEach = /*#__PURE__*/dual(2, (self, f) => Channel.runForEach(s * Runs the stream, applying the effectful predicate to each element and * stopping when it returns `false`. * - * @example + * **Example** (Running effects while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6719,8 +7370,8 @@ export const runForEach = /*#__PURE__*/dual(2, (self, f) => Channel.runForEach(s * // Processing: 3 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => Channel.runForEachWhile(self.channel, arr => { let done = false; @@ -6737,7 +7388,8 @@ export const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => Channel.runForE /** * Consumes the stream in chunks, passing each non-empty array to the callback. * - * @example + * **Example** (Consuming stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6753,14 +7405,15 @@ export const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => Channel.runForE * // Processing chunk: 1, 2, 3, 4, 5 * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ export const runForEachArray = /*#__PURE__*/dual(2, (self, f) => Channel.runForEach(self.channel, f)); /** * Runs the stream for its effects, discarding emitted elements. * - * @example + * **Example** (Draining a stream run) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6778,17 +7431,20 @@ export const runForEachArray = /*#__PURE__*/dual(2, (self, f) => Channel.runForE * // Processing: 3 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runDrain = self => Channel.runDrain(self.channel); /** * Returns a scoped pull for manually consuming the stream's output chunks. * + * **Details** + * * The pull fails with `Cause.Done` when the stream ends and with the stream * error on failure. * - * @example + * **Example** (Creating a scoped pull) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6806,14 +7462,15 @@ export const runDrain = self => Channel.runDrain(self.channel); * // [1, 2, 3] * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toPull = self => Channel.toPull(self.channel); /** * Concatenates all emitted strings into a single string. * - * @example + * **Example** (Joining strings from a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6827,14 +7484,15 @@ export const toPull = self => Channel.toPull(self.channel); * // Hello World! * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const mkString = self => Channel.runFold(self.channel, () => "", (acc, chunk) => acc + chunk.join("")); /** * Concatenates the stream's `Uint8Array` chunks into a single `Uint8Array`. * - * @example + * **Example** (Joining Uint8Array chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6848,8 +7506,8 @@ export const mkString = self => Channel.runFold(self.channel, () => "", (acc, ch * // [1, 2, 3, 4] * ``` * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const mkUint8Array = self => Effect.map(Channel.runFold(self.channel, () => ({ bytes: 0, @@ -6876,9 +7534,17 @@ export const mkUint8Array = self => Effect.map(Channel.runFold(self.channel, () /** * Converts the stream to a `ReadableStream` using the provided services. * + * **When to use** + * + * Use when bridging to Web Streams and you already have the `Context` required + * to run the stream outside an `Effect`. + * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Converting to a ReadableStream with services) + * * ```ts * import { Context, Stream } from "effect" * @@ -6886,8 +7552,8 @@ export const mkUint8Array = self => Effect.map(Channel.runFold(self.channel, () * const readableStream = Stream.toReadableStreamWith(stream, Context.empty()) * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ export const toReadableStreamWith = /*#__PURE__*/dual(args => isStream(args[0]), (self, context, options) => { let currentResolve = undefined; @@ -6926,9 +7592,12 @@ export const toReadableStreamWith = /*#__PURE__*/dual(args => isStream(args[0]), /** * Converts a stream to a `ReadableStream`. * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Converting a stream to a ReadableStream) + * * ```ts * import { Stream } from "effect" * @@ -6936,16 +7605,24 @@ export const toReadableStreamWith = /*#__PURE__*/dual(args => isStream(args[0]), * const reader = readableStream.getReader() * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toReadableStream = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => toReadableStreamWith(self, Context.empty(), options)); /** * Creates an Effect that builds a ReadableStream from the stream. * + * **When to use** + * + * Use when bridging to Web Streams from inside an `Effect` so the required + * services can be captured from the current context. + * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Creating a ReadableStream effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6959,14 +7636,20 @@ export const toReadableStream = /*#__PURE__*/dual(args => isStream(args[0]), (se * Effect.runPromise(effect) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toReadableStreamEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => Effect.map(Effect.context(), context => toReadableStreamWith(self, context, options))); /** * Converts the stream to an `AsyncIterable` using the provided services. * - * @example + * **When to use** + * + * Use when converting outside an Effect and you already have the `Context` + * needed to run the stream. + * + * **Example** (Converting to an AsyncIterable with services) + * * ```ts * import { Context, Stream } from "effect" * @@ -6978,12 +7661,15 @@ export const toReadableStreamEffect = /*#__PURE__*/dual(args => isStream(args[0] * for await (const value of iterable) { * results.push(value) * } - * return results + * console.log(results) * } + * + * collect() + * // [ 1, 2, 3 ] * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ export const toAsyncIterableWith = /*#__PURE__*/dual(2, (self, context) => ({ [Symbol.asyncIterator]() { @@ -7024,9 +7710,15 @@ export const toAsyncIterableWith = /*#__PURE__*/dual(2, (self, context) => ({ /** * Creates an effect that yields an `AsyncIterable` using the current services. * - * @example + * **When to use** + * + * Use when the `AsyncIterable` should be created inside Effect with the current + * context supplying the stream's services. + * + * **Example** (Creating an AsyncIterable effect) + * * ```ts - * import { Console, Effect, Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3) * @@ -7039,50 +7731,54 @@ export const toAsyncIterableWith = /*#__PURE__*/dual(2, (self, context) => ({ * } * return collected * }) - * yield* Console.log(values) + * yield* Effect.sync(() => console.log(values)) * }) * * Effect.runPromise(program) - * //=> [ 1, 2, 3 ] + * // [ 1, 2, 3 ] * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 3.15.0 */ export const toAsyncIterableEffect = self => Effect.map(Effect.context(), context => toAsyncIterableWith(self, context)); /** * Converts a stream to an `AsyncIterable` for `for await...of` consumption. * - * @example + * **Example** (Converting to an async iterable) + * * ```ts - * import { Effect, Stream } from "effect" + * import { Stream } from "effect" * * const stream = Stream.make(1, 2, 3) * - * const program = Effect.gen(function* () { + * const collect = async () => { * const iterable = Stream.toAsyncIterable(stream) - * const results = yield* Effect.promise(async () => { - * const values: Array = [] - * for await (const value of iterable) { - * values.push(value) - * } - * return values - * }) - * return results - * }) + * const values: Array = [] + * for await (const value of iterable) { + * values.push(value) + * } + * console.log(values) + * } + * + * collect() + * // [ 1, 2, 3 ] * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 3.15.0 */ export const toAsyncIterable = self => toAsyncIterableWith(self, Context.empty()); /** * Runs the stream, publishing elements into the provided PubSub. * + * **Details** + * * `shutdownOnEnd` controls whether the PubSub is shut down when the stream ends. * It only shuts down when set to `true`. * - * @example + * **Example** (Running a stream into a PubSub) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -7104,17 +7800,20 @@ export const toAsyncIterable = self => toAsyncIterableWith(self, Context.empty() * //=> 2 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runIntoPubSub = /*#__PURE__*/dual(args => isStream(args[0]), (self, pubsub, options) => Channel.runIntoPubSubArray(self.channel, pubsub, options)); /** - * Converts a stream to a PubSub for concurrent consumption. + * Converts a stream to a PubSub of emitted values for concurrent consumption. + * + * **Details** * * `shutdownOnEnd` indicates whether the PubSub should be shut down when the * stream ends. By default this is `true`. * - * @example + * **Example** (Converting a stream to a PubSub for concurrent consumption) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -7129,16 +7828,19 @@ export const runIntoPubSub = /*#__PURE__*/dual(args => isStream(args[0]), (self, * })) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toPubSub = /*#__PURE__*/dual(2, (self, options) => Channel.toPubSubArray(self.channel, options)); /** - * Converts a stream to a PubSub for concurrent consumption. + * Converts a stream to a PubSub of `Take` values for concurrent consumption. + * + * **Details** * * `Take` values include the stream's end and failure signals. * - * @example + * **Example** (Converting to a PubSub of takes) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -7155,14 +7857,22 @@ export const toPubSub = /*#__PURE__*/dual(2, (self, options) => Channel.toPubSub * }) * ``` * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toPubSubTake = /*#__PURE__*/dual(2, (self, options) => Channel.toPubSubTake(self.channel, options)); /** - * Converts a stream to a Queue for concurrent consumption. + * Creates a scoped dequeue that is fed by the stream for concurrent + * consumption. + * + * **Details** + * + * Elements are offered to the queue as the stream runs. Stream completion is + * signaled with `Cause.Done`, stream failures fail the queue, and the queue is + * shut down when the surrounding scope closes. + * + * **Example** (Converting a stream to a Queue for concurrent consumption) * - * @example * ```ts * import { Effect, Queue, Stream } from "effect" * @@ -7173,15 +7883,16 @@ export const toPubSubTake = /*#__PURE__*/dual(2, (self, options) => Channel.toPu * }) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toQueue = /*#__PURE__*/dual(2, (self, options) => Channel.toQueueArray(self.channel, options)); /** * Runs the stream, offering each element to the provided queue and ending it * with `Cause.Done` when the stream completes. * - * @example + * **Example** (Running a stream into a queue) + * * ```ts * import { Cause, Effect, Queue, Stream } from "effect" * @@ -7203,8 +7914,8 @@ export const toQueue = /*#__PURE__*/dual(2, (self, options) => Channel.toQueueAr * }) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runIntoQueue = /*#__PURE__*/dual(2, (self, queue) => Channel.runIntoQueueArray(self.channel, queue)); //# sourceMappingURL=Stream.js.map \ No newline at end of file