clanka 0.7.3 → 0.7.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Acp.d.ts +10 -0
- package/dist/Acp.d.ts.map +1 -1
- package/dist/Acp.js +1 -2
- package/dist/Acp.js.map +1 -1
- package/dist/AgentTools.d.ts.map +1 -1
- package/dist/AgentTools.js +1 -2
- package/dist/AgentTools.js.map +1 -1
- package/dist/GlobalWebSocket.d.ts +15 -0
- package/dist/GlobalWebSocket.d.ts.map +1 -0
- package/dist/GlobalWebSocket.js +26 -0
- package/dist/GlobalWebSocket.js.map +1 -0
- package/dist/WebToMarkdown.d.ts.map +1 -1
- package/dist/WebToMarkdown.js +8 -4
- package/dist/WebToMarkdown.js.map +1 -1
- package/dist/bin/Effect-DdkIoNCD.mjs +5058 -0
- package/dist/bin/Effect-DdkIoNCD.mjs.map +1 -0
- package/dist/bin/{McpClient-D6vFD-wP.mjs → McpClient-CJ0Vugoi.mjs} +582 -2896
- package/dist/bin/{McpClient-D6vFD-wP.mjs.map → McpClient-CJ0Vugoi.mjs.map} +1 -1
- package/dist/bin/OutputFormatter-DN8OGwuK.mjs +575 -0
- package/dist/bin/OutputFormatter-DN8OGwuK.mjs.map +1 -0
- package/dist/bin/Schema-BALIXGp7.mjs +5475 -0
- package/dist/bin/Schema-BALIXGp7.mjs.map +1 -0
- package/dist/bin/{SemanticSearch-D9iZ_Mi9.mjs → SemanticSearch-O6PZBRfd.mjs} +147 -1160
- package/dist/bin/{SemanticSearch-D9iZ_Mi9.mjs.map → SemanticSearch-O6PZBRfd.mjs.map} +1 -1
- package/dist/bin/Stream-B5ebASRi.mjs +2090 -0
- package/dist/bin/Stream-B5ebASRi.mjs.map +1 -0
- package/dist/bin/cli.mjs +9629 -41431
- package/dist/bin/cli.mjs.map +1 -1
- package/dist/bin/index.min-CI3qqohw.mjs +3300 -0
- package/dist/bin/index.min-CI3qqohw.mjs.map +1 -0
- package/dist/bin/turndown.cjs-usmCKZ4b.mjs +15195 -0
- package/dist/bin/turndown.cjs-usmCKZ4b.mjs.map +1 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +10 -6
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/package.json +2 -4
- package/src/Acp.ts +1 -2
- package/src/AgentTools.ts +3 -2
- package/src/GlobalWebSocket.ts +40 -0
- package/src/WebToMarkdown.ts +17 -7
- package/src/cli.ts +15 -6
- package/src/index.ts +5 -0
- package/dist/bin/Schema-D6y3R-At.mjs +0 -28728
- package/dist/bin/Schema-D6y3R-At.mjs.map +0 -1
- package/dist/bin/Undici-ChB4UBDa.mjs +0 -28
- package/dist/bin/Undici-ChB4UBDa.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Stream-B5ebASRi.mjs","names":["Number","Option.some","Option.none","predicate.isString","effect.fiberAwait","effect.fiberJoin","effect.fiberInterrupt","effect.fiberInterruptAs","effect.fiberInterruptAll","effect.fiberInterruptAllAs","effect.getCurrentFiber","effect.fiberRunIn","makeUnsafe","internal.makeLatchUnsafe","make","internal.makeLatch","TypeId","make","make","Arr.fromIterable","Count.normalize","takeAll","take","filter","TypeId","make","Effect.sync","Scope.makeUnsafe","Latch.makeUnsafe","MutableRef.make","bounded","unbounded","shutdown","Effect.uninterruptible","Effect.withFiber","Scope.close","Exit.interrupt","Effect.andThen","Effect.when","Effect.asVoid","Effect.suspend","Effect.succeed","Effect.contextWith","Context.get","Scope.Scope","Scope.forkUnsafe","Scope.addFinalizer","Scope.addFinalizerExit","Effect.as","Effect.forEach","MutableList.takeAll","Deferred.interruptWith","Effect.tap","take","Effect.interrupt","MutableList.Empty","takeAll","Arr.isArrayNonEmpty","Effect.flatMap","Deferred.makeUnsafe","Effect.onInterrupt","Deferred.await","Effect.void","MutableList.make","Arr.fromIterable","Count.normalize","MutableRef.get","MutableList.take","Exit.succeed","TypeId","make","core.withFiber","MutableList.make","internalEffect.succeed","internalEffect.suspend","Arr.fromIterable","core.exitSucceed","fail","failCause","core.causeFail","internalEffect.sync","core.exitFailCause","internalEffect.exitZipRight","core.Done","Count.normalize","internalEffect.andThen","take","Option.none","Option.some","MutableList.take","internalEffect.exitVoid","MutableList.takeN","internalEffect.callback","Pull.isDoneCause","internal.callback","internal.sync","internal.suspend","internal.succeed","core.withFiber","internal.void","internal.uninterruptibleMask","internal.flatMap","internal.onExitPrimitive","internal.getCurrentFiber","internal.succeedNone","internal.asSome","Exit.isExit","Exit.isSuccess","Cause.done","Effect.succeed","TypeId","identity_","Effect.catchCause","Effect.succeed","Effect.failCause","transformPull","Effect.flatMap","fromPull","Effect.fnUntraced","Scope.forkUnsafe","Scope.close","Pull.doneExitFromCause","Effect.onError","Queue.make","Effect.tap","Scope.addFinalizer","Queue.shutdown","Effect.forkIn","Scope.provide","Effect.map","Queue.takeAll","suspend","Effect.suspend","Count.normalizeNonEmpty","Effect.sync","done","Option.none","Cause.done","Option.some","succeed","fromEffect","empty","fail","Effect.fail","die","Cause.die","Take.toPull","Effect.onInterrupt","PubSub.takeAll","unwrap","PubSub.subscribe","fromPubSubTake","PubSub.take","fromReadableStream","MutableRef.make","Effect.matchCauseEffect","Effect.tryPromise","Arr.of","Effect.as","Effect.promise","map","Pull.catchDone","mapEffect","Queue.bounded","Effect.runForkWith","Effect.context","Fiber.runIn","Semaphore.makeUnsafe","Queue.failCause","Queue.offer","Effect.void","Effect.forever","Queue.take","Effect.flatten","Fiber.join","Exit.failCause","Effect.andThen","flatMap","Effect.flatMapEager","close","Exit.void","mergeAll","Arr.isReadonlyArrayNonEmpty","Result.isSuccess","Pull.isDoneCause","Result.isFailure","catch_","Cause.findError","catchIf","catchFilter","catchReason","mapError","orDie","Latch.make","Effect.gen","Effect.forkChild","Effect.raceFirst","Effect.never","Iterable.headUnsafe","Fiber.interrupt","Effect.yieldNow","Pull.filterDone","Effect.exit","Exit.succeed","merge","splitLines","Pull.matchEffect","Scope.addFinalizerExit","onEnd","ensuring","Scope.makeUnsafe","Effect.onExit","provideContext","Effect.provideContext","provideService","Effect.provideService","runDrain","runForEach","runFold","Effect.whileLoop","Effect.acquireRelease","PubSub.unbounded","PubSub.dropping","PubSub.sliding","PubSub.bounded","PubSub.shutdown","PubSub.publishAll","Effect.ensuring","toPubSubTake","PubSub.publish","Effect.forkScoped","TypeId","fromChannel","internal.fromChannel","Channel.fromEffect","Effect.map","Arr.of","Channel.fromPull","Channel.fromTransform","Effect.flatMap","Channel.toPullScoped","Channel.callbackArray","Channel.empty","Channel.succeed","Channel.suspend","Channel.fail","Channel.die","Channel.fromIterableArray","Arr.isReadonlyArrayNonEmpty","Channel.fromQueueArray","Channel.fromPubSubArray","Channel.fromPubSubTake","Channel.fromReadableStream","Channel.unwrap","Channel.map","Arr.map","Channel.flattenArray","Channel.mapEffect","Effect.as","Channel.flatMap","Channel.merge","Channel.filterArray","Channel.filterMapArray","Channel.catch","Channel.catchIf","Channel.catchFilter","Result.succeed","Result.fail","Channel.catchReason","Channel.mapError","Channel.orDie","Count.normalize","Effect.sync","done","Effect.suspend","Cause.done","Effect.succeed","Effect.catch","Exit.fail","Channel.pipeTo","Channel.splitLines","Channel.onEnd","Channel.ensuring","Channel.provideContext","Channel.provideService","Effect.scopedWith","Channel.runFold","Channel.runForEach","Effect.whileLoop","Channel.runDrain","Channel.runIntoPubSubArray","Channel.toPubSubTake"],"sources":["../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/count.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Number.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/String.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Fiber.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Latch.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/MutableRef.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/MutableList.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/PubSub.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Queue.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Semaphore.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Take.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Channel.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/stream.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Stream.js"],"sourcesContent":["/**\n * Normalizes a collection count to a non-negative integer. `NaN` and\n * non-positive values become `0`; positive infinity is preserved.\n *\n * @internal\n */\nexport const normalize = n => n > 0 ? Math.floor(n) : 0;\n/**\n * Normalizes a collection count to an integer greater than or equal to `1`.\n *\n * @internal\n */\nexport const normalizeNonEmpty = n => Math.max(1, normalize(n));\n//# sourceMappingURL=count.js.map","/**\n * Works with TypeScript `number` values.\n *\n * This module exposes the native `Number` constructor together with helpers for\n * checking, parsing, arithmetic, safe division, comparison, range checks,\n * clamping, rounding, ordering, equivalence, and numeric aggregation.\n *\n * @since 2.0.0\n */\nimport * as Equ from \"./Equivalence.js\";\nimport { dual } from \"./Function.js\";\nimport * as Option from \"./Option.js\";\nimport * as order from \"./Order.js\";\nimport * as predicate from \"./Predicate.js\";\nimport * as Reducer from \"./Reducer.js\";\n/**\n * Exposes the global number constructor.\n *\n * **When to use**\n *\n * Use to access native JavaScript numeric coercion from the Effect module\n * namespace.\n *\n * **Gotchas**\n *\n * This follows native `Number` coercion rules, including empty strings\n * becoming `0` and invalid numeric strings becoming `NaN`.\n *\n * @see {@link parse} for parsing strings into an `Option`\n *\n * **Example** (Coercing values to numbers)\n *\n * ```ts import.meta.vitest\n * import { Number as N } from \"effect\"\n *\n * N.Number(\"42\") // => 42\n * N.Number(\"3.14\") // => 3.14\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Number = globalThis.Number;\n/**\n * Checks whether a value is a `number`.\n *\n * **When to use**\n *\n * Use to validate unknown input and narrow it to `number`.\n *\n * **Example** (Checking for numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isNumber(2) // => true\n * Number.isNumber(\"2\") // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isNumber = predicate.isNumber;\n/**\n * Provides an addition operation on `number`s.\n *\n * **When to use**\n *\n * Use to add two numbers.\n *\n * **Example** (Adding numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.sum(2, 3) // => 5\n * ```\n *\n * @see {@link sumAll} for summing an iterable of numbers\n *\n * @category math\n * @since 2.0.0\n */\nexport const sum = /*#__PURE__*/dual(2, (self, that) => self + that);\n/**\n * Provides a multiplication operation on `number`s.\n *\n * **When to use**\n *\n * Use to multiply two numbers.\n *\n * **Example** (Multiplying numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.multiply(2, 3) // => 6\n * ```\n *\n * @see {@link multiplyAll} for multiplying an iterable of numbers\n *\n * @category math\n * @since 2.0.0\n */\nexport const multiply = /*#__PURE__*/dual(2, (self, that) => self * that);\n/**\n * Provides a subtraction operation on `number`s.\n *\n * **When to use**\n *\n * Use to subtract one number from another.\n *\n * **Example** (Subtracting numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.subtract(2, 3) // => -1\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const subtract = /*#__PURE__*/dual(2, (self, that) => self - that);\n/**\n * Divides `number`s safely, returning `Option.none()` if the divisor is `0`.\n *\n * **When to use**\n *\n * Use to divide numbers while representing division by zero as `Option.none`.\n *\n * **Example** (Dividing numbers safely)\n *\n * ```ts import.meta.vitest\n * import { Number, Option } from \"effect\"\n *\n * Number.divide(6, 3) // => Option.some(2)\n * Number.divide(6, 0) // => Option.none()\n * ```\n *\n * @see {@link divideUnsafe} for division that throws when the divisor is zero\n * @see {@link remainder} for the numeric remainder operation\n *\n * @category math\n * @since 2.0.0\n */\nexport const divide = /*#__PURE__*/dual(2, (self, that) => that === 0 ? Option.none() : Option.some(self / that));\n/**\n * Divides two `number` values without returning an `Option`.\n *\n * **When to use**\n *\n * Use to divide `number` values where the divisor is known to be non-zero and\n * a plain `number` result is preferred over handling `Option.none`.\n *\n * **Gotchas**\n *\n * Throws a `RangeError` if the divisor is `0`.\n *\n * **Example** (Dividing numbers unsafely)\n *\n * ```ts import.meta.vitest\n * import { Number, Result } from \"effect\"\n *\n * Number.divideUnsafe(6, 3) // => 2\n *\n * const failure = Result.try({\n * try: () => Number.divideUnsafe(6, 0),\n * catch: (error) => (error as Error).message\n * })\n * Result.merge(failure) // => \"Division by zero\"\n * ```\n *\n * @see {@link divide} for division that returns `Option.none` when the divisor is zero\n *\n * @category math\n * @since 4.0.0\n */\nexport const divideUnsafe = /*#__PURE__*/dual(2, (self, that) => Option.getOrThrowWith(divide(self, that), () => new RangeError(\"Division by zero\")));\n/**\n * Returns the result of adding `1` to a given number.\n *\n * **When to use**\n *\n * Use to increment a numeric counter by one.\n *\n * **Example** (Incrementing a number)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.increment(2) // => 3\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const increment = n => n + 1;\n/**\n * Decrements a number by `1`.\n *\n * **When to use**\n *\n * Use to decrement a numeric counter by one.\n *\n * **Example** (Decrementing a number)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.decrement(3) // => 2\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const decrement = n => n - 1;\n/**\n * Order instance for `number` values.\n *\n * **When to use**\n *\n * Use when you need to sort or compare numbers through APIs that accept an\n * ordering instance.\n *\n * **Example** (Comparing numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.Order(1, 2) // => -1\n * Number.Order(2, 1) // => 1\n * Number.Order(1, 1) // => 0\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Order = order.Number;\n/**\n * Equivalence instance for numbers where `NaN` is considered equal to `NaN`.\n *\n * **When to use**\n *\n * Use when checking numeric equality through APIs that accept an equivalence\n * relation.\n *\n * **Example** (Comparing numbers for equivalence)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.Equivalence(1, 1) // => true\n * Number.Equivalence(1, 2) // => false\n * Number.Equivalence(NaN, NaN) // => true\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence = Equ.Number;\n/**\n * Returns `true` if the first argument is less than the second, otherwise `false`.\n *\n * **When to use**\n *\n * Use to test whether one number is strictly less than another.\n *\n * **Example** (Checking less-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isLessThan(2, 3) // => true\n * Number.isLessThan(3, 3) // => false\n * Number.isLessThan(4, 3) // => false\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThan = /*#__PURE__*/order.isLessThan(Order);\n/**\n * Returns a function that checks if a given `number` is less than or equal to the provided one.\n *\n * **When to use**\n *\n * Use to test whether one number is less than or equal to another.\n *\n * **Example** (Checking less-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isLessThanOrEqualTo(2, 3) // => true\n * Number.isLessThanOrEqualTo(3, 3) // => true\n * Number.isLessThanOrEqualTo(4, 3) // => false\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThanOrEqualTo = /*#__PURE__*/order.isLessThanOrEqualTo(Order);\n/**\n * Returns `true` if the first argument is greater than the second, otherwise `false`.\n *\n * **When to use**\n *\n * Use to test whether one number is strictly greater than another.\n *\n * **Example** (Checking greater-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isGreaterThan(2, 3) // => false\n * Number.isGreaterThan(3, 3) // => false\n * Number.isGreaterThan(4, 3) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThan = /*#__PURE__*/order.isGreaterThan(Order);\n/**\n * Returns a function that checks if a given `number` is greater than or equal to the provided one.\n *\n * **When to use**\n *\n * Use to test whether one number is greater than or equal to another.\n *\n * **Example** (Checking greater-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isGreaterThanOrEqualTo(2, 3) // => false\n * Number.isGreaterThanOrEqualTo(3, 3) // => true\n * Number.isGreaterThanOrEqualTo(4, 3) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualTo = /*#__PURE__*/order.isGreaterThanOrEqualTo(Order);\n/**\n * Checks whether a `number` is between a `minimum` and `maximum` value (inclusive).\n *\n * **When to use**\n *\n * Use to test whether a number falls inside an inclusive range.\n *\n * **Example** (Checking inclusive ranges)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * const between = Number.between({ minimum: 0, maximum: 5 })\n *\n * between(3) // => true\n * between(-1) // => false\n * between(6) // => false\n * ```\n *\n * @see {@link clamp} for forcing a number into an inclusive range\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const between = /*#__PURE__*/order.isBetween(Order);\n/**\n * Restricts the given `number` to be within the range specified by the `minimum` and `maximum` values.\n *\n * **When to use**\n *\n * Use to force a number into an inclusive range.\n *\n * **Details**\n *\n * - If the `number` is less than the `minimum` value, the function returns the `minimum` value.\n * - If the `number` is greater than the `maximum` value, the function returns the `maximum` value.\n * - Otherwise, it returns the original `number`.\n * - `NaN` is ordered below every non-`NaN` number by `Number.Order`, so it is\n * clamped to `minimum`.\n *\n * **Example** (Clamping to a range)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * const clamp = Number.clamp({ minimum: 1, maximum: 5 })\n *\n * clamp(3) // => 3\n * clamp(0) // => 1\n * clamp(6) // => 5\n * ```\n *\n * @see {@link between} for checking whether a number is already inside a range\n *\n * @category math\n * @since 2.0.0\n */\nexport const clamp = /*#__PURE__*/order.clamp(Order);\n/**\n * Returns the minimum between two `number`s.\n *\n * **When to use**\n *\n * Use to select the smaller of two numbers.\n *\n * **Example** (Finding the minimum)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.min(2, 3) // => 2\n * ```\n *\n * @see {@link max} for selecting the larger value\n *\n * @category math\n * @since 2.0.0\n */\nexport const min = /*#__PURE__*/order.min(Order);\n/**\n * Returns the maximum between two `number`s.\n *\n * **When to use**\n *\n * Use to select the larger of two numbers.\n *\n * **Example** (Finding the maximum)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.max(2, 3) // => 3\n * ```\n *\n * @see {@link min} for selecting the smaller value\n *\n * @category math\n * @since 2.0.0\n */\nexport const max = /*#__PURE__*/order.max(Order);\n/**\n * Determines the sign of a given `number`.\n *\n * **When to use**\n *\n * Use to classify a number as negative, zero, or positive.\n *\n * **Example** (Determining the sign)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.sign(-5) // => -1\n * Number.sign(0) // => 0\n * Number.sign(5) // => 1\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const sign = n => Order(n, 0);\n/**\n * Takes an `Iterable` of `number`s and returns their sum as a single `number`.\n *\n * **When to use**\n *\n * Use to sum all numbers in an iterable.\n *\n * **Example** (Summing an iterable)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.sumAll([2, 3, 4]) // => 9\n * ```\n *\n * @see {@link sum} for adding two numbers\n * @see {@link ReducerSum} for summing through APIs that consume a `Reducer`\n *\n * @category math\n * @since 2.0.0\n */\nexport const sumAll = collection => {\n let out = 0;\n for (const n of collection) {\n out += n;\n }\n return out;\n};\n/**\n * Takes an `Iterable` of `number`s and returns their multiplication as a single `number`.\n *\n * **When to use**\n *\n * Use to multiply all numbers in an iterable.\n *\n * **Example** (Multiplying an iterable)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.multiplyAll([2, 3, 4]) // => 24\n * ```\n *\n * @see {@link multiply} for multiplying two numbers\n * @see {@link ReducerMultiply} for multiplying through APIs that consume a `Reducer`\n *\n * @category math\n * @since 2.0.0\n */\nexport const multiplyAll = collection => {\n let out = 1;\n for (const n of collection) {\n if (n === 0) {\n return 0;\n }\n out *= n;\n }\n return out;\n};\n/**\n * Returns the remainder left over when one operand is divided by a second operand, always taking the sign of the dividend.\n *\n * **When to use**\n *\n * Use to compute a numeric remainder while preserving decimal precision better\n * than direct JavaScript `%` for decimal operands.\n *\n * **Example** (Calculating remainders)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.remainder(2, 2) // => 0\n * Number.remainder(3, 2) // => 1\n * Number.remainder(-4, 2) // => -0\n * ```\n *\n * @see {@link divide} for quotient calculation with division-by-zero represented as `Option.none`\n *\n * @category math\n * @since 2.0.0\n */\nexport const remainder = /*#__PURE__*/dual(2, (self, divisor) => {\n const selfString = self.toString();\n const divisorString = divisor.toString();\n if (selfString.includes(\"e\") || divisorString.includes(\"e\")) {\n if (!globalThis.Number.isFinite(self) || !globalThis.Number.isFinite(divisor) || divisor === 0) {\n return NaN;\n }\n return remainderWithScientificNotation(self, divisor);\n }\n const selfDecCount = (selfString.split(\".\")[1] || \"\").length;\n const divisorDecCount = (divisorString.split(\".\")[1] || \"\").length;\n const decCount = selfDecCount > divisorDecCount ? selfDecCount : divisorDecCount;\n const selfInt = self === 0 ? self : parseInt(self.toFixed(decCount).replace(\".\", \"\"));\n const divisorInt = parseInt(divisor.toFixed(decCount).replace(\".\", \"\"));\n return selfInt % divisorInt / Math.pow(10, decCount);\n});\nfunction remainderWithScientificNotation(self, divisor) {\n const [selfCoefficient, selfExponent] = toScientificInteger(self);\n const [divisorCoefficient, divisorExponent] = toScientificInteger(divisor);\n const exponent = Math.min(selfExponent, divisorExponent);\n const selfInteger = selfCoefficient * BigInt(10) ** BigInt(selfExponent - exponent);\n const divisorInteger = divisorCoefficient * BigInt(10) ** BigInt(divisorExponent - exponent);\n const out = selfInteger % divisorInteger;\n if (out === BigInt(0)) {\n return self < 0 || Object.is(self, -0) ? -0 : 0;\n }\n const remainder = globalThis.Number(`${out}e${exponent}`);\n return remainder === 0 ? Math.sign(self) * globalThis.Number.MIN_VALUE : remainder;\n}\nfunction toScientificInteger(n) {\n const scientific = Math.abs(n).toExponential();\n const eIndex = scientific.indexOf(\"e\");\n const digits = scientific.slice(0, eIndex).replace(\".\", \"\");\n const coefficient = BigInt(digits) * (n < 0 ? -BigInt(1) : BigInt(1));\n return [coefficient, globalThis.Number(scientific.slice(eIndex + 1)) - digits.length + 1];\n}\n/**\n * Returns the next power of 2 from the given number.\n *\n * **When to use**\n *\n * Use to round a number up to the next power of two.\n *\n * **Example** (Finding the next power of two)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.nextPow2(5) // => 8\n * Number.nextPow2(17) // => 32\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const nextPow2 = n => {\n const nextPow = Math.ceil(Math.log(n) / Math.log(2));\n return Math.max(Math.pow(2, nextPow), 2);\n};\n/**\n * Parses a `number` from a `string` safely using the `Number()` function.\n * The following special string values are supported: \"NaN\", \"Infinity\", \"-Infinity\".\n *\n * **When to use**\n *\n * Use to parse numeric text without throwing on invalid input.\n *\n * **Example** (Parsing numbers from strings)\n *\n * ```ts import.meta.vitest\n * import { Number, Option } from \"effect\"\n *\n * Number.parse(\"42\") // => Option.some(42)\n * Number.parse(\"3.14\") // => Option.some(3.14)\n * Number.parse(\"NaN\") // => Option.some(NaN)\n * Number.parse(\"Infinity\") // => Option.some(Infinity)\n * Number.parse(\"-Infinity\") // => Option.some(-Infinity)\n * Number.parse(\"not a number\") // => Option.none()\n * ```\n *\n * @see {@link Number} for native constructor coercion\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const parse = s => {\n if (s === \"NaN\") {\n return Option.some(NaN);\n }\n if (s === \"Infinity\") {\n return Option.some(Infinity);\n }\n if (s === \"-Infinity\") {\n return Option.some(-Infinity);\n }\n if (s.trim() === \"\") {\n return Option.none();\n }\n const n = Number(s);\n return Number.isNaN(n) ? Option.none() : Option.some(n);\n};\n/**\n * Returns the number rounded with the given precision.\n *\n * **When to use**\n *\n * Use to round a number to a fixed number of decimal places.\n *\n * **Example** (Rounding with precision)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.round(1.1234, 2) // => 1.12\n * Number.round(1.567, 2) // => 1.57\n * ```\n *\n * @category math\n * @since 3.8.0\n */\nexport const round = /*#__PURE__*/dual(2, (self, precision) => {\n const factor = Math.pow(10, precision);\n return Math.round(self * factor) / factor;\n});\n/**\n * Reducer for combining `number`s using addition.\n *\n * **When to use**\n *\n * Use to sum many numbers through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The reducer starts from `0`, so `combineAll([])` returns `0`.\n *\n * @see {@link sumAll} for summing an iterable directly\n * @see {@link ReducerMultiply} for multiplying number values\n *\n * @category math\n * @since 4.0.0\n */\nexport const ReducerSum = /*#__PURE__*/Reducer.make((a, b) => a + b, 0);\n/**\n * Reducer for combining `number`s using multiplication.\n *\n * **When to use**\n *\n * Use to multiply many numbers through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The reducer starts from `1`, so reducing an empty collection returns `1`.\n *\n * **Gotchas**\n *\n * Reducing an iterable short-circuits when it sees `0`, so later elements are\n * not consumed.\n *\n * @see {@link multiplyAll} for multiplying an iterable directly\n *\n * @category math\n * @since 4.0.0\n */\nexport const ReducerMultiply = /*#__PURE__*/Reducer.make((a, b) => a * b, 1, collection => {\n let acc = 1;\n for (const n of collection) {\n if (n === 0) return 0;\n acc *= n;\n }\n return acc;\n});\n/**\n * Reducer for reducing `number`s by keeping the maximum value.\n *\n * **When to use**\n *\n * Use to keep the largest number through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The reducer starts from `-Infinity`, so reducing an empty collection returns\n * `-Infinity`.\n *\n * **Gotchas**\n *\n * `NaN` values propagate through `Math.max`.\n *\n * @see {@link ReducerMin} for keeping the smallest number\n * @see {@link max} for comparing two numbers directly\n *\n * @category math\n * @since 4.0.0\n */\nexport const ReducerMax = /*#__PURE__*/Reducer.make((a, b) => Math.max(a, b), -Infinity);\n/**\n * Reducer for reducing `number`s by keeping the minimum value.\n *\n * **When to use**\n *\n * Use to keep the smallest number through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The reducer starts from `Infinity`, so reducing an empty collection returns\n * `Infinity`.\n *\n * **Gotchas**\n *\n * `NaN` values propagate through `Math.min`.\n *\n * @see {@link ReducerMax} for keeping the largest number\n * @see {@link min} for comparing two numbers directly\n *\n * @category math\n * @since 4.0.0\n */\nexport const ReducerMin = /*#__PURE__*/Reducer.make((a, b) => Math.min(a, b), Infinity);\n//# sourceMappingURL=Number.js.map","/**\n * Works with TypeScript `string` values.\n *\n * This module exposes common string operations in a pipe-friendly style. The\n * helpers cover checks, comparison, concatenation, trimming, casing, slicing,\n * padding, replacement, normalization, safe character access, search helpers\n * that return `Option`, and joining strings through a reducer.\n *\n * @since 2.0.0\n */\nimport * as Equ from \"./Equivalence.js\";\nimport { dual } from \"./Function.js\";\nimport * as readonlyArray from \"./internal/array.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as number from \"./Number.js\";\nimport * as Option from \"./Option.js\";\nimport * as order from \"./Order.js\";\nimport * as predicate from \"./Predicate.js\";\nimport * as Reducer from \"./Reducer.js\";\n/**\n * Exposes the global string constructor.\n *\n * **When to use**\n *\n * Use to access native JavaScript string coercion or constructor behavior from\n * the Effect module namespace.\n *\n * **Gotchas**\n *\n * Calling `String(value)` returns a primitive string. Calling\n * `new String(value)` creates a boxed `String` object.\n *\n * @see {@link isString} for checking whether a value is a primitive string\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const String = globalThis.String;\n/**\n * Checks whether a value is a `string`.\n *\n * **Example** (Checking for strings)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.isString(\"a\") // => true\n * String.isString(1) // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isString = predicate.isString;\n/**\n * Provides an `Order` instance for comparing strings using lexicographic\n * ordering.\n *\n * **Example** (Comparing strings lexicographically)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.Order(\"apple\", \"banana\") // => -1\n * String.Order(\"banana\", \"apple\") // => 1\n * String.Order(\"apple\", \"apple\") // => 0\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Order = order.String;\n/**\n * Provides an `Equivalence` instance for strings using strict equality (`===`).\n *\n * **Example** (Comparing strings for equality)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.Equivalence(\"hello\", \"hello\") // => true\n * String.Equivalence(\"hello\", \"world\") // => false\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence = Equ.String;\n/**\n * Provides the empty string `\"\"`.\n *\n * **When to use**\n *\n * Use when you need the canonical empty string value from the `String` module.\n *\n * **Example** (Referencing the empty string)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.empty // => \"\"\n * String.isEmpty(String.empty) // => true\n * ```\n *\n * @category constants\n * @since 2.0.0\n */\nexport const empty = \"\";\n/**\n * Concatenates two strings at runtime.\n *\n * **Example** (Concatenating strings)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * String.concat(\"hello\", \"world\") // => \"helloworld\"\n * pipe(\"hello\", String.concat(\"world\")) // => \"helloworld\"\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const concat = /*#__PURE__*/dual(2, (self, that) => self + that);\n/**\n * Converts a string to uppercase.\n *\n * **Example** (Converting strings to uppercase)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"a\", String.toUpperCase) // => \"A\"\n * String.toUpperCase(\"hello\") // => \"HELLO\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const toUpperCase = self => self.toUpperCase();\n/**\n * Converts a string to lowercase.\n *\n * **Example** (Converting strings to lowercase)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"A\", String.toLowerCase) // => \"a\"\n * String.toLowerCase(\"HELLO\") // => \"hello\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const toLowerCase = self => self.toLowerCase();\n/**\n * Capitalizes the first character of a string.\n *\n * **Example** (Capitalizing a string)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"abc\", String.capitalize) // => \"Abc\"\n * String.capitalize(\"hello\") // => \"Hello\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const capitalize = self => {\n if (self.length === 0) return self;\n return toUpperCase(self[0]) + self.slice(1);\n};\n/**\n * Uncapitalizes the first character of a string.\n *\n * **Example** (Uncapitalizing a string)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"ABC\", String.uncapitalize) // => \"aBC\"\n * String.uncapitalize(\"Hello\") // => \"hello\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const uncapitalize = self => {\n if (self.length === 0) return self;\n return toLowerCase(self[0]) + self.slice(1);\n};\n/**\n * Replaces matches in a string using `String.prototype.replace`.\n *\n * **Details**\n *\n * String search values and non-global regular expressions replace the first\n * match; global regular expressions replace every match.\n *\n * **Example** (Replacing a substring)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"abc\", String.replace(\"b\", \"d\")) // => \"adc\"\n * pipe(\"hello world\", String.replace(\"world\", \"Effect\")) // => \"hello Effect\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const replace = (searchValue, replaceValue) => self => self.replace(searchValue, replaceValue);\n/**\n * Removes whitespace from both ends of a string.\n *\n * **Example** (Trimming whitespace)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.trim(\" a \") // => \"a\"\n * String.trim(\" hello world \") // => \"hello world\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const trim = self => self.trim();\n/**\n * Removes whitespace from the start of a string.\n *\n * **Example** (Trimming leading whitespace)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.trimStart(\" a \") // => \"a \"\n * String.trimStart(\" hello world\") // => \"hello world\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const trimStart = self => self.trimStart();\n/**\n * Removes whitespace from the end of a string.\n *\n * **Example** (Trimming trailing whitespace)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.trimEnd(\" a \") // => \" a\"\n * String.trimEnd(\"hello world \") // => \"hello world\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const trimEnd = self => self.trimEnd();\n/**\n * Extracts a section of a string and returns it as a new string.\n *\n * **Example** (Slicing strings)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"abcd\", String.slice(1, 3)) // => \"bc\"\n * pipe(\"hello world\", String.slice(0, 5)) // => \"hello\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const slice = (start, end) => self => self.slice(start, end);\n/**\n * Checks whether a `string` is empty.\n *\n * **Example** (Checking for empty strings)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.isEmpty(\"\") // => true\n * String.isEmpty(\"a\") // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEmpty = self => self.length === 0;\n/**\n * Checks whether a `string` is non-empty.\n *\n * **Example** (Checking for non-empty strings)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.isNonEmpty(\"\") // => false\n * String.isNonEmpty(\"a\") // => true\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isNonEmpty = self => self.length > 0;\n/**\n * Returns the JavaScript string length, measured in UTF-16 code units.\n *\n * **Example** (Getting string length)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.length(\"abc\") // => 3\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const length = self => self.length;\n/**\n * Splits a string into an array of substrings using a separator.\n *\n * **Example** (Splitting strings)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"abc\", String.split(\"\")) // => [\"a\", \"b\", \"c\"]\n * pipe(\"\", String.split(\"\")) // => [\"\"]\n * String.split(\"hello,world\", \",\") // => [\"hello\", \"world\"]\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const split = /*#__PURE__*/dual(2, (self, separator) => {\n const out = self.split(separator);\n return readonlyArray.isArrayNonEmpty(out) ? out : [self];\n});\n/**\n * Returns `true` if `searchString` appears as a substring of `self`, at one or more positions that are\n * greater than or equal to `position`; otherwise, returns `false`.\n *\n * **Example** (Checking for substrings)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"hello world\", String.includes(\"world\")) // => true\n * pipe(\"hello world\", String.includes(\"foo\")) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const includes = (searchString, position) => self => self.includes(searchString, position);\n/**\n * Returns `true` if the string starts with the specified search string.\n *\n * **Example** (Checking string prefixes)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"hello world\", String.startsWith(\"hello\")) // => true\n * pipe(\"hello world\", String.startsWith(\"world\")) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const startsWith = (searchString, position) => self => self.startsWith(searchString, position);\n/**\n * Returns `true` if the string ends with the specified search string.\n *\n * **Example** (Checking string suffixes)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"hello world\", String.endsWith(\"world\")) // => true\n * pipe(\"hello world\", String.endsWith(\"hello\")) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const endsWith = (searchString, position) => self => self.endsWith(searchString, position);\n/**\n * Returns the character code at the specified index safely, or `None` if the index is out of bounds.\n *\n * **Example** (Reading character codes)\n *\n * ```ts import.meta.vitest\n * import { Option, String } from \"effect\"\n *\n * String.charCodeAt(\"abc\", 1) // => Option.some(98)\n * String.charCodeAt(\"abc\", 4) // => Option.none()\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const charCodeAt = /*#__PURE__*/dual(2, (self, index) => Option.filter(Option.some(self.charCodeAt(index)), charCode => !isNaN(charCode)));\n/**\n * Extracts characters from a string between two specified indices.\n *\n * **Example** (Extracting substrings)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"abcd\", String.substring(1)) // => \"bcd\"\n * pipe(\"abcd\", String.substring(1, 3)) // => \"bc\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const substring = (start, end) => self => self.substring(start, end);\n/**\n * Returns the character at the specified relative index safely, or `None` if the index is out of bounds.\n *\n * **Example** (Accessing characters safely)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe, String } from \"effect\"\n *\n * pipe(\"abc\", String.at(1)) // => Option.some(\"b\")\n * pipe(\"abc\", String.at(4)) // => Option.none()\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const at = /*#__PURE__*/dual(2, (self, index) => Option.fromUndefinedOr(self.at(index)));\n/**\n * Returns the character at the specified non-negative index safely, or `None` if the index is out of bounds.\n *\n * **Example** (Reading characters safely)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe, String } from \"effect\"\n *\n * pipe(\"abc\", String.charAt(1)) // => Option.some(\"b\")\n * pipe(\"abc\", String.charAt(4)) // => Option.none()\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const charAt = /*#__PURE__*/dual(2, (self, index) => Option.filter(Option.some(self.charAt(index)), isNonEmpty));\n/**\n * Returns the Unicode code point at the specified index safely, or `None` if the index is out of bounds.\n *\n * **Example** (Reading code points)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe, String } from \"effect\"\n *\n * pipe(\"abc\", String.codePointAt(1)) // => Option.some(98)\n * pipe(\"abc\", String.codePointAt(10)) // => Option.none()\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const codePointAt = /*#__PURE__*/dual(2, (self, index) => Option.fromUndefinedOr(self.codePointAt(index)));\n/**\n * Returns the index of the first occurrence of a substring safely, or `None` if not found.\n *\n * **Example** (Finding the first substring index)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe, String } from \"effect\"\n *\n * pipe(\"abbbc\", String.indexOf(\"b\")) // => Option.some(1)\n * pipe(\"abbbc\", String.indexOf(\"z\")) // => Option.none()\n * ```\n *\n * @category searching\n * @since 2.0.0\n */\nexport const indexOf = searchString => self => Option.filter(Option.some(self.indexOf(searchString)), number.isGreaterThanOrEqualTo(0));\n/**\n * Returns the index of the last occurrence of a substring safely, or `None` if not found.\n *\n * **Example** (Finding the last substring index)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe, String } from \"effect\"\n *\n * pipe(\"abbbc\", String.lastIndexOf(\"b\")) // => Option.some(3)\n * pipe(\"abbbc\", String.lastIndexOf(\"d\")) // => Option.none()\n * ```\n *\n * @category searching\n * @since 2.0.0\n */\nexport const lastIndexOf = searchString => self => Option.filter(Option.some(self.lastIndexOf(searchString)), number.isGreaterThanOrEqualTo(0));\n/**\n * Computes locale-aware ordering for two strings, with optional locales and\n * collator options, and returns the result as an `Ordering` (`-1`, `0`, or\n * `1`).\n *\n * **Example** (Comparing strings by locale)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"a\", String.localeCompare(\"b\")) // => -1\n * pipe(\"b\", String.localeCompare(\"a\")) // => 1\n * pipe(\"a\", String.localeCompare(\"a\")) // => 0\n * ```\n *\n * @category comparisons\n * @since 2.0.0\n */\nexport const localeCompare = (that, locales, options) => self => number.sign(self.localeCompare(that, locales, options));\n/**\n * Matches a string against a pattern safely and returns `Option.some` with the match\n * array, or `Option.none` when the pattern does not match.\n *\n * **Example** (Matching regular expressions)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe, String } from \"effect\"\n *\n * pipe(\n * \"hello\",\n * String.match(/l+/),\n * Option.map((match) => [match[0], match.index])\n * ) // => Option.some([\"ll\", 2])\n * pipe(\"hello\", String.match(/x/)) // => Option.none()\n * ```\n *\n * @category searching\n * @since 2.0.0\n */\nexport const match = regExp => self => Option.fromNullOr(self.match(regExp));\n/**\n * Returns an iterator over all regular expression matches in the string using\n * native `String.prototype.matchAll` semantics.\n *\n * **Example** (Iterating regular expression matches)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * const matches = pipe(\"hello world\", String.matchAll(/l/g))\n *\n * Array.from(matches, (match) => [match[0], match.index]) // => [[\"l\", 2], [\"l\", 3], [\"l\", 9]]\n * ```\n *\n * @category searching\n * @since 2.0.0\n */\nexport const matchAll = regExp => self => self.matchAll(regExp);\n/**\n * Normalizes a string according to the specified Unicode normalization form.\n *\n * **Example** (Normalizing Unicode strings)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * const str = \"\\u1E9B\\u0323\"\n * Array.from(pipe(str, String.normalize()), (character) => character.codePointAt(0)) // => [0x1e9b, 0x323]\n * Array.from(pipe(str, String.normalize(\"NFC\")), (character) => character.codePointAt(0)) // => [0x1e9b, 0x323]\n * Array.from(\n * pipe(str, String.normalize(\"NFD\")),\n * (character) => character.codePointAt(0)\n * ) // => [0x17f, 0x323, 0x307]\n * Array.from(pipe(str, String.normalize(\"NFKC\")), (character) => character.codePointAt(0)) // => [0x1e69]\n * Array.from(\n * pipe(str, String.normalize(\"NFKD\")),\n * (character) => character.codePointAt(0)\n * ) // => [0x73, 0x323, 0x307]\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const normalize = form => self => self.normalize(form);\n/**\n * Pads the string from the end with a given fill string to a specified length.\n *\n * **Example** (Padding strings at the end)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"a\", String.padEnd(5)) // => \"a \"\n * pipe(\"a\", String.padEnd(5, \"_\")) // => \"a____\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const padEnd = (maxLength, fillString) => self => self.padEnd(maxLength, fillString);\n/**\n * Pads the string from the start with a given fill string to a specified length.\n *\n * **Example** (Padding strings at the start)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"a\", String.padStart(5)) // => \" a\"\n * pipe(\"a\", String.padStart(5, \"_\")) // => \"____a\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const padStart = (maxLength, fillString) => self => self.padStart(maxLength, fillString);\n/**\n * Repeats the string the specified number of times.\n *\n * **Details**\n *\n * `count` is rounded down. `NaN` and non-positive values are treated as `0`.\n *\n * **Example** (Repeating strings)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"a\", String.repeat(5)) // => \"aaaaa\"\n * pipe(\"hello\", String.repeat(3)) // => \"hellohellohello\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const repeat = count => self => self.repeat(Count.normalize(count));\n/**\n * Replaces all occurrences of a substring or pattern in a string.\n *\n * **Example** (Replacing all matches)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * pipe(\"ababb\", String.replaceAll(\"b\", \"c\")) // => \"acacc\"\n * pipe(\"ababb\", String.replaceAll(/ba/g, \"cc\")) // => \"accbb\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const replaceAll = (searchValue, replaceValue) => self => self.replaceAll(searchValue, replaceValue);\n/**\n * Returns the index of the first match for a string or regular expression safely, or\n * `Option.none` when no match is found.\n *\n * **Example** (Searching strings)\n *\n * ```ts import.meta.vitest\n * import { Option, String } from \"effect\"\n *\n * String.search(\"ababb\", \"b\") // => Option.some(1)\n * String.search(\"ababb\", /abb/) // => Option.some(2)\n * String.search(\"ababb\", \"d\") // => Option.none()\n * ```\n *\n * @category searching\n * @since 2.0.0\n */\nexport const search = /*#__PURE__*/dual(2, (self, regExp) => Option.filter(Option.some(self.search(regExp)), number.isGreaterThanOrEqualTo(0)));\n/**\n * Converts the string to lowercase according to the specified locale.\n *\n * **Example** (Lowercasing strings by locale)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * const str = \"\\u0130\"\n * pipe(str, String.toLocaleLowerCase(\"tr\")) // => \"i\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const toLocaleLowerCase = locale => self => self.toLocaleLowerCase(locale);\n/**\n * Converts the string to uppercase according to the specified locale.\n *\n * **Example** (Uppercasing strings by locale)\n *\n * ```ts import.meta.vitest\n * import { pipe, String } from \"effect\"\n *\n * const str = \"i\\u0307\"\n * pipe(str, String.toLocaleUpperCase(\"lt-LT\")) // => \"I\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const toLocaleUpperCase = locale => self => self.toLocaleUpperCase(locale);\n/**\n * Keeps the specified number of characters from the start of a string.\n *\n * **Details**\n *\n * If `n` is larger than the available number of characters, the string will\n * be returned whole.\n *\n * If `n` is not a positive number, including `NaN`, an empty string will be\n * returned.\n *\n * If `n` is a float, it will be rounded down to the nearest integer.\n *\n * **Example** (Taking characters from the start)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.takeLeft(\"Hello World\", 5) // => \"Hello\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const takeLeft = /*#__PURE__*/dual(2, (self, n) => self.slice(0, Count.normalize(n)));\n/**\n * Keeps the specified number of characters from the end of a string.\n *\n * **Details**\n *\n * If `n` is larger than the available number of characters, the string will\n * be returned whole.\n *\n * If `n` is not a positive number, including `NaN`, an empty string will be\n * returned.\n *\n * If `n` is a float, it will be rounded down to the nearest integer.\n *\n * **Example** (Taking characters from the end)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.takeRight(\"Hello World\", 5) // => \"World\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const takeRight = /*#__PURE__*/dual(2, (self, n) => self.slice(self.length - Math.min(Count.normalize(n), self.length), Infinity));\nconst CR = 0x0d;\nconst LF = 0x0a;\n/**\n * Returns an `IterableIterator` which yields each line contained within the\n * string, trimming off the trailing newline character.\n *\n * **Example** (Iterating lines without separators)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * Array.from(String.linesIterator(\"hello\\nworld\\n\")) // => [\"hello\", \"world\"]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const linesIterator = self => linesSeparated(self, true);\n/**\n * Returns an `IterableIterator` which yields each line contained within the\n * string as well as the trailing newline character.\n *\n * **Example** (Iterating lines with separators)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * Array.from(String.linesWithSeparators(\"hello\\nworld\\n\")) // => [\"hello\\n\", \"world\\n\"]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const linesWithSeparators = s => linesSeparated(s, false);\n/**\n * Strips a leading margin prefix from every line using the supplied margin\n * character.\n *\n * **Example** (Stripping custom margins)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.stripMarginWith(\" |hello\\n |world\", \"|\") // => \"hello\\nworld\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const stripMarginWith = /*#__PURE__*/dual(2, (self, marginChar) => {\n let out = \"\";\n for (const line of linesWithSeparators(self)) {\n let index = 0;\n while (index < line.length && line.charAt(index) <= \" \") {\n index = index + 1;\n }\n const stripped = index < line.length && line.charAt(index) === marginChar ? line.substring(index + 1) : line;\n out = out + stripped;\n }\n return out;\n});\n/**\n * Strips a leading `|` margin prefix from every line.\n *\n * **Example** (Stripping pipe margins)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.stripMargin(\" |hello\\n |world\") // => \"hello\\nworld\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const stripMargin = self => stripMarginWith(self, \"|\");\n/**\n * Converts a snake_case string to camelCase.\n *\n * **Example** (Converting snake_case to camelCase)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.snakeToCamel(\"hello_world\") // => \"helloWorld\"\n * String.snakeToCamel(\"foo_bar_baz\") // => \"fooBarBaz\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const snakeToCamel = self => {\n if (self.length === 0) return self;\n let str = self[0];\n for (let i = 1; i < self.length; i++) {\n str += self[i] === \"_\" ? self[++i].toUpperCase() : self[i];\n }\n return str;\n};\n/**\n * Converts a snake_case string to PascalCase.\n *\n * **Example** (Converting snake_case to PascalCase)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.snakeToPascal(\"hello_world\") // => \"HelloWorld\"\n * String.snakeToPascal(\"foo_bar_baz\") // => \"FooBarBaz\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const snakeToPascal = self => {\n if (self.length === 0) return self;\n let str = self[0].toUpperCase();\n for (let i = 1; i < self.length; i++) {\n str += self[i] === \"_\" ? self[++i].toUpperCase() : self[i];\n }\n return str;\n};\n/**\n * Converts a snake_case string to kebab-case.\n *\n * **Example** (Converting snake_case to kebab-case)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.snakeToKebab(\"hello_world\") // => \"hello-world\"\n * String.snakeToKebab(\"foo_bar_baz\") // => \"foo-bar-baz\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const snakeToKebab = self => self.replace(/_/g, \"-\");\n/**\n * Converts a camelCase string to snake_case.\n *\n * **Example** (Converting camelCase to snake_case)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.camelToSnake(\"helloWorld\") // => \"hello_world\"\n * String.camelToSnake(\"fooBarBaz\") // => \"foo_bar_baz\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const camelToSnake = self => self.replace(/([A-Z])/g, \"_$1\").toLowerCase();\n/**\n * Converts a PascalCase string to snake_case.\n *\n * **Example** (Converting PascalCase to snake_case)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.pascalToSnake(\"HelloWorld\") // => \"hello_world\"\n * String.pascalToSnake(\"FooBarBaz\") // => \"foo_bar_baz\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const pascalToSnake = self => (self.slice(0, 1) + self.slice(1).replace(/([A-Z])/g, \"_$1\")).toLowerCase();\n/**\n * Converts a kebab-case string to snake_case.\n *\n * **Example** (Converting kebab-case to snake_case)\n *\n * ```ts import.meta.vitest\n * import { String } from \"effect\"\n *\n * String.kebabToSnake(\"hello-world\") // => \"hello_world\"\n * String.kebabToSnake(\"foo-bar-baz\") // => \"foo_bar_baz\"\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const kebabToSnake = self => self.replace(/-/g, \"_\");\nclass LinesIterator {\n index;\n length;\n s;\n stripped;\n constructor(s, stripped = false) {\n this.s = s;\n this.stripped = stripped;\n this.index = 0;\n this.length = s.length;\n }\n next() {\n if (this.done) {\n return {\n done: true,\n value: undefined\n };\n }\n const start = this.index;\n while (!this.done && !isLineBreak(this.s[this.index])) {\n this.index = this.index + 1;\n }\n let end = this.index;\n if (!this.done) {\n const char = this.s[this.index];\n this.index = this.index + 1;\n if (!this.done && isLineBreak2(char, this.s[this.index])) {\n this.index = this.index + 1;\n }\n if (!this.stripped) {\n end = this.index;\n }\n }\n return {\n done: false,\n value: this.s.substring(start, end)\n };\n }\n [Symbol.iterator]() {\n return new LinesIterator(this.s, this.stripped);\n }\n get done() {\n return this.index >= this.length;\n }\n}\n/**\n * Checks whether the provided character is a line break character (i.e. either `\"\\r\"`\n * or `\"\\n\"`).\n */\nconst isLineBreak = char => {\n const code = char.charCodeAt(0);\n return code === CR || code === LF;\n};\n/**\n * Checks whether the provided characters combine to form a carriage return/line-feed\n * (i.e. `\"\\r\\n\"`).\n */\nconst isLineBreak2 = (char0, char1) => char0.charCodeAt(0) === CR && char1.charCodeAt(0) === LF;\nconst linesSeparated = (self, stripped) => new LinesIterator(self, stripped);\n/**\n * Normalizes a string by splitting it into word parts, transforming each part,\n * and joining the parts with a configurable delimiter.\n *\n * **When to use**\n *\n * Use when you need custom word-case output with a delimiter or part transform\n * that the fixed case helpers do not provide.\n *\n * @see {@link pascalCase} for fixed PascalCase output\n * @see {@link camelCase} for fixed lower-initial camelCase output\n * @see {@link constantCase} for fixed uppercase underscore-separated output\n * @see {@link kebabCase} for fixed lowercase hyphen-separated output\n * @see {@link snakeCase} for fixed lowercase underscore-separated output\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const noCase = /*#__PURE__*/dual(args => typeof args[0] === \"string\", (input, options) => {\n const splitRegExp = toRegExpArray(options?.splitRegExp ?? SPLIT_REGEXP);\n const stripRegExp = toRegExpArray(options?.stripRegExp ?? STRIP_REGEXP);\n const delimiter = options?.delimiter ?? \" \";\n const transform = options?.transform ?? toLowerCase;\n return normalizeCase(input, splitRegExp, stripRegExp, delimiter, transform);\n});\nconst toRegExpArray = regexp => predicate.isRegExp(regexp) ? [regexp] : regexp;\nconst normalizeCase = (input, splitRegExp, stripRegExp, delimiter, transform) => {\n let result = input;\n for (const regexp of splitRegExp) {\n result = result.replace(regexp, \"$1\\0$2\");\n }\n for (const regexp of stripRegExp) {\n result = result.replace(regexp, \"\\0\");\n }\n let start = 0;\n let end = result.length;\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\") {\n start++;\n }\n while (result.charAt(end - 1) === \"\\0\") {\n end--;\n }\n // Transform each token independently.\n return result.slice(start, end).split(\"\\0\").map(transform).join(delimiter);\n};\n// Support camel case (\"camelCase\" -> \"camel Case\" and \"CAMELCase\" -> \"CAMEL Case\")\n// and digit boundaries (\"camel2case\" -> \"camel 2 case\").\nconst SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g, /([A-Z])([0-9])/gi, /([0-9])([A-Z])/gi];\n// Config paths preserve digit groups such as \"v2\" while still supporting camel case.\nconst CONFIG_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];\n// Remove all non-word characters.\nconst STRIP_REGEXP = /[^A-Z0-9]+/gi;\nconst pascalCaseTransform = input => {\n const firstChar = input.charAt(0);\n const lowerChars = input.substring(1).toLowerCase();\n return `${firstChar.toUpperCase()}${lowerChars}`;\n};\n/**\n * Converts a string to PascalCase.\n *\n * **When to use**\n *\n * Use to normalize strings from spaces, separators, or camel/Pascal word\n * boundaries into PascalCase.\n *\n * @see {@link camelCase} for lower-initial camelCase output\n * @see {@link noCase} for configurable delimiters and part transforms\n * @see {@link snakeToPascal} for converting known snake_case input only\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const pascalCase = /*#__PURE__*/noCase({\n delimiter: \"\",\n transform: pascalCaseTransform\n});\nconst camelCaseTransform = (input, index) => index === 0 ? input.toLowerCase() : pascalCaseTransform(input);\n/**\n * Converts a string to camelCase.\n *\n * **When to use**\n *\n * Use to normalize mixed word separators or existing PascalCase/camelCase text\n * into lower-initial camelCase identifiers.\n *\n * @see {@link noCase} for configurable delimiters and part transforms\n * @see {@link pascalCase} for upper-initial PascalCase output\n * @see {@link snakeCase} for lowercase underscore-separated output\n * @see {@link kebabCase} for lowercase hyphen-separated output\n * @see {@link constantCase} for uppercase underscore-separated output\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const camelCase = /*#__PURE__*/noCase({\n delimiter: \"\",\n transform: camelCaseTransform\n});\n/**\n * Converts a string to CONSTANT_CASE (uppercase with underscores).\n *\n * **When to use**\n *\n * Use to normalize words from mixed input formats into uppercase,\n * underscore-separated identifiers.\n *\n * @see {@link snakeCase} for lowercase underscore-separated output\n * @see {@link kebabCase} for lowercase hyphen-separated output\n * @see {@link camelCase} for lower-initial camelCase output\n * @see {@link pascalCase} for upper-initial PascalCase output\n * @see {@link configCase} for configuration key casing that preserves numeric word groups\n * @see {@link noCase} for configurable delimiters and part transforms\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const constantCase = /*#__PURE__*/noCase({\n delimiter: \"_\",\n transform: toUpperCase\n});\n/**\n * Converts a string to CONFIG_CASE (uppercase with underscores) for\n * configuration keys.\n *\n * **When to use**\n *\n * Use to normalize configuration path segments into environment-variable-like\n * keys while preserving numeric word groups such as `v2`.\n *\n * **Details**\n *\n * Unlike {@link constantCase}, digit-letter boundaries are not split. For\n * example, `\"api-v2 xml\"` becomes `\"API_V2_XML\"`.\n *\n * @see {@link constantCase} for standard uppercase underscore-separated output\n * @category transforming\n * @since 4.0.0\n */\nexport const configCase = self => normalizeCase(self, CONFIG_SPLIT_REGEXP, [STRIP_REGEXP], \"_\", toUpperCase);\n/**\n * Converts a string to kebab-case (lowercase with hyphens).\n *\n * **When to use**\n *\n * Use to normalize free-form labels, identifiers, or keys into lowercase\n * hyphen-separated text.\n *\n * @see {@link noCase} for configurable delimiters and part transforms\n * @see {@link snakeCase} for lowercase underscore-separated output\n * @see {@link constantCase} for uppercase underscore-separated output\n * @see {@link camelCase} for lower-initial camelCase output\n * @see {@link pascalCase} for upper-initial PascalCase output\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const kebabCase = /*#__PURE__*/noCase({\n delimiter: \"-\"\n});\n/**\n * Converts a string to snake_case (lowercase with underscores).\n *\n * **When to use**\n *\n * Use to normalize mixed-case or separator-delimited text into lowercase words\n * joined with underscores.\n *\n * @see {@link noCase} for configurable lower-level normalization\n * @see {@link kebabCase} for lowercase hyphen-separated output\n * @see {@link constantCase} for uppercase underscore-separated output\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const snakeCase = /*#__PURE__*/noCase({\n delimiter: \"_\"\n});\n/**\n * Reducer for concatenating `string`s.\n *\n * **When to use**\n *\n * Use to concatenate many strings through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The reducer starts from `\"\"`, so combining an empty collection returns `\"\"`.\n *\n * @see {@link concat} for concatenating two strings directly\n *\n * @category combining\n * @since 4.0.0\n */\nexport const ReducerConcat = /*#__PURE__*/Reducer.make((a, b) => a + b, \"\");\n//# sourceMappingURL=String.js.map","import * as effect from \"./internal/effect.js\";\nimport { hasProperty } from \"./Predicate.js\";\nconst TypeId = \"~effect/Fiber\";\nconst await_ = effect.fiberAwait;\nexport {\n/**\n * Waits for a fiber to complete and returns its exit value.\n *\n * **When to use**\n *\n * Use when you need to inspect whether the fiber succeeded,\n * failed, died, or was interrupted without propagating the failure.\n *\n * **Details**\n *\n * The returned Effect always succeeds with an `Exit` describing the fiber's\n * outcome.\n *\n * **Gotchas**\n *\n * This does not flatten the fiber result into the current Effect. Use\n * {@link join} when you want fiber failures to fail the current Effect.\n *\n * **Example** (Awaiting a fiber exit)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const fiber = yield* Effect.forkChild(Effect.succeed(42))\n * return yield* Fiber.await(fiber)\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => Exit.succeed(42)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nawait_ as await };\n/**\n * Waits for all fibers in the provided iterable to complete and returns\n * an array of their exit values.\n *\n * **When to use**\n *\n * Use when you need every fiber outcome as data, including failures and\n * interruptions.\n *\n * **Details**\n *\n * The returned array is ordered like the input iterable.\n *\n * **Gotchas**\n *\n * Failures are captured as `Exit.Failure` values. Use {@link joinAll} when you\n * want the first failed fiber to fail the returned Effect.\n *\n * **Example** (Awaiting multiple fiber exits)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const fiber1 = yield* Effect.forkChild(Effect.succeed(1))\n * const fiber2 = yield* Effect.forkChild(Effect.succeed(2))\n * return yield* Fiber.awaitAll([fiber1, fiber2])\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [Exit.succeed(1), Exit.succeed(2)]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const awaitAll = effect.fiberAwaitAll;\n/**\n * Joins a fiber, blocking until it completes. If the fiber succeeds,\n * returns its value. If it fails, the error is propagated.\n *\n * **When to use**\n *\n * Use when you need a forked fiber's failure to fail the current Effect because\n * that fiber is part of the current workflow.\n *\n * **Gotchas**\n *\n * Joining a failed fiber propagates the fiber's Cause. Use {@link await_ await} when\n * you need to inspect the `Exit` instead of failing.\n *\n * **Example** (Joining a fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const fiber = yield* Effect.forkChild(Effect.succeed(42))\n * return yield* Fiber.join(fiber)\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => 42\n * ```\n *\n * @see {@link await_ await} for inspecting the fiber outcome as an Exit\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const join = effect.fiberJoin;\n/**\n * Waits for all fibers to succeed and returns their values in input order.\n *\n * **When to use**\n *\n * Use when you need every fiber to succeed and want the successful values\n * rather than the `Exit` values.\n *\n * **Details**\n *\n * If any fiber fails, the returned `Effect` fails with that fiber's cause and\n * stops waiting for additional results. This does not interrupt the remaining\n * fibers.\n *\n * **Gotchas**\n *\n * A failure stops waiting, but it does not interrupt any other fibers. Use\n * {@link interruptAll} separately when remaining fibers should be stopped.\n *\n * @see {@link awaitAll} for collecting every fiber outcome as an Exit\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const joinAll = effect.fiberJoinAll;\n/**\n * Interrupts a fiber, causing it to stop executing and clean up any\n * acquired resources.\n *\n * **When to use**\n *\n * Use when you need to cancel a forked fiber and wait for its cleanup to\n * complete.\n *\n * **Details**\n *\n * The returned Effect completes only after the interrupted fiber has completed.\n *\n * **Gotchas**\n *\n * Interruption is cooperative. A fiber can continue running while it is inside\n * uninterruptible work or finalizers.\n *\n * **Example** (Interrupting a fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const fiber = yield* Effect.forkChild(\n * Effect.delay(\"1 second\")(Effect.succeed(42))\n * )\n * yield* Fiber.interrupt(fiber)\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link interruptAs} for specifying the interrupting fiber ID\n * @see {@link await_ await} for observing the interrupted fiber's Exit\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interrupt = effect.fiberInterrupt;\n/**\n * Interrupts a fiber with a specific fiber ID as the interruptor. This allows\n * tracking which fiber initiated the interruption.\n *\n * **When to use**\n *\n * Use when runtime diagnostics or tracing should attribute the interruption to\n * a specific fiber ID.\n *\n * **Details**\n *\n * The returned Effect completes only after the interrupted fiber has completed.\n *\n * **Gotchas**\n *\n * The supplied ID affects the recorded interruptor. It does not make\n * interruption synchronous or force uninterruptible regions to stop early.\n *\n * **Example** (Interrupting a fiber as another fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const targetFiber = yield* Effect.forkChild(\n * Effect.delay(\"5 seconds\")(Effect.succeed(\"task completed\"))\n * )\n *\n * // Interrupt the fiber, specifying fiber ID 123 as the interruptor\n * yield* Fiber.interruptAs(targetFiber, 123)\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link interrupt} for using the current fiber as the interruptor\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptAs = effect.fiberInterruptAs;\n/**\n * Interrupts all fibers in the provided iterable, causing them to stop executing\n * and clean up any acquired resources.\n *\n * **When to use**\n *\n * Use when you need to cancel several forked fibers and wait for their cleanup\n * to complete.\n *\n * **Details**\n *\n * The current fiber is recorded as the interruptor. The returned Effect\n * completes only after all interrupted fibers have completed.\n *\n * **Gotchas**\n *\n * Interruption is cooperative for each fiber. The returned Effect can wait for\n * uninterruptible work and finalizers in any interrupted fiber.\n *\n * **Example** (Interrupting multiple fibers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const fiber1 = yield* Effect.forkChild(Effect.never)\n * const fiber2 = yield* Effect.forkChild(Effect.never)\n * const fiber3 = yield* Effect.forkChild(Effect.never)\n * yield* Fiber.interruptAll([fiber1, fiber2, fiber3])\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link interruptAllAs} for specifying the interrupting fiber ID\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptAll = effect.fiberInterruptAll;\n/**\n * Interrupts all fibers in the provided iterable using the specified fiber ID as the\n * interrupting fiber. This allows you to control which fiber is considered the source\n * of the interruption, which can be useful for debugging and tracing.\n *\n * **When to use**\n *\n * Use to interrupt several fibers while recording a specific fiber ID as the\n * interruptor.\n *\n * **Details**\n *\n * The returned Effect completes only after all interrupted fibers have\n * completed.\n *\n * **Gotchas**\n *\n * The supplied ID affects the recorded interruptor. It does not make\n * interruption synchronous or force uninterruptible regions to stop early.\n *\n * **Example** (Interrupting multiple fibers as another fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a controlling fiber\n * const controllerFiber = yield* Effect.forkChild(Effect.succeed(\"controller\"))\n *\n * const worker1 = yield* Effect.forkChild(Effect.never)\n * const worker2 = yield* Effect.forkChild(Effect.never)\n *\n * yield* Fiber.interruptAllAs([worker1, worker2], controllerFiber.id)\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link interruptAll} for using the current fiber as the interruptor\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptAllAs = effect.fiberInterruptAllAs;\n/**\n * Checks whether a value is a Fiber. This is a type guard that can be used to\n * determine if an unknown value is a Fiber instance.\n *\n * **When to use**\n *\n * Use when checking values at boundaries where an unknown value may be a\n * runtime fiber.\n *\n * **Details**\n *\n * The check looks for the internal Fiber type ID marker and does not inspect\n * the fiber's current state.\n *\n * **Example** (Checking for fibers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a fiber\n * const fiber = yield* Effect.forkChild(Effect.succeed(42))\n *\n * // Test if values are fibers\n * return [Fiber.isFiber(fiber), Fiber.isFiber(\"hello\"), Fiber.isFiber(42), Fiber.isFiber(null)]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [true, false, false, false]\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isFiber = u => hasProperty(u, effect.FiberTypeId);\n/**\n * Returns the current fiber if called from within a fiber context,\n * otherwise returns `undefined`.\n *\n * **When to use**\n *\n * Use when you need low-level runtime integrations that need access to the currently\n * executing fiber.\n *\n * **Gotchas**\n *\n * This is a synchronous accessor, not an Effect. It returns `undefined` outside\n * an active fiber runtime context.\n *\n * **Example** (Getting the current fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const current = Fiber.getCurrent()\n * return current !== undefined\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => true\n * ```\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getCurrent = effect.getCurrentFiber;\n/**\n * Adds a fiber to a `Scope` and returns the same fiber.\n *\n * **When to use**\n *\n * Use when a manually managed fiber should be interrupted when a Scope closes.\n *\n * **Details**\n *\n * When the scope is closed, the fiber is interrupted. If the scope is already\n * closed, the fiber is interrupted immediately.\n *\n * **Gotchas**\n *\n * This does not wait for the fiber to complete. It only registers the\n * interruption finalizer and returns the same fiber.\n *\n * @see {@link interrupt} for interrupting and waiting for completion\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const runIn = effect.fiberRunIn;\n//# sourceMappingURL=Fiber.js.map","import * as internal from \"./internal/effect.js\";\n/**\n * Creates a `Latch` synchronously, outside of `Effect`.\n *\n * **When to use**\n *\n * Use when you need to allocate a `Latch` synchronously outside an Effect\n * workflow.\n *\n * **Details**\n *\n * The latch starts closed by default; pass `true` to create it open.\n *\n * **Example** (Creating a latch unsafely)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, Latch } from \"effect\"\n *\n * const latch = Latch.makeUnsafe(false)\n * const waiter = latch.await.pipe(Effect.as(\"opened\"))\n *\n * const program = Effect.gen(function*() {\n * const fiber = yield* Effect.forkChild(waiter)\n * yield* latch.open\n * return yield* Fiber.join(fiber)\n * })\n *\n * await Effect.runPromise(program) // => \"opened\"\n * ```\n *\n * @see {@link make} for creating a latch inside Effect code\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = internal.makeLatchUnsafe;\n/**\n * Creates a `Latch` inside `Effect`.\n *\n * **When to use**\n *\n * Use to create a latch for coordinating fibers inside Effect code.\n *\n * **Details**\n *\n * The latch starts closed by default; pass `true` to create it open.\n *\n * **Example** (Creating a latch)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, Latch } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const latch = yield* Latch.make(false)\n * const waiter = latch.await.pipe(Effect.as(\"opened\"))\n *\n * const fiber = yield* Effect.forkChild(waiter)\n * yield* latch.open\n * return yield* Fiber.join(fiber)\n * })\n *\n * await Effect.runPromise(program) // => \"opened\"\n * ```\n *\n * @see {@link makeUnsafe} for synchronous allocation outside Effect code\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = internal.makeLatch;\n/**\n * Opens the latch and releases fibers waiting on it.\n *\n * **When to use**\n *\n * Use to open a latch and release all fibers that are waiting on it.\n *\n * **Details**\n *\n * The returned effect succeeds with `true` when this call changed the latch\n * from closed to open, or `false` if it was already open.\n *\n * @see {@link openUnsafe} for a synchronous variant\n * @see {@link release} to release waiting fibers without opening the latch\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const open = self => self.open;\n/**\n * Opens the latch synchronously and releases fibers waiting on it.\n *\n * **When to use**\n *\n * Use when you need synchronous code to open a latch immediately and release\n * the fibers waiting on it.\n *\n * **Details**\n *\n * Returns `true` when this call changed the latch from closed to open, or\n * `false` if it was already open. This unsafe variant performs the state\n * change immediately instead of returning an `Effect`.\n *\n * @see {@link open} for the effectful variant\n * @see {@link release} to release waiting fibers without opening the latch\n * @see {@link closeUnsafe} for the synchronous inverse operation\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const openUnsafe = self => self.openUnsafe();\n/**\n * Releases the fibers currently waiting on a closed latch without opening it.\n *\n * **When to use**\n *\n * Use to let the fibers currently waiting on a latch proceed while keeping the\n * latch closed for future waiters.\n *\n * **Details**\n *\n * The returned effect succeeds with `true` when release was requested while\n * the latch was closed, or `false` if the latch was already open. Future\n * waiters still suspend until the latch is opened or released again.\n *\n * @see {@link open} for opening the latch for current and future waiters\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const release = self => self.release;\nconst _await = self => self.await;\nexport {\n/**\n * Waits for the latch to be opened.\n *\n * **When to use**\n *\n * Use to suspend the current fiber until the latch is opened or the current\n * set of waiters is released.\n *\n * **Details**\n *\n * Awaiting an already open latch completes immediately. Awaiting a closed\n * latch suspends until `open` or `release` resumes the waiters.\n *\n * **Gotchas**\n *\n * `release` can resume current waiters without opening the latch, so later\n * waiters may still suspend.\n *\n * @see {@link open} for opening the latch for current and future waiters\n * @see {@link release} for resuming current waiters without opening the latch\n * @see {@link whenOpen} for waiting before running another effect\n *\n * @category getters\n * @since 4.0.0\n */\n_await as await };\n/**\n * Closes the latch so future `await` and `whenOpen` calls suspend.\n *\n * **When to use**\n *\n * Use to re-enable waiting on a latch after it was opened, so later `await`\n * and `whenOpen` calls suspend again.\n *\n * **Details**\n *\n * The returned effect succeeds with `true` when this call changed the latch\n * from open to closed, or `false` if it was already closed.\n *\n * @see {@link closeUnsafe} for a synchronous variant\n * @see {@link open} for opening the latch for current and future waiters\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const close = self => self.close;\n/**\n * Closes the latch synchronously so future `await` and `whenOpen` calls\n * suspend.\n *\n * **When to use**\n *\n * Use to close a latch synchronously when the state change must happen outside\n * an `Effect`.\n *\n * **Details**\n *\n * Returns `true` when this call changed the latch from open to closed, or\n * `false` if it was already closed. This unsafe variant performs the state\n * change immediately instead of returning an `Effect`.\n *\n * @see {@link close} for the effectful variant\n * @see {@link openUnsafe} to synchronously open the latch and release waiting\n * fibers\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const closeUnsafe = self => self.closeUnsafe();\n/**\n * Waits on the latch, then runs the provided effect.\n *\n * **When to use**\n *\n * Use to gate another effect so it starts only after the latch is opened or\n * the current waiters are released.\n *\n * **Details**\n *\n * If the latch is open, the effect runs immediately. If it is closed, the\n * returned effect suspends until the latch is opened or the current waiters are\n * released. The provided effect's success, failure, and requirements are\n * preserved.\n *\n * @see `await` for waiting without running another effect\n * @see {@link open} for opening the latch for current and future waiters\n * @see {@link release} for resuming current waiters without opening the latch\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const whenOpen = (...args) => {\n if (args.length === 1) {\n const [self] = args;\n return effect => self.whenOpen(effect);\n }\n const [self, effect] = args;\n return self.whenOpen(effect);\n};\n/**\n * Checks whether the latch is currently open or closed.\n *\n * **When to use**\n *\n * Use to check the state of the latch without suspending or changing its state.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isOpen = self => self.isOpen();\n//# sourceMappingURL=Latch.js.map","/**\n * Stores synchronous mutable state in a small reference object.\n *\n * A `MutableRef<A>` stores one current value and exposes it through `.current`.\n * Unlike `Ref`, its operations are synchronous and update the same object in\n * place. This module includes pipeable helpers for reading, setting, comparing,\n * and updating the value, plus numeric increment/decrement helpers and a\n * boolean toggle helper.\n *\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\";\nimport * as Dual from \"./Function.js\";\nimport { toJson } from \"./Inspectable.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nconst TypeId = \"~effect/MutableRef\";\nconst MutableRefProto = {\n [TypeId]: TypeId,\n ...PipeInspectableProto,\n toJSON() {\n return {\n _id: \"MutableRef\",\n current: toJson(this.current)\n };\n }\n};\n/**\n * Creates a new MutableRef with the specified initial value.\n *\n * **When to use**\n *\n * Use to create a synchronous `MutableRef` initialized with a value.\n *\n * **Example** (Creating mutable refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * // Create a counter reference\n * const counter = MutableRef.make(0)\n *\n * MutableRef.get(counter) // => 0\n *\n * // Create a configuration reference\n * const config = MutableRef.make({ debug: false, timeout: 5000 })\n *\n * MutableRef.get(config) // => { debug: false, timeout: 5000 }\n *\n * // Create a string reference\n * const status = MutableRef.make(\"idle\")\n * MutableRef.set(status, \"running\")\n *\n * MutableRef.get(status) // => \"running\"\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = value => {\n const ref = Object.create(MutableRefProto);\n ref.current = value;\n return ref;\n};\n/**\n * Sets the value to newValue atomically if the current value equals oldValue.\n * Returns true if the value was updated, false otherwise.\n * Uses Effect's Equal interface for value comparison.\n *\n * **When to use**\n *\n * Use to replace a `MutableRef` value only when the current value still matches\n * an expected value.\n *\n * **Example** (Comparing and setting values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"initial\")\n *\n * // Successful compare and set\n * const updated = MutableRef.compareAndSet(ref, \"initial\", \"updated\")\n *\n * updated // => true\n * MutableRef.get(ref) // => \"updated\"\n *\n * // Failed compare and set (value doesn't match)\n * const failed = MutableRef.compareAndSet(ref, \"initial\", \"failed\")\n *\n * failed // => false\n * MutableRef.get(ref) // => \"updated\"\n *\n * // Thread-safe counter increment\n * const counter = MutableRef.make(5)\n * let current: number\n * do {\n * current = MutableRef.get(counter)\n * } while (!MutableRef.compareAndSet(counter, current, current + 1))\n *\n * MutableRef.get(counter) // => 6\n *\n * // Pipe-able version\n * const casUpdate = MutableRef.compareAndSet(\"updated\", \"final\")\n *\n * casUpdate(ref) // => true\n * MutableRef.get(ref) // => \"final\"\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const compareAndSet = /*#__PURE__*/Dual.dual(3, (self, oldValue, newValue) => {\n if (Equal.equals(oldValue, self.current)) {\n self.current = newValue;\n return true;\n }\n return false;\n});\n/**\n * Decrements a numeric MutableRef by 1 and returns the reference.\n *\n * **When to use**\n *\n * Use when you need an in-place `MutableRef` decrement that returns the same\n * `MutableRef`.\n *\n * **Example** (Decrementing numeric refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Decrement the counter\n * MutableRef.decrement(counter)\n *\n * MutableRef.get(counter) // => 4\n *\n * // Chain operations\n * MutableRef.decrement(counter)\n * MutableRef.decrement(counter)\n *\n * MutableRef.get(counter) // => 2\n *\n * // Useful for countdown scenarios\n * const countdown = MutableRef.make(10)\n * while (MutableRef.get(countdown) > 0) {\n * MutableRef.decrement(countdown)\n * }\n *\n * MutableRef.get(countdown) // => 0\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const decrement = self => update(self, n => n - 1);\n/**\n * Decrements a numeric MutableRef by 1 and returns the new value.\n *\n * **When to use**\n *\n * Use to decrement a numeric `MutableRef` and immediately read the updated\n * value.\n *\n * **Example** (Decrementing and reading refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Decrement and get the new value\n * const newValue = MutableRef.decrementAndGet(counter)\n *\n * newValue // => 4\n * MutableRef.get(counter) // => 4\n *\n * // Use in expressions\n * const lives = MutableRef.make(3)\n * const message = `Lives remaining: ${MutableRef.decrementAndGet(lives)}`\n *\n * message // => \"Lives remaining: 2\"\n *\n * // Conditional logic based on decremented value\n * const attempts = MutableRef.make(3)\n * let retries = 0\n * while (MutableRef.decrementAndGet(attempts) >= 0) {\n * retries += 1\n * }\n *\n * retries // => 3\n * MutableRef.get(attempts) // => -1\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const decrementAndGet = self => updateAndGet(self, n => n - 1);\n/**\n * Gets the current value of the MutableRef.\n *\n * **When to use**\n *\n * Use to read the current `MutableRef` value without mutating it.\n *\n * **Example** (Reading current values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"hello\")\n *\n * MutableRef.get(ref) // => \"hello\"\n *\n * MutableRef.set(ref, \"world\")\n *\n * MutableRef.get(ref) // => \"world\"\n *\n * // Reading complex objects\n * const config = MutableRef.make({ port: 3000, host: \"localhost\" })\n * const currentConfig = MutableRef.get(config)\n *\n * currentConfig // => { port: 3000, host: \"localhost\" }\n *\n * // Multiple reads return the same value\n * const value1 = MutableRef.get(ref)\n * const value2 = MutableRef.get(ref)\n *\n * value1 === value2 // => true\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const get = self => self.current;\n/**\n * Decrements a numeric MutableRef by 1 and returns the previous value.\n *\n * **When to use**\n *\n * Use to read the current numeric `MutableRef` value before decrementing it.\n *\n * **Example** (Reading before decrementing)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Get current value and then decrement\n * const previousValue = MutableRef.getAndDecrement(counter)\n *\n * previousValue // => 5\n * MutableRef.get(counter) // => 4\n *\n * // Useful for processing where you need the original value\n * const itemsLeft = MutableRef.make(10)\n * const processedItems: Array<number> = []\n * while (MutableRef.get(itemsLeft) > 0) {\n * const currentItem = MutableRef.getAndDecrement(itemsLeft)\n * processedItems.push(currentItem)\n * }\n *\n * processedItems // => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n * MutableRef.get(itemsLeft) // => 0\n *\n * // Post-decrement semantics (like i-- in other languages)\n * const index = MutableRef.make(3)\n * const currentIndex = MutableRef.getAndDecrement(index)\n * const nextIndex = MutableRef.get(index)\n *\n * currentIndex // => 3\n * nextIndex // => 2\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndDecrement = self => getAndUpdate(self, n => n - 1);\n/**\n * Increments a numeric MutableRef by 1 and returns the previous value.\n *\n * **When to use**\n *\n * Use to read the current numeric `MutableRef` value before incrementing it.\n *\n * **Example** (Reading before incrementing)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Get current value and then increment\n * const previousValue = MutableRef.getAndIncrement(counter)\n *\n * previousValue // => 5\n * MutableRef.get(counter) // => 6\n *\n * // Useful for ID generation\n * const idGenerator = MutableRef.make(0)\n * const getId = () => MutableRef.getAndIncrement(idGenerator)\n * const ids = [getId(), getId(), getId()]\n *\n * ids // => [0, 1, 2]\n *\n * // Post-increment semantics (like i++ in other languages)\n * const position = MutableRef.make(0)\n * const currentPos = MutableRef.getAndIncrement(position)\n * const nextPos = MutableRef.get(position)\n *\n * currentPos // => 0\n * nextPos // => 1\n *\n * // Useful for iteration counters\n * const iterations = MutableRef.make(0)\n * const visited: Array<number> = []\n * while (MutableRef.get(iterations) < 5) {\n * const iteration = MutableRef.getAndIncrement(iterations)\n * visited.push(iteration)\n * }\n *\n * visited // => [0, 1, 2, 3, 4]\n * MutableRef.get(iterations) // => 5\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndIncrement = self => getAndUpdate(self, n => n + 1);\n/**\n * Sets the MutableRef to a new value and returns the previous value.\n *\n * **When to use**\n *\n * Use to replace the current `MutableRef` value while keeping the previous\n * value.\n *\n * **Example** (Reading before setting)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"old\")\n *\n * // Set new value and get the previous one\n * const previous = MutableRef.getAndSet(ref, \"new\")\n *\n * previous // => \"old\"\n * MutableRef.get(ref) // => \"new\"\n *\n * // Swapping values\n * const counter = MutableRef.make(5)\n * const oldValue = MutableRef.getAndSet(counter, 10)\n * const newValue = MutableRef.get(counter)\n *\n * oldValue // => 5\n * newValue // => 10\n *\n * // Pipe-able version\n * const setValue = MutableRef.getAndSet(\"final\")\n * const previousValue = setValue(ref)\n *\n * previousValue // => \"new\"\n * MutableRef.get(ref) // => \"final\"\n *\n * // Useful for atomic swaps in algorithms\n * const buffer = MutableRef.make<Array<string>>([\"a\", \"b\", \"c\"])\n * const oldBuffer = MutableRef.getAndSet(buffer, [])\n *\n * oldBuffer // => [\"a\", \"b\", \"c\"]\n * MutableRef.get(buffer) // => []\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndSet = /*#__PURE__*/Dual.dual(2, (self, value) => {\n const ret = self.current;\n self.current = value;\n return ret;\n});\n/**\n * Updates the MutableRef with the result of applying a function to its current value,\n * and returns the previous value.\n *\n * **When to use**\n *\n * Use to transform the current `MutableRef` value while keeping the previous\n * value.\n *\n * **Example** (Reading before updating)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment and get the old value\n * const oldValue = MutableRef.getAndUpdate(counter, (n) => n + 1)\n *\n * oldValue // => 5\n * MutableRef.get(counter) // => 6\n *\n * // Double the value and get the previous one\n * const previous = MutableRef.getAndUpdate(counter, (n) => n * 2)\n *\n * previous // => 6\n * MutableRef.get(counter) // => 12\n *\n * // Transform string and get old value\n * const message = MutableRef.make(\"hello\")\n * const oldMessage = MutableRef.getAndUpdate(message, (s) => s.toUpperCase())\n *\n * oldMessage // => \"hello\"\n * MutableRef.get(message) // => \"HELLO\"\n *\n * // Pipe-able version\n * const addOne = MutableRef.getAndUpdate((n: number) => n + 1)\n * const result = addOne(counter)\n *\n * result // => 12\n * MutableRef.get(counter) // => 13\n *\n * // Useful for implementing atomic operations\n * const list = MutableRef.make<Array<number>>([1, 2, 3])\n * const oldList = MutableRef.getAndUpdate(list, (arr) => [...arr, 4])\n *\n * oldList // => [1, 2, 3]\n * MutableRef.get(list) // => [1, 2, 3, 4]\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdate = /*#__PURE__*/Dual.dual(2, (self, f) => getAndSet(self, f(get(self))));\n/**\n * Increments a numeric MutableRef by 1 and returns the reference.\n *\n * **When to use**\n *\n * Use when you need an in-place `MutableRef` increment that returns the same\n * `MutableRef`.\n *\n * **Example** (Incrementing numeric refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment the counter\n * MutableRef.increment(counter)\n *\n * MutableRef.get(counter) // => 6\n *\n * // Chain operations\n * MutableRef.increment(counter)\n * MutableRef.increment(counter)\n *\n * MutableRef.get(counter) // => 8\n *\n * // Useful for simple counting\n * const visits = MutableRef.make(0)\n * MutableRef.increment(visits) // User visited\n * MutableRef.increment(visits) // Another visit\n *\n * MutableRef.get(visits) // => 2\n *\n * // Returns the reference for chaining\n * const result = MutableRef.increment(counter)\n *\n * result === counter // => true\n * MutableRef.get(counter) // => 9\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const increment = self => update(self, n => n + 1);\n/**\n * Increments a numeric MutableRef by 1 and returns the new value.\n *\n * **When to use**\n *\n * Use to increment a numeric `MutableRef` and immediately read the updated\n * value.\n *\n * **Example** (Incrementing and reading refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment and get the new value\n * const newValue = MutableRef.incrementAndGet(counter)\n *\n * newValue // => 6\n * MutableRef.get(counter) // => 6\n *\n * // Use in expressions\n * const score = MutableRef.make(100)\n * const message = `New score: ${MutableRef.incrementAndGet(score)}`\n *\n * message // => \"New score: 101\"\n *\n * // Pre-increment semantics (like ++i in other languages)\n * const level = MutableRef.make(0)\n * const nextLevel = MutableRef.incrementAndGet(level)\n *\n * nextLevel // => 1\n *\n * // Conditional logic based on incremented value\n * const attempts = MutableRef.make(0)\n * const tooManyAttempts = MutableRef.incrementAndGet(attempts) > 3\n *\n * tooManyAttempts // => false\n * MutableRef.get(attempts) // => 1\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const incrementAndGet = self => updateAndGet(self, n => n + 1);\n/**\n * Sets the MutableRef to a new value and returns the reference.\n *\n * **When to use**\n *\n * Use when you need an in-place `MutableRef` replacement that returns the same\n * `MutableRef`.\n *\n * **Example** (Setting values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"initial\")\n *\n * // Set a new value\n * MutableRef.set(ref, \"updated\")\n *\n * MutableRef.get(ref) // => \"updated\"\n *\n * // Chain set operations (since it returns the ref)\n * const result = MutableRef.set(ref, \"final\")\n *\n * result === ref // => true\n * MutableRef.get(ref) // => \"final\"\n *\n * // Set complex objects\n * const config = MutableRef.make({ debug: false, verbose: false })\n * MutableRef.set(config, { debug: true, verbose: true })\n *\n * MutableRef.get(config) // => { debug: true, verbose: true }\n *\n * // Pipe-able version\n * const setValue = MutableRef.set(\"new value\")\n * setValue(ref)\n *\n * MutableRef.get(ref) // => \"new value\"\n *\n * // Useful for state management\n * const state = MutableRef.make<\"idle\" | \"loading\" | \"success\" | \"error\">(\"idle\")\n * MutableRef.set(state, \"loading\")\n * // ... perform async operation\n * MutableRef.set(state, \"success\")\n *\n * MutableRef.get(state) // => \"success\"\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const set = /*#__PURE__*/Dual.dual(2, (self, value) => {\n self.current = value;\n return self;\n});\n/**\n * Sets the MutableRef to a new value and returns the new value.\n *\n * **When to use**\n *\n * Use to replace the current `MutableRef` value and immediately read the\n * replacement.\n *\n * **Example** (Setting and reading values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"old\")\n *\n * // Set and get the new value\n * const newValue = MutableRef.setAndGet(ref, \"new\")\n *\n * newValue // => \"new\"\n * MutableRef.get(ref) // => \"new\"\n *\n * // Useful for assignments that need the value\n * const counter = MutableRef.make(0)\n * const currentValue = MutableRef.setAndGet(counter, 42)\n *\n * currentValue // => 42\n *\n * // Pipe-able version\n * const setValue = MutableRef.setAndGet(\"final\")\n * const result = setValue(ref)\n *\n * result // => \"final\"\n *\n * // Difference from set: returns value instead of reference\n * const ref1 = MutableRef.make(1)\n * const returnedRef = MutableRef.set(ref1, 2) // Returns MutableRef\n * const returnedValue = MutableRef.setAndGet(ref1, 3) // Returns value\n *\n * returnedRef === ref1 // => true\n * returnedValue // => 3\n * MutableRef.get(ref1) // => 3\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const setAndGet = /*#__PURE__*/Dual.dual(2, (self, value) => {\n self.current = value;\n return self.current;\n});\n/**\n * Updates the MutableRef with the result of applying a function to its current value,\n * and returns the reference.\n *\n * **When to use**\n *\n * Use when you need an in-place `MutableRef` value transformation that returns\n * the same `MutableRef`.\n *\n * **Example** (Updating values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment the counter\n * MutableRef.update(counter, (n) => n + 1)\n *\n * MutableRef.get(counter) // => 6\n *\n * // Chain updates (since it returns the ref)\n * const result = MutableRef.update(counter, (n) => n * 2)\n *\n * result === counter // => true\n * MutableRef.get(counter) // => 12\n *\n * // Transform string\n * const message = MutableRef.make(\"hello\")\n * MutableRef.update(message, (s) => s.toUpperCase())\n *\n * MutableRef.get(message) // => \"HELLO\"\n *\n * // Update complex objects\n * const user = MutableRef.make({ name: \"Alice\", age: 30 })\n * MutableRef.update(user, (u) => ({ ...u, age: u.age + 1 }))\n *\n * MutableRef.get(user) // => { name: \"Alice\", age: 31 }\n *\n * // Pipe-able version\n * const double = MutableRef.update((n: number) => n * 2)\n * double(counter)\n *\n * MutableRef.get(counter) // => 24\n *\n * // Array operations\n * const list = MutableRef.make<Array<number>>([1, 2, 3])\n * MutableRef.update(list, (arr) => [...arr, 4])\n *\n * MutableRef.get(list) // => [1, 2, 3, 4]\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const update = /*#__PURE__*/Dual.dual(2, (self, f) => set(self, f(get(self))));\n/**\n * Updates the MutableRef with the result of applying a function to its current value,\n * and returns the new value.\n *\n * **When to use**\n *\n * Use to transform the current `MutableRef` value and immediately read the\n * updated value.\n *\n * **Example** (Updating and reading values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment and get the new value\n * const newValue = MutableRef.updateAndGet(counter, (n) => n + 1)\n *\n * newValue // => 6\n * MutableRef.get(counter) // => 6\n *\n * // Double the value and get the result\n * const doubled = MutableRef.updateAndGet(counter, (n) => n * 2)\n *\n * doubled // => 12\n *\n * // Transform string and get result\n * const message = MutableRef.make(\"hello\")\n * const upperCase = MutableRef.updateAndGet(message, (s) => s.toUpperCase())\n *\n * upperCase // => \"HELLO\"\n *\n * // Pipe-able version\n * const increment = MutableRef.updateAndGet((n: number) => n + 1)\n * const result = increment(counter)\n *\n * result // => 13\n *\n * // Useful for calculations that need the result\n * const score = MutableRef.make(100)\n * const bonus = 50\n * const newScore = MutableRef.updateAndGet(score, (s) => s + bonus)\n *\n * newScore // => 150\n *\n * // Array transformations\n * const list = MutableRef.make<Array<number>>([1, 2, 3])\n * const newList = MutableRef.updateAndGet(list, (arr) => arr.map((x) => x * 2))\n *\n * newList // => [2, 4, 6]\n * MutableRef.get(list) // => [2, 4, 6]\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const updateAndGet = /*#__PURE__*/Dual.dual(2, (self, f) => setAndGet(self, f(get(self))));\n/**\n * Switches a boolean `MutableRef` between `true` and `false`, then returns the\n * reference.\n *\n * **When to use**\n *\n * Use when you need an in-place boolean `MutableRef` toggle that returns the\n * same `MutableRef`.\n *\n * **Example** (Toggling boolean refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const flag = MutableRef.make(false)\n *\n * // Toggle the flag\n * MutableRef.toggle(flag)\n *\n * MutableRef.get(flag) // => true\n *\n * // Toggle again\n * MutableRef.toggle(flag)\n *\n * MutableRef.get(flag) // => false\n *\n * // Useful for state switches\n * const isVisible = MutableRef.make(true)\n * MutableRef.toggle(isVisible) // Hide\n *\n * MutableRef.get(isVisible) // => false\n *\n * // Toggle button implementation\n * const darkMode = MutableRef.make(false)\n * const toggleDarkMode = () => {\n * MutableRef.toggle(darkMode)\n * return MutableRef.get(darkMode) ? \"ON\" : \"OFF\"\n * }\n *\n * toggleDarkMode() // => \"ON\"\n * toggleDarkMode() // => \"OFF\"\n *\n * // Returns the reference for chaining\n * const result = MutableRef.toggle(flag)\n *\n * result === flag // => true\n * MutableRef.get(flag) // => true\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const toggle = self => update(self, _ => !_);\n//# sourceMappingURL=MutableRef.js.map","/**\n * Mutable lists for collecting ordered values and draining them from the front.\n * A `MutableList<A>` can append values to the end, prepend values to the\n * beginning, take one or more values from the front, inspect its contents as an\n * array, filter values, remove values, and clear itself. All operations update\n * the same list object in place and keep its `length` field current. Taking\n * from an empty list returns the `Empty` symbol.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as Count from \"./internal/count.js\";\n/**\n * Defines the unique symbol used to represent an empty result when taking elements from a MutableList.\n * This symbol is returned by `take` when the list is empty, allowing for safe type checking.\n *\n * **When to use**\n *\n * Use to detect that `take` returned no element before handling the result as a\n * list item.\n *\n * **Example** (Checking for empty results)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n *\n * MutableList.take(list) === MutableList.Empty // => true\n * ```\n *\n * @category symbols\n * @since 4.0.0\n */\nexport const Empty = /*#__PURE__*/Symbol.for(\"effect/MutableList/Empty\");\n/**\n * Creates an empty MutableList.\n *\n * **Example** (Creating an empty mutable list)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n *\n * list.length // => 0\n * MutableList.append(list, \"first\")\n * MutableList.take(list) // => \"first\"\n * list.length // => 0\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = () => ({\n head: undefined,\n tail: undefined,\n length: 0\n});\nconst emptyBucket = () => ({\n array: [],\n mutable: true,\n offset: 0,\n next: undefined\n});\n/**\n * Appends an element to the end of the MutableList.\n * This operation is optimized for high-frequency usage.\n *\n * **Example** (Appending elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 1)\n * MutableList.append(list, 2)\n * MutableList.append(list, 3)\n *\n * MutableList.toArray(list) // => [1, 2, 3]\n * list.length // => 3\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const append = (self, message) => {\n if (!self.tail) {\n self.head = self.tail = emptyBucket();\n } else if (!self.tail.mutable) {\n self.tail.next = emptyBucket();\n self.tail = self.tail.next;\n }\n self.tail.array.push(message);\n self.length++;\n};\n/**\n * Prepends an element to the beginning of the MutableList.\n * This operation is optimized for high-frequency usage.\n *\n * **Example** (Prepending elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n * MutableList.append(list, \"last\")\n * MutableList.prepend(list, \"third\")\n * MutableList.prepend(list, \"second\")\n * MutableList.prepend(list, \"first\")\n *\n * MutableList.toArray(list) // => [\"first\", \"second\", \"third\", \"last\"]\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const prepend = (self, message) => {\n self.head = {\n array: [message],\n mutable: true,\n offset: 0,\n next: self.head\n };\n if (!self.tail) self.tail = self.head;\n self.length++;\n};\n/**\n * Prepends all elements from an iterable to the beginning of the MutableList.\n * The elements are added in order, so the first element in the iterable becomes\n * the new head of the list.\n *\n * **Example** (Prepending multiple elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 4)\n * MutableList.append(list, 5)\n * MutableList.prependAll(list, [1, 2, 3])\n *\n * MutableList.toArray(list) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const prependAll = (self, messages) => prependAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages));\n/**\n * Prepends all elements from a ReadonlyArray to the beginning of the MutableList.\n * This is an optimized version that can reuse the array when mutable=true.\n *\n * **When to use**\n *\n * Use when prepending a trusted array directly is worth the optimized path and\n * you can transfer ownership of the input when enabling mutation.\n *\n * **Gotchas**\n *\n * When mutable=true, ownership of the input array transfers to the list. Do not\n * read or modify the array afterward.\n *\n * **Example** (Transferring an array when prepending)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 4)\n * const items = [1, 2, 3]\n * MutableList.prependAllUnsafe(list, items, true)\n *\n * MutableList.toArray(list) // => [1, 2, 3, 4]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const prependAllUnsafe = (self, messages, mutable = false) => {\n self.head = {\n array: messages,\n mutable,\n offset: 0,\n next: self.head\n };\n if (!self.tail && messages.length > 0) self.tail = self.head;\n self.length += self.head.array.length;\n};\n/**\n * Appends all elements from an iterable to the end of the MutableList.\n * Returns the number of elements added.\n *\n * **Example** (Appending multiple elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 1)\n * MutableList.append(list, 2)\n *\n * MutableList.appendAll(list, [3, 4, 5]) // => 3\n * MutableList.toArray(list) // => [1, 2, 3, 4, 5]\n * list.length // => 5\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const appendAll = (self, messages) => appendAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages));\n/**\n * Appends all elements from a ReadonlyArray to the end of the MutableList.\n * This is an optimized version that can reuse the array when mutable=true.\n * Returns the number of elements added.\n *\n * **When to use**\n *\n * Use when appending a trusted array directly is worth the optimized path and\n * you can transfer ownership of the input when enabling mutation.\n *\n * **Gotchas**\n *\n * When mutable=true, ownership of the input array transfers to the list. Do not\n * read or modify the array afterward.\n *\n * **Example** (Transferring an array when appending)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 1)\n * const items = [2, 3, 4]\n * MutableList.appendAllUnsafe(list, items, true) // => 3\n *\n * MutableList.toArray(list) // => [1, 2, 3, 4]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const appendAllUnsafe = (self, messages, mutable = false) => {\n if (messages.length === 0) {\n return 0;\n }\n const chunk = {\n array: messages,\n mutable,\n offset: 0,\n next: undefined\n };\n if (self.head) {\n self.tail = self.tail.next = chunk;\n } else {\n self.head = self.tail = chunk;\n }\n self.length += messages.length;\n return messages.length;\n};\n/**\n * Removes all elements from the MutableList, resetting it to an empty state.\n * This operation is highly optimized and releases all internal memory.\n *\n * **Example** (Clearing a mutable list)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.appendAll(list, [1, 2, 3, 4, 5])\n *\n * MutableList.clear(list)\n *\n * MutableList.toArray(list) // => []\n * list.length // => 0\n * MutableList.take(list) === MutableList.Empty // => true\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const clear = self => {\n self.head = self.tail = undefined;\n self.length = 0;\n};\n/**\n * Takes up to N elements from the beginning of the MutableList and returns them as an array.\n * The taken elements are removed from the list. This operation is optimized for performance\n * and includes zero-copy optimizations when possible.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values leave the list unchanged and return an empty array.\n *\n * **Example** (Taking batches)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n *\n * MutableList.takeN(list, 3) // => [1, 2, 3]\n * MutableList.toArray(list) // => [4, 5, 6, 7, 8, 9, 10]\n * list.length // => 7\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const takeN = (self, n) => {\n n = Count.normalize(n);\n if (n <= 0 || !self.head) return [];\n n = Math.min(n, self.length);\n if (n === self.length && self.head?.offset === 0 && !self.head.next) {\n const array = self.head.array;\n clear(self);\n return array;\n }\n const array = new Array(n);\n let index = 0;\n let chunk = self.head;\n while (chunk) {\n while (chunk.offset < chunk.array.length) {\n array[index++] = chunk.array[chunk.offset];\n if (chunk.mutable) chunk.array[chunk.offset] = undefined;\n chunk.offset++;\n if (index === n) {\n self.head = chunk;\n self.length -= n;\n if (self.length === 0) clear(self);\n return array;\n }\n }\n chunk = chunk.next;\n }\n clear(self);\n return array;\n};\n/**\n * Removes up to `n` elements from the beginning of the `MutableList` without\n * returning them.\n *\n * **When to use**\n *\n * Use to discard a bounded number of values from the head of a `MutableList`\n * when the removed values are not needed.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. If `n` is `NaN` or\n * non-positive, or the list is empty, the list is left unchanged. If the\n * normalized count is greater than or equal to the current length, the list is\n * cleared.\n *\n * @see {@link takeN} for removing up to `n` values and returning them as an array\n * @see {@link clear} for removing every value from the list\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const takeNVoid = (self, n) => {\n n = Count.normalize(n);\n if (n <= 0 || !self.head) return;\n n = Math.min(n, self.length);\n if (n === self.length && self.head?.offset === 0 && !self.head.next) {\n clear(self);\n return;\n }\n let count = 0;\n let chunk = self.head;\n while (chunk) {\n const size = chunk.array.length - chunk.offset;\n if (count + size > n) {\n chunk.offset += n - count;\n self.head = chunk;\n self.length -= n;\n return;\n }\n count += size;\n chunk = chunk.next;\n }\n clear(self);\n return;\n};\n/**\n * Takes all elements from the MutableList and returns them as an array.\n * The list becomes empty after this operation. This is equivalent to takeN(list, list.length).\n *\n * **Example** (Draining all elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n * MutableList.appendAll(list, [\"apple\", \"banana\", \"cherry\"])\n *\n * MutableList.takeAll(list) // => [\"apple\", \"banana\", \"cherry\"]\n * list.length // => 0\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const takeAll = self => takeN(self, self.length);\n/**\n * Takes a single element from the beginning of the MutableList.\n * Returns the element if available, or the Empty symbol if the list is empty.\n * The taken element is removed from the list.\n *\n * **Example** (Taking one element)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n * MutableList.appendAll(list, [\"first\", \"second\", \"third\"])\n *\n * MutableList.take(list) // => \"first\"\n * MutableList.toArray(list) // => [\"second\", \"third\"]\n * list.length // => 2\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const take = self => {\n if (!self.head) return Empty;\n const message = self.head.array[self.head.offset];\n if (self.head.mutable) self.head.array[self.head.offset] = undefined;\n self.head.offset++;\n self.length--;\n if (self.head.offset === self.head.array.length) {\n if (self.head.next) {\n self.head = self.head.next;\n } else {\n clear(self);\n }\n }\n return message;\n};\n/**\n * Copies up to `n` elements from the beginning of the `MutableList` into a new\n * array without modifying the list.\n *\n * **When to use**\n *\n * Use when you need to inspect or snapshot a bounded prefix of the list without\n * consuming it.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values return an empty array.\n *\n * @see {@link takeN} for removing up to `n` values and returning them as an array\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toArrayN = (self, n) => {\n n = Count.normalize(n);\n if (n <= 0) return [];\n const length = Math.min(n, self.length);\n const out = new Array(length);\n let index = 0;\n let bucket = self.head;\n while (bucket) {\n for (let i = bucket.offset; i < bucket.array.length; i++) {\n out[index++] = bucket.array[i];\n if (index === length) return out;\n }\n bucket = bucket.next;\n }\n return out;\n};\n/**\n * Copies all current elements of the `MutableList` into a new array without\n * modifying the list.\n *\n * **When to use**\n *\n * Use when you need a snapshot of all current elements while keeping the list\n * unchanged.\n *\n * @see {@link takeAll} for converting all elements to an array and clearing the list\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toArray = self => toArrayN(self, self.length);\n/**\n * Filters the MutableList in place, keeping only elements that satisfy the predicate.\n * This operation modifies the list and rebuilds its internal structure for efficiency.\n *\n * **Example** (Filtering in place)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n *\n * MutableList.filter(list, (n) => n % 2 === 0)\n *\n * MutableList.toArray(list) // => [2, 4, 6, 8, 10]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const filter = (self, f) => {\n const array = [];\n let chunk = self.head;\n while (chunk) {\n for (let i = chunk.offset; i < chunk.array.length; i++) {\n if (f(chunk.array[i], i)) {\n array.push(chunk.array[i]);\n }\n }\n chunk = chunk.next;\n }\n if (array.length === 0) {\n clear(self);\n return;\n }\n self.head = self.tail = {\n array,\n mutable: true,\n offset: 0,\n next: undefined\n };\n self.length = array.length;\n};\n/**\n * Removes all occurrences of a value from the `MutableList` using JavaScript\n * strict equality semantics.\n *\n * **When to use**\n *\n * Use when in-place removal should use JavaScript identity/strict equality\n * rather than Effect structural equality.\n *\n * **Details**\n *\n * The list is modified in place.\n *\n * **Gotchas**\n *\n * Values are compared with `!==`, so this does not use Effect structural\n * equality.\n *\n * **Example** (Removing matching values)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n * MutableList.appendAll(list, [\"apple\", \"banana\", \"apple\", \"cherry\", \"apple\"])\n *\n * MutableList.remove(list, \"apple\")\n *\n * MutableList.toArray(list) // => [\"banana\", \"cherry\"]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const remove = (self, value) => filter(self, v => v !== value);\n//# sourceMappingURL=MutableList.js.map","/**\n * Broadcasts values from publishers to many subscribers.\n *\n * Publishers add messages with `publish` or `publishAll`, and each active\n * `Subscription` receives its own copy of every accepted message. Unlike a\n * queue, subscribers do not compete for messages. This module includes bounded,\n * dropping, sliding, and unbounded hubs, optional replay buffers for late\n * subscribers, message-taking helpers, capacity and shutdown operations, and\n * low-level types for custom hub strategies.\n *\n * @since 2.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as Context from \"./Context.js\";\nimport * as Deferred from \"./Deferred.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\nimport { dual, identity } from \"./Function.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as Latch from \"./Latch.js\";\nimport * as MutableList from \"./MutableList.js\";\nimport * as MutableRef from \"./MutableRef.js\";\nimport { nextPow2 } from \"./Number.js\";\nimport * as Option from \"./Option.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport * as Scope from \"./Scope.js\";\nconst TypeId = \"~effect/PubSub\";\nconst SubscriptionTypeId = \"~effect/PubSub/Subscription\";\n/**\n * Creates a PubSub with a custom atomic implementation and strategy.\n *\n * **Example** (Creating a PubSub with a custom strategy)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create custom PubSub with specific atomic implementation and strategy\n * const pubsub = yield* PubSub.make<string>({\n * atomicPubSub: () => PubSub.makeAtomicBounded(100),\n * strategy: () => new PubSub.BackPressureStrategy()\n * })\n *\n * // Use the created PubSub\n * const published = yield* PubSub.publish(pubsub, \"Hello\")\n * yield* PubSub.shutdown(pubsub)\n * return published\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => Effect.sync(() => makePubSubUnsafe(options.atomicPubSub(), new Map(), Scope.makeUnsafe(), Latch.makeUnsafe(false), MutableRef.make(false), options.strategy()));\n/**\n * Creates a bounded `PubSub` that applies backpressure when it reaches\n * capacity.\n *\n * **Details**\n *\n * Published messages are retained until all current subscribers have taken\n * them. When the capacity is full, publishers suspend until space is available.\n * Pass an options object to configure both `capacity` and an optional replay\n * buffer for late subscribers.\n *\n * **Example** (Creating a bounded PubSub)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create bounded PubSub with capacity 100\n * const pubsub = yield* PubSub.bounded<string>(100)\n *\n * // Create with replay buffer for late subscribers\n * const pubsubWithReplay = yield* PubSub.bounded<string>({\n * capacity: 100,\n * replay: 10 // Last 10 messages replayed to new subscribers\n * })\n *\n * const capacities = [PubSub.capacity(pubsub), PubSub.capacity(pubsubWithReplay)]\n * yield* PubSub.shutdown(pubsub)\n * yield* PubSub.shutdown(pubsubWithReplay)\n * return capacities\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [100, 100]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const bounded = capacity => make({\n atomicPubSub: () => makeAtomicBounded(capacity),\n strategy: () => new BackPressureStrategy()\n});\n/**\n * Creates a bounded `PubSub` with the dropping strategy. The `PubSub` will drop new\n * messages if the `PubSub` is at capacity.\n *\n * **Details**\n *\n * For best performance use capacities that are powers of two.\n *\n * **Example** (Dropping messages when full)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * // Create dropping PubSub that drops new messages when full\n * const pubsub = yield* PubSub.dropping<string>(3)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Fill the PubSub and see dropping behavior\n * yield* PubSub.publish(pubsub, \"msg1\") // succeeds\n * yield* PubSub.publish(pubsub, \"msg2\") // succeeds\n * yield* PubSub.publish(pubsub, \"msg3\") // succeeds\n * const dropped = yield* PubSub.publish(pubsub, \"msg4\") // returns false (dropped)\n *\n * const messages = yield* PubSub.takeAll(subscription)\n * return { dropped: !dropped, messages }\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { dropped: true, messages: [\"msg1\", \"msg2\", \"msg3\"] }\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const dropping = capacity => make({\n atomicPubSub: () => makeAtomicBounded(capacity),\n strategy: () => new DroppingStrategy()\n});\n/**\n * Creates a bounded `PubSub` with the sliding strategy. The `PubSub` will add new\n * messages and drop old messages if the `PubSub` is at capacity.\n *\n * **Details**\n *\n * For best performance use capacities that are powers of two.\n *\n * **Example** (Sliding old messages when full)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * // Create sliding PubSub that evicts old messages when full\n * const pubsub = yield* PubSub.sliding<string>(3)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Fill and overflow the PubSub\n * yield* PubSub.publish(pubsub, \"msg1\")\n * yield* PubSub.publish(pubsub, \"msg2\")\n * yield* PubSub.publish(pubsub, \"msg3\")\n * yield* PubSub.publish(pubsub, \"msg4\") // \"msg1\" is evicted\n *\n * return yield* PubSub.takeAll(subscription)\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"msg2\", \"msg3\", \"msg4\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sliding = capacity => make({\n atomicPubSub: () => makeAtomicBounded(capacity),\n strategy: () => new SlidingStrategy()\n});\n/**\n * Creates an unbounded `PubSub`.\n *\n * **Example** (Creating an unbounded PubSub)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * // Create unbounded PubSub\n * const pubsub = yield* PubSub.unbounded<string>()\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Can publish unlimited messages\n * for (let i = 0; i < 3; i++) {\n * yield* PubSub.publish(pubsub, `message-${i}`)\n * }\n *\n * return yield* PubSub.takeAll(subscription)\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"message-0\", \"message-1\", \"message-2\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unbounded = options => make({\n atomicPubSub: () => makeAtomicUnbounded(options),\n strategy: () => new DroppingStrategy()\n});\n/**\n * Creates a bounded atomic PubSub implementation with optional replay buffer.\n *\n * **When to use**\n *\n * Use to provide bounded message storage when building a custom `PubSub` with\n * `make` and an explicit delivery strategy.\n *\n * **Details**\n *\n * Pass either a capacity number or an options object with `capacity` and\n * optional `replay`. A positive `replay` value enables a replay buffer for late\n * subscribers, and fractional replay sizes are rounded up.\n *\n * **Gotchas**\n *\n * The capacity must be greater than zero; invalid capacities throw\n * synchronously before an atomic implementation is created.\n *\n * @see {@link make} for constructing a `PubSub` from an atomic implementation and delivery strategy\n * @see {@link makeAtomicUnbounded} for an atomic implementation without a bounded capacity\n * @see {@link bounded} for the higher-level backpressure constructor\n * @see {@link dropping} for the higher-level dropping constructor\n * @see {@link sliding} for the higher-level sliding constructor\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeAtomicBounded = capacity => {\n const options = typeof capacity === \"number\" ? {\n capacity\n } : capacity;\n ensureCapacity(options.capacity);\n const replayBuffer = options.replay && options.replay > 0 ? new ReplayBuffer(Math.ceil(options.replay)) : undefined;\n if (options.capacity === 1) {\n return new BoundedPubSubSingle(replayBuffer);\n } else if (nextPow2(options.capacity) === options.capacity) {\n return new BoundedPubSubPow2(options.capacity, replayBuffer);\n } else {\n return new BoundedPubSubArb(options.capacity, replayBuffer);\n }\n};\n/**\n * Creates an unbounded atomic PubSub implementation with optional replay buffer.\n *\n * **When to use**\n *\n * Use to create the low-level storage layer for a custom `PubSub` whose active\n * subscribers may retain an unbounded number of pending messages.\n *\n * **Gotchas**\n *\n * Messages published while subscribers are active can be retained without a\n * capacity limit until those subscribers take them or unsubscribe.\n *\n * @see {@link makeAtomicBounded} for a bounded atomic implementation that enforces capacity\n * @see {@link make} for wrapping an atomic implementation with a delivery strategy\n * @see {@link unbounded} for the high-level effectful constructor for unbounded `PubSub` values\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeAtomicUnbounded = options => {\n const replay = options?.replay;\n return new UnboundedPubSub(replay && replay > 0 ? new ReplayBuffer(Math.ceil(replay)) : undefined);\n};\n/**\n * Returns the number of elements the queue can hold.\n *\n * **Example** (Getting PubSub capacity)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(100)\n * const unboundedPubsub = yield* PubSub.unbounded<string>()\n * return [PubSub.capacity(pubsub), PubSub.capacity(unboundedPubsub)]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [100, Number.MAX_SAFE_INTEGER]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const capacity = self => self.pubsub.capacity;\n/**\n * Returns the current number of messages retained by the `PubSub` for active\n * subscribers.\n *\n * **Details**\n *\n * If the `PubSub` has been shut down, the returned effect succeeds with `0`.\n * The size is not a count of waiting subscribers or suspended publishers.\n *\n * **Example** (Getting PubSub size)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * // Initially empty\n * const initialSize = yield* PubSub.size(pubsub)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Publish some messages for the active subscription\n * yield* PubSub.publish(pubsub, \"msg1\")\n * yield* PubSub.publish(pubsub, \"msg2\")\n *\n * const afterPublish = yield* PubSub.size(pubsub)\n * const messages = yield* PubSub.takeAll(subscription)\n * return { initialSize, afterPublish, messages }\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { initialSize: 0, afterPublish: 2, messages: [\"msg1\", \"msg2\"] }\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const size = self => Effect.sync(() => sizeUnsafe(self));\n/**\n * Returns the current number of messages retained by the `PubSub` for active\n * subscribers synchronously.\n *\n * **When to use**\n *\n * Use when an immediate `PubSub` size snapshot is needed outside effectful code\n * and concurrent changes between the check and later use are acceptable.\n *\n * **Details**\n *\n * Returns `0` after shutdown. Because this is an unsafe synchronous snapshot,\n * prefer `size` in effectful code.\n *\n * **Example** (Reading size synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(2)\n * return PubSub.sizeUnsafe(pubsub)\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => 0\n * ```\n *\n * @category getters\n * @since 4.0.0\n */\nexport const sizeUnsafe = self => {\n if (MutableRef.get(self.shutdownFlag)) {\n return 0;\n }\n return self.pubsub.size();\n};\n/**\n * Returns `true` when the `PubSub` has reached its configured capacity.\n *\n * **Details**\n *\n * For unbounded PubSubs this is normally `false`.\n *\n * **Example** (Checking whether a PubSub is full)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(2)\n *\n * // Initially not full\n * const initiallyFull = yield* PubSub.isFull(pubsub)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Fill the PubSub for the active subscription\n * yield* PubSub.publish(pubsub, \"msg1\")\n * yield* PubSub.publish(pubsub, \"msg2\")\n *\n * const nowFull = yield* PubSub.isFull(pubsub)\n * const messages = yield* PubSub.takeAll(subscription)\n * return { initiallyFull, nowFull, messages }\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { initiallyFull: false, nowFull: true, messages: [\"msg1\", \"msg2\"] }\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isFull = self => Effect.map(size(self), size => size === self.pubsub.capacity);\n/**\n * Returns `true` if the `Pubsub` contains zero elements, `false` otherwise.\n *\n * **Example** (Checking whether a PubSub is empty)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * // Initially empty\n * const initiallyEmpty = yield* PubSub.isEmpty(pubsub)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Publish a message for the active subscription\n * yield* PubSub.publish(pubsub, \"Hello\")\n *\n * const nowEmpty = yield* PubSub.isEmpty(pubsub)\n * const message = yield* PubSub.take(subscription)\n * return { initiallyEmpty, nowEmpty, message }\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { initiallyEmpty: true, nowEmpty: false, message: \"Hello\" }\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isEmpty = self => Effect.map(size(self), size => size === 0);\n/**\n * Shuts down the `PubSub`, interrupting suspended publishers and subscribers\n * and finalizing active subscriptions.\n *\n * **Details**\n *\n * After shutdown, `publish` and `publishAll` succeed with `false`,\n * `publishUnsafe` returns `false`, and subscription operations such as `take`\n * interrupt.\n *\n * **Example** (Shutting down a PubSub)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(1)\n *\n * // Shutdown the PubSub\n * yield* PubSub.shutdown(pubsub)\n *\n * const isShutdown = yield* PubSub.isShutdown(pubsub)\n *\n * // Publishing after shutdown returns false\n * const published = yield* PubSub.publish(pubsub, \"msg1\")\n * return { isShutdown, published }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { isShutdown: true, published: false }\n * ```\n *\n * @category lifecycle\n * @since 2.0.0\n */\nexport const shutdown = self => Effect.uninterruptible(Effect.withFiber(fiber => {\n MutableRef.set(self.shutdownFlag, true);\n return Scope.close(self.scope, Exit.interrupt(fiber.id)).pipe(Effect.andThen(self.strategy.shutdown), Effect.when(self.shutdownHook.open), Effect.asVoid);\n}));\n/**\n * Checks effectfully whether `shutdown` has been called, returning `true`\n * after shutdown and `false` otherwise.\n *\n * **Example** (Checking whether a PubSub is shut down)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * // Initially not shutdown\n * const initiallyShutdown = yield* PubSub.isShutdown(pubsub)\n *\n * // Shutdown the PubSub\n * yield* PubSub.shutdown(pubsub)\n *\n * const nowShutdown = yield* PubSub.isShutdown(pubsub)\n * return [initiallyShutdown, nowShutdown]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [false, true]\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isShutdown = self => Effect.sync(() => isShutdownUnsafe(self));\n/**\n * Checks synchronously whether `shutdown` has been called, returning `true`\n * after shutdown and `false` otherwise.\n *\n * **When to use**\n *\n * Use when an immediate `PubSub` shutdown-state snapshot is needed outside\n * effectful code and racing shutdown changes are acceptable.\n *\n * **Example** (Checking shutdown synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(2)\n * const initiallyShutdown = PubSub.isShutdownUnsafe(pubsub)\n * yield* PubSub.shutdown(pubsub)\n * return [initiallyShutdown, PubSub.isShutdownUnsafe(pubsub)]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [false, true]\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isShutdownUnsafe = self => self.shutdownFlag.current;\n/**\n * Waits until the queue is shutdown. The `Effect` returned by this method will\n * not resume until the queue has been shutdown. If the queue is already\n * shutdown, the `Effect` will resume right away.\n *\n * **Example** (Waiting for shutdown)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * // Start a fiber that waits for shutdown\n * const waiterFiber = yield* Effect.forkChild(\n * Effect.gen(function*() {\n * yield* PubSub.awaitShutdown(pubsub)\n * return \"PubSub has been shutdown!\"\n * })\n * )\n *\n * // Shutdown the PubSub\n * yield* PubSub.shutdown(pubsub)\n *\n * // The waiter will now complete\n * return yield* Fiber.join(waiterFiber)\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => \"PubSub has been shutdown!\"\n * ```\n *\n * @category lifecycle\n * @since 2.0.0\n */\nexport const awaitShutdown = self => self.shutdownHook.await;\n/**\n * Publishes a message to the `PubSub` as an `Effect`, returning whether the\n * message was accepted.\n *\n * **When to use**\n *\n * Use when you need to publish from effectful code and let the configured\n * PubSub strategy handle surplus messages.\n *\n * **Details**\n *\n * The effect succeeds with `false` if the `PubSub` is shut down. If the message\n * cannot be accepted immediately, the configured strategy decides how surplus\n * messages are handled.\n *\n * **Example** (Publishing a message)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * // Publish a message\n * const published = yield* PubSub.publish(pubsub, \"Hello World\")\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * yield* PubSub.publish(pubsub, \"Hello\")\n * const message = yield* PubSub.take(subscription)\n * return { published, message }\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { published: true, message: \"Hello\" }\n * ```\n *\n * @see {@link publishUnsafe} for a synchronous non-blocking attempt that does not run effectful surplus handling\n *\n * @category publishing\n * @since 2.0.0\n */\nexport const publish = /*#__PURE__*/dual(2, (self, value) => Effect.suspend(() => {\n if (self.shutdownFlag.current) {\n return Effect.succeed(false);\n }\n if (self.pubsub.publish(value)) {\n self.strategy.completeSubscribersUnsafe(self.pubsub, self.subscribers);\n return Effect.succeed(true);\n }\n return self.strategy.handleSurplus(self.pubsub, self.subscribers, [value], self.shutdownFlag);\n}));\n/**\n * Attempts to publish a message synchronously without applying the PubSub\n * strategy's effectful surplus handling.\n *\n * **When to use**\n *\n * Use when you need a non-blocking synchronous publish attempt where `false`\n * is an acceptable result when the message cannot be accepted immediately.\n *\n * **Details**\n *\n * Returns `false` if the `PubSub` is shut down or the message cannot be\n * accepted immediately, for example when a bounded PubSub is full. Prefer\n * `publish` when backpressure or sliding behavior should be honored.\n *\n * **Example** (Publishing without suspending)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(2)\n * return PubSub.publishUnsafe(pubsub, \"Hello\")\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => true\n * ```\n *\n * @see {@link publish} for effectful publishing that honors the configured surplus strategy\n *\n * @category publishing\n * @since 4.0.0\n */\nexport const publishUnsafe = /*#__PURE__*/dual(2, (self, value) => {\n if (self.shutdownFlag.current) return false;\n if (self.pubsub.publish(value)) {\n self.strategy.completeSubscribersUnsafe(self.pubsub, self.subscribers);\n return true;\n }\n return false;\n});\n/**\n * Publishes all of the specified messages to the `PubSub`, returning whether they\n * were published to the `PubSub`.\n *\n * **Example** (Publishing multiple messages)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * // Publish multiple messages at once\n * const allPublished = yield* PubSub.publishAll(pubsub, [\"Hello\", \"World\", \"from\", \"Effect\"])\n *\n * // With a smaller capacity and an active subscription\n * const smallPubsub = yield* PubSub.bounded<string>(2)\n * const subscription = yield* PubSub.subscribe(smallPubsub)\n *\n * // Will suspend until space becomes available for all messages\n * const fiber = yield* Effect.forkChild(PubSub.publishAll(smallPubsub, [\"msg1\", \"msg2\", \"msg3\", \"msg4\"]))\n *\n * const firstBatch = yield* PubSub.takeBetween(subscription, 2, 2)\n * const result = yield* Fiber.join(fiber)\n * const secondBatch = yield* PubSub.takeAll(subscription)\n * return { allPublished, firstBatch, result, secondBatch }\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { allPublished: true, firstBatch: [\"msg1\", \"msg2\"], result: true, secondBatch: [\"msg3\", \"msg4\"] }\n * ```\n *\n * @category publishing\n * @since 2.0.0\n */\nexport const publishAll = /*#__PURE__*/dual(2, (self, elements) => Effect.suspend(() => {\n if (self.shutdownFlag.current) {\n return Effect.succeed(false);\n }\n const surplus = self.pubsub.publishAll(elements);\n self.strategy.completeSubscribersUnsafe(self.pubsub, self.subscribers);\n if (surplus.length === 0) {\n return Effect.succeed(true);\n }\n return self.strategy.handleSurplus(self.pubsub, self.subscribers, surplus, self.shutdownFlag);\n}));\n/**\n * Subscribes to receive messages from the `PubSub`. The resulting subscription can\n * be evaluated multiple times within the scope to take a message from the `PubSub`\n * each time.\n *\n * **Example** (Subscribing to messages)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * // Subscribe within a scope for automatic cleanup\n * const first = yield* Effect.scoped(Effect.gen(function*() {\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Publish some messages\n * yield* PubSub.publish(pubsub, \"Hello\")\n * yield* PubSub.publish(pubsub, \"World\")\n *\n * // Take messages one by one\n * const msg1 = yield* PubSub.take(subscription)\n * const msg2 = yield* PubSub.take(subscription)\n *\n * // Subscription is automatically cleaned up when scope exits\n * return [msg1, msg2]\n * }))\n *\n * const second = yield* Effect.scoped(Effect.gen(function*() {\n * const sub1 = yield* PubSub.subscribe(pubsub)\n * const sub2 = yield* PubSub.subscribe(pubsub)\n *\n * // Multiple subscribers can receive the same messages\n * yield* PubSub.publish(pubsub, \"Broadcast\")\n *\n * return yield* Effect.all([\n * PubSub.take(sub1),\n * PubSub.take(sub2)\n * ])\n * }))\n * return [first, second]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [[\"Hello\", \"World\"], [\"Broadcast\", \"Broadcast\"]]\n * ```\n *\n * @category subscriptions\n * @since 2.0.0\n */\nexport const subscribe = self => Effect.uninterruptible(Effect.contextWith(services => {\n const localScope = Context.get(services, Scope.Scope);\n const scope = Scope.forkUnsafe(self.scope);\n const subscription = makeSubscriptionUnsafe(self.pubsub, self.subscribers, self.strategy);\n return Scope.addFinalizer(scope, unsubscribe(subscription)).pipe(Effect.andThen(Scope.addFinalizerExit(localScope, exit => Scope.close(scope, exit))), Effect.as(subscription));\n}));\nconst unsubscribe = self => Effect.uninterruptible(Effect.withFiber(state => {\n MutableRef.set(self.shutdownFlag, true);\n return Effect.forEach(MutableList.takeAll(self.pollers), d => Deferred.interruptWith(d, state.id), {\n discard: true,\n concurrency: \"unbounded\"\n }).pipe(Effect.tap(() => Effect.sync(() => {\n self.subscribers.delete(self.subscription);\n self.subscription.unsubscribe();\n self.replayWindow.close();\n self.strategy.onPubSubEmptySpaceUnsafe(self.pubsub, self.subscribers);\n })), Effect.when(self.shutdownHook.open), Effect.asVoid);\n}));\n/**\n * Takes a single message from the subscription. If no messages are available,\n * this will suspend until a message becomes available.\n *\n * **Example** (Taking a message)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Start a fiber to take a message (will suspend)\n * const takeFiber = yield* Effect.forkChild(PubSub.take(subscription))\n *\n * // Publish a message\n * yield* PubSub.publish(pubsub, \"Hello\")\n *\n * // The take will now complete\n * return yield* Fiber.join(takeFiber)\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => \"Hello\"\n * ```\n *\n * @category subscriptions\n * @since 4.0.0\n */\nexport const take = self => Effect.suspend(() => {\n if (self.shutdownFlag.current) {\n return Effect.interrupt;\n }\n if (self.replayWindow.remaining > 0) {\n const message = self.replayWindow.take();\n return Effect.succeed(message);\n }\n const message = self.pollers.length === 0 ? self.subscription.poll() : MutableList.Empty;\n if (message === MutableList.Empty) {\n return pollForItem(self);\n } else {\n self.strategy.onPubSubEmptySpaceUnsafe(self.pubsub, self.subscribers);\n return Effect.succeed(message);\n }\n});\n/**\n * Takes all available messages from the subscription, suspending if no items\n * are available.\n *\n * **Example** (Taking all available messages)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Publish multiple messages\n * yield* PubSub.publishAll(pubsub, [\"msg1\", \"msg2\", \"msg3\"])\n *\n * // Take all available messages at once\n * return yield* PubSub.takeAll(subscription)\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"msg1\", \"msg2\", \"msg3\"]\n * ```\n *\n * @category subscriptions\n * @since 4.0.0\n */\nexport const takeAll = self => Effect.suspend(function loop(value) {\n if (self.shutdownFlag.current) {\n return Effect.interrupt;\n }\n let as = self.pollers.length === 0 ? self.subscription.pollUpTo(Number.POSITIVE_INFINITY) : [];\n if (value) {\n as = value.concat(as);\n }\n self.strategy.onPubSubEmptySpaceUnsafe(self.pubsub, self.subscribers);\n if (self.replayWindow.remaining > 0) {\n return Effect.succeed(self.replayWindow.takeAll().concat(as));\n } else if (!Arr.isArrayNonEmpty(as)) {\n return Effect.flatMap(pollForItem(self), item => loop([item]));\n }\n return Effect.succeed(as);\n});\nconst pollForItem = self => {\n const deferred = Deferred.makeUnsafe();\n let set = self.subscribers.get(self.subscription);\n if (!set) {\n set = new Set();\n self.subscribers.set(self.subscription, set);\n }\n set.add(self.pollers);\n MutableList.append(self.pollers, deferred);\n self.strategy.completePollersUnsafe(self.pubsub, self.subscribers, self.subscription, self.pollers);\n return Effect.onInterrupt(Deferred.await(deferred), () => {\n MutableList.remove(self.pollers, deferred);\n return Effect.void;\n });\n};\n/**\n * Takes up to the specified number of messages from the subscription without\n * suspending. Finite fractional values are rounded down, while `NaN` and\n * non-positive values are treated as `0`.\n *\n * **Example** (Taking up to a maximum number of messages)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Publish multiple messages\n * yield* PubSub.publishAll(pubsub, [\"msg1\", \"msg2\", \"msg3\", \"msg4\", \"msg5\"])\n *\n * // Take up to 3 messages\n * const upTo3 = yield* PubSub.takeUpTo(subscription, 3)\n *\n * // Take up to 5 more (only 2 remaining)\n * const upTo5 = yield* PubSub.takeUpTo(subscription, 5)\n *\n * // No more messages available\n * const noMore = yield* PubSub.takeUpTo(subscription, 10)\n * return [upTo3, upTo5, noMore]\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [[\"msg1\", \"msg2\", \"msg3\"], [\"msg4\", \"msg5\"], []]\n * ```\n *\n * @category subscriptions\n * @since 4.0.0\n */\nexport const takeUpTo = /*#__PURE__*/dual(2, (self, max) => Effect.suspend(() => {\n if (self.shutdownFlag.current) return Effect.interrupt;\n max = Count.normalize(max);\n let replay = undefined;\n if (self.replayWindow.remaining >= max) {\n return Effect.succeed(self.replayWindow.takeN(max));\n } else if (self.replayWindow.remaining > 0) {\n replay = self.replayWindow.takeAll();\n max = max - replay.length;\n }\n const as = self.pollers.length === 0 ? self.subscription.pollUpTo(max) : [];\n self.strategy.onPubSubEmptySpaceUnsafe(self.pubsub, self.subscribers);\n return replay ? Effect.succeed(replay.concat(as)) : Effect.succeed(as);\n}));\n/**\n * Takes between the specified minimum and maximum number of messages from the\n * subscription. Finite fractional bounds are rounded down, while `NaN` and\n * non-positive bounds are treated as `0`. Will suspend if the normalized\n * minimum number is not immediately available.\n *\n * **Example** (Taking between a minimum and maximum)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Start taking between 2 and 5 messages (will suspend)\n * const takeFiber = yield* Effect.forkChild(PubSub.takeBetween(subscription, 2, 5))\n *\n * // Publish 3 messages\n * yield* PubSub.publishAll(pubsub, [\"msg1\", \"msg2\", \"msg3\"])\n *\n * // Now the take will complete with 3 messages\n * return yield* Fiber.join(takeFiber)\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"msg1\", \"msg2\", \"msg3\"]\n * ```\n *\n * @category subscriptions\n * @since 4.0.0\n */\nexport const takeBetween = /*#__PURE__*/dual(3, (self, min, max) => Effect.suspend(() => takeRemainderLoop(self, Count.normalize(min), Count.normalize(max), [])));\nconst takeRemainderLoop = (self, min, max, acc) => {\n if (max < min) {\n return Effect.succeed(acc);\n }\n return Effect.flatMap(takeUpTo(self, max), bs => {\n acc.push(...bs);\n const remaining = min - bs.length;\n if (remaining === 1) {\n return Effect.map(take(self), b => {\n acc.push(b);\n return acc;\n });\n }\n if (remaining > 1) {\n return Effect.flatMap(take(self), b => {\n acc.push(b);\n return takeRemainderLoop(self, remaining - 1, max - bs.length - 1, acc);\n });\n }\n return Effect.succeed(acc);\n });\n};\n/**\n * Returns the number of messages currently available in the subscription as an\n * `Effect`.\n *\n * **When to use**\n *\n * Use when checking a subscription from effectful code and shutdown should\n * interrupt the effect.\n *\n * **Details**\n *\n * The count includes replay-buffered messages. If the subscription has been\n * shut down, the effect interrupts.\n *\n * **Example** (Checking remaining messages)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(10)\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Publish some messages\n * yield* PubSub.publishAll(pubsub, [\"msg1\", \"msg2\", \"msg3\"])\n *\n * // Check how many messages are available\n * const count = yield* PubSub.remaining(subscription)\n *\n * // Take one message\n * const message = yield* PubSub.take(subscription)\n *\n * const remaining = yield* PubSub.remaining(subscription)\n * return { count, message, remaining }\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { count: 3, message: \"msg1\", remaining: 2 }\n * ```\n *\n * @see {@link remainingUnsafe} for a synchronous check that reports shutdown as `Option.none()`\n *\n * @category getters\n * @since 4.0.0\n */\nexport const remaining = self => Effect.suspend(() => self.shutdownFlag.current ? Effect.interrupt : Effect.succeed(self.subscription.size() + self.replayWindow.remaining));\n/**\n * Synchronously returns the number of messages currently available in the\n * subscription, or `Option.none()` when it is shut down.\n *\n * **When to use**\n *\n * Use when you need synchronous polling outside a managed workflow and want\n * shutdown observed as data instead of interruption.\n *\n * **Example** (Checking remaining messages synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(2)\n * const subscription = yield* PubSub.subscribe(pubsub)\n * return PubSub.remainingUnsafe(subscription)\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => Option.some(0)\n * ```\n *\n * @see {@link remaining} for the effectful variant that interrupts on shutdown\n *\n * @category getters\n * @since 4.0.0\n */\nexport const remainingUnsafe = self => {\n if (self.shutdownFlag.current) {\n return Option.none();\n }\n return Option.some(self.subscription.size() + self.replayWindow.remaining);\n};\n// -----------------------------------------------------------------------------\n// internal\n// -----------------------------------------------------------------------------\nconst AbsentValue = /*#__PURE__*/Symbol.for(\"effect/PubSub/AbsentValue\");\nconst addSubscribers = (subscribers, subscription, pollers) => {\n if (!subscribers.has(subscription)) {\n subscribers.set(subscription, new Set());\n }\n const set = subscribers.get(subscription);\n set.add(pollers);\n};\nconst removeSubscribers = (subscribers, subscription, pollers) => {\n if (!subscribers.has(subscription)) {\n return;\n }\n const set = subscribers.get(subscription);\n set.delete(pollers);\n if (set.size === 0) {\n subscribers.delete(subscription);\n }\n};\nconst makeSubscriptionUnsafe = (pubsub, subscribers, strategy) => new SubscriptionImpl(pubsub, subscribers, pubsub.subscribe(), MutableList.make(), Latch.makeUnsafe(false), MutableRef.make(false), strategy, pubsub.replayWindow());\nclass BoundedPubSubArb {\n array;\n replayIndices;\n publisherIndex = 0;\n subscribers;\n subscriberCount = 0;\n subscribersIndex = 0;\n capacity;\n replayBuffer;\n constructor(capacity, replayBuffer) {\n this.capacity = capacity;\n this.replayBuffer = replayBuffer;\n this.array = Array.from({\n length: capacity\n });\n this.replayIndices = replayBuffer ? Array.from({\n length: capacity\n }) : [];\n this.subscribers = Array.from({\n length: capacity\n });\n }\n replayWindow() {\n return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow;\n }\n isEmpty() {\n return this.publisherIndex === this.subscribersIndex;\n }\n isFull() {\n return this.publisherIndex === this.subscribersIndex + this.capacity;\n }\n size() {\n return this.publisherIndex - this.subscribersIndex;\n }\n publish(value) {\n if (this.isFull()) {\n return false;\n }\n const replayIndex = this.replayBuffer?.offer(value);\n if (this.subscriberCount !== 0) {\n const index = this.publisherIndex % this.capacity;\n this.array[index] = value;\n if (replayIndex !== undefined) {\n this.replayIndices[index] = replayIndex;\n }\n this.subscribers[index] = this.subscriberCount;\n this.publisherIndex += 1;\n }\n return true;\n }\n publishAll(elements) {\n if (this.subscriberCount === 0) {\n if (this.replayBuffer) {\n this.replayBuffer.offerAll(elements);\n }\n return [];\n }\n const chunk = Arr.fromIterable(elements);\n const n = chunk.length;\n const size = this.publisherIndex - this.subscribersIndex;\n const available = this.capacity - size;\n const forPubSub = Math.min(n, available);\n if (forPubSub === 0) {\n return chunk;\n }\n let iteratorIndex = 0;\n const publishAllIndex = this.publisherIndex + forPubSub;\n while (this.publisherIndex !== publishAllIndex) {\n const a = chunk[iteratorIndex++];\n const index = this.publisherIndex % this.capacity;\n this.array[index] = a;\n const replayIndex = this.replayBuffer?.offer(a);\n if (replayIndex !== undefined) {\n this.replayIndices[index] = replayIndex;\n }\n this.subscribers[index] = this.subscriberCount;\n this.publisherIndex += 1;\n }\n return chunk.slice(iteratorIndex);\n }\n slide() {\n if (this.subscribersIndex !== this.publisherIndex) {\n const index = this.subscribersIndex % this.capacity;\n const value = this.array[index];\n this.array[index] = AbsentValue;\n this.subscribers[index] = 0;\n this.subscribersIndex += 1;\n this.replayBuffer?.slide(value, this.replayIndices[index]);\n }\n }\n subscribe() {\n this.subscriberCount += 1;\n return new BoundedPubSubArbSubscription(this, this.publisherIndex, false);\n }\n}\nclass BoundedPubSubArbSubscription {\n self;\n subscriberIndex;\n unsubscribed;\n constructor(self, subscriberIndex, unsubscribed) {\n this.self = self;\n this.subscriberIndex = subscriberIndex;\n this.unsubscribed = unsubscribed;\n }\n isEmpty() {\n return this.unsubscribed || this.self.publisherIndex === this.subscriberIndex || this.self.publisherIndex === this.self.subscribersIndex;\n }\n size() {\n if (this.unsubscribed) {\n return 0;\n }\n return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex);\n }\n poll() {\n if (this.unsubscribed) {\n return MutableList.Empty;\n }\n this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);\n if (this.subscriberIndex !== this.self.publisherIndex) {\n const index = this.subscriberIndex % this.self.capacity;\n const elem = this.self.array[index];\n this.self.subscribers[index] -= 1;\n if (this.self.subscribers[index] === 0) {\n this.self.array[index] = AbsentValue;\n this.self.subscribersIndex += 1;\n }\n this.subscriberIndex += 1;\n return elem;\n }\n return MutableList.Empty;\n }\n pollUpTo(n) {\n n = Count.normalize(n);\n if (this.unsubscribed) {\n return [];\n }\n this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);\n const size = this.self.publisherIndex - this.subscriberIndex;\n const toPoll = Math.min(n, size);\n if (toPoll <= 0) {\n return [];\n }\n const builder = [];\n const pollUpToIndex = this.subscriberIndex + toPoll;\n while (this.subscriberIndex !== pollUpToIndex) {\n const index = this.subscriberIndex % this.self.capacity;\n const a = this.self.array[index];\n this.self.subscribers[index] -= 1;\n if (this.self.subscribers[index] === 0) {\n this.self.array[index] = AbsentValue;\n this.self.subscribersIndex += 1;\n }\n builder.push(a);\n this.subscriberIndex += 1;\n }\n return builder;\n }\n unsubscribe() {\n if (!this.unsubscribed) {\n this.unsubscribed = true;\n this.self.subscriberCount -= 1;\n this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);\n while (this.subscriberIndex !== this.self.publisherIndex) {\n const index = this.subscriberIndex % this.self.capacity;\n this.self.subscribers[index] -= 1;\n if (this.self.subscribers[index] === 0) {\n this.self.array[index] = AbsentValue;\n this.self.subscribersIndex += 1;\n }\n this.subscriberIndex += 1;\n }\n }\n }\n}\nclass BoundedPubSubPow2 {\n array;\n replayIndices;\n mask;\n publisherIndex = 0;\n subscribers;\n subscriberCount = 0;\n subscribersIndex = 0;\n capacity;\n replayBuffer;\n constructor(capacity, replayBuffer) {\n this.capacity = capacity;\n this.replayBuffer = replayBuffer;\n this.array = Array.from({\n length: capacity\n });\n this.replayIndices = replayBuffer ? Array.from({\n length: capacity\n }) : [];\n this.mask = capacity - 1;\n this.subscribers = Array.from({\n length: capacity\n });\n }\n replayWindow() {\n return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow;\n }\n isEmpty() {\n return this.publisherIndex === this.subscribersIndex;\n }\n isFull() {\n return this.publisherIndex === this.subscribersIndex + this.capacity;\n }\n size() {\n return this.publisherIndex - this.subscribersIndex;\n }\n publish(value) {\n if (this.isFull()) {\n return false;\n }\n const replayIndex = this.replayBuffer?.offer(value);\n if (this.subscriberCount !== 0) {\n const index = this.publisherIndex & this.mask;\n this.array[index] = value;\n if (replayIndex !== undefined) {\n this.replayIndices[index] = replayIndex;\n }\n this.subscribers[index] = this.subscriberCount;\n this.publisherIndex += 1;\n }\n return true;\n }\n publishAll(elements) {\n if (this.subscriberCount === 0) {\n if (this.replayBuffer) {\n this.replayBuffer.offerAll(elements);\n }\n return [];\n }\n const chunk = Arr.fromIterable(elements);\n const n = chunk.length;\n const size = this.publisherIndex - this.subscribersIndex;\n const available = this.capacity - size;\n const forPubSub = Math.min(n, available);\n if (forPubSub === 0) {\n return chunk;\n }\n let iteratorIndex = 0;\n const publishAllIndex = this.publisherIndex + forPubSub;\n while (this.publisherIndex !== publishAllIndex) {\n const elem = chunk[iteratorIndex++];\n const index = this.publisherIndex & this.mask;\n this.array[index] = elem;\n const replayIndex = this.replayBuffer?.offer(elem);\n if (replayIndex !== undefined) {\n this.replayIndices[index] = replayIndex;\n }\n this.subscribers[index] = this.subscriberCount;\n this.publisherIndex += 1;\n }\n return chunk.slice(iteratorIndex);\n }\n slide() {\n if (this.subscribersIndex !== this.publisherIndex) {\n const index = this.subscribersIndex & this.mask;\n const value = this.array[index];\n this.array[index] = AbsentValue;\n this.subscribers[index] = 0;\n this.subscribersIndex += 1;\n this.replayBuffer?.slide(value, this.replayIndices[index]);\n }\n }\n subscribe() {\n this.subscriberCount += 1;\n return new BoundedPubSubPow2Subscription(this, this.publisherIndex, false);\n }\n}\nclass BoundedPubSubPow2Subscription {\n self;\n subscriberIndex;\n unsubscribed;\n constructor(self, subscriberIndex, unsubscribed) {\n this.self = self;\n this.subscriberIndex = subscriberIndex;\n this.unsubscribed = unsubscribed;\n }\n isEmpty() {\n return this.unsubscribed || this.self.publisherIndex === this.subscriberIndex || this.self.publisherIndex === this.self.subscribersIndex;\n }\n size() {\n if (this.unsubscribed) {\n return 0;\n }\n return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex);\n }\n poll() {\n if (this.unsubscribed) {\n return MutableList.Empty;\n }\n this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);\n if (this.subscriberIndex !== this.self.publisherIndex) {\n const index = this.subscriberIndex & this.self.mask;\n const elem = this.self.array[index];\n this.self.subscribers[index] -= 1;\n if (this.self.subscribers[index] === 0) {\n this.self.array[index] = AbsentValue;\n this.self.subscribersIndex += 1;\n }\n this.subscriberIndex += 1;\n return elem;\n }\n return MutableList.Empty;\n }\n pollUpTo(n) {\n n = Count.normalize(n);\n if (this.unsubscribed) {\n return [];\n }\n this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);\n const size = this.self.publisherIndex - this.subscriberIndex;\n const toPoll = Math.min(n, size);\n if (toPoll <= 0) {\n return [];\n }\n const builder = [];\n const pollUpToIndex = this.subscriberIndex + toPoll;\n while (this.subscriberIndex !== pollUpToIndex) {\n const index = this.subscriberIndex & this.self.mask;\n const elem = this.self.array[index];\n this.self.subscribers[index] -= 1;\n if (this.self.subscribers[index] === 0) {\n this.self.array[index] = AbsentValue;\n this.self.subscribersIndex += 1;\n }\n builder.push(elem);\n this.subscriberIndex += 1;\n }\n return builder;\n }\n unsubscribe() {\n if (!this.unsubscribed) {\n this.unsubscribed = true;\n this.self.subscriberCount -= 1;\n this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);\n while (this.subscriberIndex !== this.self.publisherIndex) {\n const index = this.subscriberIndex & this.self.mask;\n this.self.subscribers[index] -= 1;\n if (this.self.subscribers[index] === 0) {\n this.self.array[index] = AbsentValue;\n this.self.subscribersIndex += 1;\n }\n this.subscriberIndex += 1;\n }\n }\n }\n}\nclass BoundedPubSubSingle {\n publisherIndex = 0;\n subscriberCount = 0;\n subscribers = 0;\n value = AbsentValue;\n replayIndex = 0;\n capacity = 1;\n replayBuffer;\n constructor(replayBuffer) {\n this.replayBuffer = replayBuffer;\n }\n replayWindow() {\n return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow;\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n isEmpty() {\n return this.subscribers === 0;\n }\n isFull() {\n return !this.isEmpty();\n }\n size() {\n return this.isEmpty() ? 0 : 1;\n }\n publish(value) {\n if (this.isFull()) {\n return false;\n }\n const replayIndex = this.replayBuffer?.offer(value);\n if (this.subscriberCount !== 0) {\n this.value = value;\n if (replayIndex !== undefined) {\n this.replayIndex = replayIndex;\n }\n this.subscribers = this.subscriberCount;\n this.publisherIndex += 1;\n }\n return true;\n }\n publishAll(elements) {\n if (this.subscriberCount === 0) {\n if (this.replayBuffer) {\n this.replayBuffer.offerAll(elements);\n }\n return [];\n }\n const chunk = Arr.fromIterable(elements);\n if (chunk.length === 0) {\n return chunk;\n }\n if (this.publish(chunk[0])) {\n return chunk.slice(1);\n } else {\n return chunk;\n }\n }\n slide() {\n if (this.isFull()) {\n const value = this.value;\n this.subscribers = 0;\n this.value = AbsentValue;\n this.replayBuffer?.slide(value, this.replayIndex);\n }\n }\n subscribe() {\n this.subscriberCount += 1;\n return new BoundedPubSubSingleSubscription(this, this.publisherIndex, false);\n }\n}\nclass BoundedPubSubSingleSubscription {\n self;\n subscriberIndex;\n unsubscribed;\n constructor(self, subscriberIndex, unsubscribed) {\n this.self = self;\n this.subscriberIndex = subscriberIndex;\n this.unsubscribed = unsubscribed;\n }\n isEmpty() {\n return this.unsubscribed || this.self.subscribers === 0 || this.subscriberIndex === this.self.publisherIndex;\n }\n size() {\n return this.isEmpty() ? 0 : 1;\n }\n poll() {\n if (this.isEmpty()) {\n return MutableList.Empty;\n }\n const elem = this.self.value;\n this.self.subscribers -= 1;\n if (this.self.subscribers === 0) {\n this.self.value = AbsentValue;\n }\n this.subscriberIndex = this.self.publisherIndex;\n return elem;\n }\n pollUpTo(n) {\n if (Count.normalize(n) < 1 || this.isEmpty()) {\n return [];\n }\n return [this.poll()];\n }\n unsubscribe() {\n if (!this.unsubscribed) {\n this.unsubscribed = true;\n this.self.subscriberCount -= 1;\n if (this.self.subscribers !== 0 && this.subscriberIndex !== this.self.publisherIndex) {\n this.self.subscribers -= 1;\n if (this.self.subscribers === 0) {\n this.self.value = AbsentValue;\n }\n }\n }\n }\n}\nclass UnboundedPubSub {\n publisherHead = {\n value: AbsentValue,\n replayIndex: undefined,\n subscribers: 0,\n next: null\n };\n publisherTail = this.publisherHead;\n publisherIndex = 0;\n subscribersIndex = 0;\n capacity = Number.MAX_SAFE_INTEGER;\n replayBuffer;\n constructor(replayBuffer) {\n this.replayBuffer = replayBuffer;\n }\n replayWindow() {\n return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow;\n }\n isEmpty() {\n return this.publisherHead === this.publisherTail;\n }\n isFull() {\n return false;\n }\n size() {\n return this.publisherIndex - this.subscribersIndex;\n }\n publish(value) {\n const replayIndex = this.replayBuffer?.offer(value);\n const subscribers = this.publisherTail.subscribers;\n if (subscribers !== 0) {\n const node = {\n value,\n replayIndex,\n subscribers,\n next: null\n };\n this.publisherTail.next = node;\n this.publisherTail = this.publisherTail.next;\n this.publisherIndex += 1;\n }\n return true;\n }\n publishAll(elements) {\n if (this.publisherTail.subscribers !== 0) {\n for (const a of elements) {\n this.publish(a);\n }\n } else if (this.replayBuffer) {\n this.replayBuffer.offerAll(elements);\n }\n return [];\n }\n slide() {\n if (this.publisherHead !== this.publisherTail) {\n const node = this.publisherHead.next;\n const value = node.value;\n this.publisherHead = this.publisherHead.next;\n this.publisherHead.value = AbsentValue;\n this.subscribersIndex += 1;\n this.replayBuffer?.slide(value, node.replayIndex);\n }\n }\n subscribe() {\n this.publisherTail.subscribers += 1;\n return new UnboundedPubSubSubscription(this, this.publisherTail, this.publisherIndex, false);\n }\n}\nclass UnboundedPubSubSubscription {\n self;\n subscriberHead;\n subscriberIndex;\n unsubscribed;\n constructor(self, subscriberHead, subscriberIndex, unsubscribed) {\n this.self = self;\n this.subscriberHead = subscriberHead;\n this.subscriberIndex = subscriberIndex;\n this.unsubscribed = unsubscribed;\n }\n isEmpty() {\n if (this.unsubscribed) {\n return true;\n }\n let empty = true;\n let loop = true;\n while (loop) {\n if (this.subscriberHead === this.self.publisherTail) {\n loop = false;\n } else {\n if (this.subscriberHead.next.value !== AbsentValue) {\n empty = false;\n loop = false;\n } else {\n this.subscriberHead = this.subscriberHead.next;\n this.subscriberIndex += 1;\n }\n }\n }\n return empty;\n }\n size() {\n if (this.unsubscribed) {\n return 0;\n }\n return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex);\n }\n poll() {\n if (this.unsubscribed) {\n return MutableList.Empty;\n }\n let loop = true;\n let polled = MutableList.Empty;\n while (loop) {\n if (this.subscriberHead === this.self.publisherTail) {\n loop = false;\n } else {\n const elem = this.subscriberHead.next.value;\n if (elem !== AbsentValue) {\n polled = elem;\n this.subscriberHead.subscribers -= 1;\n if (this.subscriberHead.subscribers === 0) {\n this.self.publisherHead = this.self.publisherHead.next;\n this.self.publisherHead.value = AbsentValue;\n this.self.subscribersIndex += 1;\n }\n loop = false;\n }\n this.subscriberHead = this.subscriberHead.next;\n this.subscriberIndex += 1;\n }\n }\n return polled;\n }\n pollUpTo(n) {\n n = Count.normalize(n);\n const builder = [];\n let i = 0;\n while (i !== n) {\n const a = this.poll();\n if (a === MutableList.Empty) {\n i = n;\n } else {\n builder.push(a);\n i += 1;\n }\n }\n return builder;\n }\n unsubscribe() {\n if (!this.unsubscribed) {\n this.unsubscribed = true;\n this.self.publisherTail.subscribers -= 1;\n while (this.subscriberHead !== this.self.publisherTail) {\n if (this.subscriberHead.next.value !== AbsentValue) {\n this.subscriberHead.subscribers -= 1;\n if (this.subscriberHead.subscribers === 0) {\n this.self.publisherHead = this.self.publisherHead.next;\n this.self.publisherHead.value = AbsentValue;\n this.self.subscribersIndex += 1;\n }\n }\n this.subscriberHead = this.subscriberHead.next;\n }\n }\n }\n}\nclass SubscriptionImpl {\n [SubscriptionTypeId] = {\n _A: identity\n };\n pubsub;\n subscribers;\n subscription;\n pollers;\n shutdownHook;\n shutdownFlag;\n strategy;\n replayWindow;\n constructor(pubsub, subscribers, subscription, pollers, shutdownHook, shutdownFlag, strategy, replayWindow) {\n this.pubsub = pubsub;\n this.subscribers = subscribers;\n this.subscription = subscription;\n this.pollers = pollers;\n this.shutdownHook = shutdownHook;\n this.shutdownFlag = shutdownFlag;\n this.strategy = strategy;\n this.replayWindow = replayWindow;\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\nclass PubSubImpl {\n [TypeId] = {\n _A: identity\n };\n pubsub;\n subscribers;\n scope;\n shutdownHook;\n shutdownFlag;\n strategy;\n constructor(pubsub, subscribers, scope, shutdownHook, shutdownFlag, strategy) {\n this.pubsub = pubsub;\n this.subscribers = subscribers;\n this.scope = scope;\n this.shutdownHook = shutdownHook;\n this.shutdownFlag = shutdownFlag;\n this.strategy = strategy;\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\nconst makePubSubUnsafe = (pubsub, subscribers, scope, shutdownHook, shutdownFlag, strategy) => new PubSubImpl(pubsub, subscribers, scope, shutdownHook, shutdownFlag, strategy);\nconst ensureCapacity = capacity => {\n if (capacity <= 0) {\n throw new Error(`Cannot construct PubSub with capacity of ${capacity}`);\n }\n};\n// -----------------------------------------------------------------------------\n// PubSub.Strategy\n// -----------------------------------------------------------------------------\n/**\n * Represents the back-pressure strategy for bounded `PubSub` values.\n *\n * **When to use**\n *\n * Use to preserve every message for current subscribers when a bounded custom\n * `PubSub` should make publishers wait for capacity instead of dropping or\n * evicting messages.\n *\n * **Details**\n *\n * Publishers wait when the `PubSub` is at capacity, so all current subscribers\n * can receive every published message.\n *\n * **Gotchas**\n *\n * A slow subscriber can slow down publishers and other subscribers.\n *\n * @see {@link bounded} for creating bounded PubSubs with back pressure by default\n * @see {@link DroppingStrategy} for dropping new messages when capacity is full\n * @see {@link SlidingStrategy} for evicting old messages when capacity is full\n *\n * @category models\n * @since 4.0.0\n */\nexport class BackPressureStrategy {\n publishers = /*#__PURE__*/MutableList.make();\n get shutdown() {\n return Effect.withFiber(fiber => Effect.forEach(MutableList.takeAll(this.publishers), ([_, deferred, last]) => last ? Deferred.interruptWith(deferred, fiber.id) : Effect.void, {\n concurrency: \"unbounded\",\n discard: true\n }));\n }\n handleSurplus(pubsub, subscribers, elements, isShutdown) {\n return Effect.suspend(() => {\n const deferred = Deferred.makeUnsafe();\n this.offerUnsafe(elements, deferred);\n this.onPubSubEmptySpaceUnsafe(pubsub, subscribers);\n this.completeSubscribersUnsafe(pubsub, subscribers);\n return (MutableRef.get(isShutdown) ? Effect.interrupt : Deferred.await(deferred)).pipe(Effect.onInterrupt(() => {\n this.removeUnsafe(deferred);\n return Effect.void;\n }));\n });\n }\n onPubSubEmptySpaceUnsafe(pubsub, subscribers) {\n let keepPolling = true;\n while (keepPolling && !pubsub.isFull()) {\n const publisher = MutableList.take(this.publishers);\n if (publisher === MutableList.Empty) {\n keepPolling = false;\n } else {\n const [value, deferred] = publisher;\n const published = pubsub.publish(value);\n if (published && publisher[2]) {\n Deferred.doneUnsafe(deferred, Exit.succeed(true));\n } else if (!published) {\n MutableList.prepend(this.publishers, publisher);\n }\n this.completeSubscribersUnsafe(pubsub, subscribers);\n }\n }\n }\n completePollersUnsafe(pubsub, subscribers, subscription, pollers) {\n return strategyCompletePollersUnsafe(this, pubsub, subscribers, subscription, pollers);\n }\n completeSubscribersUnsafe(pubsub, subscribers) {\n return strategyCompleteSubscribersUnsafe(this, pubsub, subscribers);\n }\n offerUnsafe(elements, deferred) {\n const iterator = elements[Symbol.iterator]();\n let next = iterator.next();\n if (!next.done) {\n // oxlint-disable-next-line no-constant-condition\n while (1) {\n const value = next.value;\n next = iterator.next();\n if (next.done) {\n MutableList.append(this.publishers, [value, deferred, true]);\n break;\n }\n MutableList.append(this.publishers, [value, deferred, false]);\n }\n }\n }\n removeUnsafe(deferred) {\n MutableList.filter(this.publishers, ([_, d]) => d !== deferred);\n }\n}\n/**\n * Represents the dropping strategy for bounded `PubSub` values.\n *\n * **When to use**\n *\n * Use to keep publishers fast by dropping new messages when the `PubSub` is at\n * capacity.\n *\n * **Details**\n *\n * A publish that arrives while the `PubSub` is full is dropped instead of\n * waiting for capacity.\n *\n * **Gotchas**\n *\n * Subscribers may miss messages published while they are subscribed.\n *\n * **Example** (Applying a dropping strategy)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * // Explicitly create a PubSub with a dropping strategy\n * const pubsub = yield* PubSub.make<string>({\n * atomicPubSub: () => PubSub.makeAtomicBounded(2),\n * strategy: () => new PubSub.DroppingStrategy()\n * })\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Fill the PubSub\n * const pub1 = yield* PubSub.publish(pubsub, \"msg1\") // true\n * const pub2 = yield* PubSub.publish(pubsub, \"msg2\") // true\n * const pub3 = yield* PubSub.publish(pubsub, \"msg3\") // false (dropped)\n *\n * // Subscribers will only see the first two messages\n * const messages = yield* PubSub.takeAll(subscription)\n * return { published: [pub1, pub2, pub3], messages }\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { published: [true, true, false], messages: [\"msg1\", \"msg2\"] }\n * ```\n *\n * @category models\n * @since 4.0.0\n */\nexport class DroppingStrategy {\n get shutdown() {\n return Effect.void;\n }\n handleSurplus(_pubsub, _subscribers, _elements, _isShutdown) {\n return Effect.succeed(false);\n }\n onPubSubEmptySpaceUnsafe(_pubsub, _subscribers) {\n //\n }\n completePollersUnsafe(pubsub, subscribers, subscription, pollers) {\n return strategyCompletePollersUnsafe(this, pubsub, subscribers, subscription, pollers);\n }\n completeSubscribersUnsafe(pubsub, subscribers) {\n return strategyCompleteSubscribersUnsafe(this, pubsub, subscribers);\n }\n}\n/**\n * Represents the sliding strategy for bounded `PubSub` values.\n *\n * **When to use**\n *\n * Use to keep the most recent messages when the `PubSub` is at capacity.\n *\n * **Details**\n *\n * New messages are accepted by evicting older messages from the bounded\n * `PubSub`.\n *\n * **Gotchas**\n *\n * Slow subscribers may miss older messages that are evicted before they are\n * consumed.\n *\n * **Example** (Applying a sliding strategy)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * // Explicitly create a PubSub with a sliding strategy\n * const pubsub = yield* PubSub.make<string>({\n * atomicPubSub: () => PubSub.makeAtomicBounded(2),\n * strategy: () => new PubSub.SlidingStrategy()\n * })\n *\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Publish messages that exceed capacity\n * yield* PubSub.publish(pubsub, \"msg1\") // stored\n * yield* PubSub.publish(pubsub, \"msg2\") // stored\n * yield* PubSub.publish(pubsub, \"msg3\") // \"msg1\" evicted, \"msg3\" stored\n * yield* PubSub.publish(pubsub, \"msg4\") // \"msg2\" evicted, \"msg4\" stored\n *\n * // Subscribers will see the most recent messages\n * return yield* PubSub.takeAll(subscription)\n * }))\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"msg3\", \"msg4\"]\n * ```\n *\n * @category models\n * @since 4.0.0\n */\nexport class SlidingStrategy {\n get shutdown() {\n return Effect.void;\n }\n handleSurplus(pubsub, subscribers, elements, _isShutdown) {\n return Effect.sync(() => {\n this.slidingPublishUnsafe(pubsub, elements);\n this.completeSubscribersUnsafe(pubsub, subscribers);\n return true;\n });\n }\n onPubSubEmptySpaceUnsafe(_pubsub, _subscribers) {\n //\n }\n completePollersUnsafe(pubsub, subscribers, subscription, pollers) {\n return strategyCompletePollersUnsafe(this, pubsub, subscribers, subscription, pollers);\n }\n completeSubscribersUnsafe(pubsub, subscribers) {\n return strategyCompleteSubscribersUnsafe(this, pubsub, subscribers);\n }\n slidingPublishUnsafe(pubsub, elements) {\n const it = elements[Symbol.iterator]();\n let next = it.next();\n if (!next.done && pubsub.capacity > 0) {\n let a = next.value;\n let loop = true;\n while (loop) {\n pubsub.slide();\n const pub = pubsub.publish(a);\n if (pub && (next = it.next()) && !next.done) {\n a = next.value;\n } else if (pub) {\n loop = false;\n }\n }\n }\n }\n}\nconst strategyCompletePollersUnsafe = (strategy, pubsub, subscribers, subscription, pollers) => {\n let keepPolling = true;\n while (keepPolling && !subscription.isEmpty()) {\n const poller = MutableList.take(pollers);\n if (poller === MutableList.Empty) {\n removeSubscribers(subscribers, subscription, pollers);\n if (pollers.length === 0) {\n keepPolling = false;\n } else {\n addSubscribers(subscribers, subscription, pollers);\n }\n } else {\n const pollResult = subscription.poll();\n if (pollResult === MutableList.Empty) {\n MutableList.prepend(pollers, poller);\n } else {\n Deferred.doneUnsafe(poller, Exit.succeed(pollResult));\n strategy.onPubSubEmptySpaceUnsafe(pubsub, subscribers);\n }\n }\n }\n};\nconst strategyCompleteSubscribersUnsafe = (strategy, pubsub, subscribers) => {\n for (const [subscription, pollersSet] of subscribers) {\n for (const pollers of pollersSet) {\n strategy.completePollersUnsafe(pubsub, subscribers, subscription, pollers);\n }\n }\n};\nclass ReplayBuffer {\n capacity;\n head = {\n value: AbsentValue,\n index: 0,\n next: null\n };\n tail = this.head;\n slideValues = [];\n size = 0;\n index = 0;\n publisherIndex = 0;\n constructor(capacity) {\n this.capacity = capacity;\n }\n slide(value, publisherIndex) {\n this.slideValues[this.index % this.capacity] = {\n value,\n index: publisherIndex\n };\n this.index++;\n }\n offer(a) {\n const index = this.publisherIndex++;\n this.tail.value = a;\n this.tail.index = index;\n this.tail.next = {\n value: AbsentValue,\n index: 0,\n next: null\n };\n this.tail = this.tail.next;\n if (this.size === this.capacity) {\n this.head = this.head.next;\n } else {\n this.size += 1;\n }\n return index;\n }\n offerAll(as) {\n for (const a of as) {\n this.offer(a);\n }\n }\n}\nclass ReplayWindowImpl {\n buffer;\n values;\n index = 0;\n remaining;\n slideIndex;\n newestIndex = -1;\n constructor(buffer) {\n this.buffer = buffer;\n this.remaining = buffer.size;\n this.slideIndex = buffer.index;\n this.values = new Array(this.remaining);\n let node = buffer.head;\n for (let i = 0; i < this.remaining; i++) {\n this.values[i] = node.value;\n this.newestIndex = node.index;\n node = node.next;\n }\n }\n close() {\n this.values.length = 0;\n this.remaining = 0;\n }\n sync() {\n const slides = this.buffer.index - this.slideIndex;\n if (slides === 0 || this.remaining === 0) {\n return;\n }\n const count = Math.min(slides, this.buffer.capacity);\n const start = this.buffer.index - count;\n for (let i = 0; i < count; i++) {\n const entry = this.buffer.slideValues[(start + i) % this.buffer.capacity];\n if (entry.index > this.newestIndex) {\n this.index = (this.index + 1) % this.values.length;\n this.values[(this.index + this.remaining - 1) % this.values.length] = entry.value;\n this.newestIndex = entry.index;\n }\n }\n this.slideIndex = this.buffer.index;\n }\n take() {\n if (this.remaining === 0) {\n return undefined;\n }\n this.sync();\n const value = this.values[this.index];\n this.values[this.index] = AbsentValue;\n this.index = (this.index + 1) % this.values.length;\n this.remaining--;\n if (this.remaining === 0) {\n this.close();\n }\n return value;\n }\n takeN(n) {\n n = Count.normalize(n);\n const len = Math.min(n, this.remaining);\n const items = new Array(len);\n for (let i = 0; i < len; i++) {\n items[i] = this.take();\n }\n return items;\n }\n takeAll() {\n return this.takeN(this.remaining);\n }\n}\nconst emptyReplayWindow = {\n remaining: 0,\n take: () => undefined,\n takeN: () => [],\n takeAll: () => [],\n close: () => void 0\n};\n//# sourceMappingURL=PubSub.js.map","/**\n * Passes values asynchronously between fibers.\n *\n * A `Queue<A, E>` accepts values, hands each value to one consumer in offer\n * order, and can complete, fail, interrupt, or shut down. Queues can be bounded\n * or unbounded, and bounded queues can suspend, drop, or slide values when\n * producers are faster than consumers.\n *\n * @since 3.8.0\n */\nimport * as Arr from \"./Array.js\";\nimport { constant, constTrue, dual, identity } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as internalEffect from \"./internal/effect.js\";\nimport * as MutableList from \"./MutableList.js\";\nimport * as Option from \"./Option.js\";\nimport { hasProperty } from \"./Predicate.js\";\nimport * as Pull from \"./Pull.js\";\nconst TypeId = \"~effect/Queue\";\nconst EnqueueTypeId = \"~effect/Queue/Enqueue\";\nconst DequeueTypeId = \"~effect/Queue/Dequeue\";\n/**\n * Type guard to check if a value is a Queue.\n *\n * **When to use**\n *\n * Use to narrow an unknown value to a full `Queue` before passing it to APIs\n * that need both offering and taking capabilities.\n *\n * @see {@link isEnqueue} for checking values that only need write access\n * @see {@link isDequeue} for checking values that only need read access\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isQueue = u => hasProperty(u, TypeId);\n/**\n * Type guard to check if a value is an Enqueue.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before calling queue operations that require\n * write-side access.\n *\n * **Gotchas**\n *\n * A full `Queue` also satisfies this guard because every queue includes the\n * enqueue side.\n *\n * @see {@link isQueue} for checking for a full read-write queue handle\n * @see {@link isDequeue} for checking for the read side of a queue\n * @see {@link asEnqueue} for narrowing an existing `Queue` to its write-only interface\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEnqueue = u => hasProperty(u, EnqueueTypeId);\n/**\n * Type guard to check if a value is a Dequeue.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before passing it to read-side queue\n * operations.\n *\n * @see {@link Dequeue} for the read-side queue handle checked by this guard\n * @see {@link isQueue} for checking for a full read-write queue handle\n * @see {@link isEnqueue} for checking for the write side of a queue\n * @see {@link asDequeue} for narrowing an existing `Queue` to its read-only interface\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isDequeue = u => hasProperty(u, DequeueTypeId);\n/**\n * Converts a `Queue` to its write-only `Enqueue` interface.\n *\n * **When to use**\n *\n * Use to expose only the producer side of a `Queue` to code that should offer\n * values or signal queue lifecycle.\n *\n * **Gotchas**\n *\n * This is a type-level capability restriction. It returns the same queue\n * object, so it does not hide read operations at runtime.\n *\n * @see {@link asDequeue} for exposing only the read side of a `Queue`\n * @see {@link Enqueue} for the write-only queue handle returned by this conversion\n *\n * @category converting\n * @since 4.0.0\n */\nexport const asEnqueue = self => self;\n/**\n * Narrows a `Queue` to a `Dequeue`, exposing the consumer side of the queue.\n *\n * **When to use**\n *\n * Use to pass a queue to code that should consume values while keeping\n * producer-side operations out of that code's TypeScript type.\n *\n * **Gotchas**\n *\n * This is a type-level narrowing operation. It returns the same queue object\n * and does not create a runtime wrapper.\n *\n * @see {@link asEnqueue} for narrowing a queue to its producer side\n * @see {@link Dequeue} for the consumer-side queue handle returned by this function\n *\n * @category converting\n * @since 4.0.0\n */\nexport const asDequeue = identity;\nconst variance = {\n _A: identity,\n _E: identity\n};\nconst QueueProto = {\n [TypeId]: variance,\n [EnqueueTypeId]: variance,\n [DequeueTypeId]: variance,\n ...PipeInspectableProto,\n toJSON() {\n return {\n _id: \"effect/Queue\",\n state: this.state._tag,\n size: sizeUnsafe(this)\n };\n }\n};\n/**\n * Creates a `Queue` with optional capacity and overflow strategy.\n *\n * **Details**\n *\n * By default the queue is unbounded and uses the `\"suspend\"` strategy. Provide\n * `capacity` for a bounded queue and choose `\"suspend\"`, `\"dropping\"`, or\n * `\"sliding\"` to control what happens when the queue is full. The returned\n * queue can be offered to, taken from, failed, ended, interrupted, or shut down.\n *\n * **Example** (Creating queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.make<number, string | Cause.Done>()\n *\n * // add messages to the queue\n * yield* Queue.offer(queue, 1)\n * yield* Queue.offer(queue, 2)\n * yield* Queue.offerAll(queue, [3, 4, 5])\n *\n * // take messages from the queue\n * const messages = yield* Queue.takeAll(queue)\n *\n * // signal that the queue is done\n * yield* Queue.end(queue)\n * const done = yield* Effect.flip(Queue.take(queue))\n *\n * // signal that another queue has failed\n * const failedQueue = yield* Queue.make<number, string>()\n * const failed = yield* Queue.fail(failedQueue, \"boom\")\n * return { messages, done, failed }\n * })\n *\n * await Effect.runPromise(program) // => { messages: [1, 2, 3, 4, 5], done: Cause.Done(), failed: true }\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => core.withFiber(fiber => {\n const self = Object.create(QueueProto);\n self.dispatcher = fiber.currentDispatcher;\n self.capacity = options?.capacity ?? Number.POSITIVE_INFINITY;\n self.strategy = options?.strategy ?? \"suspend\";\n self.messages = MutableList.make();\n self.scheduleRunning = false;\n self.state = {\n _tag: \"Open\",\n takers: new Set(),\n offers: new Set(),\n awaiters: new Set()\n };\n return internalEffect.succeed(self);\n});\n/**\n * Creates a bounded queue with the specified capacity that uses backpressure strategy.\n *\n * **Details**\n *\n * When the queue reaches capacity, producers will be suspended until space becomes available.\n * This ensures all messages are processed but may slow down producers.\n *\n * **Example** (Creating bounded queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<string>(5)\n *\n * // This will succeed as queue has capacity\n * yield* Queue.offer(queue, \"first\")\n * yield* Queue.offer(queue, \"second\")\n *\n * const size = yield* Queue.size(queue)\n * return size\n * })\n *\n * await Effect.runPromise(program) // => 2\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const bounded = capacity => make({\n capacity\n});\n/**\n * Creates a bounded queue with sliding strategy. When the queue reaches capacity,\n * new elements are added and the oldest elements are dropped.\n *\n * **When to use**\n *\n * Use when you need producer offers not to block and can accept dropping the\n * oldest messages, such as when maintaining a rolling window of recent values.\n *\n * **Example** (Creating sliding queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.sliding<number>(3)\n *\n * // Fill the queue to capacity\n * yield* Queue.offer(queue, 1)\n * yield* Queue.offer(queue, 2)\n * yield* Queue.offer(queue, 3)\n *\n * // This will succeed, dropping the oldest element (1)\n * yield* Queue.offer(queue, 4)\n *\n * const all = yield* Queue.takeAll(queue)\n * return all\n * })\n *\n * await Effect.runPromise(program) // => [2, 3, 4]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sliding = capacity => make({\n capacity,\n strategy: \"sliding\"\n});\n/**\n * Creates a bounded queue with dropping strategy. When the queue reaches capacity,\n * new elements are dropped and the offer operation returns false.\n *\n * **When to use**\n *\n * Use when you need producer offers not to block while preserving existing\n * queued messages, even if new messages may be dropped when the queue is full.\n *\n * **Example** (Creating dropping queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.dropping<number>(2)\n *\n * // Fill the queue to capacity\n * const success1 = yield* Queue.offer(queue, 1)\n * const success2 = yield* Queue.offer(queue, 2)\n *\n * // This will be dropped\n * const success3 = yield* Queue.offer(queue, 3)\n *\n * const all = yield* Queue.takeAll(queue)\n * return [success1, success2, success3, all]\n * })\n *\n * await Effect.runPromise(program) // => [true, true, false, [1, 2]]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const dropping = capacity => make({\n capacity,\n strategy: \"dropping\"\n});\n/**\n * Creates an unbounded queue that can grow to any size without blocking producers.\n *\n * **When to use**\n *\n * Use when you need producers to add messages without backpressure and accept\n * unbounded memory growth.\n *\n * **Example** (Creating unbounded queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.unbounded<string>()\n *\n * // Producers can always add messages without blocking\n * yield* Queue.offer(queue, \"message1\")\n * yield* Queue.offer(queue, \"message2\")\n * yield* Queue.offerAll(queue, [\"message3\", \"message4\", \"message5\"])\n *\n * // Check current size\n * const size = yield* Queue.size(queue)\n *\n * // Take all messages\n * const messages = yield* Queue.takeAll(queue)\n * return { size, messages }\n * })\n *\n * await Effect.runPromise(program) // => { size: 5, messages: [\"message1\", \"message2\", \"message3\", \"message4\", \"message5\"] }\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unbounded = () => make();\n/**\n * Adds a message to the queue. Returns `false` if the queue is done.\n *\n * **Details**\n *\n * For bounded queues, this operation may suspend if the queue is at capacity,\n * depending on the backpressure strategy. For dropping/sliding queues, it may\n * return false or succeed immediately by dropping/sliding existing messages.\n *\n * **Example** (Offering a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(3)\n *\n * // Successfully add messages to queue\n * const success1 = yield* Queue.offer(queue, 1)\n * const success2 = yield* Queue.offer(queue, 2)\n *\n * // Queue state\n * const size = yield* Queue.size(queue)\n * return { offered: [success1, success2], size }\n * })\n *\n * await Effect.runPromise(program) // => { offered: [true, true], size: 2 }\n * ```\n *\n * @category offering\n * @since 2.0.0\n */\nexport const offer = (self, message) => internalEffect.suspend(() => {\n if (self.state._tag !== \"Open\") {\n return exitFalse;\n } else if (self.messages.length >= self.capacity) {\n switch (self.strategy) {\n case \"dropping\":\n return exitFalse;\n case \"suspend\":\n if (self.capacity <= 0 && self.state.takers.size > 0) {\n MutableList.append(self.messages, message);\n releaseTakers(self);\n return exitTrue;\n }\n return offerRemainingSingle(self, message);\n case \"sliding\":\n MutableList.take(self.messages);\n MutableList.append(self.messages, message);\n return exitTrue;\n }\n }\n MutableList.append(self.messages, message);\n scheduleReleaseTaker(self);\n return exitTrue;\n});\n/**\n * Adds a message to the queue synchronously. Returns `false` if the queue is done.\n *\n * **When to use**\n *\n * Use when you are already in synchronous queue internals or a performance\n * boundary where wrapping the mutation in `Effect` is intentionally avoided.\n *\n * **Gotchas**\n *\n * This is an unsafe operation that directly modifies the queue without Effect wrapping.\n * Use this only when you're certain about the synchronous nature of the operation.\n *\n * **Example** (Offering a value synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * // Create a queue effect and extract the queue for unsafe operations\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(3)\n *\n * // Add messages synchronously using unsafe API\n * const success1 = Queue.offerUnsafe(queue, 1)\n * const success2 = Queue.offerUnsafe(queue, 2)\n *\n * // Check current size\n * const size = Queue.sizeUnsafe(queue)\n * return { offered: [success1, success2], size }\n * })\n *\n * await Effect.runPromise(program) // => { offered: [true, true], size: 2 }\n * ```\n *\n * @category offering\n * @since 4.0.0\n */\nexport const offerUnsafe = (self, message) => {\n if (self.state._tag !== \"Open\") {\n return false;\n } else if (self.messages.length >= self.capacity) {\n if (self.strategy === \"sliding\") {\n MutableList.take(self.messages);\n MutableList.append(self.messages, message);\n return true;\n } else if (self.capacity <= 0 && self.state.takers.size > 0) {\n MutableList.append(self.messages, message);\n releaseTakers(self);\n return true;\n }\n return false;\n }\n MutableList.append(self.messages, message);\n scheduleReleaseTaker(self);\n return true;\n};\n/**\n * Adds multiple messages to the queue. Returns the remaining messages that\n * were not added.\n *\n * **When to use**\n *\n * Use when producers can submit a batch at once and need to know which messages\n * did not fit under the queue's capacity strategy.\n *\n * **Details**\n *\n * For bounded queues, this operation may suspend if the queue doesn't have\n * enough capacity. The operation returns an array of messages that couldn't\n * be added (empty array means all messages were successfully added).\n *\n * **Example** (Offering multiple values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.dropping<number>(3)\n *\n * // Try to add more messages than capacity without suspending\n * const remaining1 = yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n * return remaining1\n * })\n *\n * await Effect.runPromise(program) // => [4, 5]\n * ```\n *\n * @category offering\n * @since 2.0.0\n */\nexport const offerAll = (self, messages) => internalEffect.suspend(() => {\n if (self.state._tag !== \"Open\") {\n return internalEffect.succeed(Arr.fromIterable(messages));\n }\n const remaining = offerAllUnsafe(self, messages);\n if (remaining.length === 0) {\n return core.exitSucceed([]);\n } else if (self.strategy === \"dropping\") {\n return internalEffect.succeed(remaining);\n }\n return offerRemainingArray(self, remaining);\n});\n/**\n * Adds multiple messages to the queue synchronously. Returns the remaining messages that\n * were not added.\n *\n * **When to use**\n *\n * Use when queue internals or a performance boundary need a synchronous batch\n * offer and can handle any messages that do not fit.\n *\n * **Gotchas**\n *\n * This is an unsafe operation that directly modifies the queue without Effect wrapping.\n *\n * **Example** (Offering multiple values synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * // Create a bounded queue and use unsafe API\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(3)\n *\n * // Try to add 5 messages to capacity-3 queue using unsafe API\n * const remaining = Queue.offerAllUnsafe(queue, [1, 2, 3, 4, 5])\n *\n * // Check what's in the queue\n * const size = Queue.sizeUnsafe(queue)\n * return { remaining, size }\n * })\n *\n * await Effect.runPromise(program) // => { remaining: [4, 5], size: 3 }\n * ```\n *\n * @category offering\n * @since 4.0.0\n */\nexport const offerAllUnsafe = (self, messages) => {\n if (self.state._tag !== \"Open\") {\n return Arr.fromIterable(messages);\n } else if (self.capacity === Number.POSITIVE_INFINITY || self.strategy === \"sliding\") {\n MutableList.appendAll(self.messages, messages);\n if (self.strategy === \"sliding\") {\n MutableList.takeN(self.messages, self.messages.length - self.capacity);\n }\n scheduleReleaseTaker(self);\n return [];\n }\n const free = self.capacity <= 0 ? self.state.takers.size : self.capacity - self.messages.length;\n if (free === 0) {\n return Arr.fromIterable(messages);\n }\n const remaining = [];\n let i = 0;\n for (const message of messages) {\n if (i < free) {\n MutableList.append(self.messages, message);\n } else {\n remaining.push(message);\n }\n i++;\n }\n scheduleReleaseTaker(self);\n return remaining;\n};\n/**\n * Fails the queue with an error. If the queue is already done, `false` is\n * returned.\n *\n * **Example** (Failing queues with an error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, string>(10)\n *\n * // Fail the queue with an error\n * const failed = yield* Queue.fail(queue, \"Something went wrong\")\n *\n * // Taking from the failed queue fails with the error\n * const exit = yield* Effect.exit(Queue.take(queue))\n * return [failed, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.fail(\"Something went wrong\")]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const fail = (self, error) => failCause(self, core.causeFail(error));\n/**\n * Fails the queue with a cause. If the queue is already done, `false` is\n * returned.\n *\n * **Example** (Failing queues with a cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, string>(10)\n *\n * // Create a cause and fail the queue\n * const cause = Cause.fail(\"Queue processing failed\")\n * const failed = yield* Queue.failCause(queue, cause)\n *\n * // The queue is now done with the specified failure cause\n * const exit = yield* Effect.exit(Queue.take(queue))\n * return [failed, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail(\"Queue processing failed\"))]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const failCause = /*#__PURE__*/dual(2, (self, cause) => internalEffect.sync(() => failCauseUnsafe(self, cause)));\n/**\n * Fails the queue with a cause synchronously. If the queue is already done, `false` is\n * returned.\n *\n * **When to use**\n *\n * Use when queue completion must be driven from synchronous internals while\n * preserving the full failure `Cause`.\n *\n * **Gotchas**\n *\n * This is an unsafe operation that directly modifies the queue without Effect wrapping.\n *\n * **Example** (Failing queues with a cause synchronously)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, string>(10)\n *\n * // Create a cause and fail the queue synchronously\n * const cause = Cause.fail(\"Processing error\")\n * const failed = Queue.failCauseUnsafe(queue, cause)\n *\n * // The queue is now done with the specified failure cause\n * const exit = Queue.takeUnsafe(queue)\n * return [failed, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail(\"Processing error\"))]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const failCauseUnsafe = (self, cause) => {\n if (self.state._tag !== \"Open\") {\n return false;\n }\n const exit = core.exitFailCause(cause);\n const fail = internalEffect.exitZipRight(exit, exitFailDone);\n if (self.state.offers.size === 0 && self.messages.length === 0) {\n finalize(self, fail);\n return true;\n }\n self.state = {\n ...self.state,\n _tag: \"Closing\",\n exit: fail\n };\n return true;\n};\n/**\n * Signals queue completion.\n *\n * **When to use**\n *\n * Use to stop accepting new offers while allowing already queued messages to be\n * consumed.\n *\n * **Details**\n *\n * Returns `false` if the queue is already done.\n *\n * **Example** (Ending queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n * // Add some messages\n * yield* Queue.offer(queue, 1)\n * yield* Queue.offer(queue, 2)\n *\n * // Signal completion - no more messages will be accepted\n * const ended = yield* Queue.end(queue)\n *\n * // Trying to offer more messages will return false\n * const offerResult = yield* Queue.offer(queue, 3)\n *\n * // But we can still take existing messages\n * const message = yield* Queue.take(queue)\n * return [ended, offerResult, message]\n * })\n *\n * await Effect.runPromise(program) // => [true, false, 1]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const end = self => failCause(self, core.causeFail(core.Done()));\n/**\n * Signals queue completion synchronously.\n *\n * **When to use**\n *\n * Use when implementing low-level queue integrations that must complete a queue\n * without wrapping the operation in `Effect`.\n *\n * **Details**\n *\n * Returns `false` if the queue is already done.\n *\n * **Gotchas**\n *\n * This is an unsafe operation that directly modifies the queue without Effect wrapping.\n *\n * **Example** (Ending queues synchronously)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * // Create a queue and use unsafe operations\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n * // Add some messages\n * Queue.offerUnsafe(queue, 1)\n * Queue.offerUnsafe(queue, 2)\n *\n * // End the queue synchronously\n * const ended = Queue.endUnsafe(queue)\n *\n * // Existing messages can still be consumed while the queue is closing\n * const states = [queue.state._tag]\n *\n * Queue.takeUnsafe(queue)\n * Queue.takeUnsafe(queue)\n *\n * // After buffered messages are consumed, the queue is done\n * states.push(queue.state._tag)\n * return { ended, states }\n * })\n *\n * await Effect.runPromise(program) // => { ended: true, states: [\"Closing\", \"Done\"] }\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const endUnsafe = self => failCauseUnsafe(self, core.causeFail(core.Done()));\n/**\n * Interrupts the queue gracefully, transitioning it to a closing state.\n *\n * **Details**\n *\n * This operation stops accepting new offers but allows existing messages to be consumed.\n * Once all messages are drained, the queue transitions to the Done state with an interrupt cause.\n *\n * **Example** (Interrupting queues gracefully)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(10)\n *\n * // Add some messages\n * yield* Queue.offer(queue, 1)\n * yield* Queue.offer(queue, 2)\n *\n * // Interrupt gracefully - no more offers accepted, but messages can be consumed\n * const interrupted = yield* Queue.interrupt(queue)\n *\n * // Trying to offer more messages will return false\n * const offerResult = yield* Queue.offer(queue, 3)\n *\n * // But we can still take existing messages\n * const message1 = yield* Queue.take(queue)\n *\n * const message2 = yield* Queue.take(queue)\n *\n * // After all messages are consumed, queue is done\n * const isDone = queue.state._tag === \"Done\"\n * return { interrupted, offerResult, messages: [message1, message2], isDone }\n * })\n *\n * await Effect.runPromise(program) // => { interrupted: true, offerResult: false, messages: [1, 2], isDone: true }\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const interrupt = self => core.withFiber(fiber => failCause(self, internalEffect.causeInterrupt(fiber.id)));\n/**\n * Shuts down the queue immediately, discarding buffered messages and resuming\n * pending operations.\n *\n * **Details**\n *\n * The operation is idempotent and returns `true`, including when the queue has\n * already been shut down or completed.\n *\n * **Example** (Shutting down queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(2)\n *\n * // Add messages\n * yield* Queue.offer(queue, 1)\n * yield* Queue.offer(queue, 2)\n *\n * // Shutdown clears buffered messages and prevents further offers\n * const wasShutdown = yield* Queue.shutdown(queue)\n *\n * // Queue is now done and cleared\n * const size = yield* Queue.size(queue)\n * return { wasShutdown, size }\n * })\n *\n * await Effect.runPromise(program) // => { wasShutdown: true, size: 0 }\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const shutdown = self => internalEffect.sync(() => {\n if (self.state._tag === \"Done\") {\n return true;\n }\n MutableList.clear(self.messages);\n const offers = self.state.offers;\n finalize(self, self.state._tag === \"Open\" ? exitInterrupt : self.state.exit);\n if (offers.size > 0) {\n for (const entry of offers) {\n if (entry._tag === \"Single\") {\n entry.resume(exitFalse);\n } else {\n entry.resume(core.exitSucceed(entry.remaining.slice(entry.offset)));\n }\n }\n offers.clear();\n }\n return true;\n});\n/**\n * Takes and returns all currently buffered messages without waiting for more.\n *\n * **Details**\n *\n * Returns an empty array when the queue is empty or has completed normally. If\n * the queue has failed, the effect fails with the queue's error.\n *\n * **Example** (Clearing queued values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(10)\n *\n * // Add several messages\n * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n *\n * // Clear all messages from the queue\n * const messages = yield* Queue.clear(queue)\n *\n * // Queue is now empty\n * const size = yield* Queue.size(queue)\n *\n * // Clearing empty queue returns empty array\n * const empty = yield* Queue.clear(queue)\n * return { messages, size, empty }\n * })\n *\n * await Effect.runPromise(program) // => { messages: [1, 2, 3, 4, 5], size: 0, empty: [] }\n * ```\n *\n * @category taking\n * @since 4.0.0\n */\nexport const clear = self => internalEffect.suspend(() => {\n if (self.state._tag === \"Done\") {\n if (Pull.isDoneCause(self.state.exit.cause)) {\n return internalEffect.succeed([]);\n }\n return self.state.exit;\n }\n const messages = takeAllUnsafe(self);\n releaseCapacity(self);\n return internalEffect.succeed(messages);\n});\n/**\n * Takes all currently available messages, waiting until at least one message\n * is available when the queue is empty.\n *\n * **When to use**\n *\n * Use when consumers should process the next non-empty batch of buffered\n * messages instead of repeatedly taking one message at a time.\n *\n * **Details**\n *\n * Returns a non-empty array. If the queue completes or fails before a message\n * can be taken, the effect fails with the queue's terminal error.\n *\n * **Example** (Taking all available values)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(5)\n *\n * // Add several messages\n * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n *\n * // Take all available messages\n * const messages1 = yield* Queue.takeAll(queue)\n * return messages1\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const takeAll = self => takeBetween(self, 1, Number.POSITIVE_INFINITY);\n/**\n * Takes all messages from the queue, until the queue has errored or is done.\n *\n * **Example** (Collecting values until completion)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(5)\n *\n * // Add several messages\n * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n * yield* Queue.end(queue)\n *\n * // Collect all available messages\n * return yield* Queue.collect(queue)\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category taking\n * @since 4.0.0\n */\nexport const collect = self => internalEffect.suspend(() => {\n const out = Arr.empty();\n return internalEffect.as(Pull.catchDone(internalEffect.whileLoop({\n while: constTrue,\n body: constant(takeAll(self)),\n step(items) {\n for (let i = 0; i < items.length; i++) {\n out.push(items[i]);\n }\n }\n }), () => internalEffect.void), out);\n});\n/**\n * Takes up to `n` messages from the queue.\n *\n * **Details**\n *\n * The operation may wait until enough messages are available to satisfy the\n * queue's batching rules. Finite fractional values of `n` are rounded down.\n * If `n` is `NaN` or non-positive, it succeeds with an empty array. If the\n * queue completes or fails before messages can be taken, the effect fails with\n * the queue's terminal error.\n *\n * **Example** (Taking a fixed number of values)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n * // Add several messages\n * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7])\n *\n * // Take exactly 3 messages\n * const first3 = yield* Queue.takeN(queue, 3)\n *\n * // Take exactly 2 more messages\n * const next2 = yield* Queue.takeN(queue, 2)\n *\n * // Take remaining messages\n * const remaining = yield* Queue.takeN(queue, 2)\n * return [first3, next2, remaining]\n * })\n *\n * await Effect.runPromise(program) // => [[1, 2, 3], [4, 5], [6, 7]]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const takeN = (self, n) => takeBetween(self, n, n);\n/**\n * Takes between `min` and `max` messages from the queue.\n *\n * **Details**\n *\n * The operation waits when fewer than the required minimum messages are\n * available. It returns at most `max` messages. Finite fractional bounds are\n * rounded down, while `NaN` and non-positive bounds are treated as `0`. If the\n * queue completes or fails before the minimum can be satisfied, the effect\n * fails with the queue's terminal error.\n *\n * **Example** (Taking a bounded batch of values)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(10)\n *\n * // Add several messages\n * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7, 8])\n *\n * // Take between 2 and 5 messages\n * const batch1 = yield* Queue.takeBetween(queue, 2, 5)\n *\n * // Take between 1 and 10 messages (but only 3 remain)\n * const batch2 = yield* Queue.takeBetween(queue, 1, 10)\n *\n * // No more messages available, will wait or return done\n * // const batch3 = yield* Queue.takeBetween(queue, 1, 3)\n * return [batch1, batch2]\n * })\n *\n * await Effect.runPromise(program) // => [[1, 2, 3, 4, 5], [6, 7, 8]]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const takeBetween = (self, min, max) => {\n min = Count.normalize(min);\n max = Count.normalize(max);\n return internalEffect.suspend(() => takeBetweenUnsafe(self, min, max) ?? internalEffect.andThen(awaitTake(self), takeBetween(self, 1, max)));\n};\n/**\n * Takes a single message from the queue, or wait for a message to be\n * available.\n *\n * **Details**\n *\n * If the queue is done, it will fail with `Done`. If the\n * queue fails, the Effect will fail with the error.\n *\n * **Example** (Taking one value)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<string, Cause.Done>(3)\n *\n * // Add some messages\n * yield* Queue.offer(queue, \"first\")\n * yield* Queue.offer(queue, \"second\")\n *\n * // Take messages one by one\n * const msg1 = yield* Queue.take(queue)\n * const msg2 = yield* Queue.take(queue)\n *\n * // End the queue\n * yield* Queue.end(queue)\n *\n * // Taking from an ended queue fails with Done\n * const result = yield* Effect.exit(Queue.take(queue))\n * return [[msg1, msg2], result]\n * })\n *\n * await Effect.runPromise(program) // => [[\"first\", \"second\"], Exit.fail(Cause.Done())]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const take = self => internalEffect.suspend(() => takeUnsafe(self) ?? internalEffect.andThen(awaitTake(self), take(self)));\n/**\n * Attempts to take one item from the queue without waiting.\n *\n * **Details**\n *\n * Returns `Option.some` when an item is immediately available. Returns\n * `Option.none` when no item is available, when the queue is done, or when the\n * immediate take observes a queue failure.\n *\n * **Example** (Polling without blocking)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(10)\n *\n * // Poll returns Option.none if empty\n * const maybe1 = yield* Queue.poll(queue)\n *\n * // Add an item\n * yield* Queue.offer(queue, 42)\n *\n * // Poll returns Option.some with the item\n * const maybe2 = yield* Queue.poll(queue)\n * return [maybe1, maybe2]\n * })\n *\n * await Effect.runPromise(program) // => [Option.none(), Option.some(42)]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const poll = self => internalEffect.suspend(() => {\n const result = takeUnsafe(self);\n if (result === undefined) {\n return internalEffect.succeed(Option.none());\n }\n if (result._tag === \"Success\") {\n return internalEffect.succeed(Option.some(result.value));\n }\n return internalEffect.succeed(Option.none());\n});\n/**\n * Peeks at the next item without removing it.\n *\n * **Details**\n *\n * Blocks until an item is available. If the queue is done or fails, the error is propagated.\n *\n * **Example** (Peeking at the next value)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(10)\n * yield* Queue.offer(queue, 42)\n *\n * // Peek at the next item without removing it\n * const item = yield* Queue.peek(queue)\n * return item\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @category taking\n * @since 4.0.0\n */\nexport const peek = self => internalEffect.suspend(() => {\n if (self.state._tag === \"Done\") {\n return self.state.exit;\n }\n if (self.messages.length > 0 && self.messages.head) {\n return internalEffect.succeed(self.messages.head.array[self.messages.head.offset]);\n }\n return internalEffect.andThen(awaitTake(self), peek(self));\n});\n/**\n * Attempts to take one message from the queue synchronously.\n *\n * **When to use**\n *\n * Use when polling queue internals must not suspend or register a waiting taker,\n * and `undefined` is an acceptable result for an empty queue.\n *\n * **Details**\n *\n * Returns an `Exit` for an immediately available message or for the queue's\n * terminal state. Returns `undefined` when no message is immediately available.\n * This operation does not wait or register a taker.\n *\n * **Example** (Taking one value synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Queue } from \"effect\"\n *\n * // Create a queue and use unsafe operations\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number>(10)\n *\n * // Add some messages\n * Queue.offerUnsafe(queue, 1)\n * Queue.offerUnsafe(queue, 2)\n *\n * // Take a message synchronously\n * const result1 = Queue.takeUnsafe(queue)\n *\n * const result2 = Queue.takeUnsafe(queue)\n *\n * // No more messages - returns undefined\n * const result3 = Queue.takeUnsafe(queue)\n * return [result1, result2, result3]\n * })\n *\n * await Effect.runPromise(program) // => [Exit.succeed(1), Exit.succeed(2), undefined]\n * ```\n *\n * @category taking\n * @since 4.0.0\n */\nexport const takeUnsafe = self => {\n if (self.state._tag === \"Done\") {\n return self.state.exit;\n }\n if (self.messages.length > 0) {\n const message = MutableList.take(self.messages);\n releaseCapacity(self);\n return core.exitSucceed(message);\n } else if (self.capacity <= 0 && self.state.offers.size > 0) {\n const message = takeOfferUnsafe(self.state.offers);\n releaseCapacity(self);\n return core.exitSucceed(message);\n }\n return undefined;\n};\n/**\n * Manually releases current queue takers synchronously.\n *\n * **When to use**\n *\n * Use when synchronous offers should release waiting consumers immediately\n * instead of waiting for the scheduled release task.\n *\n * **Details**\n *\n * This immediately runs the queue's taker-release pass instead of waiting for\n * its scheduled task. It does not complete the queue or resume fibers waiting\n * on `Queue.await`.\n *\n * **Example** (Releasing a waiting taker synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.unbounded<number>()\n * const taker = yield* Queue.take(queue).pipe(Effect.forkChild)\n * yield* Effect.yieldNow\n *\n * Queue.offerUnsafe(queue, 1)\n * Queue.flushUnsafe(queue)\n *\n * return yield* Fiber.join(taker)\n * })\n *\n * await Effect.runPromise(program) // => 1\n * ```\n *\n * @category offering\n * @since 4.0.0\n */\nexport const flushUnsafe = self => releaseTakers(self);\n/**\n * Manually releases current queue takers.\n *\n * **When to use**\n *\n * Use when synchronous offers should release waiting consumers through an\n * `Effect` instead of waiting for the scheduled release task.\n *\n * **Details**\n *\n * This immediately runs the queue's taker-release pass instead of waiting for\n * its scheduled task. It does not complete the queue or resume fibers waiting\n * on `Queue.await`.\n *\n * **Example** (Releasing a waiting taker)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.unbounded<number>()\n * const taker = yield* Queue.take(queue).pipe(Effect.forkChild)\n * yield* Effect.yieldNow\n *\n * Queue.offerUnsafe(queue, 1)\n * yield* Queue.flush(queue)\n *\n * return yield* Fiber.join(taker)\n * })\n *\n * await Effect.runPromise(program) // => 1\n * ```\n *\n * @category offering\n * @since 4.0.0\n */\nexport const flush = self => internalEffect.sync(() => flushUnsafe(self));\nconst await_ = self => internalEffect.callback(resume => {\n const awaiter = effect => resume(Pull.catchDone(effect, () => internalEffect.exitVoid));\n if (self.state._tag === \"Done\") {\n return awaiter(self.state.exit);\n }\n self.state.awaiters.add(awaiter);\n return internalEffect.sync(() => {\n if (self.state._tag !== \"Done\") {\n self.state.awaiters.delete(awaiter);\n }\n });\n});\nexport {\n/**\n * Waits until a queue reaches the `Done` state.\n *\n * **When to use**\n *\n * Use to suspend a fiber until no further values can be taken from the queue\n * and its terminal outcome is known.\n *\n * **Details**\n *\n * The effect succeeds with `void` for normal `Done` completion. Other\n * terminal causes are preserved, so failures and interruptions complete this\n * effect with the same terminal outcome.\n *\n * **Gotchas**\n *\n * A queue can be closing before it is done. `await` resumes at `Done`, not at\n * the first completion signal, so buffered messages may need to be drained\n * first.\n *\n * @see {@link end} for signaling normal completion while preserving buffered messages for consumers\n * @see {@link fail} for signaling an error while preserving buffered messages for consumers\n * @see {@link interrupt} for graceful interruption after buffered messages are drained\n * @see {@link shutdown} for immediately discarding buffered messages and resuming pending operations\n *\n * @category completion\n * @since 4.0.0\n */\nawait_ as await };\n/**\n * Returns the current number of buffered messages in the queue.\n *\n * **Details**\n *\n * After `end`, a queue remains `Closing` while buffered messages are drained,\n * and its size continues to include those messages. A `Done` queue reports a\n * size of `0`.\n *\n * **Example** (Checking queue size)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n * // Check size of empty queue\n * const size1 = yield* Queue.size(queue)\n *\n * // Add some messages\n * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n *\n * // Check size after adding messages\n * const size2 = yield* Queue.size(queue)\n *\n * // End the queue\n * yield* Queue.end(queue)\n *\n * // Ending retains the buffered size while the queue is Closing\n * const size3 = yield* Queue.size(queue)\n * return [size1, size2, size3]\n * })\n *\n * await Effect.runPromise(program) // => [0, 5, 5]\n * ```\n *\n * @category sizes\n * @since 2.0.0\n */\nexport const size = self => internalEffect.sync(() => sizeUnsafe(self));\n/**\n * Checks whether the queue is full.\n *\n * **Example** (Checking if queues are full)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(3)\n *\n * const before = yield* Queue.isFull(queue)\n *\n * // Add some messages\n * yield* Queue.offerAll(queue, [1, 2, 3])\n *\n * const after = yield* Queue.isFull(queue)\n * return [before, after]\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isFull = self => internalEffect.sync(() => isFullUnsafe(self));\n/**\n * Returns the current number of buffered messages in the queue synchronously.\n *\n * **When to use**\n *\n * Use when you need an immediate `Queue` size snapshot for diagnostics or\n * internals and do not need the read wrapped in `Effect`.\n *\n * **Details**\n *\n * After `endUnsafe`, a queue remains `Closing` while buffered messages are\n * drained, and its size continues to include those messages. A `Done` queue\n * reports a size of `0`. This unsafe operation reads the queue state directly\n * without Effect wrapping.\n *\n * **Example** (Checking queue size synchronously)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n * // Check size of empty queue\n * const size1 = Queue.sizeUnsafe(queue)\n *\n * // Add some messages\n * Queue.offerUnsafe(queue, 1)\n * Queue.offerUnsafe(queue, 2)\n * Queue.offerUnsafe(queue, 3)\n *\n * // Check size after adding messages\n * const size2 = Queue.sizeUnsafe(queue)\n *\n * // End the queue\n * Queue.endUnsafe(queue)\n *\n * // Ending retains the buffered size while the queue is Closing\n * const size3 = Queue.sizeUnsafe(queue)\n * return [size1, size2, size3]\n * })\n *\n * await Effect.runPromise(program) // => [0, 3, 3]\n * ```\n *\n * @category sizes\n * @since 4.0.0\n */\nexport const sizeUnsafe = self => self.state._tag === \"Done\" ? 0 : self.messages.length;\n/**\n * Checks whether the queue is full synchronously.\n *\n * **When to use**\n *\n * Use when an immediate `Queue` capacity snapshot is needed outside effectful\n * code and racing queue changes are acceptable.\n *\n * **Example** (Checking fullness synchronously)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(3)\n *\n * const before = Queue.isFullUnsafe(queue)\n *\n * // Add some messages\n * yield* Queue.offerAll(queue, [1, 2, 3])\n *\n * const after = Queue.isFullUnsafe(queue)\n * return [before, after]\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isFullUnsafe = self => sizeUnsafe(self) === self.capacity;\n/**\n * Runs an `Effect` into a `Queue`, where success ends the queue and failure\n * fails the queue.\n *\n * **Example** (Running effects into queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n * // Create an effect that succeeds\n * const dataProcessing = Effect.gen(function*() {\n * yield* Effect.yieldNow\n * return \"Processing completed successfully\"\n * })\n *\n * // Pipe the effect into the queue\n * // If dataProcessing succeeds, queue ends successfully\n * // If dataProcessing fails, queue fails with the error\n * const effectIntoQueue = Queue.into(queue)(dataProcessing)\n *\n * const wasCompleted = yield* effectIntoQueue\n * const exit = yield* Effect.exit(Queue.take(queue))\n * return [wasCompleted, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.fail(Cause.Done())]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const into = /*#__PURE__*/dual(2, (effect, self) => internalEffect.uninterruptibleMask(restore => internalEffect.matchCauseEffect(restore(effect), {\n onFailure: cause => failCause(self, cause),\n onSuccess: _ => end(self)\n})));\n// -----------------------------------------------------------------------------\n// internals\n// -----------------------------------------------------------------------------\n//\nconst exitFalse = /*#__PURE__*/core.exitSucceed(false);\nconst exitTrue = /*#__PURE__*/core.exitSucceed(true);\nconst exitFailDone = /*#__PURE__*/core.exitFail(/*#__PURE__*/core.Done());\nconst exitInterrupt = /*#__PURE__*/internalEffect.exitInterrupt();\nconst releaseTakers = self => {\n if (self.state._tag === \"Done\" || self.state.takers.size === 0) {\n return;\n }\n for (const taker of self.state.takers) {\n self.state.takers.delete(taker);\n taker(internalEffect.exitVoid);\n if (self.messages.length === 0) {\n break;\n }\n }\n};\nconst scheduleReleaseTaker = self => {\n if (self.scheduleRunning || self.state._tag === \"Done\" || self.state.takers.size === 0) {\n return;\n }\n self.scheduleRunning = true;\n self.dispatcher.scheduleTask(() => {\n self.scheduleRunning = false;\n releaseTakers(self);\n }, 0);\n};\nconst takeBetweenUnsafe = (self, min, max) => {\n if (self.state._tag === \"Done\") {\n return self.state.exit;\n } else if (max <= 0 || min <= 0) {\n return core.exitSucceed([]);\n } else if (self.capacity <= 0 && self.messages.length === 0 && self.state.offers.size > 0) {\n const messages = [takeOfferUnsafe(self.state.offers)];\n releaseCapacity(self);\n return core.exitSucceed(messages);\n }\n min = Math.min(min, self.capacity || 1);\n if (min <= self.messages.length) {\n const messages = MutableList.takeN(self.messages, max);\n releaseCapacity(self);\n return core.exitSucceed(messages);\n }\n};\nconst offerRemainingSingle = (self, message) => {\n return internalEffect.callback(resume => {\n if (self.state._tag !== \"Open\") {\n return resume(exitFalse);\n }\n const entry = {\n _tag: \"Single\",\n message,\n resume\n };\n self.state.offers.add(entry);\n return internalEffect.sync(() => {\n if (self.state._tag === \"Open\") {\n self.state.offers.delete(entry);\n }\n });\n });\n};\nconst offerRemainingArray = (self, remaining) => {\n return internalEffect.callback(resume => {\n if (self.state._tag !== \"Open\") {\n return resume(core.exitSucceed(remaining));\n }\n const entry = {\n _tag: \"Array\",\n remaining,\n offset: 0,\n resume\n };\n self.state.offers.add(entry);\n return internalEffect.sync(() => {\n if (self.state._tag === \"Open\") {\n self.state.offers.delete(entry);\n }\n });\n });\n};\n// Reserve a pending message for the consumer before the producer can reenter.\nconst takeOfferUnsafe = offers => {\n const entry = offers.values().next().value;\n if (entry._tag === \"Single\") {\n offers.delete(entry);\n entry.resume(exitTrue);\n return entry.message;\n }\n const message = entry.remaining[entry.offset++];\n if (entry.offset === entry.remaining.length) {\n offers.delete(entry);\n entry.resume(core.exitSucceed([]));\n }\n return message;\n};\nconst releaseCapacity = self => {\n if (self.state._tag === \"Done\") {\n return Pull.isDoneCause(self.state.exit.cause);\n } else if (self.state.offers.size === 0) {\n if (self.state._tag === \"Closing\" && self.messages.length === 0) {\n finalize(self, self.state.exit);\n return Pull.isDoneCause(self.state.exit.cause);\n }\n return false;\n }\n // Resuming a producer can synchronously take, offer, or shut down this queue.\n for (const entry of self.state.offers) {\n let n = self.capacity - self.messages.length;\n if (n <= 0) break;else if (entry._tag === \"Single\") {\n MutableList.append(self.messages, entry.message);\n self.state.offers.delete(entry);\n entry.resume(exitTrue);\n } else {\n for (; entry.offset < entry.remaining.length; entry.offset++) {\n if (n === 0) return false;\n MutableList.append(self.messages, entry.remaining[entry.offset]);\n n--;\n }\n self.state.offers.delete(entry);\n entry.resume(core.exitSucceed([]));\n }\n }\n return false;\n};\nconst awaitTake = self => internalEffect.callback(resume => {\n if (self.state._tag === \"Done\") {\n return resume(self.state.exit);\n }\n self.state.takers.add(resume);\n return internalEffect.sync(() => {\n if (self.state._tag !== \"Done\") {\n self.state.takers.delete(resume);\n }\n });\n});\nconst takeAllUnsafe = self => {\n if (self.messages.length > 0) {\n const messages = MutableList.takeAll(self.messages);\n releaseCapacity(self);\n return messages;\n } else if (self.state._tag !== \"Done\" && self.state.offers.size > 0) {\n const messages = [takeOfferUnsafe(self.state.offers)];\n releaseCapacity(self);\n return messages;\n }\n return [];\n};\nconst finalize = (self, exit) => {\n if (self.state._tag === \"Done\") {\n return;\n }\n const openState = self.state;\n self.state = {\n _tag: \"Done\",\n exit\n };\n for (const taker of openState.takers) {\n taker(exit);\n }\n openState.takers.clear();\n for (const awaiter of openState.awaiters) {\n awaiter(exit);\n }\n openState.awaiters.clear();\n};\n//# sourceMappingURL=Queue.js.map","import { dual } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport * as internal from \"./internal/effect.js\";\n/**\n * Creates a `Semaphore` synchronously with the specified total\n * number of permits.\n *\n * **When to use**\n *\n * Use to construct a semaphore synchronously when an immediate value is\n * required outside an Effect workflow.\n *\n * **Example** (Creating an unsafe semaphore)\n *\n * ```ts import.meta.vitest\n * import { Effect, Semaphore } from \"effect\"\n *\n * const semaphore = Semaphore.makeUnsafe(3)\n *\n * const task = (id: number) =>\n * semaphore.withPermits(1)(\n * Effect.gen(function*() {\n * yield* Effect.yieldNow\n * return id\n * })\n * )\n *\n * // Only 3 tasks can run concurrently\n * const program = Effect.all([\n * task(1),\n * task(2),\n * task(3),\n * task(4),\n * task(5)\n * ], { concurrency: \"unbounded\" })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = permits => new SemaphoreImpl(permits);\nconst waitForPermits = (self, n, effect) => internal.callback(resume => {\n if (self.free >= n) return resume(effect);\n const observer = () => {\n if (self.free < n) return;\n self.waiters.delete(observer);\n resume(effect);\n };\n self.waiters.add(observer);\n return internal.sync(() => {\n self.waiters.delete(observer);\n });\n});\nclass SemaphoreImpl {\n waiters = /*#__PURE__*/new Set();\n taken = 0;\n permits;\n constructor(permits) {\n this.permits = permits;\n }\n get free() {\n return this.permits - this.taken;\n }\n take(n) {\n const take = internal.suspend(() => {\n if (this.free < n) {\n return waitForPermits(this, n, take);\n }\n this.taken += n;\n return internal.succeed(n);\n });\n return take;\n }\n takeIfAvailable(n) {\n return internal.suspend(() => {\n if (this.free < n) return internal.succeed(false);\n this.taken += n;\n return internal.succeed(true);\n });\n }\n releaseUnsafe(fiber, n) {\n this.taken -= n;\n if (this.waiters.size > 0) {\n fiber.currentDispatcher.scheduleTask(() => {\n for (const observer of this.waiters) {\n if (this.free <= 0) break;\n observer();\n }\n }, 0);\n }\n return this.free;\n }\n resize(permits) {\n return core.withFiber(fiber => {\n this.permits = permits;\n if (this.free < 0) return internal.void;\n this.releaseUnsafe(fiber, 0);\n return internal.void;\n });\n }\n release(n) {\n return core.withFiber(fiber => internal.succeed(this.releaseUnsafe(fiber, n)));\n }\n get releaseAll() {\n return core.withFiber(fiber => internal.succeed(this.releaseUnsafe(fiber, this.taken)));\n }\n withPermits(n) {\n return self => internal.uninterruptibleMask(restore => {\n const acquire = internal.suspend(() => {\n if (this.free < n) {\n const wait = waitForPermits(this, n, internal.void);\n return internal.flatMap(restore(wait), () => acquire);\n }\n this.taken += n;\n return internal.onExitPrimitive(restore(self), () => {\n this.releaseUnsafe(internal.getCurrentFiber(), n);\n return undefined;\n }, true);\n });\n return acquire;\n });\n }\n withPermit = /*#__PURE__*/this.withPermits(1);\n withPermitsIfAvailable(n) {\n return self => internal.uninterruptibleMask(restore => {\n if (this.free < n) return internal.succeedNone;\n this.taken += n;\n return internal.onExitPrimitive(restore(internal.asSome(self)), () => {\n this.releaseUnsafe(internal.getCurrentFiber(), n);\n return undefined;\n }, true);\n });\n }\n}\n/**\n * Creates a `Semaphore` initialized with the specified total number of permits.\n *\n * **When to use**\n *\n * Use to create a semaphore inside Effect code for bounding concurrency with\n * automatic or manual permit management.\n *\n * **Example** (Creating a semaphore)\n *\n * ```ts import.meta.vitest\n * import { Effect, Semaphore } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const semaphore = yield* Semaphore.make(2)\n *\n * const task = (id: number) =>\n * semaphore.withPermits(1)(\n * Effect.gen(function*() {\n * yield* Effect.yieldNow\n * return id\n * })\n * )\n *\n * // Run 4 tasks, but only 2 can run concurrently\n * return yield* Effect.all([task(1), task(2), task(3), task(4)])\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = permits => internal.sync(() => new SemaphoreImpl(permits));\n/**\n * Sets the total number of permits managed by the semaphore.\n *\n * **When to use**\n *\n * Use to change the concurrency limit of an existing semaphore while keeping\n * current acquisitions in place.\n *\n * **Details**\n *\n * Existing acquisitions remain taken after resizing. If the new total is less\n * than the currently taken permit count, new acquisitions wait until enough\n * permits are released.\n *\n * @see {@link make} for creating a semaphore with an initial permit count\n * @see {@link release} for returning permits without changing semaphore capacity\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const resize = /*#__PURE__*/dual(2, (self, permits) => self.resize(permits));\n/**\n * Runs an effect with the given number of permits and releases the permits when\n * the effect completes.\n *\n * **When to use**\n *\n * Use to run an effect while holding a specified number of semaphore permits\n * for the duration of that effect.\n *\n * **Details**\n *\n * The effect waits until enough permits are available. Acquired permits are\n * released when the wrapped effect exits.\n *\n * @see {@link withPermit} for acquiring exactly one permit\n * @see {@link withPermitsIfAvailable} for running only when permits are immediately available\n * @see {@link take} for manually acquiring permits\n * @see {@link release} for manually returning permits\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withPermits = (self, permits, effect) => {\n const withPermits = self.withPermits(permits);\n return effect ? withPermits(effect) : withPermits;\n};\n/**\n * Runs an effect with a single permit and releases the permit when the effect\n * completes.\n *\n * **When to use**\n *\n * Use to guard an effect with exactly one semaphore permit while automatically\n * releasing that permit when the effect exits.\n *\n * @see {@link withPermits} for acquiring more than one permit\n * @see {@link withPermitsIfAvailable} for running only when permits are immediately available\n * @see {@link take} for manually acquiring permits\n * @see {@link release} for manually returning permits\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withPermit = (self, effect) => {\n if (!effect) return self.withPermit;\n return self.withPermit(effect);\n};\n/**\n * Runs an effect only if the specified number of permits are immediately\n * available.\n *\n * **When to use**\n *\n * Use when guarded work should run only if the requested permits are\n * immediately available.\n *\n * **Details**\n *\n * When the permits are unavailable, the effect is not run and the result is\n * `Option.none`. When permits are available, the effect is run, its result is\n * wrapped in `Option.some`, and the acquired permits are released when the\n * effect exits.\n *\n * @see {@link withPermits} for the variant that waits until permits are available\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withPermitsIfAvailable = (self, permits, effect) => {\n const withPermits = self.withPermitsIfAvailable(permits);\n return effect ? withPermits(effect) : withPermits;\n};\n/**\n * Acquires the specified number of permits and returns the acquired permit\n * count.\n *\n * **When to use**\n *\n * Use when you need manual permit acquisition for a lower-level protocol with\n * explicit acquisition and release control.\n *\n * **Details**\n *\n * The effect waits until enough permits are available.\n *\n * @see {@link withPermit} for automatically acquiring and releasing one permit around an effect\n * @see {@link withPermits} for automatically acquiring and releasing multiple permits around an effect\n * @see {@link takeIfAvailable} for manually acquiring permits without waiting\n * @see {@link release} for returning manually acquired permits\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const take = /*#__PURE__*/dual(2, (self, permits) => self.take(permits));\n/**\n * Acquires the specified number of permits only if they are immediately\n * available.\n *\n * **When to use**\n *\n * Use when you need fail-fast manual permit acquisition for a lower-level\n * protocol with explicit acquisition and release control.\n *\n * **Details**\n *\n * If enough permits are available, they are acquired and the effect returns\n * `true`. Otherwise, the effect returns `false` immediately without acquiring\n * any permits.\n *\n * @see {@link take} for the variant that waits until permits are available\n * @see {@link release} for returning manually acquired permits\n * @see {@link withPermitsIfAvailable} for automatic acquisition and release around an effect\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const takeIfAvailable = /*#__PURE__*/dual(2, (self, permits) => self.takeIfAvailable(permits));\n/**\n * Releases the specified number of permits and returns the resulting available\n * permits.\n *\n * **When to use**\n *\n * Use when you need to return permits acquired with `take` in a lower-level\n * permit protocol with explicit release control.\n *\n * **Details**\n *\n * Running the effect releases the requested permits, wakes waiting acquirers\n * when permits become available, and returns the current available permit\n * count.\n *\n * **Gotchas**\n *\n * Manual `take` / `release` usage must keep permit counts balanced. Prefer\n * `withPermit` or `withPermits` when the acquisition can be scoped to one\n * effect.\n *\n * @see {@link take} for manually acquiring permits\n * @see {@link releaseAll} for returning every currently taken permit\n * @see {@link withPermits} for automatic acquire and release around an effect\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const release = /*#__PURE__*/dual(2, (self, permits) => self.release(permits));\n/**\n * Releases all permits held by this semaphore and returns the resulting\n * available permits.\n *\n * **When to use**\n *\n * Use to return every currently taken permit to a semaphore at once, typically\n * during cleanup of manual `take` / `release` protocols.\n *\n * @see {@link release} for releasing a known permit count\n * @see {@link withPermits} for automatic acquire and release around an effect\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const releaseAll = self => self.releaseAll;\n//# sourceMappingURL=Semaphore.js.map","import * as Cause from \"./Cause.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\n/**\n * Converts a `Take` into a `Pull`, succeeding with value batches, failing with\n * failure exits, and translating successful exits into pull completion.\n *\n * **When to use**\n *\n * Use to interpret a stored or transferred `Take` as a `Pull` step while\n * preserving emitted batches, ordinary failures, and completion values.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toPull = take => Exit.isExit(take) ? Exit.isSuccess(take) ? Cause.done(take.value) : take : Effect.succeed(take);\n//# sourceMappingURL=Take.js.map","/**\n * Provides low-level building blocks for streaming data through Effect.\n *\n * A `Channel` can read input elements, write output elements, fail with a typed\n * error, and finish with a typed result while managing resources safely.\n * Streams and sinks are built on channels, so most application code uses those\n * higher-level modules instead. This module is useful when implementing stream\n * operators or specialized streaming workflows.\n *\n * @since 2.0.0\n */\n// @effect-diagnostics returnEffectInGen:off\nimport * as Arr from \"./Array.js\";\nimport * as Cause from \"./Cause.js\";\nimport * as Chunk from \"./Chunk.js\";\nimport * as Context from \"./Context.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\nimport * as Fiber from \"./Fiber.js\";\nimport { constant, constTrue, constVoid, dual, identity as identity_ } from \"./Function.js\";\nimport * as Count from \"./internal/count.js\";\nimport { ClockRef, endSpan, scopeFinalizerCountUnsafe } from \"./internal/effect.js\";\nimport { addSpanStackTrace } from \"./internal/tracer.js\";\nimport * as Iterable from \"./Iterable.js\";\nimport * as Latch from \"./Latch.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as MutableRef from \"./MutableRef.js\";\nimport * as Option from \"./Option.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty, isTagged } from \"./Predicate.js\";\nimport * as PubSub from \"./PubSub.js\";\nimport * as Pull from \"./Pull.js\";\nimport * as Queue from \"./Queue.js\";\nimport { TracerTimingEnabled } from \"./References.js\";\nimport * as Result from \"./Result.js\";\nimport * as Schedule from \"./Schedule.js\";\nimport * as Scope from \"./Scope.js\";\nimport * as Semaphore from \"./Semaphore.js\";\nimport * as String from \"./String.js\";\nimport * as Take from \"./Take.js\";\nimport { ParentSpan } from \"./Tracer.js\";\n/**\n * Runtime identifier stored on `Channel` values and used by `isChannel` to\n * recognize them.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/Channel\";\n/**\n * Checks whether a value is a `Channel`.\n *\n * **Example** (Checking for channels)\n *\n * ```ts import.meta.vitest\n * import { Channel } from \"effect\"\n *\n * const channel = Channel.succeed(42)\n * Channel.isChannel(channel) // => true\n * Channel.isChannel(\"not a channel\") // => false\n * ```\n *\n * @category guards\n * @since 3.5.4\n */\nexport const isChannel = u => hasProperty(u, TypeId);\nconst ChannelProto = {\n [TypeId]: {\n _Env: identity_,\n _InErr: identity_,\n _InElem: identity_,\n _OutErr: identity_,\n _OutElem: identity_\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n// -----------------------------------------------------------------------------\n// Constructors\n// -----------------------------------------------------------------------------\n/**\n * Creates a `Channel` from a transformation function that operates on upstream pulls.\n *\n * **Example** (Creating channels from transforms)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromTransform((upstream, scope) =>\n * Effect.succeed(upstream)\n * )\n * await Effect.runPromise(Channel.runCollect(channel)) // => []\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromTransform = transform => {\n const self = Object.create(ChannelProto);\n self.transform = (upstream, scope) => Effect.catchCause(transform(upstream, scope), cause => Effect.succeed(Effect.failCause(cause)));\n return self;\n};\n/**\n * Transforms a Channel by applying a function to its Pull implementation.\n *\n * **Example** (Transforming pull behavior)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Transform a channel by modifying its pull behavior\n * const originalChannel = Channel.fromIterable([1, 2, 3])\n *\n * const transformedChannel = Channel.transformPull(\n * originalChannel,\n * (pull, scope) =>\n * Effect.succeed(\n * Effect.map(pull, (value) => value * 2)\n * )\n * )\n * await Effect.runPromise(Channel.runCollect(transformedChannel)) // => [2, 4, 6]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const transformPull = (self, f) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), pull => f(pull, scope)));\n/**\n * Creates a `Channel` from an `Effect` that produces a `Pull`.\n *\n * **Example** (Creating channels from pulls)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromPull(Effect.sync(() => {\n * let emitted = false\n * return Effect.suspend(() => {\n * if (emitted) return Cause.done()\n * emitted = true\n * return Effect.succeed(42)\n * })\n * }))\n * await Effect.runPromise(Channel.runCollect(channel)) // => [42]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPull = effect => fromTransform((_, __) => effect);\n/**\n * Creates a `Channel` from a transformation function that operates on upstream\n * pulls, but also provides a forked scope that closes when the resulting\n * Channel completes.\n *\n * **When to use**\n *\n * Use when building channels that require scoped resource lifecycle management,\n * providing both the channel scope and a forked scope that automatically closes\n * when the channel completes.\n *\n * @see {@link fromTransform} for a simpler transformation without a forked scope\n * @category constructors\n * @since 4.0.0\n */\nexport const fromTransformBracket = f => fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n const closableScope = Scope.forkUnsafe(scope);\n const onCause = cause => Scope.close(closableScope, Pull.doneExitFromCause(cause));\n const pull = yield* Effect.onError(f(upstream, scope, closableScope), onCause);\n return Effect.onError(pull, onCause);\n}));\n/**\n * Converts a `Channel` back to its underlying transformation function.\n *\n * **Example** (Extracting channel transforms)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.succeed(42)\n * const transform = Channel.toTransform(channel)\n * typeof transform // => \"function\"\n * Effect.runSync(Channel.runCollect(channel)) // => [42]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toTransform = channel => channel.transform;\n/**\n * The default chunk size used by channels for batching operations.\n *\n * **Example** (Reading the default chunk size)\n *\n * ```ts import.meta.vitest\n * import { Channel } from \"effect\"\n *\n * Channel.DefaultChunkSize // => 4096\n * ```\n *\n * @category constants\n * @since 4.0.0\n */\nexport const DefaultChunkSize = 4096;\nconst asyncQueue = (scope, f, options) => Queue.make({\n capacity: options?.bufferSize,\n strategy: options?.strategy\n}).pipe(Effect.tap(queue => Scope.addFinalizer(scope, Queue.shutdown(queue))), Effect.tap(queue => Effect.forkIn(Scope.provide(f(queue), scope), scope)));\n/**\n * Creates a `Channel` that interacts with a callback function using a queue.\n *\n * **Example** (Creating channels from callbacks)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Queue } from \"effect\"\n *\n * const channel = Channel.callback<number>((queue) =>\n * Effect.gen(function*() {\n * yield* Queue.offer(queue, 1)\n * yield* Queue.offer(queue, 2)\n * yield* Queue.offer(queue, 3)\n * yield* Queue.end(queue)\n * })\n * )\n * await Effect.runPromise(Channel.runCollect(channel)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const callback = (f, options) => fromTransform((_, scope) => Effect.map(asyncQueue(scope, f, options), Queue.take));\n/**\n * Creates a `Channel` that interacts with a callback function using a queue, emitting arrays.\n *\n * **Example** (Creating array channels from callbacks)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Queue } from \"effect\"\n *\n * const channel = Channel.callbackArray<number>(Effect.fn(function*(queue) {\n * yield* Queue.offer(queue, 1)\n * yield* Queue.offer(queue, 2)\n * yield* Queue.end(queue)\n * }))\n * await Effect.runPromise(Channel.runCollect(channel)) // => [[1, 2]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const callbackArray = (f, options) => fromTransform((_, scope) => Effect.map(asyncQueue(scope, f, options), Queue.takeAll));\n/**\n * Creates a `Channel` that lazily evaluates to another channel.\n *\n * **Example** (Suspending channel creation)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.suspend(() => Channel.succeed(42))\n * Effect.runSync(Channel.runCollect(channel)) // => [42]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const suspend = evaluate => fromTransform((upstream, scope) => Effect.suspend(() => toTransform(evaluate())(upstream, scope)));\n/**\n * Acquires a resource, uses it to build a `Channel`, and guarantees that\n * `release` runs with the channel's `Exit` when the channel completes, fails,\n * or is interrupted.\n *\n * **Details**\n *\n * Acquisition is uninterruptible. If acquisition fails, `use` is not run and\n * `release` is not registered.\n *\n * **Example** (Managing resources with acquire-use-release)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const released: Array<string> = []\n * const channel = Channel.acquireUseRelease(\n * Effect.succeed(\"resource\"),\n * (resource) => Channel.succeed(resource.toUpperCase()),\n * (resource, exit) => Effect.sync(() => released.push(resource))\n * )\n * const observed = [await Effect.runPromise(Channel.runCollect(channel)), released] // => [[\"RESOURCE\"], [\"resource\"]]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const acquireUseRelease = (acquire, use, release) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) {\n let option = Option.none();\n yield* Scope.addFinalizerExit(forkedScope, exit => Option.isSome(option) ? release(option.value, exit) : Effect.void);\n const value = yield* Effect.uninterruptible(acquire);\n option = Option.some(value);\n return yield* toTransform(use(value))(upstream, scope);\n}));\n/**\n * Acquires a resource, emits the acquired value as a single channel element,\n * and registers `release` in the channel scope.\n *\n * **Details**\n *\n * The release action runs when the channel scope closes and receives the scope\n * exit. If acquisition fails, no element is emitted and `release` is not\n * registered.\n *\n * **Example** (Managing resources with acquire-release)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const released: Array<string> = []\n * const channel = Channel.acquireRelease(\n * Effect.succeed(\"resource\"),\n * (resource, exit) => Effect.sync(() => released.push(resource))\n * )\n * const observed = [await Effect.runPromise(Channel.runCollect(channel)), released] // => [[\"resource\"], [\"resource\"]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const acquireRelease = /*#__PURE__*/dual(2, (self, release) => unwrap(Effect.map(Effect.acquireRelease(self, release), succeed)));\n/**\n * Creates a `Channel` from an iterator.\n *\n * **Example** (Creating channels from iterators)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const channel = Channel.fromIterator(() => numbers[Symbol.iterator]())\n * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterator = iterator => fromPull(Effect.sync(() => {\n const iter = iterator();\n return Effect.suspend(() => {\n const state = iter.next();\n return state.done ? Cause.done(state.value) : Effect.succeed(state.value);\n });\n}));\n/**\n * Creates a `Channel` that emits all elements from an array.\n *\n * **Example** (Creating channels from arrays)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromArray([1, 2, 3, 4, 5])\n * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromArray = array => fromPull(Effect.sync(() => {\n let index = 0;\n return Effect.suspend(() => index >= array.length ? Cause.done() : Effect.succeed(array[index++]));\n}));\n/**\n * Creates a `Channel` that emits all elements from a chunk.\n *\n * **Example** (Creating channels from chunks)\n *\n * ```ts import.meta.vitest\n * import { Channel, Chunk, Effect } from \"effect\"\n *\n * const chunk = Chunk.make(1, 2, 3)\n * const channel = Channel.fromChunk(chunk)\n * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromChunk = chunk => fromArray(Chunk.toReadonlyArray(chunk));\n/**\n * Creates a `Channel` from an iterator that emits arrays of elements.\n *\n * **Details**\n *\n * Finite fractional `chunkSize` values are rounded down. `NaN` and non-positive\n * values are treated as `1` so every successful pull emits a non-empty array.\n *\n * **Example** (Batching iterator output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel from a simple iterator\n * const numberIterator = (): Iterator<number, string> => {\n * let count = 0\n * return {\n * next: () => {\n * if (count < 3) {\n * return { value: count++, done: false }\n * }\n * return { value: \"finished\", done: true }\n * }\n * }\n * }\n *\n * const channel = Channel.fromIteratorArray(() => numberIterator(), 2)\n * Effect.runSync(Channel.runCollect(channel)) // => [[0, 1], [2]]\n * ```\n *\n * **Example** (Batching generator output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create channel from a generator function\n * function* fibonacci(): Generator<number, void, unknown> {\n * let a = 0, b = 1\n * for (let i = 0; i < 5; i++) {\n * yield a\n * ;[a, b] = [b, a + b]\n * }\n * }\n *\n * const fibChannel = Channel.fromIteratorArray(() => fibonacci(), 3)\n * Effect.runSync(Channel.runCollect(fibChannel)) // => [[0, 1, 1], [2, 3]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIteratorArray = (iterator, chunkSize = DefaultChunkSize) => {\n const size = Count.normalizeNonEmpty(chunkSize);\n return fromPull(Effect.sync(() => {\n const iter = iterator();\n let done = Option.none();\n return Effect.suspend(() => {\n if (done._tag === \"Some\") return Cause.done(done.value);\n const buffer = [];\n while (buffer.length < size) {\n const state = iter.next();\n if (state.done) {\n if (buffer.length === 0) {\n return Cause.done(state.value);\n }\n done = Option.some(state.value);\n break;\n }\n buffer.push(state.value);\n }\n return Effect.succeed(buffer);\n });\n }));\n};\n/**\n * Creates a `Channel` that emits all elements from an iterable.\n *\n * **Example** (Creating channels from iterables)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const set = new Set([1, 2, 3])\n * const channel = Channel.fromIterable(set)\n * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterable = iterable => fromIterator(() => iterable[Symbol.iterator]());\n/**\n * Creates a `Channel` that emits arrays of elements from an iterable.\n *\n * **Details**\n *\n * Finite fractional `chunkSize` values are rounded down. `NaN` and non-positive\n * values are treated as `1`.\n *\n * **Example** (Batching iterable output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const channel = Channel.fromIterableArray(numbers, 4)\n * Effect.runSync(Channel.runCollect(channel)) // => [[1, 2, 3, 4], [5]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterableArray = (iterable, chunkSize = DefaultChunkSize) => fromIteratorArray(() => iterable[Symbol.iterator](), chunkSize);\n/**\n * Creates a `Channel` that emits a single value and then ends.\n *\n * **Example** (Creating channels that succeed)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.succeed(42)\n * Effect.runSync(Channel.runCollect(channel)) // => [42]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeed = value => fromEffect(Effect.succeed(value));\n/**\n * Creates a `Channel` that immediately ends with the specified value.\n *\n * **Example** (Ending with a value)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.end(\"done\")\n * Effect.runSync(Channel.runCollect(channel)) // => []\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const end = value => fromPull(Effect.succeed(Cause.done(value)));\n/**\n * Creates a `Channel` that immediately ends with the lazily evaluated value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const endSync = evaluate => fromPull(Effect.sync(() => Cause.done(evaluate())));\n/**\n * Creates a `Channel` that emits a single value computed by a lazy evaluation.\n *\n * **Example** (Computing values lazily)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * let requests = 0\n *\n * const channel = Channel.sync(() => {\n * requests += 1\n * return `request-${requests}`\n * })\n * Effect.runSync(Channel.runCollect(channel)) // => [\"request-1\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sync = evaluate => fromEffect(Effect.sync(evaluate));\n/**\n * Represents a `Channel` that emits no elements.\n *\n * **Example** (Creating empty channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create an empty channel\n * const emptyChannel = Channel.empty\n *\n * // Use empty channel in composition\n * const combined = Channel.concatWith(emptyChannel, () => Channel.succeed(42))\n * // Will immediately provide the second channel's output\n *\n * // Empty channel can be used as a no-op in conditional logic\n * const conditionalChannel = (shouldEmit: boolean) =>\n * shouldEmit ? Channel.succeed(\"data\") : Channel.empty\n *\n * Effect.runSync(Channel.runCollect(conditionalChannel(true))) // => [\"data\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/fromPull(/*#__PURE__*/Effect.succeed(/*#__PURE__*/Cause.done()));\n/**\n * Represents a `Channel` that never completes.\n *\n * **Example** (Creating non-terminating channels)\n *\n * ```ts import.meta.vitest\n * import { Channel } from \"effect\"\n *\n * // Create a channel that never completes\n * const neverChannel = Channel.never\n *\n * // Use in conditional logic\n * const withFallback = Channel.concatWith(\n * neverChannel,\n * () => Channel.succeed(\"fallback\")\n * )\n *\n * // Never channel is useful for testing or as a placeholder\n * const conditionalChannel = (shouldComplete: boolean) =>\n * shouldComplete ? Channel.succeed(\"done\") : Channel.never\n *\n * Channel.isChannel(conditionalChannel(false)) // => true\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const never = /*#__PURE__*/fromPull(/*#__PURE__*/Effect.succeed(Effect.never));\n/**\n * Constructs a channel that fails immediately with the specified error.\n *\n * **Example** (Failing with an error)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Exit } from \"effect\"\n *\n * const failedChannel = Channel.fail(\"Something went wrong\")\n * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))) // => Exit.fail(\"Something went wrong\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fail = error => fromPull(Effect.succeed(Effect.fail(error)));\n/**\n * Constructs a channel that fails immediately with the specified lazily\n * evaluated error.\n *\n * **When to use**\n *\n * Use when the error value should be computed each time the channel runs instead\n * of when the channel is constructed.\n *\n * **Example** (Failing with a lazy error)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Exit } from \"effect\"\n *\n * let attempts = 0\n * const conditionalError = Channel.failSync(() => {\n * attempts += 1\n * return `Error after attempt ${attempts}`\n * })\n * const observed = [\n * Effect.runSync(Effect.exit(Channel.runCollect(conditionalError))),\n * attempts\n * ] // => [Exit.fail(\"Error after attempt 1\"), 1]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failSync = evaluate => fromPull(Effect.failSync(evaluate));\n/**\n * Constructs a channel that fails immediately with the specified `Cause`.\n *\n * **When to use**\n *\n * Use when the channel failure must preserve a full `Cause`, such as defects,\n * interruptions, or combined failures.\n *\n * **Example** (Failing with causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Exit } from \"effect\"\n *\n * const simpleCause = Cause.fail(\"Simple error\")\n * const failedChannel = Channel.failCause(simpleCause)\n * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))) // => Exit.failCause(simpleCause)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCause = cause => fromPull(Effect.failCause(cause));\n/**\n * Constructs a channel that fails immediately with the specified lazily\n * evaluated `Cause`.\n *\n * **Example** (Failing with lazy causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Exit } from \"effect\"\n *\n * // Create a channel that fails with a lazily computed cause\n * let attempts = 0\n * const failedChannel = Channel.failCauseSync(() => {\n * attempts += 1\n * return Cause.fail(`Runtime error after attempt ${attempts}`)\n * })\n *\n * const observed = [\n * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))),\n * attempts\n * ] // => [Exit.fail(\"Runtime error after attempt 1\"), 1]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCauseSync = evaluate => fromPull(Effect.failCauseSync(evaluate));\n/**\n * Constructs a channel that fails immediately with the specified defect.\n *\n * **Example** (Dying with defects)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Exit } from \"effect\"\n *\n * const defect = \"Unrecoverable error\"\n * const diedChannel = Channel.die(defect)\n * Effect.runSync(Effect.exit(Channel.runCollect(diedChannel))) // => Exit.failCause(Cause.die(defect))\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const die = defect => failCause(Cause.die(defect));\n/**\n * Uses an effect to write a single value to the channel.\n *\n * **Example** (Creating channels from effects)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const successChannel = Channel.fromEffect(\n * Effect.succeed(\"Hello from effect!\")\n * )\n * Effect.runSync(Channel.runCollect(successChannel)) // => [\"Hello from effect!\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromEffect = effect => fromPull(Effect.sync(() => {\n let done = false;\n return Effect.suspend(() => {\n if (done) return Cause.done();\n done = true;\n return effect;\n });\n}));\n/**\n * Creates a channel that evaluates an effect and uses its successful value as\n * the channel's done value without emitting any output elements.\n *\n * **Details**\n *\n * If the effect fails, the channel fails with the effect's error.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectDone = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Cause.done)));\n/**\n * Uses an effect and discards its result.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectDrain = effect => fromPull(Effect.flatMap(effect, () => Cause.done()));\n/**\n * Creates a channel from an effect that produces a `Take`.\n *\n * **Details**\n *\n * A successful `Take` emits a non-empty array of output elements. A failed\n * `Take` fails the channel. A done `Take` completes the channel with its done\n * value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectTake = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Take.toPull)));\n/**\n * Creates a channel from a queue.\n *\n * **Example** (Creating channels from queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<string, Cause.Done>(3)\n * yield* Queue.offerAll(queue, [\"item1\", \"item2\", \"item3\"])\n * yield* Queue.end(queue)\n * const channel = Channel.fromQueue(queue)\n * return yield* Channel.runCollect(channel)\n * })\n * await Effect.runPromise(program) // => [\"item1\", \"item2\", \"item3\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromQueue = queue => fromPull(Effect.succeed(Queue.take(queue)));\n/**\n * Creates a channel from a queue that emits arrays of elements.\n *\n * **Example** (Creating batched channels from queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(4)\n * yield* Queue.offerAll(queue, [1, 2, 3, 4])\n * yield* Queue.end(queue)\n * const arrayChannel = Channel.fromQueueArray(queue)\n * return yield* Channel.runCollect(arrayChannel)\n * })\n * await Effect.runPromise(program) // => [[1, 2, 3, 4]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromQueueArray = queue => fromPull(Effect.succeed(Queue.takeAll(queue)));\n/**\n * Creates a channel that forwards upstream input elements, input errors, and\n * the upstream done value unchanged.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const identity = () => fromTransform((upstream, _scope) => Effect.succeed(upstream));\n/**\n * Creates a channel from a PubSub subscription.\n *\n * **Example** (Creating channels from subscriptions)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class SubscriptionError extends Data.TaggedError(\"SubscriptionError\")<{\n * readonly reason: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n * // Create a PubSub\n * const pubsub = yield* PubSub.bounded<string>(32)\n *\n * // Create a subscription\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Publish some messages\n * yield* PubSub.publish(pubsub, \"Hello\")\n * yield* PubSub.publish(pubsub, \"World\")\n * yield* PubSub.publish(pubsub, \"from\")\n * yield* PubSub.publish(pubsub, \"PubSub\")\n *\n * // Create a channel from the subscription\n * const channel = Channel.fromSubscription(subscription)\n *\n * // The channel will receive all published messages\n * return channel\n * })\n * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead))\n * await Effect.runPromise(result) // => Option.some(\"Hello\")\n *\n * // Real-time notifications example\n * const notificationChannel = Effect.gen(function*() {\n * const eventBus = yield* PubSub.unbounded<{ type: string; payload: any }>()\n * const userSubscription = yield* PubSub.subscribe(eventBus)\n *\n * return Channel.fromSubscription(userSubscription)\n * })\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSubscription = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.take(subscription), () => Cause.done())));\n/**\n * Creates a channel from a PubSub subscription that outputs arrays of values.\n *\n * **Details**\n *\n * This constructor creates a channel that reads from a PubSub subscription and outputs\n * arrays of values in chunks. It's useful when you want to process multiple values at once\n * for better performance.\n *\n * **Example** (Batching subscription values)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class StreamError extends Data.TaggedError(\"StreamError\")<{\n * readonly message: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<number>(16)\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Create a channel that reads arrays of values\n * const channel = Channel.fromSubscriptionArray(subscription)\n *\n * // Publish some values\n * yield* PubSub.publish(pubsub, 1)\n * yield* PubSub.publish(pubsub, 2)\n * yield* PubSub.publish(pubsub, 3)\n * yield* PubSub.publish(pubsub, 4)\n *\n * // The channel will output arrays like [1, 2, 3] and [4]\n * return channel\n * })\n * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead))\n * await Effect.runPromise(result) // => Option.some([1, 2, 3, 4])\n * ```\n *\n * **Example** (Processing subscription values in batches)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class BatchProcessingError extends Data.TaggedError(\"BatchProcessingError\")<{\n * readonly reason: string\n * }> {}\n *\n * const batchProcessor = Effect.gen(function*() {\n * const pubsub = yield* PubSub.bounded<string>(32)\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * // Create a channel that processes items in batches\n * const batchChannel = Channel.fromSubscriptionArray(subscription)\n *\n * // Transform to process each batch\n * const processedChannel = Channel.map(batchChannel, (batch) =>\n * batch.map((item) => item.toUpperCase())\n * )\n *\n * yield* PubSub.publishAll(pubsub, [\"one\", \"two\"])\n * return processedChannel\n * })\n * const batch = Effect.scoped(Effect.flatMap(batchProcessor, Channel.runHead))\n * await Effect.runPromise(batch) // => Option.some([\"ONE\", \"TWO\"])\n * ```\n *\n * **Example** (Aggregating subscription metrics)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * const metricsAggregator = Effect.gen(function*() {\n * const metricsPubSub = yield* PubSub.bounded<\n * { timestamp: number; value: number }\n * >(100)\n * const subscription = yield* PubSub.subscribe(metricsPubSub)\n *\n * // Create a channel that collects metrics in chunks\n * const metricsChannel = Channel.fromSubscriptionArray(subscription)\n *\n * // Transform to calculate aggregate statistics\n * const aggregatedChannel = Channel.map(metricsChannel, (metrics) => {\n * const values = metrics.map((m) => m.value)\n * const sum = values.reduce((a, b) => a + b, 0)\n * const avg = sum / values.length\n * const min = Math.min(...values)\n * const max = Math.max(...values)\n *\n * return {\n * count: values.length,\n * sum,\n * average: avg,\n * min,\n * max,\n * firstTimestamp: Math.min(...metrics.map((m) => m.timestamp)),\n * lastTimestamp: Math.max(...metrics.map((m) => m.timestamp))\n * }\n * })\n *\n * yield* PubSub.publish(metricsPubSub, { timestamp: 1, value: 10 })\n * return aggregatedChannel\n * })\n * const metric = Effect.scoped(Effect.flatMap(metricsAggregator, Channel.runHead))\n * const result = await Effect.runPromise(metric)\n * Option.map(result, ({ count, sum, average, min, max }) => ({ count, sum, average, min, max })) // => Option.some({ count: 1, sum: 10, average: 10, min: 10, max: 10 })\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSubscriptionArray = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.takeAll(subscription), () => Cause.done())));\n/**\n * Creates a channel from a PubSub that outputs individual values.\n *\n * **Details**\n *\n * This constructor creates a channel that reads from a PubSub by automatically\n * subscribing to it. The channel outputs individual values as they are published\n * to the PubSub, making it ideal for real-time streaming scenarios.\n *\n * **Example** (Creating channels from PubSubs)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class StreamError extends Data.TaggedError(\"StreamError\")<{\n * readonly message: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.unbounded<number>({ replay: 3 })\n *\n * // Create a channel that reads individual values\n * const channel = Channel.fromPubSub(pubsub)\n *\n * // Publish some values\n * yield* PubSub.publish(pubsub, 1)\n * yield* PubSub.publish(pubsub, 2)\n * yield* PubSub.publish(pubsub, 3)\n *\n * // The channel will output: 1, 2, 3 (individual values)\n * return channel\n * })\n * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead))\n * await Effect.runPromise(result) // => Option.some(1)\n * ```\n *\n * **Example** (Streaming PubSub notifications)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * const notificationService = Effect.gen(function*() {\n * const notificationPubSub = yield* PubSub.unbounded<string>({ replay: 1 })\n *\n * // Create a channel for real-time notifications\n * const notificationChannel = Channel.fromPubSub(notificationPubSub)\n *\n * // Transform notifications to add timestamps\n * const receivedAt = \"2024-01-01T00:00:00.000Z\"\n * const timestampedChannel = Channel.map(notificationChannel, (message) => ({\n * message,\n * receivedAt,\n * id: `notification:${message}`\n * }))\n *\n * yield* PubSub.publish(notificationPubSub, \"ready\")\n * return timestampedChannel\n * })\n * const notification = Effect.scoped(Effect.flatMap(notificationService, Channel.runHead))\n * await Effect.runPromise(notification) // => Option.some({ message: \"ready\", receivedAt: \"2024-01-01T00:00:00.000Z\", id: \"notification:ready\" })\n * ```\n *\n * **Example** (Processing PubSub events)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * interface DomainEvent {\n * readonly type: string\n * readonly payload: unknown\n * readonly timestamp: number\n * }\n *\n * const eventProcessor = Effect.gen(function*() {\n * const eventPubSub = yield* PubSub.unbounded<DomainEvent>({ replay: 1 })\n *\n * // Create a channel for processing domain events\n * const eventChannel = Channel.fromPubSub(eventPubSub)\n *\n * // Filter and transform events\n * const processedChannel = Channel.map(eventChannel, (event) => {\n * if (event.type === \"user.created\") {\n * return {\n * ...event,\n * processed: true,\n * processedAt: event.timestamp + 1\n * }\n * }\n * return event\n * })\n *\n * yield* PubSub.publish(eventPubSub, { type: \"user.created\", payload: {}, timestamp: 1 })\n * return processedChannel\n * })\n * const event = Effect.scoped(Effect.flatMap(eventProcessor, Channel.runHead))\n * const result = await Effect.runPromise(event) // => Option.some({ type: \"user.created\", payload: {}, timestamp: 1, processed: true, processedAt: 2 })\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscription));\n/**\n * Creates a channel from a PubSub that outputs arrays of values.\n *\n * **Details**\n *\n * This constructor creates a channel that reads from a PubSub by automatically\n * subscribing to it and collecting values into arrays. The channel outputs\n * arrays of values in chunks, making it ideal for batch processing scenarios.\n *\n * **Example** (Batching PubSub values)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class BatchError extends Data.TaggedError(\"BatchError\")<{\n * readonly message: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.unbounded<number>({ replay: 4 })\n *\n * // Create a channel that reads arrays of values\n * const channel = Channel.fromPubSubArray(pubsub)\n *\n * // Publish some values\n * yield* PubSub.publish(pubsub, 1)\n * yield* PubSub.publish(pubsub, 2)\n * yield* PubSub.publish(pubsub, 3)\n * yield* PubSub.publish(pubsub, 4)\n *\n * // The channel will output arrays like [1, 2, 3] and [4]\n * return channel\n * })\n * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead))\n * await Effect.runPromise(result) // => Option.some([1, 2, 3, 4])\n * ```\n *\n * **Example** (Processing PubSub orders in batches)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * interface Order {\n * readonly id: string\n * readonly customerId: string\n * readonly items: ReadonlyArray<string>\n * readonly total: number\n * readonly submittedAt: number\n * }\n *\n * const orderBatchProcessor = Effect.gen(function*() {\n * const orderPubSub = yield* PubSub.unbounded<Order>({ replay: 1 })\n *\n * // Create a channel that processes orders in batches\n * const orderChannel = Channel.fromPubSubArray(orderPubSub)\n *\n * // Transform to process each batch of orders\n * const processedChannel = Channel.map(orderChannel, (orderBatch) => {\n * const totalRevenue = orderBatch.reduce((sum, order) => sum + order.total, 0)\n * const customerCount = new Set(orderBatch.map((order) =>\n * order.customerId\n * )).size\n *\n * return {\n * batchSize: orderBatch.length,\n * totalRevenue,\n * uniqueCustomers: customerCount,\n * firstSubmittedAt: Math.min(...orderBatch.map((order) => order.submittedAt)),\n * orders: orderBatch\n * }\n * })\n *\n * yield* PubSub.publish(orderPubSub, {\n * id: \"1\", customerId: \"a\", items: [\"book\"], total: 10, submittedAt: 1\n * })\n * return processedChannel\n * })\n * const order = Effect.scoped(Effect.flatMap(orderBatchProcessor, Channel.runHead))\n * const result = await Effect.runPromise(order)\n * Option.map(result, (batch) => [batch.batchSize, batch.totalRevenue, batch.uniqueCustomers]) // => Option.some([1, 10, 1])\n * ```\n *\n * **Example** (Processing PubSub logs in batches)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * interface LogEntry {\n * readonly timestamp: number\n * readonly level: \"info\" | \"warn\" | \"error\"\n * readonly message: string\n * readonly source: string\n * }\n *\n * const logAggregator = Effect.gen(function*() {\n * const logPubSub = yield* PubSub.unbounded<LogEntry>({ replay: 1 })\n *\n * // Create a channel that collects logs in batches\n * const logChannel = Channel.fromPubSubArray(logPubSub)\n *\n * // Transform to analyze log batches\n * const analysisChannel = Channel.map(logChannel, (logBatch) => {\n * const errorCount = logBatch.filter((log) => log.level === \"error\").length\n * const warnCount = logBatch.filter((log) => log.level === \"warn\").length\n * const infoCount = logBatch.filter((log) => log.level === \"info\").length\n *\n * const timeRange = {\n * start: Math.min(...logBatch.map((log) => log.timestamp)),\n * end: Math.max(...logBatch.map((log) => log.timestamp))\n * }\n *\n * return {\n * batchId: `${timeRange.start}-${timeRange.end}`,\n * totalEntries: logBatch.length,\n * errorCount,\n * warnCount,\n * infoCount,\n * timeRange,\n * sources: [...new Set(logBatch.map((log) => log.source))]\n * }\n * })\n *\n * yield* PubSub.publish(logPubSub, {\n * timestamp: 1,\n * level: \"info\",\n * message: \"ready\",\n * source: \"app\"\n * } satisfies LogEntry)\n * return analysisChannel\n * })\n * const log = Effect.scoped(Effect.flatMap(logAggregator, Channel.runHead))\n * const result = await Effect.runPromise(log)\n * Option.map(result, (batch) => [batch.batchId, batch.totalEntries, batch.infoCount]) // => Option.some([\"1-1\", 1, 1])\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPubSubArray = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscriptionArray));\n/**\n * Subscribes to a `PubSub` of `Take` values and exposes them as a channel.\n *\n * **Details**\n *\n * Output `Take` values are emitted as non-empty arrays. Failed `Take` values\n * fail the channel. Done `Take` values complete the channel.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPubSubTake = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), sub => fromEffectTake(PubSub.take(sub))));\n/**\n * Creates a Channel from a Schedule.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => step(void 0)));\n/**\n * Creates a channel from a lazily supplied Web `ReadableStream`.\n *\n * **Example** (Reading from a Web stream)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromReadableStream({\n * evaluate: () => new ReadableStream({\n * start(controller) {\n * controller.enqueue(1)\n * controller.close()\n * }\n * }),\n * onError: (cause) => new Error(String(cause))\n * })\n *\n * await Effect.runPromise(Channel.runCollect(channel)) // => [[1]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadableStream = options => fromTransform((_, scope) => readableStreamToPullUnsafe({\n scope,\n readable: options.evaluate(),\n onError: options.onError,\n releaseLockOnEnd: options.releaseLockOnEnd\n}));\n/** @internal */\nexport const pullIntoWritableStream = options => Effect.acquireUseRelease(Effect.sync(() => options.writable.getWriter()), writer => {\n const loop = options.pull.pipe(Effect.flatMap(chunk => Effect.forEach(chunk, value => Effect.tryPromise({\n try: () => writer.ready.then(() => writer.write(value)),\n catch: options.onError\n }), {\n discard: true\n })), Effect.forever({\n disableYield: true\n }));\n const withClose = options.closeOnDone !== false ? Pull.catchDone(loop, done => Effect.andThen(Effect.tryPromise({\n try: () => writer.close(),\n catch: options.onError\n }), Cause.done(done))) : loop;\n return Effect.onError(withClose, cause => Pull.isDoneCause(cause) ? Effect.void : Effect.promise(() => writer.abort(cause).catch(constVoid)));\n}, writer => Effect.sync(() => writer.releaseLock()));\n/**\n * Creates a channel that writes upstream values to a lazily supplied Web\n * `WritableStream`.\n *\n * **Example** (Writing channel input)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const written: Array<number> = []\n * const sink = Channel.fromWritableStream<never, Error, number>({\n * evaluate: () => new WritableStream({\n * write(value) {\n * written.push(value)\n * }\n * }),\n * onError: (cause) => new Error(String(cause))\n * })\n *\n * const program = Channel.fromArray([[1, 2] as [number, number]]).pipe(\n * Channel.pipeTo(sink),\n * Channel.runDrain\n * )\n *\n * await Effect.runPromise(program)\n * written // => [1, 2]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritableStream = options => fromTransform(pull => {\n const writable = options.evaluate();\n return Effect.succeed(pullIntoWritableStream({\n ...options,\n writable,\n pull\n }));\n});\n/**\n * Creates a channel backed by a Web `TransformStream`, writing upstream values\n * while emitting transformed values from its readable side.\n *\n * **Example** (Transforming channel input)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const transform = Channel.fromTransformStream<never, number, number, Error>({\n * evaluate: () => new TransformStream({\n * transform(value, controller) {\n * controller.enqueue(value * 2)\n * }\n * }),\n * onError: (cause) => new Error(String(cause))\n * })\n *\n * const program = Channel.fromArray([[1, 2] as [number, number]]).pipe(\n * Channel.pipeTo(transform),\n * Channel.runCollect\n * )\n *\n * await Effect.runPromise(program) // => [[2], [4]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromTransformStream = options => fromTransform((upstream, scope) => {\n const transform = options.evaluate();\n const exit = MutableRef.make(undefined);\n return pullIntoWritableStream({\n pull: upstream,\n writable: transform.writable,\n onError: options.onError,\n closeOnDone: options.closeOnDone\n }).pipe(Effect.catchCause(cause => {\n if (!Pull.isDoneCause(cause)) {\n exit.current = Exit.failCause(cause);\n }\n return Effect.void;\n }), Effect.forkIn(scope), Effect.flatMap(() => readableStreamToPullUnsafe({\n scope,\n exit,\n readable: transform.readable,\n onError: options.onError,\n releaseLockOnEnd: options.releaseLockOnEnd\n })));\n});\nconst readableStreamToPullUnsafe = options => {\n const reader = options.readable.getReader();\n const exit = options.exit ?? MutableRef.make(undefined);\n const pull = Effect.suspend(() => {\n if (exit.current) return exit.current;\n return Effect.matchCauseEffect(Effect.tryPromise({\n try: () => reader.read(),\n catch: options.onError\n }), {\n onFailure: cause => exit.current ?? Effect.failCause(cause),\n onSuccess: ({\n done,\n value\n }) => {\n if (exit.current) return exit.current;\n return done ? Cause.done() : Effect.succeed(Arr.of(value));\n }\n });\n });\n return Effect.as(Scope.addFinalizer(options.scope, options.releaseLockOnEnd ? Effect.sync(() => reader.releaseLock()) : Effect.promise(() => reader.cancel().catch(constVoid))), pull);\n};\n/**\n * Creates a channel that pulls values from an `AsyncIterable`.\n *\n * **Details**\n *\n * Each yielded value is emitted as an output element. The iterator's return\n * value becomes the channel's done value. Thrown or rejected iterator errors\n * are converted with `onError`. If the channel scope closes early and the\n * iterator has a `return` method, that method is called.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromAsyncIterable = (iterable, onError) => fromTransform(Effect.fnUntraced(function* (_, scope) {\n const iter = iterable[Symbol.asyncIterator]();\n if (iter.return) {\n yield* Scope.addFinalizer(scope, Effect.promise(() => iter.return()));\n }\n return Effect.flatMap(Effect.tryPromise({\n try: () => iter.next(),\n catch: onError\n }), result => result.done ? Cause.done(result.value) : Effect.succeed(result.value));\n}));\n/**\n * Creates a channel from an `AsyncIterable`, emitting each yielded value as a\n * single-element non-empty array.\n *\n * **Details**\n *\n * The iterator's return value becomes the channel's done value. Thrown or\n * rejected iterator errors are converted with `onError`. If the channel scope\n * closes early and the iterator has a `return` method, that method is called.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromAsyncIterableArray = (iterable, onError) => map(fromAsyncIterable(iterable, onError), Arr.of);\n/**\n * Maps the output of this channel using the specified function.\n *\n * **Example** (Mapping channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class TransformError extends Data.TaggedError(\"TransformError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Basic mapping of channel values\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n * const doubledChannel = Channel.map(numbersChannel, (n) => n * 2)\n * Effect.runSync(Channel.runCollect(doubledChannel)) // => [2, 4, 6, 8, 10]\n *\n * // Transform string data\n * const wordsChannel = Channel.fromIterable([\"hello\", \"world\", \"effect\"])\n * const upperCaseChannel = Channel.map(wordsChannel, (word) => word.toUpperCase())\n * Effect.runSync(Channel.runCollect(upperCaseChannel)) // => [\"HELLO\", \"WORLD\", \"EFFECT\"]\n *\n * // Complex object transformation\n * type User = { id: number; name: string }\n * type UserDisplay = { displayName: string; isActive: boolean }\n *\n * const usersChannel = Channel.fromIterable([\n * { id: 1, name: \"Alice\" },\n * { id: 2, name: \"Bob\" }\n * ])\n * const displayChannel = Channel.map(usersChannel, (user): UserDisplay => ({\n * displayName: `User: ${user.name}`,\n * isActive: true\n * }))\n * Effect.runSync(Channel.runCollect(displayChannel)) // => [{ displayName: \"User: Alice\", isActive: true }, { displayName: \"User: Bob\", isActive: true }]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => Effect.sync(() => {\n let i = 0;\n return Effect.map(pull, o => f(o, i++));\n})));\n/**\n * Maps the done value of this channel using the specified function.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const mapDone = /*#__PURE__*/dual(2, (self, f) => mapDoneEffect(self, o => Effect.succeed(f(o))));\n/**\n * Maps the done value of this channel using the specified effectful function.\n *\n * **When to use**\n *\n * Use when the terminal done value transformation needs services or can fail,\n * while emitted elements should pass through unchanged.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const mapDoneEffect = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, done => Effect.flatMap(f(done), Cause.done)))));\nconst concurrencyIsSequential = concurrency => concurrency === undefined || concurrency !== \"unbounded\" && concurrency <= 1;\n/**\n * Maps each output element with an effectful function, preserving the source\n * channel's done value.\n *\n * **When to use**\n *\n * Use when transforming each channel output needs an Effect, service\n * dependency, failure channel, or configured concurrency.\n *\n * **Details**\n *\n * The mapping function receives the output element and its zero-based index.\n * By default elements are mapped sequentially. Use `options.concurrency` to\n * map multiple elements concurrently, and `options.unordered` to allow\n * concurrently mapped outputs to be emitted as soon as they complete.\n *\n * **Example** (Mapping channel output with effects)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n * const processedChannel = Channel.mapEffect(\n * numbersChannel,\n * (n) => Effect.succeed(n * n)\n * )\n * await Effect.runPromise(Channel.runCollect(processedChannel)) // => [1, 4, 9, 16, 25]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? mapEffectSequential(self, f) : mapEffectConcurrent(self, f, options));\nconst mapEffectSequential = (self, f) => fromTransform((upstream, scope) => {\n let i = 0;\n return Effect.map(toTransform(self)(upstream, scope), Effect.flatMap(o => f(o, i++)));\n});\nconst mapEffectConcurrent = (self, f, options) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) {\n let i = 0;\n const pull = yield* toTransform(self)(upstream, scope);\n const concurrencyN = options.concurrency === \"unbounded\" ? Number.MAX_SAFE_INTEGER : options.concurrency;\n const queue = yield* Queue.bounded(0);\n yield* Scope.addFinalizer(forkedScope, Queue.shutdown(queue));\n const runFork = Effect.runForkWith(yield* Effect.context());\n const trackFiber = Fiber.runIn(forkedScope);\n if (options.unordered) {\n const semaphore = Semaphore.makeUnsafe(concurrencyN);\n const release = constant(semaphore.release(1));\n const handle = Effect.matchCauseEffect({\n onFailure: cause => Effect.flatMap(Queue.failCause(queue, cause), release),\n onSuccess: value => Effect.flatMap(Queue.offer(queue, value), release)\n });\n yield* semaphore.take(1).pipe(Effect.flatMap(() => pull), Effect.flatMap(value => {\n trackFiber(runFork(handle(f(value, i++))));\n return Effect.void;\n }), Effect.forever({\n disableYield: true\n }), Effect.catchCause(cause => semaphore.withPermits(concurrencyN - 1)(Queue.failCause(queue, cause))), Effect.forkIn(forkedScope));\n } else {\n // capacity is n - 2 because\n // - 1 for the offer *after* starting a fiber\n // - 1 for the current processing fiber\n const effects = yield* Queue.bounded(concurrencyN - 2);\n yield* Scope.addFinalizer(forkedScope, Queue.shutdown(effects));\n yield* Queue.take(effects).pipe(Effect.flatten, Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever({\n disableYield: true\n }), Effect.catchCause(cause => Queue.failCause(queue, cause)), Effect.forkIn(forkedScope));\n let errorCause;\n const onExit = exit => {\n if (exit._tag === \"Success\") return;\n errorCause = exit.cause;\n Queue.failCauseUnsafe(queue, exit.cause);\n };\n yield* pull.pipe(Effect.flatMap(value => {\n if (errorCause) return Effect.failCause(errorCause);\n const fiber = runFork(f(value, i++));\n trackFiber(fiber);\n fiber.addObserver(onExit);\n return Queue.offer(effects, Fiber.join(fiber));\n }), Effect.forever({\n disableYield: true\n }), Effect.catchCause(cause => Queue.offer(effects, Exit.failCause(cause)).pipe(Effect.andThen(Queue.failCause(effects, cause)))), Effect.forkIn(forkedScope));\n }\n return Queue.take(queue);\n}));\n/**\n * Returns a new channel which is the same as this one but applies the given\n * function to the input channel’s input elements.\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const mapInput = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.flatMap(upstream, el => f(el)), scope)));\n/**\n * Returns a new channel which is the same as this one but applies the given\n * function to the input errors.\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const mapInputError = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.catch(upstream, err => {\n if (Cause.isDone(err)) return Effect.fail(err);\n return Effect.flatMap(f(err), Effect.fail);\n}), scope)));\n/**\n * Applies a side effect function to each output element of the channel,\n * returning a new channel that emits the same elements.\n *\n * **Details**\n *\n * The `tap` function allows you to perform side effects (like logging or\n * debugging) on each element emitted by a channel without modifying the\n * elements themselves.\n *\n * **Example** (Tapping channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class LogError extends Data.TaggedError(\"LogError\")<{\n * readonly message: string\n * }> {}\n *\n * // Create a channel that outputs numbers\n * const numberChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Tap into each output element to perform side effects\n * const processed: Array<number> = []\n * const tappedChannel = Channel.tap(\n * numberChannel,\n * (n) => Effect.sync(() => processed.push(n))\n * )\n *\n * const observed = [await Effect.runPromise(Channel.runCollect(tappedChannel)), processed] // => [[1, 2, 3], [1, 2, 3]]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const tap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => mapEffect(self, a => Effect.as(f(a), a), options));\n/**\n * Maps each output element to a channel and flattens the child channel\n * outputs.\n *\n * **Details**\n *\n * The source channel's done value is preserved. Child channel done values are\n * used only for child-channel completion. By default child channels are run\n * sequentially. Use `options.concurrency` and `options.bufferSize` to run child\n * channels concurrently.\n *\n * **Example** (Flat mapping channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ProcessError extends Data.TaggedError(\"ProcessError\")<{\n * readonly cause: string\n * }> {}\n *\n * // Create a channel that outputs numbers\n * const numberChannel = Channel.fromIterable([1, 2, 3])\n *\n * // FlatMap each number to create new channels\n * const flatMappedChannel = Channel.flatMap(\n * numberChannel,\n * (n) =>\n * Channel.fromIterable(Array.from({ length: n }, (_, i) => `item-${n}-${i}`))\n * )\n *\n * Effect.runSync(Channel.runCollect(flatMappedChannel)) // => [\"item-1-0\", \"item-2-0\", \"item-2-1\", \"item-3-0\", \"item-3-1\", \"item-3-2\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? flatMapSequential(self, f) : flatMapConcurrent(self, f, options));\nconst flatMapSequential = (self, f) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => {\n let childPull;\n let childScope;\n const makePull = Effect.flatMap(pull, value => {\n childScope ??= Scope.forkUnsafe(scope);\n return Effect.flatMapEager(toTransform(f(value))(upstream, childScope), pull => {\n childPull = catchHalt(pull);\n return childPull;\n });\n });\n const catchHalt = Pull.catchDone(_ => {\n childPull = undefined;\n // we can reuse the scope if the only finalizer is the \"fork\" one\n if (childScope.state._tag === \"Open\" && scopeFinalizerCountUnsafe(childScope) === 1) {\n return makePull;\n }\n const close = Scope.close(childScope, Exit.void);\n childScope = undefined;\n return Effect.flatMap(close, () => makePull);\n });\n return Effect.suspend(() => childPull ?? makePull);\n}));\nconst flatMapConcurrent = (self, f, options) => self.pipe(map(f), mergeAll(options));\n/**\n * Concatenates this channel with another channel created from the terminal value\n * of this channel. The new channel is created using the provided function.\n *\n * **Example** (Concatenating with completion values)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ConcatError extends Data.TaggedError(\"ConcatError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Create a channel that outputs numbers and terminates with sum\n * const numberChannel = Channel.fromIterable([1, 2, 3]).pipe(\n * Channel.concatWith((sum: void) => Channel.succeed(`Completed processing`))\n * )\n *\n * Effect.runSync(Channel.runCollect(numberChannel)) // => [1, 2, 3, \"Completed processing\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const concatWith = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => {\n let currentPull;\n const forkedScope = Scope.forkUnsafe(scope);\n const makePull = Effect.flatMap(toTransform(self)(upstream, forkedScope), pull => {\n currentPull = Pull.catchDone(pull, leftover => {\n return Scope.close(forkedScope, Exit.void).pipe(Effect.flatMap(() => toTransform(f(leftover))(upstream, scope)), Effect.flatMap(pull => {\n currentPull = pull;\n return pull;\n }));\n });\n return currentPull;\n });\n return Effect.suspend(() => currentPull ?? makePull);\n})));\n/**\n * Concatenates this channel with another channel, so that the second channel\n * starts emitting values after the first channel has completed.\n *\n * **Example** (Concatenating channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ConcatError extends Data.TaggedError(\"ConcatError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Create two channels\n * const firstChannel = Channel.fromIterable([1, 2, 3])\n * const secondChannel = Channel.fromIterable([\"a\", \"b\", \"c\"])\n *\n * // Concatenate them\n * const concatenatedChannel = Channel.concat(firstChannel, secondChannel)\n *\n * Effect.runSync(Channel.runCollect(concatenatedChannel)) // => [1, 2, 3, \"a\", \"b\", \"c\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const concat = /*#__PURE__*/dual(2, (self, that) => concatWith(self, _ => that));\n/**\n * Combines two channels with a stateful pull function.\n *\n * **When to use**\n *\n * Use to coordinate pulling from two channels when each output element depends\n * on both sides and local state.\n *\n * **Details**\n *\n * The combining function receives the current state and pull functions for the\n * left and right channels. It returns the next output element together with the\n * next state.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const combine = /*#__PURE__*/dual(4, (self, that, s, f) => fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n const leftPull = yield* toTransform(self)(upstream, scope);\n const rightPull = yield* toTransform(that)(upstream, scope);\n let state = s();\n return Effect.suspend(() => {\n const combinedPull = f(state, leftPull, rightPull);\n return Effect.map(combinedPull, ([a, s1]) => {\n state = s1;\n return a;\n });\n });\n})));\n/**\n * Runs a fallback channel if this channel completes without emitting any\n * output elements.\n *\n * **Details**\n *\n * If the source emits at least one element, the source is used unchanged. If\n * the source completes before emitting an element, the fallback function\n * receives the source done value and returns the replacement channel.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const orElseIfEmpty = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => {\n let currentPull;\n const forkedScope = Scope.forkUnsafe(scope);\n const makePull = Effect.flatMap(toTransform(self)(upstream, forkedScope), pull => {\n const next = pull.pipe(Effect.tap(() => {\n currentPull = pull;\n return Effect.void;\n }), Pull.catchDone(leftover => Scope.close(forkedScope, Exit.succeed(leftover)).pipe(Effect.andThen(toTransform(f(leftover))(upstream, scope)), Effect.flatMap(pull => {\n currentPull = pull;\n return pull;\n }))));\n currentPull = next;\n return next;\n });\n return Effect.suspend(() => currentPull ?? makePull);\n})));\n/**\n * Flattens a channel of channels.\n *\n * **Example** (Flattening nested channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class FlattenError extends Data.TaggedError(\"FlattenError\")<{\n * readonly cause: string\n * }> {}\n *\n * // Create a channel that outputs channels\n * const nestedChannels = Channel.fromIterable([\n * Channel.fromIterable([1, 2]),\n * Channel.fromIterable([3, 4]),\n * Channel.fromIterable([5, 6])\n * ])\n *\n * // Flatten the nested channels\n * const flattenedChannel = Channel.flatten(nestedChannels)\n *\n * Effect.runSync(Channel.runCollect(flattenedChannel)) // => [1, 2, 3, 4, 5, 6]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const flatten = channels => flatMap(channels, identity_);\n/**\n * Flattens a channel that outputs arrays into a channel that outputs individual elements.\n *\n * **Example** (Flattening arrays of channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class FlattenError extends Data.TaggedError(\"FlattenError\")<{\n * readonly message: string\n * }> {}\n *\n * // Create a channel that outputs arrays\n * const arrayChannel = Channel.fromIterable([\n * [1, 2, 3],\n * [4, 5],\n * [6, 7, 8, 9]\n * ])\n *\n * // Flatten the arrays into individual elements\n * const flattenedChannel = Channel.flattenArray(arrayChannel)\n *\n * Effect.runSync(Channel.runCollect(flattenedChannel)) // => [1, 2, 3, 4, 5, 6, 7, 8, 9]\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const flattenArray = self => transformPull(self, pull => {\n let array;\n let index = 0;\n const pump = Effect.suspend(function loop() {\n if (array === undefined) {\n return Effect.flatMap(pull, array_ => {\n switch (array_.length) {\n case 0:\n return loop();\n case 1:\n return Effect.succeed(array_[0]);\n default:\n {\n array = array_;\n return Effect.succeed(array_[index++]);\n }\n }\n });\n }\n const next = array[index++];\n if (index >= array.length) {\n array = undefined;\n index = 0;\n }\n return Effect.succeed(next);\n });\n return Effect.succeed(pump);\n});\n/**\n * Flattens a channel that emits `Take` values into a channel that emits the\n * `Take` outputs directly.\n *\n * **Details**\n *\n * Output `Take` values are emitted as non-empty arrays. Failed `Take` values\n * fail the returned channel. Done `Take` values complete the returned channel.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const flattenTake = self => mapEffectSequential(self, Take.toPull);\n/**\n * Creates a new channel that consumes all output from the source channel\n * but emits nothing, preserving only the completion value.\n *\n * **Example** (Draining channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel that outputs values\n * const sourceChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Drain all output, keeping only the completion\n * const drainedChannel = Channel.drain(sourceChannel)\n *\n * Effect.runSync(Channel.runCollect(drainedChannel)) // => []\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const drain = self => transformPull(self, pull => Effect.succeed(Effect.forever(pull, {\n disableYield: true\n})));\n/**\n * Repeats this channel according to the provided schedule.\n *\n * @category repetition\n * @since 4.0.0\n */\nexport const repeat = /*#__PURE__*/dual(2, (self, schedule) => Schedule.toStepWithMetadata(typeof schedule === \"function\" ? schedule(identity_) : schedule).pipe(Effect.map(step => {\n let meta = Schedule.CurrentMetadata.defaultValue();\n const loop = concatWith(provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)), done => step(done).pipe(Effect.map(meta_ => {\n meta = meta_;\n return loop;\n }), Pull.catchDone(() => Effect.succeed(end(done))), unwrap));\n return loop;\n}), unwrap));\n/**\n * Repeats this channel forever.\n *\n * @category repetition\n * @since 4.0.0\n */\nexport const forever = self => concatWith(self, () => forever(self));\n/**\n * Runs a schedule step for each output element while preserving the emitted\n * elements.\n *\n * **Details**\n *\n * The schedule receives each output element as input. Schedule delays are\n * applied between emitted elements. If the schedule fails, the returned channel\n * fails. If the schedule finishes, the returned channel completes with the\n * schedule output.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const schedule = /*#__PURE__*/dual(2, (self, schedule) => transformPull(self, (pull, _scope) => Effect.map(Schedule.toStepWithSleep(schedule), step => {\n const pullWithStep = Effect.tap(pull, step);\n return pullWithStep;\n})));\n/**\n * Filters the output elements of a channel using a predicate function.\n * Elements that don't match the predicate are discarded.\n *\n * **Example** (Filtering channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel with mixed numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5, 6, 7, 8])\n *\n * // Filter to keep only even numbers\n * const evenChannel = Channel.filter(numbersChannel, (n) => n % 2 === 0)\n * Effect.runSync(Channel.runCollect(evenChannel)) // => [2, 4, 6, 8]\n *\n * // Filter with type refinement\n * const mixedChannel = Channel.fromIterable([1, \"hello\", 2, \"world\", 3])\n * const numbersOnlyChannel = Channel.filter(\n * mixedChannel,\n * (value): value is number => typeof value === \"number\"\n * )\n * Effect.runSync(Channel.runCollect(numbersOnlyChannel)) // => [1, 2, 3]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) {\n return predicate(elem) ? Effect.succeed(elem) : Effect.flatMap(pull, loop);\n}))));\n/**\n * Filters and maps output elements using a `Filter`.\n *\n * **When to use**\n *\n * Use to keep only channel output elements accepted by a `Filter` and emit\n * each filter success value.\n *\n * **Details**\n *\n * Successful filter results are emitted as mapped values. Failed filter\n * results are discarded. The source channel's errors and done value are\n * preserved.\n *\n * @see {@link filter} for keeping original output elements with a predicate\n * @see {@link filterMapEffect} for using an effectful `Filter`\n * @see {@link filterMapArray} for filtering arrays of output elements\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) {\n const result = filter(elem);\n return Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success);\n}))));\n/**\n * Filters output elements with an effectful predicate.\n *\n * **When to use**\n *\n * Use when the keep/discard decision depends on an Effect or service and\n * predicate failures should fail the returned channel.\n *\n * **Details**\n *\n * Elements for which the predicate succeeds with `true` are emitted. Elements\n * for which the predicate succeeds with `false` are discarded. Predicate\n * failures fail the returned channel.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterEffect = /*#__PURE__*/dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) {\n return Effect.flatMap(predicate(elem), passes => passes ? Effect.succeed(elem) : Effect.flatMap(pull, loop));\n}))));\n/**\n * Filters and maps output elements using an effectful `Filter`.\n *\n * **When to use**\n *\n * Use to apply effectful logic that can discard channel output elements and\n * emit transformed values for the elements that pass.\n *\n * **Details**\n *\n * Successful filter results are emitted as mapped values. Failed filter\n * results are discarded. Failures from the effectful filter fail the returned\n * channel.\n *\n * @see {@link filterMap} for using a synchronous `Filter`\n * @see {@link filterEffect} for effectfully keeping original output elements\n * @see {@link mapEffect} for effectfully transforming every output element\n * @see {@link filterMapArrayEffect} for effectful filtering of array outputs\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) {\n return Effect.flatMap(filter(elem), result => Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success));\n}))));\n/**\n * Filters arrays of elements emitted by a channel, applying the filter\n * to each element within the arrays and only emitting non-empty filtered arrays.\n *\n * **Example** (Filtering array output)\n *\n * ```ts import.meta.vitest\n * import { Array, Channel, Effect } from \"effect\"\n *\n * const nonEmptyArrayPredicate = Array.isReadonlyArrayNonEmpty\n *\n * // Create a channel that outputs arrays of mixed data\n * const arrayChannel = Channel.fromIterable([\n * Array.make(1, 2, 3, 4, 5),\n * Array.make(6, 7, 8, 9, 10),\n * Array.make(11, 12, 13, 14, 15)\n * ]).pipe(Channel.filter(nonEmptyArrayPredicate))\n *\n * // Filter arrays to keep only even numbers\n * const evenArraysChannel = Channel.filterArray(arrayChannel, (n) => n % 2 === 0)\n * Effect.runSync(Channel.runCollect(evenArraysChannel)) // => [[2, 4], [6, 8, 10], [12, 14]]\n * // Note: Only non-empty filtered arrays are emitted\n *\n * // Arrays that would become empty after filtering are discarded entirely\n * const oddChannel = Channel.fromIterable([\n * Array.make(1, 3, 5),\n * Array.make(2, 4),\n * Array.make(7, 9)\n * ]).pipe(Channel.filter(nonEmptyArrayPredicate))\n * const filteredOddChannel = Channel.filterArray(oddChannel, (n) => n % 2 === 0)\n * Effect.runSync(Channel.runCollect(filteredOddChannel)) // => [[2, 4]]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterArray = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) {\n const passes = [];\n for (let i = 0; i < arr.length; i++) {\n if (predicate(arr[i])) {\n passes.push(arr[i]);\n }\n }\n return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop);\n}))));\n/**\n * Filters and maps each element inside emitted non-empty arrays using a\n * `Filter`.\n *\n * **Details**\n *\n * Successful filter results are kept as mapped values. Failed filter results\n * are removed from the array. Arrays that become empty are discarded.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMapArray = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) {\n const passes = [];\n for (let i = 0; i < arr.length; i++) {\n const result = filter(arr[i]);\n if (Result.isSuccess(result)) {\n passes.push(result.success);\n }\n }\n return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop);\n}))));\n/**\n * Filters each element inside emitted non-empty arrays with an effectful\n * predicate.\n *\n * **When to use**\n *\n * Use when filtering array-valued channel outputs requires Effects or services,\n * and arrays that become empty should be skipped.\n *\n * **Details**\n *\n * The predicate receives the element and its index within the array. Elements\n * for which the predicate succeeds with `true` are kept. Arrays that become\n * empty are discarded. Predicate failures fail the returned channel.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterArrayEffect = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, pull => {\n const f = Effect.flatMap(pull, arr => Effect.filter(arr, predicate));\n return Effect.succeed(Effect.flatMap(f, function loop(arr) {\n return Arr.isReadonlyArrayNonEmpty(arr) ? Effect.succeed(arr) : Effect.flatMap(f, loop);\n }));\n}));\n/**\n * Filters and maps each element inside emitted non-empty arrays using an\n * effectful `Filter`.\n *\n * **When to use**\n *\n * Use when array-valued channel outputs need an effectful filter-map that can\n * fail and can discard arrays that become empty.\n *\n * **Details**\n *\n * Successful filter results are kept as mapped values. Failed filter results\n * are removed from the array. Arrays that become empty are discarded. Failures\n * from the effectful filter fail the returned channel.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMapArrayEffect = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) {\n return Effect.flatMap(Effect.filterMapEffect(arr, filter), passes => Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop));\n}))));\n/**\n * Maps over a channel statefully with an accumulator, where each element can produce multiple output values.\n *\n * **Example** (Mapping with accumulated state)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4])\n *\n * // Use mapAccum to create running sums and emit both current and sum\n * const runningSum = Channel.mapAccum(\n * numbersChannel,\n * () => 0, // initial accumulator state\n * (sum, current) => {\n * const newSum = sum + current\n * // Return [newState, outputValues]\n * return [newSum, [current, newSum]] as const\n * }\n * )\n * // Using with Effect for async processing\n * const asyncMapAccum = Channel.mapAccum(\n * numbersChannel,\n * () => \"\",\n * (acc, value) =>\n * Effect.gen(function*() {\n * const newAcc = acc + value.toString()\n * return [newAcc, [`${value}-processed`, newAcc]] as const\n * })\n * )\n * Effect.runSync(Channel.runCollect(runningSum)) // => [1, 1, 2, 3, 3, 6, 4, 10]\n * Effect.runSync(Channel.runCollect(asyncMapAccum)) // => [\"1-processed\", \"1\", \"2-processed\", \"12\", \"3-processed\", \"123\", \"4-processed\", \"1234\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const mapAccum = /*#__PURE__*/dual(args => isChannel(args[0]), (self, initial, f, options) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => {\n let state = initial();\n let current;\n let index = 0;\n let cause;\n const pullNext = Effect.matchCauseEffect(pull, {\n onFailure(cause_) {\n cause = cause_;\n const b = options?.onHalt && options.onHalt(state);\n return b && b.length > 0 ? Effect.succeed([state, b]) : Effect.failCause(cause_);\n },\n onSuccess(a) {\n const b = f(state, a);\n return Arr.isArray(b) ? Effect.succeed(b) : b;\n }\n });\n const pump = Effect.suspend(function loop() {\n if (current === undefined) {\n if (cause) return Effect.failCause(cause);\n return Effect.flatMap(pullNext, ([newState, values]) => {\n state = newState;\n if (values.length === 0) {\n return loop();\n } else if (values.length === 1) {\n return Effect.succeed(values[0]);\n }\n current = values;\n return loop();\n });\n }\n const next = current[index++];\n if (index >= current.length) {\n current = undefined;\n index = 0;\n }\n return Effect.succeed(next);\n });\n return pump;\n})));\n/**\n * Transforms a channel statefully by scanning over its output with an accumulator function.\n * Emits the intermediate results of the scan operation.\n *\n * **Example** (Scanning channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Scan to create running sum\n * const runningSumChannel = Channel.scan(numbersChannel, 0, (sum, n) => sum + n)\n * Effect.runSync(Channel.runCollect(runningSumChannel)) // => [0, 1, 3, 6, 10, 15]\n * // Note: emits the initial value and each intermediate result\n *\n * // Scan with string concatenation\n * const wordsChannel = Channel.fromIterable([\"hello\", \"world\", \"from\", \"effect\"])\n * const sentenceChannel = Channel.scan(\n * wordsChannel,\n * \"\",\n * (sentence, word) => sentence === \"\" ? word : `${sentence} ${word}`\n * )\n * Effect.runSync(Channel.runCollect(sentenceChannel)) // => [\"\", \"hello\", \"hello world\", \"hello world from\", \"hello world from effect\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const scan = /*#__PURE__*/dual(3, (self, initial, f) => scanEffect(self, initial, (s, a) => Effect.succeed(f(s, a))));\n/**\n * Transforms a channel statefully by scanning over its output with an effectful accumulator function.\n * Emits the intermediate results of the scan operation.\n *\n * **When to use**\n *\n * Use when maintaining accumulated state over channel output requires Effects\n * or can fail, while still emitting each intermediate state.\n *\n * **Example** (Scanning channel output with effects)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ScanError extends Data.TaggedError(\"ScanError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4])\n *\n * // Effectful scan with async operations\n * const asyncScanChannel = Channel.scanEffect(\n * numbersChannel,\n * \"\",\n * (acc, value) =>\n * Effect.gen(function*() {\n * return acc + value.toString()\n * })\n * )\n * await Effect.runPromise(Channel.runCollect(asyncScanChannel)) // => [\"\", \"1\", \"12\", \"123\", \"1234\"]\n *\n * // Scan with error handling\n * const errorHandlingScan = Channel.scanEffect(\n * numbersChannel,\n * 0,\n * (sum, n) => {\n * if (n < 0) {\n * return Effect.fail(new ScanError({ reason: \"negative number\" }))\n * }\n * return Effect.succeed(sum + n)\n * }\n * )\n * await Effect.runPromise(Channel.runCollect(errorHandlingScan)) // => [0, 1, 3, 6, 10]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const scanEffect = /*#__PURE__*/dual(3, (self, initial, f) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => {\n let state = initial;\n let isFirst = true;\n return Effect.suspend(() => {\n if (isFirst) {\n isFirst = false;\n return Effect.succeed(state);\n }\n return Effect.map(Effect.flatMap(pull, a => f(state, a)), newState => {\n state = newState;\n return state;\n });\n });\n})));\n/**\n * Catches any cause of failure from the channel and allows recovery by\n * creating a new channel based on the caught cause.\n *\n * **Example** (Recovering from failure causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Data, Effect } from \"effect\"\n *\n * class ProcessError extends Data.TaggedError(\"ProcessError\")<{\n * readonly reason: string\n * }> {}\n *\n * class RecoveryError extends Data.TaggedError(\"RecoveryError\")<{\n * readonly message: string\n * }> {}\n *\n * // Create a failing channel\n * const failingChannel = Channel.fail(\n * new ProcessError({ reason: \"network error\" })\n * )\n *\n * // Catch the cause and provide recovery\n * const recoveredChannel = Channel.catchCause(failingChannel, (cause) => {\n * if (Cause.hasFails(cause)) {\n * return Channel.succeed(\"Recovered from failure\")\n * }\n * return Channel.succeed(\"Recovered from interruption\")\n * })\n *\n * Effect.runSync(Channel.runCollect(recoveredChannel)) // => [\"Recovered from failure\"]\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchCause = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => {\n let forkedScope = Scope.forkUnsafe(scope);\n return Effect.map(toTransform(self)(upstream, forkedScope), pull => {\n let currentPull = pull.pipe(Effect.catchCause(cause => {\n if (Pull.isDoneCause(cause)) {\n return Effect.failCause(cause);\n }\n const toClose = forkedScope;\n forkedScope = Scope.forkUnsafe(scope);\n return Scope.close(toClose, Exit.failCause(cause)).pipe(Effect.andThen(toTransform(f(cause))(upstream, forkedScope)), Effect.flatMap(childPull => {\n currentPull = childPull;\n return childPull;\n }));\n }));\n return Effect.suspend(() => currentPull);\n });\n}));\n/**\n * Recovers from defects using the provided function.\n *\n * **Details**\n *\n * Typed failures and interruptions are not caught.\n *\n * **Example** (Recovering from a defect)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromEffect(Effect.die(\"boom\")).pipe(\n * Channel.catchDefect((defect) => Channel.succeed(`recovered: ${defect}`))\n * )\n *\n * Effect.runSync(Channel.runCollect(channel)) // => [\"recovered: boom\"]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchDefect = /*#__PURE__*/dual(2, (self, f) => catchCauseFilter(self, Cause.findDefect, f));\n/**\n * Runs an effect with the full failure `Cause` when the channel fails, then\n * fails the returned channel with the original cause.\n *\n * **When to use**\n *\n * Use when observing the full channel failure `Cause` is needed without\n * changing successful output or replacing the original cause.\n *\n * **Details**\n *\n * Use this for observing failures, such as logging or metrics. If the observer\n * effect fails, that failure can fail the returned channel.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const tapCause = /*#__PURE__*/dual(2, (self, f) => catchCause(self, cause => fromEffectDrain(Effect.flatMap(f(cause), _ => Effect.failCause(cause)))));\n/**\n * Catches causes of failure that match a specific filter, allowing\n * conditional error recovery based on the type of failure.\n *\n * **When to use**\n *\n * Use to recover a channel only when its full `Cause` satisfies a boolean\n * predicate.\n *\n * **Details**\n *\n * When the predicate matches, the recovery function receives the original\n * cause. When it does not match, the returned channel fails with the original\n * cause.\n *\n * @see {@link catchCauseFilter} for selecting causes with a `Filter`\n * @see {@link catchCause} for recovering from every cause\n * @see {@link catchIf} for recovering from typed channel errors\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCauseIf = /*#__PURE__*/dual(3, (self, predicate, f) => catchCause(self, cause => {\n return predicate(cause) ? f(cause) : failCause(cause);\n}));\n/**\n * Recovers from channel failures whose full `Cause` is selected by a `Filter`.\n *\n * **When to use**\n *\n * Use when you need to recover a channel only from causes selected by a\n * `Filter`, while giving the recovery both the selected value and the original\n * `Cause`.\n *\n * **Details**\n *\n * When the filter succeeds, the recovery function receives the selected value\n * and the original cause. When the filter fails, the returned channel fails\n * with the residual cause produced by the filter.\n *\n * @see {@link catchCauseIf} for selecting causes with a predicate\n * @see {@link catchFilter} for selecting typed errors with a `Filter`\n * @see {@link catchCause} for recovering from every cause\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCauseFilter = /*#__PURE__*/dual(3, (self, filter, f) => catchCause(self, cause => {\n const result = filter(cause);\n return Result.isFailure(result) ? failCause(result.failure) : f(result.success, cause);\n}));\nconst catch_ = /*#__PURE__*/dual(2, (self, f) => catchCauseFilter(self, Cause.findError, e => f(e)));\nexport {\n/**\n * Recovers from typed channel errors by running a fallback channel.\n *\n * @category error handling\n * @since 4.0.0\n */\ncatch_ as catch };\n/**\n * Runs an effect when the channel fails with a typed error, then preserves the\n * original channel failure.\n *\n * **Details**\n *\n * The effect is not run for normal channel completion. If the observer effect\n * fails, that failure can fail the returned channel.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const tapError = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => Effect.succeed(Effect.tapError(pull, err => Cause.isDone(err) ? Effect.void : Effect.asVoid(f(err))))));\n/**\n * Recovers from typed channel errors that match a predicate or refinement.\n *\n * **When to use**\n *\n * Use to recover from typed channel errors when a predicate or refinement\n * selects the failures that should switch to a recovery channel.\n *\n * **Details**\n *\n * Matching errors are handled by the recovery function. Non-matching errors\n * are handled by `orElse` when provided. Without `orElse`, non-matching errors\n * are re-failed.\n *\n * @see {@link catch_ catch} for recovering from every typed channel error\n * @see {@link catchFilter} for selecting typed errors with a `Filter`\n * @see {@link catchTag} for selecting tagged typed errors\n * @see {@link catchCauseFilter} for selecting full causes with a `Filter`\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchIf = /*#__PURE__*/dual(args => isChannel(args[0]), (self, predicate, f, orElse) => catch_(self, err => {\n return predicate(err) ? f(err) : orElse ? orElse(err) : fail(err);\n}));\n/**\n * Recovers from typed channel errors selected by a `Filter`.\n *\n * **When to use**\n *\n * Use to recover from channel errors with a reusable `Filter` when matching\n * can also narrow or transform the error before choosing the recovery channel.\n *\n * **Details**\n *\n * Successful filter results are handled by the recovery function. Failed\n * filter results are handled by `orElse` when provided. Without `orElse`,\n * failed filter results are re-failed.\n *\n * @see {@link catchIf} for selecting typed errors with a predicate\n * @see {@link catchTag} for selecting tagged typed errors\n * @see {@link catchCauseFilter} for selecting full causes with a `Filter`\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchFilter = /*#__PURE__*/dual(args => isChannel(args[0]), (self, filter, f, orElse) => catch_(self, err => {\n const result = filter(err);\n return Result.isFailure(result) ? orElse ? orElse(result.failure) : fail(result.failure) : f(result.success);\n}));\n/**\n * Recovers from tagged channel errors whose `_tag` matches one or more tags.\n *\n * **Details**\n *\n * Matching tagged errors are handled by the recovery function. Non-matching\n * errors are handled by `orElse` when provided. Without `orElse`,\n * non-matching errors are re-failed.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchTag = /*#__PURE__*/dual(args => isChannel(args[0]), (self, k, f, orElse) => {\n const pred = Array.isArray(k) ? e => hasProperty(e, \"_tag\") && k.includes(e._tag) : isTagged(k);\n return catchIf(self, pred, f, orElse);\n});\n/**\n * Catches a specific reason within a tagged error.\n *\n * **Example** (Recovering from nested reasons)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class RateLimitError extends Data.TaggedError(\"RateLimitError\")<{\n * retryAfter: number\n * }> {}\n *\n * class QuotaExceededError extends Data.TaggedError(\"QuotaExceededError\")<{\n * limit: number\n * }> {}\n *\n * class AiError extends Data.TaggedError(\"AiError\")<{\n * reason: RateLimitError | QuotaExceededError\n * }> {}\n *\n * const reason = new RateLimitError({ retryAfter: 60 })\n * const channel = Channel.fail(new AiError({ reason }))\n *\n * const recovered = channel.pipe(\n * Channel.catchReason(\"AiError\", \"RateLimitError\", (reason) =>\n * Channel.succeed(`retry: ${reason.retryAfter}`)\n * )\n * )\n * Effect.runSync(Channel.runCollect(recovered)) // => [\"retry: 60\"]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchReason = /*#__PURE__*/dual(args => isChannel(args[0]), (self, errorTag, reasonTag, f, orElse) => catch_(self, error => {\n if (isTagged(error, errorTag) && hasProperty(error, \"reason\")) {\n const reason = error.reason;\n if (isTagged(reason, reasonTag)) {\n return f(reason, error);\n }\n return orElse ? orElse(reason, error) : fail(error);\n }\n return fail(error);\n}));\n/**\n * Catches multiple reasons within a tagged error using an object of handlers.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchReasons = /*#__PURE__*/dual(args => isChannel(args[0]), (self, errorTag, cases, orElse) => {\n let keys;\n return catch_(self, error => {\n if (isTagged(error, errorTag) && hasProperty(error, \"reason\") && hasProperty(error.reason, \"_tag\") && String.isString(error.reason._tag)) {\n const reason = error.reason;\n keys ??= new Set(Object.keys(cases));\n if (keys.has(reason._tag)) {\n return cases[reason._tag](reason, error);\n }\n return orElse ? orElse(reason, error) : fail(error);\n }\n return fail(error);\n });\n});\n/**\n * Promotes nested reason errors into the channel error, replacing the parent error.\n *\n * **Example** (Promoting nested reasons)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Exit } from \"effect\"\n *\n * class RateLimitError extends Data.TaggedError(\"RateLimitError\")<{\n * retryAfter: number\n * }> {}\n *\n * class QuotaExceededError extends Data.TaggedError(\"QuotaExceededError\")<{\n * limit: number\n * }> {}\n *\n * class AiError extends Data.TaggedError(\"AiError\")<{\n * reason: RateLimitError | QuotaExceededError\n * }> {}\n *\n * const reason = new RateLimitError({ retryAfter: 60 })\n * const channel = Channel.fail(new AiError({ reason }))\n *\n * const unwrapped = channel.pipe(Channel.unwrapReason(\"AiError\"))\n * Effect.runSync(Effect.exit(Channel.runCollect(unwrapped))) // => Exit.fail(reason)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const unwrapReason = /*#__PURE__*/dual(2, (self, errorTag) => catchFilter(self, error => isTagged(error, errorTag) && hasProperty(error, \"reason\") ? Result.succeed(error.reason) : Result.fail(error), fail));\n/**\n * Returns a new channel, which is the same as this one, except the failure\n * value of the returned channel is created by applying the specified function\n * to the failure value of this channel.\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const mapError = /*#__PURE__*/dual(2, (self, f) => catch_(self, err => fail(f(err))));\n/**\n * Converts all errors in the channel to defects (unrecoverable failures).\n * This is useful when you want to treat errors as programming errors.\n *\n * **Example** (Converting failures to defects)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Data, Effect, Exit } from \"effect\"\n *\n * class ValidationError extends Data.TaggedError(\"ValidationError\")<{\n * readonly field: string\n * }> {}\n *\n * // Create a channel that might fail\n * const error = new ValidationError({ field: \"email\" })\n * const failingChannel = Channel.fail(error)\n *\n * // Convert failures to defects\n * const fatalChannel = Channel.orDie(failingChannel)\n *\n * Effect.runSync(Effect.exit(Channel.runCollect(fatalChannel))) // => Exit.failCause(Cause.die(error))\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orDie = self => catch_(self, die);\n/**\n * Ignores all errors in the channel, converting them to an empty channel.\n *\n * **Details**\n *\n * Use the `log` option to emit the full {@link Cause} when the channel fails.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const ignore = /*#__PURE__*/dual(args => isChannel(args[0]), (self, options) => {\n if (!options?.log) {\n return catch_(self, () => empty);\n }\n const logEffect = Effect.logWithLevel(options.log === true ? undefined : options.log);\n return catch_(tapCause(self, cause => Cause.hasFails(cause) ? logEffect(cause) : Effect.void), () => empty);\n});\nconst ignoreCause_ = self => catchCause(self, () => empty);\n/**\n * Ignores all errors in the channel including defects, converting them to an empty channel.\n *\n * **When to use**\n *\n * Use when a channel should become best-effort and all failure causes, including\n * defects and interruptions, can be converted to empty output.\n *\n * **Details**\n *\n * Use the `log` option to emit the full {@link Cause} when the channel fails.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const ignoreCause = /*#__PURE__*/dual(args => isChannel(args[0]), (self, options) => {\n if (!options?.log) return ignoreCause_(self);\n const logEffect = Effect.logWithLevel(options.log === true ? undefined : options.log);\n return ignoreCause_(tapCause(self, cause => logEffect(cause)));\n});\n/**\n * Returns a new channel that retries this channel according to the specified\n * schedule whenever it fails.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const retry = /*#__PURE__*/dual(2, (self, schedule) => suspend(() => {\n let step = undefined;\n let meta = Schedule.CurrentMetadata.defaultValue();\n const selfWithMeta = provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta));\n const withReset = onFirst(selfWithMeta, () => {\n step = undefined;\n return Effect.void;\n });\n const resolvedSchedule = typeof schedule === \"function\" ? schedule(identity_) : schedule;\n const loop = catch_(withReset, Effect.fnUntraced(function* (error) {\n if (!step) {\n step = yield* Schedule.toStepWithMetadata(resolvedSchedule);\n }\n meta = yield* step(error);\n return loop;\n }, (effect, error) => Pull.catchDone(effect, () => Effect.succeed(fail(error))), unwrap));\n return loop;\n}));\n/**\n * Maps each output element to a channel and emits values from the most recent\n * active child channels.\n *\n * **Details**\n *\n * With the default concurrency of `1`, starting a new child channel interrupts\n * the previous child channel. Use `options.concurrency` to allow more active\n * child channels. The source channel's done value is preserved.\n *\n * **Example** (Switching mapped channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class SwitchError extends Data.TaggedError(\"SwitchError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Create a channel that outputs numbers\n * const numberChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Switch to new channels based on each value\n * const switchedChannel = Channel.switchMap(\n * numberChannel,\n * (n) => Channel.fromIterable([`value-${n}`])\n * )\n *\n * await Effect.runPromise(Channel.runCollect(switchedChannel)) // => [\"value-3\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const switchMap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => self.pipe(map(f), mergeAll({\n ...options,\n concurrency: options?.concurrency ?? 1,\n switch: true\n})));\n/**\n * Merges multiple channels with specified concurrency and buffering options.\n *\n * **When to use**\n *\n * Use when channel outputs are themselves channels and multiple inner channels\n * should run with configured concurrency and buffering.\n *\n * **Example** (Merging nested channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class MergeAllError extends Data.TaggedError(\"MergeAllError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Create channels that output other channels\n * const nestedChannels = Channel.fromIterable([\n * Channel.fromIterable([1, 2]),\n * Channel.fromIterable([3, 4]),\n * Channel.fromIterable([5, 6])\n * ])\n *\n * // Merge all channels with bounded concurrency\n * const mergedChannel = Channel.mergeAll({\n * concurrency: 1,\n * bufferSize: 16\n * })(nestedChannels)\n *\n * await Effect.runPromise(Channel.runCollect(mergedChannel)) // => [1, 2, 3, 4, 5, 6]\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const mergeAll = /*#__PURE__*/dual(2, (channels, {\n bufferSize = 16,\n concurrency,\n switch: switch_ = false\n}) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) {\n const concurrencyN = concurrency === \"unbounded\" ? Number.MAX_SAFE_INTEGER : Math.max(1, concurrency);\n const semaphore = switch_ ? undefined : Semaphore.makeUnsafe(concurrencyN);\n const doneLatch = yield* Latch.make(true);\n const fibers = new Set();\n const queue = yield* Queue.bounded(bufferSize);\n yield* Scope.addFinalizer(forkedScope, Queue.shutdown(queue));\n const pull = yield* toTransform(channels)(upstream, scope);\n yield* Effect.gen(function* () {\n while (true) {\n let pullFiber;\n if (semaphore) {\n if (fibers.size < concurrencyN) {\n yield* semaphore.take(1);\n } else {\n pullFiber = yield* Effect.forkChild(pull);\n yield* Effect.raceFirst(semaphore.take(1), Effect.andThen(Fiber.join(pullFiber), Effect.never));\n }\n }\n const channel = pullFiber === undefined ? yield* pull : yield* Fiber.join(pullFiber);\n const childScope = Scope.forkUnsafe(forkedScope);\n const childPull = yield* toTransform(channel)(upstream, childScope);\n while (fibers.size >= concurrencyN) {\n const fiber = Iterable.headUnsafe(fibers);\n fibers.delete(fiber);\n if (fibers.size === 0) yield* doneLatch.open;\n yield* Fiber.interrupt(fiber);\n }\n const fiber = yield* childPull.pipe(Effect.tap(() => Effect.yieldNow), Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever({\n disableYield: true\n }), Effect.onError(Effect.fnUntraced(function* (cause) {\n const halt = Pull.filterDone(cause);\n yield* Effect.exit(Scope.close(childScope, !Result.isFailure(halt) ? Exit.succeed(halt.success.value) : Exit.failCause(halt.failure)));\n if (!fibers.has(fiber)) return;\n fibers.delete(fiber);\n if (semaphore) yield* semaphore.release(1);\n if (fibers.size === 0) yield* doneLatch.open;\n if (Result.isSuccess(halt)) return;\n return yield* Queue.failCause(queue, cause);\n })), Effect.forkChild);\n doneLatch.closeUnsafe();\n fibers.add(fiber);\n }\n }).pipe(Effect.catchCause(cause => {\n const halt = Pull.filterDone(cause);\n if (Result.isSuccess(halt)) {\n return doneLatch.whenOpen(Queue.failCause(queue, cause));\n }\n return Queue.failCause(queue, cause);\n }), Effect.forkIn(forkedScope));\n return Queue.take(queue);\n})));\n/**\n * Returns a new channel, which is the merge of this channel and the specified\n * channel.\n *\n * **Example** (Merging channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create two channels\n * const leftChannel = Channel.fromIterable([1, 2, 3])\n * const rightChannel = Channel.fromIterable([\"a\", \"b\", \"c\"])\n *\n * // The default \"both\" strategy waits for both channels to complete\n * const mergedChannel = Channel.merge(leftChannel, rightChannel)\n *\n * const values = await Effect.runPromise(Channel.runCollect(mergedChannel))\n * values.map(String).sort() // => [\"1\", \"2\", \"3\", \"a\", \"b\", \"c\"]\n * ```\n *\n * @category combining\n * @since 4.0.0\n */\nexport const merge = /*#__PURE__*/dual(args => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(Effect.fnUntraced(function* (upstream, _scope, forkedScope) {\n const strategy = options?.haltStrategy ?? \"both\";\n const queue = yield* Queue.bounded(0);\n yield* Scope.addFinalizer(forkedScope, Queue.shutdown(queue));\n let done = 0;\n function onExit(side, cause) {\n done++;\n if (!Pull.isDoneCause(cause)) {\n return Queue.failCause(queue, cause);\n }\n switch (strategy) {\n case \"both\":\n {\n return done === 2 ? Queue.failCause(queue, cause) : Effect.void;\n }\n case \"left\":\n case \"right\":\n {\n return side === strategy ? Queue.failCause(queue, cause) : Effect.void;\n }\n case \"either\":\n {\n return Queue.failCause(queue, cause);\n }\n }\n }\n const runSide = (side, channel, scope) => toTransform(channel)(upstream, scope).pipe(Effect.flatMap(pull => pull.pipe(Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever)), Effect.onError(cause => Effect.andThen(Scope.close(scope, Pull.doneExitFromCause(cause)), onExit(side, cause))), Effect.forkIn(forkedScope));\n yield* runSide(\"left\", left, Scope.forkUnsafe(forkedScope));\n yield* runSide(\"right\", right, Scope.forkUnsafe(forkedScope));\n return Queue.take(queue);\n})));\n/**\n * Runs an effect concurrently with a channel while emitting only the channel's\n * output elements.\n *\n * **When to use**\n *\n * Use when a side effect should run for the lifetime of a channel and only the\n * channel's output elements should be emitted.\n *\n * **Details**\n *\n * The effect's successful value is ignored. If the effect fails while the\n * channel is running, the returned channel fails with that error.\n *\n * @category combining\n * @since 4.0.0\n */\nexport const mergeEffect = /*#__PURE__*/dual(2, (self, effect) => merge(self, fromEffectDrain(effect), {\n haltStrategy: \"left\"\n}));\n/**\n * Splits upstream string chunks into lines, recognizing `\\n`, `\\r\\n`, and\n * standalone `\\r` as line terminators. The behavior matches\n * `String.linesIterator` regardless of how the input is chunked.\n *\n * **Details**\n *\n * A line terminator at the very end of the stream does **not** produce a\n * trailing empty line (consistent with `String.linesIterator`). Conversely,\n * if the stream ends without a terminator the final partial line is still\n * emitted.\n *\n * **Example** (Splitting string chunks into lines)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const result = await Effect.runPromise(Stream.runCollect(\n * Stream.splitLines(Stream.make(\"hel\", \"lo\\r\\nwor\", \"ld\\n\"))\n * ))\n * result // => [\"hello\", \"world\"]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitLines = () => fromTransform((upstream, _scope) => Effect.sync(() => {\n // Accumulates text that has not yet been terminated by a line break.\n // Content is carried across chunks until a terminator is found.\n let stringBuilder = \"\";\n // A trailing \\r completes the line immediately. Remember it only to\n // suppress a leading \\n in the next nonempty string.\n let midCRLF = false;\n // Remembers the upstream Done value after the first time the upstream\n // signals completion, so subsequent pulls return Done immediately\n // without pulling upstream again.\n let done = Option.none();\n function splitLinesArray(chunk) {\n const chunkBuilder = [];\n function pushLine(segment) {\n if (stringBuilder.length === 0) {\n chunkBuilder.push(segment);\n } else {\n chunkBuilder.push(stringBuilder + segment);\n stringBuilder = \"\";\n }\n }\n for (let i = 0; i < chunk.length; i++) {\n const str = chunk[i];\n if (str.length !== 0) {\n let from = 0;\n let indexOfCR = str.indexOf(\"\\r\");\n let indexOfLF = str.indexOf(\"\\n\");\n if (midCRLF) {\n if (indexOfLF === 0) {\n from = 1;\n indexOfLF = str.indexOf(\"\\n\", from);\n }\n midCRLF = false;\n }\n while (indexOfCR !== -1 || indexOfLF !== -1) {\n if (indexOfCR === -1 || indexOfLF !== -1 && indexOfLF < indexOfCR) {\n pushLine(str.substring(from, indexOfLF));\n from = indexOfLF + 1;\n indexOfLF = str.indexOf(\"\\n\", from);\n } else {\n pushLine(str.substring(from, indexOfCR));\n if (str.length === indexOfCR + 1) {\n midCRLF = true;\n from = str.length;\n indexOfCR = -1;\n } else {\n from = indexOfCR + (indexOfLF === indexOfCR + 1 ? 2 : 1);\n indexOfCR = str.indexOf(\"\\r\", from);\n indexOfLF = str.indexOf(\"\\n\", from);\n }\n }\n }\n stringBuilder = stringBuilder + str.substring(from);\n }\n }\n return Arr.isReadonlyArrayNonEmpty(chunkBuilder) ? chunkBuilder : null;\n }\n const pullOrFlush = Effect.suspend(() => {\n if (done._tag === \"Some\") {\n return Cause.done(done.value);\n }\n return Pull.matchEffect(upstream, {\n onSuccess: loop,\n onFailure: Effect.failCause,\n onDone: leftover => {\n done = Option.some(leftover);\n if (stringBuilder.length > 0) {\n const last = stringBuilder;\n stringBuilder = \"\";\n midCRLF = false;\n return Effect.succeed([last]);\n }\n return Cause.done(leftover);\n }\n });\n });\n function loop(chunk) {\n const lines = splitLinesArray(chunk);\n return lines !== null ? Effect.succeed(lines) : pullOrFlush;\n }\n return pullOrFlush;\n}));\n/**\n * Decodes incoming `Uint8Array` chunks into strings using `TextDecoder`.\n *\n * **Details**\n *\n * Input chunks are decoded with streaming enabled so multi-byte characters may\n * span `Uint8Array` boundaries. The optional `encoding` and `options` are\n * passed to `TextDecoder`.\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeText = (encoding, options) => fromTransform((upstream, _scope) => Effect.sync(() => {\n const decoder = new TextDecoder(encoding, options);\n const streamOptions = {\n stream: true\n };\n return Effect.map(upstream, Arr.map(line => decoder.decode(line, streamOptions)));\n}));\n/**\n * Encodes incoming string chunks into `Uint8Array` values using `TextEncoder`.\n *\n * **Details**\n *\n * Each string inside an emitted array is encoded independently.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeText = () => fromTransform((upstream, _scope) => Effect.sync(() => {\n const encoder = new TextEncoder();\n return Effect.map(upstream, Arr.map(line => encoder.encode(line)));\n}));\n/**\n * Returns a new channel that pipes the output of this channel into the\n * specified channel. The returned channel has the input type of this channel,\n * and the output type of the specified channel, terminating with the value of\n * the specified channel.\n *\n * **Example** (Piping one channel into another)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class PipeError extends Data.TaggedError(\"PipeError\")<{\n * readonly stage: string\n * }> {}\n *\n * // Create source and transform channels\n * const sourceChannel = Channel.fromIterable([1, 2, 3])\n * const transformChannel = Channel.map(sourceChannel, (n: number) => n * 2)\n *\n * // Pipe the source into the transform\n * const pipedChannel = Channel.pipeTo(sourceChannel, transformChannel)\n *\n * Effect.runSync(Channel.runCollect(pipedChannel)) // => [2, 4, 6]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const pipeTo = /*#__PURE__*/dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => toTransform(that)(upstream, scope))));\n/**\n * Returns a new channel that pipes the output of this channel into the\n * specified channel and preserves this channel's failures without providing\n * them to the other channel for observation.\n *\n * **Example** (Piping while preserving failures)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Exit } from \"effect\"\n *\n * class SourceError extends Data.TaggedError(\"SourceError\")<{\n * readonly code: number\n * }> {}\n *\n * // Create a failing source channel\n * const error = new SourceError({ code: 404 })\n * const failingSource = Channel.fail(error)\n * const safeTransform = Channel.identity<never, never, never>()\n *\n * // Pipe while preserving source failures\n * const safePipedChannel = Channel.pipeToOrFail(failingSource, safeTransform)\n *\n * Effect.runSync(Effect.exit(Channel.runCollect(safePipedChannel))) // => Exit.fail(error)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const pipeToOrFail = /*#__PURE__*/dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => {\n const upstreamPull = Effect.catchCause(upstream, cause => Pull.isDoneCause(cause) ? Effect.failCause(cause) : Effect.die(Cause.Done(cause)));\n return Effect.map(toTransform(that)(upstreamPull, scope), pull => Effect.catchDefect(pull, defect => Cause.isDone(defect) ? Effect.failCause(defect.value) : Effect.die(defect)));\n})));\n/**\n * Constructs a `Channel` from a scoped effect that will result in a\n * `Channel` if successful.\n *\n * **Example** (Unwrapping channel effects)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class UnwrapError extends Data.TaggedError(\"UnwrapError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Create an effect that produces a channel\n * const channelEffect = Effect.succeed(\n * Channel.fromIterable([1, 2, 3])\n * )\n *\n * // Unwrap the effect to get the channel\n * const unwrappedChannel = Channel.unwrap(channelEffect)\n *\n * Effect.runSync(Channel.runCollect(unwrappedChannel)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unwrap = channel => fromTransform((upstream, scope) => {\n let pull;\n return Effect.succeed(Effect.suspend(() => {\n if (pull) return pull;\n return channel.pipe(Scope.provide(scope), Effect.flatMap(channel => toTransform(channel)(upstream, scope)), Effect.flatMap(pull_ => pull = pull_));\n }));\n});\n/**\n * Runs a channel with a scope provided for the duration of the channel\n * execution, removing the channel's `Scope` requirement.\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const scoped = self => fromTransformBracket((upstream, scope, forkedScope) => Effect.map(Scope.provide(toTransform(self)(upstream, scope), forkedScope), Scope.provide(forkedScope)));\n/**\n * Runs an input handler against the upstream pull while the wrapped channel\n * runs without receiving upstream input directly.\n *\n * **Details**\n *\n * The input handler is forked in the channel scope. The wrapped channel is run\n * with an already-completed input.\n *\n * **Example** (Embedding custom input handling)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a base channel\n * const baseChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Drain the embedded input while the base channel runs\n * const embeddedChannel = Channel.embedInput(\n * baseChannel,\n * (upstream) =>\n * upstream.pipe(\n * Effect.forever,\n * Effect.ignore\n * )\n * )\n * await Effect.runPromise(Channel.runCollect(embeddedChannel)) // => [1, 2, 3]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const embedInput = /*#__PURE__*/dual(2, (self, input) => fromTransformBracket((upstream, scope, forkedScope) => Effect.andThen(Effect.forkIn(input(upstream), forkedScope), toTransform(self)(Cause.done(), scope))));\n/**\n * Buffers individual output elements in a queue with the configured `capacity`\n * so a faster producer can progress independently of a slower consumer.\n *\n * **When to use**\n *\n * Use when output elements can be decoupled from downstream demand and the\n * configured backpressure or loss strategy is acceptable.\n *\n * **Details**\n *\n * Finite queues use the `strategy` option. The default `\"suspend\"` strategy\n * applies backpressure, while `\"dropping\"` and `\"sliding\"` can discard output\n * elements when the queue is full. `\"unbounded\"` capacity does not use a finite\n * capacity strategy.\n *\n * **Gotchas**\n *\n * Dropping and sliding strategies can lose output elements under backpressure.\n *\n * @see {@link bufferArray} for buffering elements from array outputs\n *\n * @category buffering\n * @since 2.0.0\n */\nexport const buffer = /*#__PURE__*/dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n const pull = yield* toTransform(self)(upstream, scope);\n const queue = yield* Queue.make({\n capacity: options.capacity === \"unbounded\" ? undefined : options.capacity,\n strategy: options.capacity === \"unbounded\" ? undefined : options.strategy\n });\n yield* Scope.addFinalizer(scope, Queue.shutdown(queue));\n yield* pull.pipe(Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever({\n disableYield: true\n }), Effect.onError(cause => Queue.failCause(queue, cause)), Effect.forkIn(scope));\n return Queue.take(queue);\n})));\n/**\n * Buffers array output elements in a queue with the configured `capacity` so a\n * faster producer can progress independently of a slower consumer.\n *\n * **When to use**\n *\n * Use when emitted arrays are batches of elements and it is acceptable for\n * buffering to flatten and rebuild those batches.\n *\n * **Details**\n *\n * Finite queues use the `strategy` option. The default `\"suspend\"` strategy\n * applies backpressure, while `\"dropping\"` and `\"sliding\"` can discard output\n * elements when the queue is full. `\"unbounded\"` capacity does not use a finite\n * capacity strategy.\n *\n * **Gotchas**\n *\n * Input arrays are offered to the queue element-by-element and outputs are\n * rebuilt from the currently available queued elements, so upstream array\n * boundaries are not preserved.\n *\n * @see {@link buffer} for buffering output elements without flattening arrays\n *\n * @category buffering\n * @since 4.0.0\n */\nexport const bufferArray = /*#__PURE__*/dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n const pull = yield* toTransform(self)(upstream, scope);\n const queue = yield* Queue.make({\n capacity: options.capacity === \"unbounded\" ? undefined : options.capacity,\n strategy: options.capacity === \"unbounded\" ? undefined : options.strategy\n });\n yield* Scope.addFinalizer(scope, Queue.shutdown(queue));\n yield* pull.pipe(Effect.flatMap(value => Queue.offerAll(queue, value)), Effect.forever({\n disableYield: true\n }), Effect.onError(cause => Queue.failCause(queue, cause)), Effect.forkIn(scope));\n return Queue.takeAll(queue);\n})));\n/**\n * Interrupts a channel when another effect completes.\n *\n * **When to use**\n *\n * Use to race channel execution against an external effect whose success can\n * become the channel's done value.\n *\n * **Details**\n *\n * If the effect completes first, its success value becomes the returned\n * channel's done value. If the channel completes first, the original channel's\n * done value is preserved.\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptWhen = /*#__PURE__*/dual(2, (self, effect) => merge(self, fromPull(Effect.succeed(Effect.flatMap(effect, Cause.done))), {\n haltStrategy: \"either\"\n}));\n/**\n * Stops a channel when the specified effect completes or fails.\n *\n * **Details**\n *\n * If the effect completes before the channel is done, its success value becomes\n * the returned channel's done value. If the effect fails, the returned channel\n * fails with that error. If the channel completes first, the channel's done\n * value is preserved.\n *\n * @category interruption\n * @since 4.0.0\n */\nexport const haltWhen = /*#__PURE__*/dual(2, (self, effect) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) {\n const pull = yield* toTransform(self)(upstream, scope);\n const fiber = yield* Effect.forkIn(effect, forkedScope, {\n startImmediately: true\n });\n return Effect.suspend(() => {\n const exit = fiber.pollUnsafe();\n return exit === undefined ? pull : Exit.match(exit, {\n onFailure: Effect.failCause,\n onSuccess: Cause.done\n });\n });\n})));\n/**\n * Attaches a finalizer that runs only when the channel exits with failure.\n *\n * **Details**\n *\n * The finalizer receives the failure `Cause`. The original channel failure is\n * preserved. The finalizer itself must not fail.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const onError = /*#__PURE__*/dual(2, (self, finalizer) => onExit(self, exit => Exit.isFailure(exit) ? finalizer(exit.cause) : Effect.void));\n/**\n * Returns a channel with an exit-aware finalizer that is guaranteed to run once\n * the channel begins execution, whether it succeeds or fails.\n *\n * **Example** (Running exit finalizers)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Exit } from \"effect\"\n *\n * class ExitError extends Data.TaggedError(\"ExitError\")<{\n * readonly stage: string\n * }> {}\n *\n * // Create a channel\n * const dataChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Attach exit handler\n * const exits: Array<Exit.Exit<void, ExitError>> = []\n * const channelWithExit = Channel.onExit(dataChannel, (exit) => {\n * exits.push(exit)\n * return Effect.void\n * })\n * const observed = [await Effect.runPromise(Channel.runCollect(channelWithExit)), exits] // => [[1, 2, 3], [Exit.void]]\n * ```\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onExit = /*#__PURE__*/dual(2, (self, finalizer) => fromTransformBracket((upstream, scope, forkedScope) => Scope.addFinalizerExit(forkedScope, finalizer).pipe(Effect.andThen(toTransform(self)(upstream, scope)))));\n/**\n * Runs an effect before the channel starts.\n *\n * **Details**\n *\n * The effect's successful value is ignored. If the effect fails, the returned\n * channel fails before running the source channel.\n *\n * @category hooks\n * @since 4.0.0\n */\nexport const onStart = /*#__PURE__*/dual(2, (self, onStart) => unwrap(Effect.as(onStart, self)));\n/**\n * Runs an effect the first time the channel emits an output element.\n *\n * **When to use**\n *\n * Use when initialization depends on the first output element rather than only\n * on channel startup.\n *\n * **Details**\n *\n * The effect receives the first emitted element. The first element is still\n * emitted unchanged. The effect is not run if the channel completes without\n * emitting an element.\n *\n * @category hooks\n * @since 4.0.0\n */\nexport const onFirst = /*#__PURE__*/dual(2, (self, onFirst) => transformPull(self, pull => Effect.sync(() => {\n let isFirst = true;\n const pullFirst = Effect.tap(pull, element => {\n isFirst = false;\n return onFirst(element);\n });\n return Effect.suspend(() => isFirst ? pullFirst : pull);\n})));\n/**\n * Runs an effect when the channel completes successfully.\n *\n * **Details**\n *\n * The effect runs before the original done value is propagated. The effect is\n * not run when the channel fails. If the effect fails, the returned channel\n * fails with that error.\n *\n * @category hooks\n * @since 4.0.0\n */\nexport const onEnd = /*#__PURE__*/dual(2, (self, onEnd) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, leftover => Effect.flatMap(onEnd, () => Cause.done(leftover))))));\n/**\n * Returns a channel with a finalizer effect that is guaranteed to run once the\n * channel begins execution, whether it succeeds or fails.\n *\n * **Example** (Ensuring cleanup runs)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class EnsureError extends Data.TaggedError(\"EnsureError\")<{\n * readonly operation: string\n * }> {}\n *\n * // Create a channel\n * const dataChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Ensure cleanup always runs\n * const events: Array<string> = []\n * const channelWithCleanup = Channel.ensuring(\n * dataChannel,\n * Effect.sync(() => events.push(\"cleanup\"))\n * )\n * const observed = [await Effect.runPromise(Channel.runCollect(channelWithCleanup)), events] // => [[1, 2, 3], [\"cleanup\"]]\n * ```\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => onExit(self, _ => finalizer));\nconst runWith = (self, f, onHalt) => Effect.suspend(() => {\n const scope = Scope.makeUnsafe();\n const makePull = toTransform(self)(Cause.done(), scope);\n return Pull.catchDone(Effect.flatMap(makePull, f), onHalt ? onHalt : Effect.succeed).pipe(Effect.onExit(exit => Scope.close(scope, exit)));\n});\n/**\n * Creates a channel from the specified services.\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const contextWith = f => fromTransform((upstream, scope) => Effect.contextWith(context => toTransform(f(context))(upstream, scope)));\n/**\n * Provides a `Context` to the channel, removing the corresponding service\n * requirements from the returned channel.\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideContext = /*#__PURE__*/dual(2, (self, context) => fromTransform((upstream, scope) => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context))));\n/**\n * Provides a concrete service for a context key, removing that service\n * requirement from the returned channel.\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideService = /*#__PURE__*/dual(3, (self, key, service) => fromTransform((upstream, scope) => Effect.map(Effect.provideService(toTransform(self)(upstream, scope), key, service), Effect.provideService(key, service))));\n/**\n * Provides a service to the channel after obtaining it from an effect.\n *\n * **When to use**\n *\n * Use to supply a channel dependency when constructing the service itself is\n * effectful or can fail.\n *\n * **Details**\n *\n * If the service effect fails, the returned channel fails. The provided service\n * removes the corresponding service requirement from the returned channel.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provideServiceEffect = /*#__PURE__*/dual(3, (self, key, service) => fromTransform((upstream, scope) => Effect.flatMap(service, s => toTransform(provideService(self, key, s))(upstream, scope))));\n/**\n * Provides a `Layer` or `Context` to the channel, removing the corresponding\n * service requirements.\n *\n * **Details**\n *\n * Providing a `Context` delegates to `provideContext`. Providing a `Layer`\n * builds the layer in the channel scope. Use `options.local` to build a fresh\n * layer instance for this provision.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provide = /*#__PURE__*/dual(args => isChannel(args[0]), (self, layer, options) => Context.isContext(layer) ? provideContext(self, layer) : fromTransform((upstream, scope) => Effect.flatMap(options?.local ? Layer.buildWithMemoMap(layer, Layer.makeMemoMapUnsafe(), scope) : Layer.buildWithScope(layer, scope), context => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context)))));\n/**\n * Transforms the current context before running the channel.\n *\n * **Details**\n *\n * The function receives the surrounding context and returns the context to\n * provide to the channel. The returned channel requires the services needed to\n * build that context.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const updateContext = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.contextWith(context => {\n const toProvide = f(context);\n return toTransform(provideContext(self, toProvide))(upstream, scope);\n})));\n/**\n * Updates a service in the current context before running the channel.\n *\n * **Details**\n *\n * The existing service is read from the context. The updated service is\n * provided to the channel under the same key.\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const updateService = /*#__PURE__*/dual(3, (self, service, f) => updateContext(self, context => Context.add(context, service, f(Context.get(context, service)))));\n/**\n * Runs the channel inside a tracing span with the specified name and options.\n *\n * **Details**\n *\n * The created span is provided as the current parent span while the channel\n * runs. The span is ended with the channel's exit value.\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withSpan = function () {\n const dataFirst = isChannel(arguments[0]);\n const name = dataFirst ? arguments[1] : arguments[0];\n const options = addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]);\n if (dataFirst) {\n const self = arguments[0];\n return withSpanImpl(self, name, options);\n }\n return self => withSpanImpl(self, name, options);\n};\nconst withSpanImpl = (self, name, options) => acquireUseRelease(Effect.makeSpan(name, options), span => provideService(self, ParentSpan, span), (span, exit) => Effect.withFiber(fiber => {\n const clock = fiber.getRef(ClockRef);\n const timingEnabled = fiber.getRef(TracerTimingEnabled);\n return endSpan(span, exit, clock, timingEnabled);\n}));\n/**\n * The starting channel for Do notation, emitting an empty object.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Do = /*#__PURE__*/succeed({});\nconst let_ = /*#__PURE__*/dual(3, (self, name, f) => map(self, elem => ({\n ...elem,\n [name]: f(elem)\n})));\nexport {\n/**\n * Adds a computed field to each object emitted by a channel.\n *\n * @category mapping\n * @since 4.0.0\n */\nlet_ as let };\n/**\n * Adds a field to each object emitted by a channel by running another channel\n * derived from that object.\n *\n * **Details**\n *\n * The field name must not already exist on the emitted object. The derived\n * channel's output becomes the value of the new field. `options.concurrency`\n * and `options.bufferSize` control how derived channels are flattened.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const bind = /*#__PURE__*/dual(args => isChannel(args[0]), (self, name, f, options) => flatMap(self, elem => map(f(elem), b => ({\n ...elem,\n [name]: b\n})), options));\n/**\n * Wraps each output element in an object under the specified field name.\n *\n * **When to use**\n *\n * Use when you need to start a Channel Do-notation chain from an existing\n * output value by assigning that value to a field name.\n *\n * @see {@link Do} for starting Do notation from an empty object\n * @see {@link bind} for adding a field produced by another channel\n * @see {@link let_ let} for adding a computed field\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, elem => ({\n [name]: elem\n})));\n/**\n * Runs a channel and counts the number of elements it outputs.\n *\n * **Example** (Counting channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class CountError extends Data.TaggedError(\"CountError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Create a channel with multiple elements\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Count the elements\n * const countEffect = Channel.runCount(numbersChannel)\n *\n * Effect.runSync(countEffect) // => 5\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runCount = self => runFold(self, () => 0, acc => acc + 1);\n/**\n * Runs a channel and discards all output elements, returning only the final result.\n *\n * **Example** (Draining channel output at runtime)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class DrainError extends Data.TaggedError(\"DrainError\")<{\n * readonly stage: string\n * }> {}\n *\n * // Create a channel that outputs elements and completes with a result\n * const resultChannel = Channel.fromIterable([1, 2, 3])\n * const completedChannel = Channel.concat(resultChannel, Channel.end(\"completed\"))\n *\n * // Drain all elements and get only the final result\n * const drainEffect = Channel.runDrain(completedChannel)\n *\n * Effect.runSync(drainEffect) // => \"completed\"\n * ```\n *\n * @category running\n * @since 2.0.0\n */\nexport const runDrain = self => runWith(self, pull => Effect.forever(pull, {\n disableYield: true\n}));\n/**\n * Runs a channel and applies an effect to each output element.\n *\n * **Example** (Running effects for each output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ForEachError extends Data.TaggedError(\"ForEachError\")<{\n * readonly element: unknown\n * }> {}\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Run forEach to process each element\n * const processed: Array<number> = []\n * const forEachEffect = Channel.runForEach(\n * numbersChannel,\n * (n) => Effect.sync(() => processed.push(n))\n * )\n *\n * await Effect.runPromise(forEachEffect)\n * processed // => [1, 2, 3]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runForEach = /*#__PURE__*/dual(2, (self, f) => runWith(self, pull => Effect.forever(Effect.flatMap(pull, f), {\n disableYield: true\n})));\n/**\n * Runs a channel and applies an effectful predicate to each output element\n * until the predicate returns `false`.\n *\n * **Details**\n *\n * Returning `true` continues consuming the channel. Returning `false` stops\n * consumption early. The returned effect completes with `void`.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => runWith(self, pull => pull.pipe(Effect.flatMap(f), Effect.flatMap(cont => cont ? Effect.void : Cause.done()), Effect.forever({\n disableYield: true\n}))));\n/**\n * Concatenates a channel's `Uint8Array` chunks into a single `Uint8Array`.\n *\n * **Gotchas**\n *\n * This materializes the full content in memory. The source channel must not\n * reuse or mutate emitted buffers, which are retained until collection completes.\n *\n * **Example** (Joining channel byte chunks)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromArray([\n * [new Uint8Array([1, 2])],\n * [new Uint8Array([3, 4])]\n * ] as const)\n *\n * const bytes = Effect.runSync(Channel.mkUint8Array(channel))\n * Array.from(bytes) // => [1, 2, 3, 4]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const mkUint8Array = self => Effect.map(runFold(self, () => ({\n bytes: 0,\n arrays: []\n}), (acc, chunk) => {\n for (let i = 0; i < chunk.length; i++) {\n acc.bytes += chunk[i].length;\n acc.arrays.push(chunk[i]);\n }\n return acc;\n}), ({\n arrays,\n bytes\n}) => {\n const result = new Uint8Array(bytes);\n let offset = 0;\n for (let i = 0; i < arrays.length; i++) {\n const array = arrays[i];\n result.set(array, offset);\n offset += array.length;\n }\n return result;\n});\n/**\n * Runs a channel and collects all output elements into an array.\n *\n * **Example** (Collecting channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class CollectError extends Data.TaggedError(\"CollectError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Create a channel with elements\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Collect all elements into an array\n * const collectEffect = Channel.runCollect(numbersChannel)\n *\n * Effect.runSync(collectEffect) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category running\n * @since 2.0.0\n */\nexport const runCollect = self => runFold(self, () => [], (acc, o) => {\n acc.push(o);\n return acc;\n});\n/**\n * Runs a channel until the first output element is available, returning it in\n * an `Option`.\n *\n * **Details**\n *\n * Returns `Option.some` with the first output element, or `Option.none` if the\n * channel completes without emitting output.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runHead = self => Effect.suspend(() => {\n let head = Option.none();\n return runWith(self, pull => pull.pipe(Effect.asSome, Effect.flatMap(head_ => {\n head = head_;\n return Cause.done();\n })), () => Effect.succeed(head));\n});\n/**\n * Runs a channel to completion and returns the last output element in an\n * `Option`.\n *\n * **Details**\n *\n * Returns `Option.some` with the last emitted element, or `Option.none` if the\n * channel completes without emitting output.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runLast = self => Effect.suspend(() => {\n const absent = Symbol(); // Prevent boxing\n let last = absent;\n return runWith(self, pull => Effect.forever(Effect.flatMap(pull, item => {\n last = item;\n return Effect.void;\n }), {\n disableYield: true\n }), () => last === absent ? Effect.succeedNone : Effect.succeedSome(last));\n});\n/**\n * Runs a channel and folds over all output elements with an accumulator.\n *\n * **Example** (Folding channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class FoldError extends Data.TaggedError(\"FoldError\")<{\n * readonly operation: string\n * }> {}\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Fold to calculate sum\n * const sumEffect = Channel.runFold(numbersChannel, () => 0, (acc, n) => acc + n)\n *\n * Effect.runSync(sumEffect) // => 15\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runFold = /*#__PURE__*/dual(3, (self, initial, f) => Effect.suspend(() => {\n let state = initial();\n return runWith(self, pull => Effect.whileLoop({\n while: constTrue,\n body: () => pull,\n step: value => {\n state = f(state, value);\n }\n }), () => Effect.succeed(state));\n}));\n/**\n * Runs a channel and effectfully folds all output elements with an accumulator.\n *\n * **When to use**\n *\n * Use when folding channel output needs effects, services, or an additional\n * failure channel during accumulation.\n *\n * **Details**\n *\n * The initial accumulator is evaluated lazily. Each output element is passed to\n * the effectful accumulator function. The returned effect succeeds with the\n * final accumulator value.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Effect.suspend(() => {\n let state = initial();\n return runWith(self, pull => Effect.whileLoop({\n while: constTrue,\n body: constant(pull.pipe(Effect.flatMap(o => f(state, o)), Effect.map(s => {\n state = s;\n }))),\n step: constVoid\n }), () => Effect.succeed(state));\n}));\n/**\n * Converts a channel to a scoped `Pull` for low-level consumption.\n *\n * **Details**\n *\n * The effect requires a `Scope`. The returned pull should be consumed only\n * while that scope remains open. Pulls are serialized so only one pull is\n * evaluated at a time.\n *\n * **Example** (Converting channels to pulls)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class PullError extends Data.TaggedError(\"PullError\")<{\n * readonly step: string\n * }> {}\n *\n * // Create a channel\n * const numbersChannel = Channel.fromIterable([1, 2, 3])\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pull = yield* Channel.toPull(numbersChannel)\n * return [yield* pull, yield* pull, yield* pull]\n * }))\n * await Effect.runPromise(program) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toPull = /*#__PURE__*/Effect.fnUntraced(function* (self) {\n const semaphore = Semaphore.makeUnsafe(1);\n const context = yield* Effect.context();\n const scope = Context.get(context, Scope.Scope);\n const pull = yield* toTransform(self)(Cause.done(), scope);\n return pull.pipe(Effect.provideContext(context), semaphore.withPermits(1));\n},\n/*#__PURE__*/\n// ensure errors are redirected to the pull effect\nEffect.catchCause(cause => Effect.succeed(Effect.failCause(cause))));\n/**\n * Converts a channel to a Pull within an existing scope.\n *\n * **Example** (Converting channels to scoped pulls)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Scope } from \"effect\"\n *\n * class ScopedPullError extends Data.TaggedError(\"ScopedPullError\")<{\n * readonly reason: string\n * }> {}\n *\n * // Create a channel\n * const numbersChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Convert to Pull with explicit scope\n * const scopedPullEffect = Effect.gen(function*() {\n * const scope = yield* Effect.scope\n * const pull = yield* Channel.toPullScoped(numbersChannel, scope)\n * return [yield* pull, yield* pull, yield* pull]\n * })\n * await Effect.runPromise(Effect.scoped(scopedPullEffect)) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toPullScoped = (self, scope) => toTransform(self)(Cause.done(), scope);\n/**\n * Runs a channel and offers each output element into a queue.\n *\n * **Details**\n *\n * When the channel completes, the queue is ended. When the channel fails, the\n * queue is failed with the channel's cause. The returned effect itself\n * completes with `void`.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runIntoQueue = /*#__PURE__*/dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offer(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => {\n if (Exit.isSuccess(exit)) {\n Queue.endUnsafe(queue);\n } else {\n Queue.failCauseUnsafe(queue, exit.cause);\n }\n return Effect.void;\n}))));\n/**\n * Runs a channel that emits non-empty arrays and offers each array element into\n * a queue.\n *\n * **Details**\n *\n * When the channel completes, the queue is ended. When the channel fails, the\n * queue is failed with the channel's cause. The returned effect itself\n * completes with `void`.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runIntoQueueArray = /*#__PURE__*/dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offerAll(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => {\n if (Exit.isSuccess(exit)) {\n Queue.endUnsafe(queue);\n } else {\n Queue.failCauseUnsafe(queue, exit.cause);\n }\n return Effect.void;\n}))));\n/**\n * Creates a scoped queue and forks the channel to feed it for concurrent\n * consumption.\n *\n * **Details**\n *\n * Output elements are offered to the queue. Channel completion and failure are\n * signaled through the queue. The queue is shut down when the surrounding scope\n * closes.\n *\n * **Example** (Converting channels to queues)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Queue } from \"effect\"\n *\n * class QueueError extends Data.TaggedError(\"QueueError\")<{\n * readonly operation: string\n * }> {}\n *\n * // Create a channel with data\n * const dataChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Convert to queue for concurrent processing\n * const program = Effect.scoped(Effect.gen(function*() {\n * const queue = yield* Channel.toQueue(dataChannel, { capacity: 32 })\n * return yield* Queue.takeBetween(queue, 5, 5)\n * }))\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toQueue = /*#__PURE__*/dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n const scope = yield* Effect.scope;\n const queue = yield* Queue.make({\n capacity: typeof options.capacity === \"number\" ? options.capacity : undefined,\n strategy: typeof options.capacity === \"number\" ? options.strategy : undefined\n });\n yield* Scope.addFinalizer(scope, Queue.shutdown(queue));\n yield* Effect.forkIn(runIntoQueue(self, queue), scope);\n return queue;\n}));\n/**\n * Creates a scoped queue and forks an array-emitting channel to feed it.\n *\n * **Details**\n *\n * Each element inside emitted non-empty arrays is offered to the queue. Channel\n * completion and failure are signaled through the queue. The queue is shut down\n * when the surrounding scope closes.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toQueueArray = /*#__PURE__*/dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n const scope = yield* Effect.scope;\n const queue = yield* Queue.make({\n capacity: typeof options.capacity === \"number\" ? options.capacity : undefined,\n strategy: typeof options.capacity === \"number\" ? options.strategy : undefined\n });\n yield* Scope.addFinalizer(scope, Queue.shutdown(queue));\n yield* Effect.forkIn(runIntoQueueArray(self, queue), scope);\n return queue;\n}));\n/**\n * Converts a channel to a PubSub for concurrent consumption.\n *\n * **Details**\n *\n * `shutdownOnEnd` indicates whether the PubSub should be shut down when the\n * channel ends. By default this is `true`.\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toPubSub = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n const pubsub = yield* makePubSub(options);\n yield* Effect.forkScoped(runIntoPubSub(self, pubsub, {\n shutdownOnEnd: options.shutdownOnEnd !== false\n }));\n return pubsub;\n}));\n/**\n * Runs a channel and publishes each output element to a `PubSub`.\n *\n * **Details**\n *\n * The channel's output values are published as individual PubSub messages. Use\n * `options.shutdownOnEnd` to shut down the PubSub when channel execution ends.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runIntoPubSub = /*#__PURE__*/dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publish(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_));\nconst 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);\n/**\n * Converts an array-emitting channel to a scoped `PubSub` for concurrent\n * consumption.\n *\n * **Details**\n *\n * Each element inside emitted non-empty arrays is published as an individual\n * PubSub message. `shutdownOnEnd` indicates whether the PubSub should be shut\n * down when the channel ends. By default this is `true`.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toPubSubArray = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n const pubsub = yield* makePubSub(options);\n yield* Effect.forkScoped(runIntoPubSubArray(self, pubsub, {\n shutdownOnEnd: options.shutdownOnEnd !== false\n }));\n return pubsub;\n}));\n/**\n * Runs an array-emitting channel and publishes each array element to a\n * `PubSub`.\n *\n * **Details**\n *\n * Each element inside emitted non-empty arrays is published as an individual\n * PubSub message. Use `options.shutdownOnEnd` to shut down the PubSub when\n * channel execution ends.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runIntoPubSubArray = /*#__PURE__*/dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publishAll(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_));\n/**\n * Converts a channel to a scoped `PubSub` of `Take` values.\n *\n * **Details**\n *\n * Emitted non-empty arrays are published as output `Take` values. When the\n * channel ends, its final `Exit` is published so subscribers can observe\n * completion or failure.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toPubSubTake = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n const pubsub = yield* makePubSub(options);\n yield* runForEach(self, value => PubSub.publish(pubsub, value)).pipe(Effect.onExit(exit => PubSub.publish(pubsub, exit)), Effect.forkScoped);\n return pubsub;\n}));\n//# sourceMappingURL=Channel.js.map","import { identity } from \"../Function.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nconst TypeId = \"~effect/Stream\";\nconst streamVariance = {\n _R: identity,\n _E: identity,\n _A: identity\n};\nconst Stream = function (channel) {\n this.channel = channel;\n};\nStream.prototype = {\n [TypeId]: streamVariance,\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/** @internal */\nexport const fromChannel = channel => new Stream(channel);\n//# sourceMappingURL=stream.js.map","/**\n * Describes effectful sources that emit values over time.\n *\n * A `Stream<A, E, R>` can emit many `A` values, fail with `E`, and require\n * services `R` while it is being consumed. Streams are useful for data that is\n * pulled in steps, such as values from collections, queues, pubsubs, schedules,\n * callbacks, async iterables, or platform streams. The APIs here cover the full\n * stream lifecycle: create a stream, transform or combine it, control buffering\n * and timing, handle failures, and finally consume it.\n *\n * @since 2.0.0\n */\n// @effect-diagnostics returnEffectInGen:off\nimport * as Arr from \"./Array.js\";\nimport * as ByteSize from \"./ByteSize.js\";\nimport * as Cause from \"./Cause.js\";\nimport * as Channel from \"./Channel.js\";\nimport { Clock } from \"./Clock.js\";\nimport * as Context from \"./Context.js\";\nimport * as Duration from \"./Duration.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Equal from \"./Equal.js\";\nimport * as ExecutionPlan from \"./ExecutionPlan.js\";\nimport * as Exit from \"./Exit.js\";\nimport * as Fiber from \"./Fiber.js\";\nimport { constant, constTrue, constVoid, dual, identity } from \"./Function.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as internalExecutionPlan from \"./internal/executionPlan.js\";\nimport * as internal from \"./internal/stream.js\";\nimport { addSpanStackTrace } from \"./internal/tracer.js\";\nimport * as Iterable from \"./Iterable.js\";\nimport * as Latch from \"./Latch.js\";\nimport * as MutableHashMap from \"./MutableHashMap.js\";\nimport * as MutableList from \"./MutableList.js\";\nimport * as Option from \"./Option.js\";\nimport { hasProperty, isNotUndefined, isTagged } from \"./Predicate.js\";\nimport * as PubSub from \"./PubSub.js\";\nimport * as Pull from \"./Pull.js\";\nimport * as Queue from \"./Queue.js\";\nimport * as RcMap from \"./RcMap.js\";\nimport * as RcRef from \"./RcRef.js\";\nimport * as Result from \"./Result.js\";\nimport * as Schedule from \"./Schedule.js\";\nimport * as Scope from \"./Scope.js\";\nimport * as Sink from \"./Sink.js\";\nimport { isString } from \"./String.js\";\n/**\n * Runtime identifier stored on `Stream` values and used by `isStream` to\n * recognize them.\n *\n * **Details**\n *\n * This marker is part of the runtime representation of `Stream` values. Prefer\n * `isStream` when narrowing unknown values.\n *\n * @see {@link isStream} for the public guard that checks this identifier\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/Stream\";\n/**\n * Checks whether a value is a Stream.\n *\n * **Example** (Checking whether a value is a Stream)\n *\n * ```ts import.meta.vitest\n * import { Stream } from \"effect\"\n *\n * Stream.isStream(Stream.make(1, 2, 3)) // => true\n * Stream.isStream({ data: [1, 2, 3] }) // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isStream = u => hasProperty(u, TypeId);\n/**\n * The default chunk size used by Stream constructors and combinators.\n *\n * **Example** (Reading the default chunk size)\n *\n * ```ts import.meta.vitest\n * import { Stream } from \"effect\"\n *\n * Stream.DefaultChunkSize // => 4096\n * ```\n *\n * @category constants\n * @since 2.0.0\n */\nexport const DefaultChunkSize = Channel.DefaultChunkSize;\n/**\n * Creates a stream from a array-emitting `Channel`.\n *\n * **Example** (Creating a stream from an array-emitting channel)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Stream } from \"effect\"\n *\n * const channel = Channel.succeed([1, 2, 3] as const)\n * const stream = Stream.fromChannel(channel)\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromChannel = internal.fromChannel;\n/**\n * Creates a stream from an effect.\n *\n * **Example** (Creating a stream from an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.fromEffect(Effect.succeed(42))\n * await Effect.runPromise(Stream.runCollect(stream)) // => [42]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromEffect = effect => fromChannel(Channel.fromEffect(Effect.map(effect, Arr.of)));\n/**\n * Accesses a service from the context and emits it as a single element.\n *\n * **Example** (Accessing a service as a stream)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Greeter extends Context.Service<Greeter, {\n * readonly greet: (name: string) => string\n * }>()(\"Greeter\") {}\n *\n * const stream = Stream.service(Greeter).pipe(\n * Stream.map((greeter) => greeter.greet(\"World\"))\n * )\n *\n * await Effect.runPromise(\n * stream.pipe(\n * Stream.provideService(Greeter, {\n * greet: (name) => `Hello, ${name}!`\n * }),\n * Stream.runCollect\n * )\n * ) // => [\"Hello, World!\"]\n * ```\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const service = service => fromEffect(Effect.service(service));\n/**\n * Optionally accesses a service from the context and emits the result as a\n * single element.\n *\n * **When to use**\n *\n * Use when you need a stream that emits an optional service from the context\n * without requiring that service to be present.\n *\n * **Example** (Accessing an optional service as a stream)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Option, Stream } from \"effect\"\n *\n * class Greeter extends Context.Service<Greeter, {\n * readonly greet: (name: string) => string\n * }>()(\"Greeter\") {}\n *\n * const stream = Stream.serviceOption(Greeter).pipe(\n * Stream.map((maybeGreeter) =>\n * Option.match(maybeGreeter, {\n * onNone: () => \"No greeter\",\n * onSome: (greeter) => greeter.greet(\"World\")\n * })\n * )\n * )\n *\n * await Effect.runPromise(\n * stream.pipe(\n * Stream.provideService(Greeter, {\n * greet: (name) => `Hello, ${name}!`\n * }),\n * Stream.runCollect\n * )\n * ) // => [\"Hello, World!\"]\n * ```\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const serviceOption = service => fromEffect(Effect.serviceOption(service));\n/**\n * Creates a stream that runs the effect and emits no elements.\n *\n * **Example** (Draining an effect into a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * let drained = false\n * await Effect.runPromise(\n * Stream.fromEffectDrain(Effect.sync(() => {\n * drained = true\n * })).pipe(Stream.runDrain)\n * )\n * drained // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectDrain = effect => fromPull(Effect.succeed(Effect.flatMap(effect, () => Cause.done())));\n/**\n * Creates a stream from an effect producing a value of type `A` which repeats forever.\n *\n * **Example** (Repeating an effect forever)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * let n = 0\n * const stream = Stream.fromEffectRepeat(Effect.sync(() => ++n)).pipe(Stream.take(5))\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectRepeat = effect => fromPull(Effect.succeed(Effect.map(effect, Arr.of)));\n/**\n * Creates a stream from an effect producing a value of type `A`, which is\n * repeated using the specified schedule.\n *\n * **Example** (Repeating an effect with a schedule)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const stream = Stream.fromEffectSchedule(Effect.succeed(\"ping\"), Schedule.recurs(2))\n * await Effect.runPromise(Stream.runCollect(stream)) // => [\"ping\", \"ping\", \"ping\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectSchedule = (effect, schedule) => fromPull(Effect.gen(function* () {\n const step = yield* Schedule.toStepWithMetadata(schedule);\n let s = yield* Effect.provideService(effect, Schedule.CurrentMetadata, Schedule.CurrentMetadata.defaultValue());\n let initial = true;\n const pull = Effect.suspend(() => step(s)).pipe(Effect.flatMap(meta => Effect.provideService(effect, Schedule.CurrentMetadata, meta)), Effect.map(next => {\n s = next;\n return Arr.of(next);\n }));\n return Effect.suspend(() => {\n if (initial) {\n initial = false;\n return Effect.succeed(Arr.of(s));\n }\n return pull;\n });\n}));\n/**\n * Creates a stream that emits `void` immediately once, then emits another\n * `void` after each specified interval.\n *\n * **Example** (Emitting ticks on an interval)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.tick(0).pipe(Stream.take(3), Stream.runCollect)) // => [undefined, undefined, undefined]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const tick = interval => fromPull(Effect.sync(() => {\n let first = true;\n const effect = Effect.succeed(Arr.of(undefined));\n const delayed = Effect.delay(effect, interval);\n return Effect.suspend(() => {\n if (first) {\n first = false;\n return effect;\n }\n return delayed;\n });\n}));\n/**\n * Creates a stream from a pull effect, such as one produced by `Stream.toPull`.\n *\n * **Details**\n *\n * A pull effect yields chunks on demand and completes when the upstream stream ends.\n * See `Stream.toPull` for a matching producer.\n *\n * **Example** (Creating a stream from a pull effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * const source = Stream.make(1, 2, 3)\n * const pull = yield* Stream.toPull(source)\n * const stream = Stream.fromPull(Effect.succeed(pull))\n * return yield* Stream.runCollect(stream)\n * })\n * )\n *\n * await Effect.runPromise(program) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromPull = pull => fromChannel(Channel.fromPull(pull));\n/**\n * Derives a stream by transforming its pull effect.\n *\n * **Example** (Transforming a pull effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * const transformed = Stream.transformPull(stream, (pull) => Effect.succeed(pull))\n *\n * await Effect.runPromise(Stream.runCollect(transformed)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const transformPull = (self, f) => fromChannel(Channel.fromTransform((_, scope) => Effect.flatMap(Channel.toPullScoped(self.channel, scope), pull => f(pull, scope))));\n/**\n * Transforms a stream by effectfully transforming its pull effect.\n *\n * **Details**\n *\n * A forked scope is also provided to the transformation function, which is\n * closed once the resulting stream has finished processing.\n *\n * **Example** (Transforming a stream by effectfully transforming its pull effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Scope, Stream } from \"effect\"\n *\n * const finalized: Array<boolean> = []\n * const stream = Stream.make(1, 2, 3)\n *\n * const transformed = Stream.transformPullBracket(\n * stream,\n * (pull, _scope, forkedScope) =>\n * Effect.gen(function*() {\n * yield* Scope.addFinalizer(forkedScope, Effect.sync(() => finalized.push(true)))\n * return pull\n * })\n * )\n *\n * await Effect.runPromise(Stream.runCollect(transformed)) // => [1, 2, 3]\n * finalized // => [true]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const transformPullBracket = (self, f) => fromChannel(Channel.fromTransformBracket((_, scope, forkedScope) => Effect.flatMap(Channel.toPullScoped(self.channel, scope), pull => f(pull, scope, forkedScope))));\n/**\n * Creates a channel from a stream.\n *\n * **Example** (Converting a stream to a channel)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Stream } from \"effect\"\n *\n * const channel = Stream.toChannel(Stream.make(1, 2, 3))\n * const values = await Effect.runPromise(Channel.runCollect(channel))\n * values.flat() // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const toChannel = stream => stream.channel;\n/**\n * Creates a stream from a callback that can emit values into a queue.\n *\n * **When to use**\n *\n * Use when you need callback-based code to emit stream values by offering to a\n * `Queue`, or signal stream completion through the `Queue` module APIs.\n *\n * By default it uses an \"unbounded\" buffer size.\n * You can customize the buffer size and strategy by passing an object as the\n * second argument with the `bufferSize` and `strategy` fields.\n *\n * **Example** (Creating a stream from a callback that can emit values into a queue)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue, Stream } from \"effect\"\n *\n * const stream = Stream.callback<number>((queue) =>\n * Effect.sync(() => {\n * // Emit values to the stream\n * Queue.offerUnsafe(queue, 1)\n * Queue.offerUnsafe(queue, 2)\n * Queue.offerUnsafe(queue, 3)\n * // Signal completion\n * Queue.endUnsafe(queue)\n * })\n * )\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const callback = (f, options) => fromChannel(Channel.callbackArray(f, options));\n/**\n * Creates an empty stream.\n *\n * **Example** (Creating an empty stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.runCollect(Stream.empty)) // => []\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = /*#__PURE__*/fromChannel(Channel.empty);\n/**\n * Creates a single-valued pure stream.\n *\n * **Example** (Creating a single-valued pure stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.runCollect(Stream.succeed(3))) // => [3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeed = value => fromChannel(Channel.succeed(Arr.of(value)));\n/**\n * Creates a stream from a sequence of values.\n *\n * **Example** (Creating a stream from a sequence of values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = (...values) => fromArray(values);\n/**\n * Creates a stream that synchronously evaluates a function and emits the result as a single value.\n *\n * **Details**\n *\n * The function is evaluated each time the stream is run.\n *\n * **Example** (Evaluating a value synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.sync(() => 2 + 1).pipe(Stream.runCollect)) // => [3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sync = evaluate => fromChannel(Channel.sync(() => Arr.of(evaluate())));\n/**\n * Creates a lazily constructed stream.\n *\n * **Details**\n *\n * The stream factory is evaluated each time the stream is run.\n *\n * **Example** (Creating a lazily constructed stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.suspend(() => Stream.make(1, 2, 3)).pipe(Stream.runCollect)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const suspend = stream => fromChannel(Channel.suspend(() => stream().channel));\n/**\n * Terminates with the specified error.\n *\n * **Example** (Failing a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.exit(Stream.runCollect(Stream.fail(\"Uh oh!\")))) // => Exit.fail(\"Uh oh!\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fail = error => fromChannel(Channel.fail(error));\n/**\n * Terminates with the specified lazily evaluated error.\n *\n * **Example** (Failing a stream lazily)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Stream } from \"effect\"\n *\n * const stream = Stream.failSync(() => \"Uh oh!\")\n *\n * await Effect.runPromise(Stream.runCollect(stream).pipe(Effect.exit)) // => Exit.fail(\"Uh oh!\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failSync = evaluate => fromChannel(Channel.failSync(evaluate));\n/**\n * Creates a stream that fails with the specified `Cause`.\n *\n * **Example** (Failing with a cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.failCause(Cause.fail(\"Database connection failed\")).pipe(\n * Stream.catchCause(() => Stream.succeed(\"recovered\"))\n * )\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [\"recovered\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCause = cause => fromChannel(Channel.failCause(cause));\n/**\n * The stream that dies with the specified defect.\n *\n * **Example** (Dying with a defect)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Stream } from \"effect\"\n *\n * const defect = new Error(\"Boom\")\n * const stream = Stream.die(defect)\n *\n * await Effect.runPromise(Effect.exit(Stream.runCollect(stream))) // => Exit.failCause(Cause.die(defect))\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const die = defect => fromChannel(Channel.die(defect));\n/**\n * The stream that always fails with the specified lazily evaluated `Cause`.\n *\n * **Example** (Failing with a lazy cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Stream } from \"effect\"\n *\n * const stream = Stream.failCauseSync(() =>\n * Cause.fail(\"Connection timeout after retries\")\n * )\n *\n * await Effect.runPromise(Stream.runCollect(stream).pipe(Effect.exit)) // => Exit.fail(\"Connection timeout after retries\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCauseSync = evaluate => fromChannel(Channel.failCauseSync(evaluate));\n/**\n * Creates a stream that consumes values from an iterator.\n *\n * **Details**\n *\n * The `maxChunkSize` parameter controls how many values are pulled per chunk.\n * Finite fractional values are rounded down, while `NaN` and non-positive\n * values are treated as `1`.\n *\n * **Example** (Consuming values from an iterator)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * function* numbers() {\n * yield 1\n * yield 2\n * yield 3\n * }\n *\n * const stream = Stream.fromIteratorSucceed(numbers())\n *\n * const program = Effect.gen(function* () {\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIteratorSucceed = (iterator, maxChunkSize) => fromChannel(Channel.fromIteratorArray(() => iterator, maxChunkSize));\n/**\n * Creates a new `Stream` from an iterable collection of values.\n *\n * **Details**\n *\n * - `chunkSize`: Maximum number of values emitted per chunk. Finite fractional\n * values are rounded down, while `NaN` and non-positive values are treated as\n * `1`.\n *\n * **Example** (Creating a stream from an iterable)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.fromIterable(numbers)\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterable = (iterable, options) => Array.isArray(iterable) && options?.chunkSize === undefined ? fromArray(iterable) : fromChannel(Channel.fromIterableArray(iterable, options?.chunkSize));\n/**\n * Creates a stream from an effect producing an iterable of values.\n *\n * **When to use**\n *\n * Use when the iterable must be acquired from an Effect before the stream emits,\n * and acquisition services or failures should be part of the stream.\n *\n * **Example** (Creating a stream from an iterable effect)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class UserRepo extends Context.Service<UserRepo, {\n * readonly list: Effect.Effect<ReadonlyArray<string>>\n * }>()(\"UserRepo\") {}\n *\n * const listUsers = Effect.service(UserRepo).pipe(\n * Effect.andThen((repo) => repo.list)\n * )\n *\n * const stream = Stream.fromIterableEffect(listUsers)\n *\n * const program = Effect.gen(function*() {\n * const users = yield* stream.pipe(\n * Stream.provideService(UserRepo, {\n * list: Effect.succeed([\"user1\", \"user2\"])\n * }),\n * Stream.runCollect\n * )\n * users // => [\"user1\", \"user2\"]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterableEffect = iterable => unwrap(Effect.map(iterable, fromIterable));\n/**\n * Creates a stream by repeatedly running an effect that yields an iterable of values.\n *\n * **Example** (Repeating an iterable effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.fromIterableEffectRepeat(Effect.succeed([1, 2])).pipe(\n * Stream.take(5)\n * )\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 1, 2, 1]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterableEffectRepeat = iterable => flatMap(fromEffectRepeat(iterable), fromIterable);\n/**\n * Creates a stream from an array of values.\n *\n * **Example** (Creating a stream from an array of values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.fromArray([1, 2, 3])\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromArray = array => Arr.isReadonlyArrayNonEmpty(array) ? fromChannel(Channel.succeed(array)) : empty;\n/**\n * Creates a stream from an effect that produces an array of values.\n *\n * **When to use**\n *\n * Use when the array must be acquired from an Effect before the stream emits,\n * and acquisition services or failures should be part of the stream.\n *\n * **Example** (Creating a stream from an effect that produces an array of values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.fromArrayEffect(Effect.succeed([\"Ada\", \"Grace\"]))\n * const values = yield* Stream.runCollect(stream)\n * values // => [\"Ada\", \"Grace\"]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromArrayEffect = effect => unwrap(Effect.map(effect, fromArray));\n/**\n * Creates a stream from an arbitrary number of arrays.\n *\n * **Example** (Creating a stream from an arbitrary number of arrays)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.fromArrays([1, 2], [3, 4])\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 3, 4]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromArrays = (...arrays) => fromChannel(Channel.fromArray(Arr.filter(arrays, Arr.isReadonlyArrayNonEmpty)));\n/**\n * Creates a stream that pulls values from a `Queue.Dequeue`.\n *\n * **Details**\n *\n * The stream emits non-empty batches of queued values and ends when the queue\n * fails with `Cause.Done`; other queue failures are propagated.\n *\n * **Example** (Creating a stream from a queue of values)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.unbounded<number, Cause.Done>()\n * yield* Queue.offer(queue, 1)\n * yield* Queue.offer(queue, 2)\n * yield* Queue.offer(queue, 3)\n * yield* Queue.end(queue)\n *\n * const stream = Stream.fromQueue(queue)\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromQueue = queue => fromChannel(Channel.fromQueueArray(queue));\n/**\n * Creates a stream from a subscription to a `PubSub`.\n *\n * **Example** (Creating a stream from a subscription to a PubSub)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.unbounded<number>({ replay: 3 })\n *\n * const fiber = yield* Stream.fromPubSub(pubsub).pipe(\n * Stream.take(3),\n * Stream.runCollect,\n * Effect.forkChild\n * )\n *\n * yield* PubSub.publish(pubsub, 1)\n * yield* PubSub.publish(pubsub, 2)\n * yield* PubSub.publish(pubsub, 3)\n *\n * const values = yield* Fiber.join(fiber)\n * values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromPubSub = pubsub => fromChannel(Channel.fromPubSubArray(pubsub));\n/**\n * Creates a stream from a PubSub of `Take` values.\n *\n * **Details**\n *\n * `Take` values include end and failure signals.\n *\n * **Example** (Creating a stream from PubSub takes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, PubSub, Stream, Take } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const pubsub = yield* PubSub.unbounded<Take.Take<number, string>>({\n * replay: 3\n * })\n *\n * yield* PubSub.publish(pubsub, [1])\n * yield* PubSub.publish(pubsub, [2])\n * yield* PubSub.publish(pubsub, Exit.succeed<void>(undefined))\n *\n * const values = yield* Stream.fromPubSubTake(pubsub).pipe(Stream.runCollect)\n * values // => [1, 2]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPubSubTake = pubsub => fromChannel(Channel.fromPubSubTake(pubsub));\n/**\n * Creates a stream from a lazily supplied Web `ReadableStream`.\n *\n * **Details**\n *\n * The stream reads from a `ReadableStreamDefaultReader`, maps read failures\n * with `onError`, and closes the reader when the stream finalizes. By default\n * the reader is canceled; set `releaseLockOnEnd` to release the lock instead.\n *\n * **Example** (Creating a stream from a ReadableStream)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } from \"effect\"\n *\n * class StreamError extends Data.TaggedError(\"StreamError\")<{ readonly cause: unknown }> {}\n *\n * const readableStream = new ReadableStream({\n * start(controller) {\n * controller.enqueue(1)\n * controller.enqueue(2)\n * controller.enqueue(3)\n * controller.close()\n * }\n * })\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.fromReadableStream({\n * evaluate: () => readableStream,\n * onError: (cause) => new StreamError({ cause })\n * })\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromReadableStream = options => fromChannel(Channel.fromReadableStream(options));\n/**\n * Creates a stream from an AsyncIterable.\n *\n * **Example** (Creating a stream from an AsyncIterable)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } from \"effect\"\n *\n * class StreamError extends Data.TaggedError(\"StreamError\")<{ readonly cause: unknown }> {}\n *\n * const iterable = (async function*() {\n * yield 1\n * yield 2\n * yield 3\n * })()\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const stream = Stream.fromAsyncIterable(iterable, (cause) => new StreamError({ cause }))\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 3]\n * }))\n *\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromAsyncIterable = (iterable, onError) => fromChannel(Channel.fromAsyncIterableArray(iterable, onError));\n/**\n * Creates a stream that emits each output of a schedule that does not require input,\n * for as long as the schedule continues.\n *\n * **Example** (Creating a stream from a schedule)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const schedule = Schedule.recurs(3)\n * const stream = Stream.fromSchedule(schedule)\n * const values = yield* Stream.runCollect(stream)\n * values // => [0, 1, 2]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => Pull.catchDone(Effect.map(step(void 0), Arr.of), () => Cause.done())));\n/**\n * Creates a stream from a PubSub subscription.\n *\n * **When to use**\n *\n * Use when you already have a `PubSub.Subscription` and want to expose its\n * messages as a `Stream`, with `Stream.take` or cancellation controlling how\n * many values are consumed.\n *\n * **Example** (Creating a stream from a PubSub subscription)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const pubsub = yield* PubSub.unbounded<number>()\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * yield* PubSub.publish(pubsub, 1)\n * yield* PubSub.publish(pubsub, 2)\n *\n * const stream = Stream.fromSubscription(subscription)\n * const values = yield* stream.pipe(Stream.take(2), Stream.runCollect)\n * values // => [1, 2]\n * }))\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSubscription = pubsub => fromChannel(Channel.fromSubscriptionArray(pubsub));\n/**\n * Creates a stream from an event listener.\n *\n * **Example** (Creating a stream from an event listener)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * class NumberTarget implements Stream.EventListener<number> {\n * addEventListener(event: string, f: (event: number) => void) {\n * if (event === \"data\") {\n * f(1)\n * f(2)\n * f(3)\n * }\n * }\n * removeEventListener(_event: string, _f: (event: number) => void) {}\n * }\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const stream = Stream.fromEventListener(new NumberTarget(), \"data\").pipe(\n * Stream.take(3)\n * )\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 3]\n * }))\n *\n * ```\n *\n * @category constructors\n * @since 3.1.0\n */\nexport const fromEventListener = (target, type, options) => callback(queue => {\n const once = typeof options === \"object\" && options.once;\n function emit(event) {\n Queue.offerUnsafe(queue, event);\n if (once) Queue.endUnsafe(queue);\n }\n return Effect.acquireRelease(Effect.sync(() => target.addEventListener(type, emit, options)), () => Effect.sync(() => target.removeEventListener(type, emit, options)));\n}, {\n bufferSize: typeof options === \"object\" ? options.bufferSize : undefined\n});\n/**\n * Creates a stream by repeatedly applying an effectful step function to a\n * state.\n *\n * **Details**\n *\n * Each `readonly [value, nextState]` result emits `value` and continues with\n * `nextState`; returning `undefined` ends the stream.\n *\n * **Example** (Unfolding stream state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.unfold(1, (n) => Effect.succeed([n, n + 1] as const))\n * const values = yield* Stream.runCollect(stream.pipe(Stream.take(5)))\n * values // => [ 1, 2, 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unfold = (s, f) => fromPull(Effect.sync(() => {\n let state = s;\n return Effect.flatMap(Effect.suspend(() => f(state)), next => {\n if (next === undefined) return Cause.done();\n state = next[1];\n return Effect.succeed(Arr.of(next[0]));\n });\n}));\n/**\n * Creates a stream by repeatedly evaluating an effectful page function.\n *\n * **When to use**\n *\n * Use to consume paginated APIs where each step returns a batch of values\n * together with an optional next state.\n *\n * **Details**\n *\n * This is similar to {@link unfold}, but each step can emit zero or more values\n * and independently decide whether another state should be requested.\n *\n * **Example** (Paginating stream state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.paginate(0, (n: number) =>\n * Effect.succeed(\n * [\n * [n],\n * n < 3 ? Option.some(n + 1) : Option.none<number>()\n * ] as const\n * ))\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [0, 1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const paginate = (s, f) => fromPull(Effect.sync(() => {\n let state = s;\n let done = false;\n return Effect.suspend(function loop() {\n if (done) return Cause.done();\n return Effect.flatMap(f(state), ([a, s]) => {\n if (Option.isNone(s)) {\n done = true;\n } else {\n state = s.value;\n }\n if (!Arr.isReadonlyArrayNonEmpty(a)) return loop();\n return Effect.succeed(a);\n });\n });\n}));\n/**\n * Creates an infinite stream by repeatedly applying a function to a seed value.\n *\n * **Example** (Iterating from a seed value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.iterate(1, (n) => n + 1).pipe(Stream.take(3))\n *\n * const program = Effect.gen(function* () {\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const iterate = (value, next) => unfold(value, a => Effect.succeed([a, next(a)]));\n/**\n * Constructs a stream from a range of integers, including both endpoints.\n *\n * **Details**\n *\n * If the provided `min` is greater than `max`, the stream will not emit any\n * values. Finite fractional `chunkSize` values are rounded down, while `NaN`\n * and non-positive values are treated as `1`.\n *\n * **Example** (Creating a numeric range)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.range(1, 5).pipe(Stream.runCollect)\n * values // => [ 1, 2, 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const range = (min, max, chunkSize = Channel.DefaultChunkSize) => min > max ? empty : fromPull(Effect.sync(() => {\n const size = Count.normalizeNonEmpty(chunkSize);\n let start = min;\n let done = false;\n return Effect.suspend(() => {\n if (done) return Cause.done();\n const remaining = max - start + 1;\n if (remaining > size) {\n const chunk = Arr.range(start, start + size - 1);\n start += size;\n return Effect.succeed(chunk);\n }\n const chunk = Arr.range(start, start + remaining - 1);\n done = true;\n return Effect.succeed(chunk);\n });\n}));\n/**\n * The stream that never produces any value or fails with any error.\n *\n * **Example** (Creating a never-ending stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Stream.never.pipe(\n * Stream.take(0),\n * Stream.runCollect\n * )\n *\n * await Effect.runPromise(program) // => []\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const never = /*#__PURE__*/fromChannel(Channel.never);\n/**\n * Creates a stream produced from an `Effect`.\n *\n * **Example** (Unwrapping a stream effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const effect = Effect.succeed(Stream.make(1, 2, 3))\n *\n * const stream = Stream.unwrap(effect)\n *\n * const program = Effect.gen(function*() {\n * const chunk = yield* Stream.runCollect(stream)\n * chunk // => [ 1, 2, 3 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unwrap = effect => fromChannel(Channel.unwrap(Effect.map(effect, toChannel)));\n/**\n * Runs a stream that requires `Scope` in a managed scope, ensuring its\n * finalizers are run when the stream completes.\n *\n * **Example** (Scoping a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const stream = Stream.scoped(\n * Stream.fromEffect(\n * Effect.acquireRelease(\n * Effect.sync(() => {\n * events.push(\"acquire\")\n * return \"resource\"\n * }),\n * () => Effect.sync(() => events.push(\"release\"))\n * )\n * )\n * )\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [\"resource\"]\n * events // => [\"acquire\", \"release\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const scoped = self => fromChannel(Channel.scoped(self.channel));\n/**\n * Transforms the elements of this stream using the supplied function.\n *\n * **Example** (Mapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.fromArray([1, 2, 3]).pipe(Stream.map((n, i) => n + i))\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 3, 5]\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => suspend(() => {\n let i = 0;\n return fromChannel(Channel.map(self.channel, Arr.map(o => f(o, i++))));\n}));\n/**\n * Maps both the failure and success channels of a stream.\n *\n * **Example** (Mapping both the failure and success channels of a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const mapper = {\n * onFailure: (error: string) => `error: ${error}`,\n * onSuccess: (value: number) => value * 2\n * }\n *\n * const program = Effect.gen(function*() {\n * const success = yield* Stream.make(1, 2).pipe(\n * Stream.mapBoth(mapper),\n * Stream.runCollect\n * )\n * success // => [ 2, 4 ]\n *\n * const failure = yield* Stream.fail(\"boom\").pipe(\n * Stream.mapBoth(mapper),\n * Stream.catch((error: string) => Stream.succeed(error)),\n * Stream.runCollect\n * )\n * failure // => [ 'error: boom' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapBoth = /*#__PURE__*/dual(2, (self, options) => self.pipe(map(options.onSuccess), mapError(options.onFailure)));\n/**\n * Transforms each emitted chunk using the provided function, which receives the chunk and its index.\n *\n * **Example** (Mapping stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.make(1, 2, 3, 4).pipe(\n * Stream.rechunk(2),\n * Stream.mapArray((chunk, index) => Array.map(chunk, (n) => n + index)),\n * Stream.runCollect\n * )\n * result // => [ 1, 2, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapArray = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.map(self.channel, f)));\n/**\n * Maps over elements of the stream with the specified effectful function.\n *\n * **When to use**\n *\n * Use when each stream element transformation needs an Effect, service\n * dependency, failure channel, or configured concurrency.\n *\n * **Example** (Effectfully mapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const stream = Stream.make(1, 2, 3)\n *\n * const mappedStream = stream.pipe(\n * Stream.mapEffect((n) =>\n * Effect.sync(() => {\n * events.push(`Processing: ${n}`)\n * return n * 2\n * })\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(mappedStream)\n * result // => [2, 4, 6]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"Processing: 1\", \"Processing: 2\", \"Processing: 3\"]\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport 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));\n/**\n * Flattens a stream of `Effect` values into a stream of their results.\n *\n * **When to use**\n *\n * Use when stream elements already are effects and their successes should become\n * stream elements while their failures enter the stream error channel.\n *\n * **Example** (Flattening a stream of Effect values into a stream of their results)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(Effect.succeed(1), Effect.succeed(2), Effect.succeed(3))\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(stream.pipe(Stream.flattenEffect()))\n * result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const flattenEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => mapEffect(self, identity, options));\n/**\n * Maps over non-empty array chunks emitted by the stream effectfully.\n *\n * **When to use**\n *\n * Use when transformation needs to see and replace each non-empty emitted chunk\n * effectfully instead of mapping individual stream elements.\n *\n * **Example** (Effectfully mapping stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.fromArray([1, 2, 3, 4]).pipe(\n * Stream.rechunk(2),\n * Stream.mapArrayEffect((chunk, index) =>\n * Effect.succeed(Array.map(chunk, (n) => n + index * 10))\n * ),\n * Stream.runCollect\n * )\n * result // => [ 1, 2, 13, 14 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapArrayEffect = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.mapEffect(self.channel, f)));\n/**\n * Lifts failures and successes into a `Result`, yielding a stream that cannot fail.\n *\n * **Details**\n *\n * The stream ends after the first failure, emitting a `Result.fail` value.\n *\n * **Example** (Converting failures to results)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const results = yield* Stream.make(1, 2).pipe(\n * Stream.concat(Stream.fail(\"boom\")),\n * Stream.result,\n * Stream.map(Result.match({\n * onFailure: (error) => `failure: ${error}`,\n * onSuccess: (value) => `success: ${value}`\n * })),\n * Stream.runCollect\n * )\n * results // => [ 'success: 1', 'success: 2', 'failure: boom' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const result = self => self.pipe(map(Result.succeed), catch_(e => succeed(Result.fail(e))));\n/**\n * Runs the provided effect for each element while preserving the elements.\n *\n * **Example** (Tapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.fromArray([1, 2, 3]).pipe(\n * Stream.tap((n) => Effect.sync(() => events.push(`before mapping: ${n}`))),\n * Stream.map((n) => n * 2),\n * Stream.tap((n) => Effect.sync(() => events.push(`after mapping: ${n}`))),\n * Stream.runCollect\n * )\n *\n * result // => [2, 4, 6]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"before mapping: 1\", \"after mapping: 2\", \"before mapping: 2\", \"after mapping: 4\", \"before mapping: 3\", \"after mapping: 6\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => mapEffect(self, a => Effect.as(f(a), a), options));\n/**\n * Returns a stream that effectfully \"peeks\" at elements and failures.\n *\n * **Example** (Tapping values and errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n * const stream = Stream.make(1, 2).pipe(\n * Stream.concat(Stream.fail(\"boom\")),\n * Stream.tapBoth({\n * onElement: (value) => Effect.sync(() => events.push(`seen: ${value}`)),\n * onError: (error) => Effect.sync(() => events.push(`error: ${error}`))\n * }),\n * Stream.catch(() => Stream.make(3))\n * )\n * const result = yield* Stream.runCollect(stream)\n * result // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"seen: 1\", \"seen: 2\", \"error: boom\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tapBoth = /*#__PURE__*/dual(2, (self, options) => self.pipe(tapError(options.onError), tap(options.onElement, {\n concurrency: options.concurrency\n})));\n/**\n * Runs a sink for all stream elements while still emitting them downstream.\n *\n * **Example** (Tapping values with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref, Sink, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const seen = yield* Ref.make<Array<number>>([])\n * const sink = Sink.forEach((value: number) =>\n * Ref.update(seen, (items) => [...items, value])\n * )\n * const result = yield* Stream.make(1, 2, 3).pipe(\n * Stream.tapSink(sink),\n * Stream.runCollect\n * )\n * const tapped = yield* Ref.get(seen)\n * tapped // => [ 1, 2, 3 ]\n * result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tapSink = /*#__PURE__*/dual(2, (self, sink) => transformPullBracket(self, Effect.fnUntraced(function* (pull, _, scope) {\n const upstreamLatch = Latch.makeUnsafe();\n const sinkLatch = Latch.makeUnsafe();\n let chunk = undefined;\n let causeSink = undefined;\n let sinkDone = false;\n let streamDone = false;\n const sinkUpstream = upstreamLatch.whenOpen(Effect.suspend(() => {\n if (chunk) {\n const arr = chunk;\n chunk = undefined;\n if (!streamDone) upstreamLatch.closeUnsafe();\n return Effect.as(sinkLatch.open, arr);\n }\n return Cause.done();\n }));\n yield* Effect.suspend(() => sink.transform(sinkUpstream, scope)).pipe(eff => Effect.onExitPrimitive(eff, exit => {\n sinkDone = true;\n if (Exit.isFailure(exit)) {\n causeSink = exit.cause;\n }\n return sinkLatch.open;\n }, true), Effect.forkIn(scope));\n const pullAndOffer = pull.pipe(Effect.flatMap(chunk_ => {\n chunk = chunk_;\n sinkLatch.closeUnsafe();\n upstreamLatch.openUnsafe();\n return Effect.as(sinkLatch.await, chunk_);\n }), Pull.catchDone(() => {\n streamDone = true;\n sinkLatch.closeUnsafe();\n upstreamLatch.openUnsafe();\n return Effect.flatMap(sinkLatch.await, () => Cause.done());\n }));\n return Effect.suspend(() => {\n if (causeSink) {\n return Effect.failCause(causeSink);\n } else if (sinkDone) {\n return pull;\n }\n return pullAndOffer;\n });\n})));\n/**\n * Maps each element to a stream and flattens the resulting streams.\n *\n * **Details**\n *\n * With the default sequential concurrency, inner streams are concatenated in\n * input order. When `concurrency` is greater than `1` or `\"unbounded\"`,\n * multiple inner streams may run at the same time and their outputs are merged\n * as they arrive.\n *\n * **Example** (Flat mapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3).pipe(\n * Stream.flatMap((n) => Stream.make(n, n * 2)),\n * Stream.runCollect\n * )\n * values // => [ 1, 2, 2, 4, 3, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.flatMap(a => f(a).channel, options), fromChannel));\n/**\n * Switches to the latest stream produced by the mapping function, interrupting\n * the previous stream when a new element arrives.\n *\n * **Example** (Switching to the latest stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Stream.make(1, 2, 3).pipe(\n * Stream.switchMap((n) => (n === 3 ? Stream.make(n) : Stream.never)),\n * Stream.runCollect\n * )\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const result = yield* program\n * result // => [ 3 ]\n * }))\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const switchMap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.switchMap(a => f(a).channel, options), fromChannel));\n/**\n * Flattens a stream of streams into a single stream.\n *\n * **Details**\n *\n * With the default sequential concurrency, inner streams are concatenated in\n * strict order. When `concurrency` is greater than `1` or `\"unbounded\"`,\n * multiple inner streams may run at the same time and their outputs are merged\n * as they arrive.\n *\n * **Example** (Flattening nested streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const streamOfStreams = Stream.make(\n * Stream.make(1, 2),\n * Stream.make(3, 4),\n * Stream.make(5, 6)\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(Stream.flatten(streamOfStreams))\n * values // => [ 1, 2, 3, 4, 5, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const flatten = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => flatMap(self, identity, options));\n/**\n * Flattens a stream of non-empty arrays into a stream of elements.\n *\n * **Example** (Flattening a stream of non-empty arrays into a stream of elements)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(Array.make(1, 2), Array.make(3))\n *\n * const program = Effect.gen(function* () {\n * const result = yield* Stream.runCollect(Stream.flattenArray(stream))\n * result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const flattenArray = self => fromChannel(Channel.flattenArray(self.channel));\n/**\n * Converts this stream to one that runs its effects but emits no elements.\n *\n * **Example** (Draining stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.range(1, 6).pipe(Stream.drain, Stream.runCollect)\n * result // => []\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const drain = self => fromChannel(Channel.drain(self.channel));\n/**\n * Runs the provided stream in the background while this stream runs, interrupting it\n * when this stream completes and failing if the background stream fails or defects.\n *\n * **Example** (Draining a stream in the background)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const foreground = Stream.make(1, 2)\n * const background = Stream.fromEffect(Effect.sync(() => events.push(\"background task\")))\n *\n * const program = Effect.gen(function*() {\n * const values = yield* foreground.pipe(\n * Stream.drainFork(background),\n * Stream.runCollect\n * )\n * values // => [1, 2]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"background task\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const drainFork = /*#__PURE__*/dual(2, (self, that) => mergeEffect(self, runDrain(that)));\n/**\n * Repeats the entire stream according to the provided schedule.\n *\n * **Example** (Repeating a stream on a schedule)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n * const result = yield* Stream.make(1).pipe(\n * Stream.repeat(Schedule.recurs(4)),\n * Stream.runCollect\n * )\n *\n * result // => [ 1, 1, 1, 1, 1 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const repeat = /*#__PURE__*/dual(2, (self, schedule) => fromChannel(Channel.repeat(self.channel, schedule)));\n/**\n * Schedules the stream's elements according to the provided schedule.\n *\n * **Example** (Scheduling stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.make(1, 2, 3).pipe(\n * Stream.schedule(Schedule.recurs(3)),\n * Stream.runCollect\n * )\n *\n * result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category rate limiting\n * @since 2.0.0\n */\nexport const schedule = /*#__PURE__*/dual(2, (self, schedule) => self.channel.pipe(Channel.flattenArray, Channel.schedule(schedule), Channel.map(Arr.of), fromChannel));\n/**\n * Ends the stream if it does not produce a value within the specified duration.\n *\n * **Example** (Timing out a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1).pipe(\n * Stream.concat(Stream.never),\n * Stream.timeout(\"1 second\"),\n * Stream.runCollect\n * )\n * values // => [ 1 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category delays & timeouts\n * @since 2.0.0\n */\nexport const timeout = /*#__PURE__*/dual(2, (self, duration) => timeoutOrElse(self, {\n duration,\n orElse: () => empty\n}));\n/**\n * Switches to a fallback stream if this stream does not emit a value within\n * the specified duration.\n *\n * **When to use**\n *\n * Use when a stream should continue with another stream if an upstream pull\n * waits longer than the allowed duration.\n *\n * **Details**\n *\n * The timeout is checked for each pull. A zero duration uses `orElse`\n * immediately, while an infinite duration leaves the original stream\n * unchanged.\n *\n * **Gotchas**\n *\n * The fallback stream is not timed after the switch.\n *\n * @see {@link timeout} for ending the stream instead of switching to a fallback stream\n *\n * @category delays & timeouts\n * @since 4.0.0\n */\nexport const timeoutOrElse = /*#__PURE__*/dual(2, (self, options) => {\n const duration = Duration.fromInputUnsafe(options.duration);\n if (!Duration.isFinite(duration)) return self;\n if (Duration.isZero(duration)) return suspend(options.orElse);\n const timeoutSymbol = Symbol();\n return catchCause(suspend(() => {\n const parent = Fiber.getCurrent();\n const clock = parent.getRef(Clock);\n const durationMs = Duration.toMillis(duration);\n let deadline = undefined;\n const latch = Latch.makeUnsafe(false);\n return merge(transformPull(self, (pull, _scope) => Effect.suspend(() => {\n deadline = clock.currentTimeMillisUnsafe() + durationMs;\n latch.openUnsafe();\n return pull;\n }).pipe(Effect.map(arr => {\n latch.closeUnsafe();\n deadline = undefined;\n return arr;\n }), Effect.succeed)), fromEffectDrain(Effect.gen(function* () {\n while (true) {\n yield* latch.await;\n if (deadline === undefined) continue;\n yield* Effect.sleep(deadline - clock.currentTimeMillisUnsafe());\n if (deadline === undefined) continue;\n const remaining = deadline - clock.currentTimeMillisUnsafe();\n if (remaining > 0) continue;\n return yield* Effect.die(timeoutSymbol);\n }\n })), {\n haltStrategy: \"left\"\n });\n }), cause => {\n const isTimeout = cause.reasons.find(r => r._tag === \"Die\" && r.defect === timeoutSymbol);\n if (isTimeout) return options.orElse();\n return failCause(cause);\n });\n});\n/**\n * Repeats each element of the stream according to the provided schedule,\n * including the original emission.\n *\n * **Example** (Repeating stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(\"A\", \"B\", \"C\").pipe(\n * Stream.repeatElements(Schedule.recurs(1)),\n * Stream.runCollect\n * )\n * values // => [ 'A', 'A', 'B', 'B', 'C', 'C' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const repeatElements = /*#__PURE__*/dual(2, (self, schedule) => fromChannel(Channel.fromTransform((upstream, scope) => Effect.map(Channel.toTransform(Channel.flattenArray(self.channel))(upstream, scope), pullElement => {\n let pullRepeat = undefined;\n const pull = Effect.gen(function* () {\n const element = yield* pullElement;\n const chunk = Arr.of(element);\n const step = yield* Schedule.toStepWithSleep(schedule);\n pullRepeat = step(element).pipe(Effect.as(chunk), Pull.catchDone(_ => {\n pullRepeat = undefined;\n return pull;\n }));\n return chunk;\n });\n return Effect.suspend(() => pullRepeat ?? pull);\n}))));\n/**\n * Repeats this stream forever.\n *\n * **Example** (Repeating a stream forever)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"A\", \"B\").pipe(\n * Stream.forever,\n * Stream.take(5)\n * )\n *\n * const program = Effect.gen(function*() {\n * const output = yield* Stream.runCollect(stream)\n * output // => [ 'A', 'B', 'A', 'B', 'A' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const forever = self => fromChannel(Channel.forever(self.channel));\n/**\n * Flattens the iterables emitted by this stream into the stream's structure.\n *\n * **Example** (Flattening iterable values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.make([1, 2], [3, 4]).pipe(Stream.flattenIterable)\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 1, 2, 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const flattenIterable = self => flatMap(self, fromIterable);\n/**\n * Unwraps `Take` values, emitting elements from non-empty arrays and ending or\n * failing when the `Exit` signals completion.\n *\n * **Example** (Flattening Take values)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Exit, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const takes = Stream.make(\n * Array.make(1, 2),\n * Array.make(3),\n * Exit.succeed<void>(undefined)\n * )\n *\n * const values = yield* Stream.flattenTake(takes).pipe(Stream.runCollect)\n * values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flattenTake = self => self.channel.pipe(Channel.flattenArray, Channel.flattenTake, fromChannel);\n/**\n * Concatenates two streams, emitting all elements from the first stream\n * followed by all elements from the second stream.\n *\n * **Example** (Concatenating streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.concat(Stream.make(1, 2, 3), Stream.make(4, 5, 6))\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 1, 2, 3, 4, 5, 6 ]\n * }))\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const concat = /*#__PURE__*/dual(2, (self, that) => flatten(fromArray([self, that])));\n/**\n * Prepends the values from the provided iterable before the stream's elements.\n *\n * **Example** (Prepending values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(3, 4).pipe(\n * Stream.prepend([1, 2]),\n * Stream.runCollect\n * )\n *\n * values // => [ 1, 2, 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const prepend = /*#__PURE__*/dual(2, (self, values) => concat(fromIterable(values), self));\n/**\n * Merges two streams, emitting elements from both as they arrive.\n *\n * **Details**\n *\n * By default, the merged stream ends when both streams end. Use\n * `haltStrategy` to change the termination behavior.\n *\n * **Example** (Merging stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const fast = Stream.make(1, 2, 3)\n * const slow = Stream.fromEffect(Effect.delay(Effect.succeed(4), \"50 millis\"))\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(Stream.merge(fast, slow))\n * result // => [ 1, 2, 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const merge = /*#__PURE__*/dual(args => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel(Channel.merge(toChannel(self), toChannel(that), options)));\n/**\n * Merges this stream with a background effect, keeping the stream's elements.\n *\n * **When to use**\n *\n * Use when an effect should run concurrently for the lifetime of a stream while\n * only the stream's elements remain in the output.\n *\n * **Details**\n *\n * The effect runs concurrently, fails the stream if it fails, and is interrupted\n * when the stream completes.\n *\n * **Example** (Merging with a background effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3).pipe(\n * Stream.mergeEffect(Effect.sync(() => events.push(\"side task\"))),\n * Stream.runCollect\n * )\n *\n * values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"side task\"]\n * ```\n *\n * @category merging\n * @since 4.0.0\n */\nexport const mergeEffect = /*#__PURE__*/dual(2, (self, effect) => self.channel.pipe(Channel.mergeEffect(effect), fromChannel));\n/**\n * Merges this stream and the specified stream together, tagging values from the\n * left stream as `Result.succeed` and values from the right stream as `Result.fail`.\n *\n * **When to use**\n *\n * Use when values from both streams should be emitted and downstream code needs\n * left values wrapped as successful `Result` values and right values wrapped as\n * failed `Result` values.\n *\n * **Example** (Merging streams into results)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result, Stream } from \"effect\"\n *\n * const left = Stream.fromEffect(Effect.succeed(\"left\"))\n * const right = Stream.fromEffect(Effect.delay(Effect.succeed(\"right\"), \"10 millis\"))\n *\n * const merged = left.pipe(\n * Stream.mergeResult(right),\n * Stream.map(\n * Result.match({\n * onFailure: (value) => `right:${value}`,\n * onSuccess: (value) => `left:${value}`\n * })\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(merged)\n * result // => [ 'left:left', 'right:right' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 4.0.0\n */\nexport const mergeResult = /*#__PURE__*/dual(2, (self, that) => merge(map(self, Result.succeed), map(that, Result.fail)));\n/**\n * Merges two streams while emitting only the values from the left stream.\n *\n * **When to use**\n *\n * Use when the right stream is needed for its effects or failures, but downstream\n * consumers should only receive values from the left stream.\n *\n * **Details**\n *\n * The right stream still runs for its effects, and any failures from the right\n * stream are propagated. The merged stream completes when the left stream\n * completes, interrupting the right stream.\n *\n * **Example** (Merging streams while keeping left values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const left = Stream.make(1, 2)\n * const right = Stream.make(\"a\", \"b\")\n * const values = yield* left.pipe(Stream.mergeLeft(right), Stream.runCollect)\n * values // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const mergeLeft = /*#__PURE__*/dual(2, (left, right) => mergeEffect(left, runDrain(right)));\n/**\n * Merges this stream and the specified stream together, emitting only the\n * values from the right stream while the left stream runs for its effects.\n *\n * **When to use**\n *\n * Use when the left stream is needed for its effects or failures, but downstream\n * consumers should only receive values from the right stream.\n *\n * **Details**\n *\n * The merged stream ends when the right stream completes, interrupting the\n * left stream. Failures from the left stream still fail the merged stream.\n *\n * **Example** (Merging streams while keeping right values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const left = Stream.make(\"left-1\", \"left-2\").pipe(\n * Stream.tap(() => Effect.sync(() => undefined))\n * )\n * const right = Stream.make(1, 2)\n *\n * const merged = Stream.mergeRight(left, right)\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(merged)\n * result // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const mergeRight = /*#__PURE__*/dual(2, (left, right) => mergeEffect(right, runDrain(left)));\n/**\n * Merges a collection of streams, running up to the specified number concurrently.\n *\n * **When to use**\n *\n * Use to merge an iterable of already-created streams while bounding how many\n * inner streams may run at the same time.\n *\n * **Details**\n *\n * The `concurrency` option is required and may be a number or `\"unbounded\"`.\n * `bufferSize` controls buffering between inner streams, and outputs are\n * emitted as they arrive under concurrent merging.\n *\n * **Example** (Merging streams with bounded concurrency)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const streams = [\n * Stream.fromEffect(Effect.delay(Effect.succeed(\"A\"), \"20 millis\")),\n * Stream.fromEffect(Effect.delay(Effect.succeed(\"B\"), \"10 millis\"))\n * ]\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.mergeAll(streams, { concurrency: 2 }).pipe(\n * Stream.runCollect\n * )\n * values // => [ 'B', 'A' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link merge} for merging exactly two streams and choosing a halt strategy\n * @see {@link flatten} for flattening a stream that already emits streams\n *\n * @category merging\n * @since 2.0.0\n */\nexport const mergeAll = /*#__PURE__*/dual(2, (streams, options) => flatten(fromIterable(streams), options));\n/**\n * Creates the cartesian product of two streams, running the `right` stream for\n * each element in the `left` stream.\n *\n * **Details**\n *\n * See also `Stream.zip` for the more common point-wise variant.\n *\n * **Example** (Computing cartesian products)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const left = Stream.make(1, 2)\n * const right = Stream.make(\"a\", \"b\")\n * const values = yield* Stream.runCollect(Stream.cross(left, right))\n * values // => [ [ 1, 'a' ], [ 1, 'b' ], [ 2, 'a' ], [ 2, 'b' ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const cross = /*#__PURE__*/dual(2, (left, right) => crossWith(left, right, (l, r) => [l, r]));\n/**\n * Creates a cartesian product of elements from two streams using a function.\n *\n * **Details**\n *\n * The `right` stream is rerun for every element in the `left` stream.\n *\n * See also `Stream.zipWith` for the more common point-wise variant.\n *\n * **Example** (Combining cartesian products)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const left = Stream.make(1, 2)\n * const right = Stream.make(\"a\", \"b\")\n * const combined = Stream.crossWith(left, right, (n, s) => `${n}-${s}`)\n * const result = yield* Stream.runCollect(combined)\n * result // => [ '1-a', '1-b', '2-a', '2-b' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const crossWith = /*#__PURE__*/dual(3, (left, right, f) => flatMap(left, l => map(right, r => f(l, r))));\n/**\n * Zips two streams point-wise with a combining function, ending when either stream ends.\n *\n * **Example** (Zipping streams with a function)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream1 = Stream.make(1, 2, 3, 4, 5, 6)\n * const stream2 = Stream.make(\"a\", \"b\", \"c\")\n *\n * const zipped = Stream.zipWith(stream1, stream2, (n, s) => `${n}-${s}`)\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(zipped)\n * result // => [ '1-a', '2-b', '3-c' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith = /*#__PURE__*/dual(3, (left, right, f) => zipWithArray(left, right, zipArrays(f)));\nconst zipArrays = f => (leftArr, rightArr) => {\n const minLength = Math.min(leftArr.length, rightArr.length);\n const result = [];\n for (let i = 0; i < minLength; i++) {\n result.push(f(leftArr[i], rightArr[i]));\n }\n return [result, leftArr.slice(minLength), rightArr.slice(minLength)];\n};\n/**\n * Zips two streams by applying a function to non-empty arrays of elements.\n *\n * **Details**\n *\n * The function returns output plus leftover arrays that carry into the next pull.\n *\n * **Example** (Zipping stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Stream } from \"effect\"\n *\n * const left = Stream.fromArrays([1, 2, 3], [4, 5])\n * const right = Stream.fromArrays([\"a\", \"b\"], [\"c\", \"d\", \"e\"])\n *\n * const zipped = Stream.zipWithArray(left, right, (leftChunk, rightChunk) => {\n * const minLength = Math.min(leftChunk.length, rightChunk.length)\n * const output = Array.makeBy(minLength, (i) => [leftChunk[i], rightChunk[i]] as const)\n *\n * return [output, leftChunk.slice(minLength), rightChunk.slice(minLength)]\n * })\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(zipped)\n * result // => [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ], [ 4, 'd' ], [ 5, 'e' ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 4.0.0\n */\nexport const zipWithArray = /*#__PURE__*/dual(3, (left, right, f) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_, scope) {\n const pullLeft = yield* Channel.toPullScoped(left.channel, scope);\n const pullRight = yield* Channel.toPullScoped(right.channel, scope);\n const pullBoth = Effect.gen(function* () {\n const fiberLeft = yield* Effect.forkIn(pullLeft, scope);\n const fiberRight = yield* Effect.forkIn(pullRight, scope);\n return yield* Fiber.joinAll([fiberLeft, fiberRight]);\n });\n let state = {\n _tag: \"PullBoth\"\n };\n const pull = Effect.gen(function* () {\n const [left, right] = state._tag === \"PullBoth\" ? yield* pullBoth : state._tag === \"PullLeft\" ? [yield* pullLeft, state.rightArray] : [state.leftArray, yield* pullRight];\n const result = f(left, right);\n if (Arr.isReadonlyArrayNonEmpty(result[1])) {\n state = {\n _tag: \"PullRight\",\n leftArray: result[1]\n };\n } else if (Arr.isReadonlyArrayNonEmpty(result[2])) {\n state = {\n _tag: \"PullLeft\",\n rightArray: result[2]\n };\n } else {\n state = {\n _tag: \"PullBoth\"\n };\n }\n return result[0];\n });\n return pull;\n}))));\n/**\n * Zips this stream with another point-wise and emits tuples of elements from\n * both streams. The new stream ends when either stream ends.\n *\n * **Example** (Zipping streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream1 = Stream.make(1, 2, 3)\n * const stream2 = Stream.make(\"a\", \"b\", \"c\")\n *\n * const zipped = Stream.zip(stream1, stream2)\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(zipped)\n * result // => [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zip = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, (a, a2) => [a, a2]));\n/**\n * Zips this stream with another point-wise and keeps only the values from\n * the left stream.\n *\n * **Details**\n *\n * The resulting stream ends when either side ends.\n *\n * **Example** (Zipping streams while keeping left values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream1 = Stream.make(1, 2, 3, 4)\n * const stream2 = Stream.make(\"a\", \"b\")\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.zipLeft(stream1, stream2).pipe(Stream.runCollect)\n * result // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipLeft = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => {\n const minLength = Math.min(leftArr.length, rightArr.length);\n const output = leftArr.slice(0, minLength);\n const leftoverLeft = leftArr.slice(minLength);\n const leftoverRight = rightArr.slice(minLength);\n return [output, leftoverLeft, leftoverRight];\n}));\n/**\n * Zips this stream with another point-wise, keeping only right values and ending when either stream ends.\n *\n * **Example** (Zipping streams while keeping right values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream1 = Stream.make(1, 2)\n * const stream2 = Stream.make(\"a\", \"b\", \"c\", \"d\")\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.zipRight(stream1, stream2).pipe(Stream.runCollect)\n * result // => [ 'a', 'b' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipRight = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => {\n const minLength = Math.min(leftArr.length, rightArr.length);\n const output = rightArr.slice(0, minLength);\n const leftoverLeft = leftArr.slice(minLength);\n const leftoverRight = rightArr.slice(minLength);\n return [output, leftoverLeft, leftoverRight];\n}));\n/**\n * Zips this stream with another point-wise and emits tuples of elements from\n * both streams, flattening the left tuple.\n *\n * **Details**\n *\n * The new stream will end when one of the sides ends.\n *\n * **Example** (Zipping and flattening tuples)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream1 = Stream.make(\n * [1, \"a\"] as const,\n * [2, \"b\"] as const,\n * [3, \"c\"] as const\n * )\n * const stream2 = Stream.make(\"x\", \"y\", \"z\")\n * const result = yield* Stream.zipFlatten(stream1, stream2).pipe(Stream.runCollect)\n *\n * result // => [ [ 1, 'a', 'x' ], [ 2, 'b', 'y' ], [ 3, 'c', 'z' ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipFlatten = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, (a, a2) => [...a, a2]));\n/**\n * Zips this stream together with the index of elements.\n *\n * **Example** (Zipping elements with indices)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const indexed = yield* Stream.make(\"a\", \"b\", \"c\", \"d\").pipe(\n * Stream.zipWithIndex,\n * Stream.runCollect\n * )\n * indexed // => [ [ 'a', 0 ], [ 'b', 1 ], [ 'c', 2 ], [ 'd', 3 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWithIndex = self => map(self, (a, i) => [a, i]);\n/**\n * Zips each element with the next element, pairing the final element with\n * `Option.none()`.\n *\n * **Example** (Zipping elements with next values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.zipWithNext(Stream.make(1, 2, 3, 4))\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [[1, Option.some(2)], [2, Option.some(3)], [3, Option.some(4)], [4, Option.none()]]\n * }))\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWithNext = self => mapAccumArray(self, Option.none, (acc, arr) => {\n let i = 0;\n if (acc._tag === \"None\") {\n i = 1;\n acc = Option.some(arr[0]);\n }\n const pairs = Arr.empty();\n for (; i < arr.length; i++) {\n const value = acc.value;\n acc = Option.some(arr[i]);\n pairs.push([value, acc]);\n }\n return [acc, pairs];\n}, {\n onHalt(state) {\n return state._tag === \"Some\" ? [[state.value, Option.none()]] : [];\n }\n});\n/**\n * Zips each element with its previous element, starting with `None`.\n *\n * **Example** (Zipping elements with previous values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.zipWithPrevious(Stream.make(1, 2, 3, 4))\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(stream)\n * result // => [[Option.none(), 1], [Option.some(1), 2], [Option.some(2), 3], [Option.some(3), 4]]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWithPrevious = self => mapAccumArray(self, Option.none, (acc, arr) => {\n const pairs = Arr.empty();\n for (let i = 0; i < arr.length; i++) {\n const value = arr[i];\n pairs.push([acc, value]);\n acc = Option.some(arr[i]);\n }\n return [acc, pairs];\n});\n/**\n * Zips each element with its previous and next values.\n *\n * **Example** (Zipping elements with neighbors)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Option, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3).pipe(\n * Stream.zipWithPreviousAndNext,\n * Stream.runCollect\n * )\n * values // => [[Option.none(), 1, Option.some(2)], [Option.some(1), 2, Option.some(3)], [Option.some(2), 3, Option.none()]]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWithPreviousAndNext = self => mapAccumArray(self, () => ({\n prev: Option.none(),\n current: Option.none()\n}), (acc, arr) => {\n let i = 0;\n let current;\n if (acc.current._tag === \"None\") {\n i = 1;\n current = arr[0];\n acc.current = Option.some(current);\n } else {\n current = acc.current.value;\n }\n const pairs = Arr.empty();\n for (; i < arr.length; i++) {\n const element = arr[i];\n acc.current = Option.some(element);\n pairs.push([acc.prev, current, acc.current]);\n acc.prev = Option.some(current);\n current = element;\n }\n return [acc, pairs];\n}, {\n onHalt(acc) {\n return acc.current._tag === \"Some\" ? [[acc.prev, acc.current.value, Option.none()]] : [];\n }\n});\n/**\n * Zips multiple streams so that when a value is emitted by any stream, it is\n * combined with the latest values from the other streams to produce a result.\n *\n * **When to use**\n *\n * Use when each stream should contribute its latest value after all streams have\n * emitted at least once.\n *\n * **Gotchas**\n *\n * Note: tracking the latest value is done on a per-array basis. That means\n * that emitted elements that are not the last value in arrays will never be\n * used for zipping.\n *\n * **Example** (Zipping latest values from many streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.zipLatestAll(\n * Stream.make(1, 2, 3).pipe(Stream.rechunk(1)),\n * Stream.make(\"a\", \"b\", \"c\").pipe(Stream.rechunk(1)),\n * Stream.make(true, false, true).pipe(Stream.rechunk(1))\n * )\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(stream)\n * result // => [[1, \"a\", true], [2, \"a\", true], [2, \"b\", true], [2, \"b\", false], [3, \"b\", false], [3, \"c\", false], [3, \"c\", true]]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 3.3.0\n */\nexport const zipLatestAll = (...streams) => fromChannel(Channel.suspend(() => {\n const latest = [];\n const emitted = new Set();\n const readyLatch = Latch.makeUnsafe();\n return Channel.mergeAll(Channel.fromArray(streams.map((s, i) => s.channel.pipe(Channel.flattenArray, Channel.mapEffect(a => {\n latest[i] = a;\n if (!emitted.has(i)) {\n emitted.add(i);\n if (emitted.size < streams.length) {\n return readyLatch.await;\n }\n return Effect.as(readyLatch.open, Arr.of(latest.slice()));\n }\n return Effect.succeed(Arr.of(latest.slice()));\n }), Channel.filter(isNotUndefined)))), {\n concurrency: \"unbounded\",\n bufferSize: 0\n });\n}));\n/**\n * Combines two streams by emitting each new element with the latest value from the other stream.\n *\n * **When to use**\n *\n * Use when two streams should start emitting combined pairs after both have\n * produced at least one value.\n *\n * **Gotchas**\n *\n * Note: tracking the latest value is done on a per-array basis. That means\n * that emitted elements that are not the last value in arrays will never be\n * used for zipping.\n *\n * **Example** (Zipping latest values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.zipLatest(\n * Stream.make(1),\n * Stream.make(\"a\")\n * ).pipe(Stream.runCollect)\n *\n * result // => [ [ 1, 'a' ] ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipLatest = /*#__PURE__*/dual(2, (left, right) => zipLatestAll(left, right));\n/**\n * Combines the latest values from both streams whenever either emits, using\n * the provided function.\n *\n * **When to use**\n *\n * Use when two streams should start emitting custom combined values after both\n * have produced at least one value.\n *\n * **Gotchas**\n *\n * Note: tracking the latest value is done on a per-array basis. That means\n * that emitted elements that are not the last value in arrays will never be\n * used for zipping.\n *\n * **Example** (Zipping latest values with a function)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const result = yield* Stream.make(1, 2, 3).pipe(\n * Stream.rechunk(1),\n * Stream.zipLatestWith(\n * Stream.make(10, 20).pipe(Stream.rechunk(1)),\n * (n, m) => n + m\n * ),\n * Stream.runCollect\n * )\n *\n * result // => [ 11, 12, 22, 23 ]\n * }))\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipLatestWith = /*#__PURE__*/dual(3, (left, right, f) => map(zipLatestAll(left, right), ([a, a2]) => f(a, a2)));\n/**\n * Runs all streams concurrently until one stream emits its first value, then\n * mirrors that winning stream and interrupts the rest.\n *\n * **Details**\n *\n * Failures or completion from losing streams before a winner is chosen are\n * ignored unless every stream fails or completes before emitting. After a\n * winner is chosen, that stream's later failures are propagated.\n *\n * **Example** (Racing multiple streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.raceAll(\n * Stream.empty,\n * Stream.make(0, 1, 2)\n * ).pipe(Stream.runCollect)\n * result // => [ 0, 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category racing\n * @since 3.5.0\n */\nexport const raceAll = (...streams) => fromChannel(Channel.fromTransform((_, scope) => Effect.sync(() => {\n let winner;\n const race = Effect.raceAll(streams.map(stream => {\n const childScope = Scope.forkUnsafe(scope);\n return Channel.toPullScoped(stream.channel, childScope).pipe(Effect.flatMap(pull => Effect.zip(Effect.succeed(pull), pull)), Effect.onExit(exit => {\n if (exit._tag === \"Success\") {\n if (winner) {\n return Scope.close(childScope, exit);\n }\n winner = exit.value[0];\n return Effect.void;\n }\n return Scope.close(childScope, exit);\n }), Effect.map(([, chunk]) => chunk));\n }));\n return Effect.suspend(() => winner ?? race);\n})));\n/**\n * Runs both streams concurrently until one stream emits its first value, then\n * mirrors that winning stream and interrupts the other.\n *\n * **Details**\n *\n * A failure or completion from one side before the other side emits does not\n * win the race unless both sides fail or complete before emitting. After a\n * winner is chosen, that stream's later failures are propagated.\n *\n * **Example** (Racing two streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.race(\n * Stream.empty,\n * Stream.make(0, 1, 2)\n * )\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(stream)\n * result // => [ 0, 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category racing\n * @since 3.7.0\n */\nexport const race = /*#__PURE__*/dual(2, (left, right) => raceAll(left, right));\n/**\n * Filters a stream to the elements that satisfy a predicate.\n *\n * **Example** (Filtering stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.make(1, 2, 3, 4).pipe(\n * Stream.filter((n) => n % 2 === 0)\n * )\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 2, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => fromChannel(Channel.filterArray(toChannel(self), predicate)));\n/**\n * Filters and maps stream elements in one pass using a `Filter`.\n *\n * **When to use**\n *\n * Use to keep only stream elements accepted by a `Filter` and emit each filter\n * success value.\n *\n * **Details**\n *\n * `Result.succeed` values are emitted and `Result.fail` values are skipped.\n *\n * @see {@link filter} for keeping original elements with a boolean predicate or refinement\n * @see {@link filterMapEffect} for an effectful `Filter`\n * @see {@link partition} for consuming both filter success and failure values\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, filter) => fromChannel(Channel.filterMapArray(toChannel(self), filter)));\n/**\n * Filters elements in a single pass effectfully.\n *\n * **Example** (Effectfully filtering stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4).pipe(Stream.filterEffect((n) => Effect.succeed(n > 2)))\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(stream)\n * result // => [ 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterEffect = /*#__PURE__*/dual(2, (self, predicate) => fromChannel(Channel.filterArrayEffect(toChannel(self), predicate)));\n/**\n * Filters and maps elements in one pass effectfully using a `FilterEffect`.\n *\n * **When to use**\n *\n * Use to apply effectful logic that can reject stream elements or emit\n * transformed values before they continue downstream.\n *\n * **Details**\n *\n * `Result.succeed` values are emitted, `Result.fail` values are skipped, and\n * effect failures fail the stream.\n *\n * @see {@link filterMap} for the synchronous `Filter` variant\n * @see {@link filterEffect} for effectfully keeping original elements\n * @see {@link mapEffect} for effectfully transforming every element\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromChannel(Channel.filterMapArrayEffect(toChannel(self), filter)));\n/**\n * Partitions a stream using a `Filter` and exposes passing and failing values\n * as scoped queues.\n *\n * **Details**\n *\n * The queues are backed by a fiber in the current scope and should be consumed\n * while that scope remains open. Each queue fails with the stream error or\n * `Cause.Done` when the source ends.\n *\n * **Example** (Partitioning a stream into queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const [passes, fails] = yield* Stream.make(1, 2, 3, 4).pipe(\n * Stream.partitionQueue((n) => n % 2 === 0 ? Result.succeed(n) : Result.fail(n))\n * )\n *\n * const passValues = yield* Stream.fromQueue(passes).pipe(Stream.runCollect)\n * const failValues = yield* Stream.fromQueue(fails).pipe(Stream.runCollect)\n *\n * passValues // => [ 2, 4 ]\n * failValues // => [ 1, 3 ]\n * })\n *\n * await Effect.runPromise(Effect.scoped(program))\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const partitionQueue = /*#__PURE__*/dual(args => isStream(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, filter, options) {\n const scope = yield* Effect.scope;\n const pull = yield* Channel.toPullScoped(self.channel, scope);\n const capacity = options?.capacity === \"unbounded\" ? undefined : options?.capacity ?? DefaultChunkSize;\n const passes = yield* Queue.make({\n capacity\n });\n const fails = yield* Queue.make({\n capacity\n });\n yield* Effect.gen(function* () {\n while (true) {\n const chunk = yield* pull;\n const excluded = [];\n const satisfying = [];\n for (let i = 0; i < chunk.length; i++) {\n const result = filter(chunk[i]);\n if (Result.isFailure(result)) {\n excluded.push(result.failure);\n } else {\n satisfying.push(result.success);\n }\n }\n let passFiber = undefined;\n if (satisfying.length > 0) {\n const leftover = Queue.offerAllUnsafe(passes, satisfying);\n if (leftover.length > 0) {\n passFiber = yield* Effect.forkChild(Queue.offerAll(passes, leftover));\n }\n }\n if (excluded.length > 0) {\n const leftover = Queue.offerAllUnsafe(fails, excluded);\n if (leftover.length > 0) {\n yield* Queue.offerAll(fails, leftover);\n }\n }\n if (passFiber) yield* Fiber.join(passFiber);\n }\n }).pipe(Effect.onError(cause => {\n Queue.failCauseUnsafe(passes, cause);\n Queue.failCauseUnsafe(fails, cause);\n return Effect.void;\n }), Effect.forkIn(scope));\n return [passes, fails];\n}));\n/**\n * Splits a stream with an effectful `Filter`, returning scoped streams for\n * filter successes and failures.\n *\n * **When to use**\n *\n * Use when you need to classify each stream element with an effectful `Filter`\n * and consume both passing and failing mapped values as streams.\n *\n * **Details**\n *\n * The returned streams are backed by queues in the current scope and should be\n * consumed while that scope remains open. The first stream emits success values\n * from the filter, and the second emits failure values.\n *\n * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream\n * @see {@link partitionQueue} for the lower-level queue result\n * @see {@link filterMapEffect} for effectful filtering that discards failed filter results\n *\n * @category filtering\n * @since 4.0.0\n */\nexport 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)]));\n/**\n * Splits a stream into scoped excluded and satisfying substreams using a\n * `Filter`.\n *\n * **Details**\n *\n * The returned streams are backed by queues in the current scope and should be\n * consumed while that scope remains open. The faster stream may advance up to\n * `bufferSize` elements ahead of the slower one.\n *\n * **Example** (Partitioning a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const [excluded, satisfying] = yield* Stream.partition(\n * Stream.make(1, 2, 3, 4),\n * (n) => n % 2 === 0 ? Result.succeed(n) : Result.fail(n)\n * )\n * const left = yield* Stream.runCollect(excluded)\n * const right = yield* Stream.runCollect(satisfying)\n * left // => [ 1, 3 ]\n * right // => [ 2, 4 ]\n * })\n * await Effect.runPromise(Effect.scoped(program))\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partition = /*#__PURE__*/dual(args => isStream(args[0]), (self, filter, options) => Effect.map(partitionQueue(self, filter, {\n capacity: options?.bufferSize ?? 16\n}), ([passes, fails]) => [fromQueue(fails), fromQueue(passes)]));\n/**\n * Returns the specified stream if the given condition is satisfied, otherwise\n * returns an empty stream.\n *\n * **Example** (Conditionally keeping a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(\n * Stream.when(Stream.make(1, 2, 3), Effect.succeed(false))\n * )\n * result // => []\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const when = /*#__PURE__*/dual(2, (self, test) => test.pipe(Effect.map(pass => pass ? self : empty), unwrap));\n/**\n * Runs a sink to peel off enough elements to produce a value and returns that\n * value with the remaining stream in a scope.\n *\n * **Details**\n *\n * The returned stream is only valid within the scope.\n *\n * **Example** (Peeling a stream with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const stream = Stream.fromArrays([1, 2, 3], [4, 5, 6])\n * const sink = Sink.take<number>(3)\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * const [peeled, rest] = yield* Stream.peel(stream, sink)\n * const remaining = yield* Stream.runCollect(rest)\n * const result = [peeled, remaining] // => [[1, 2, 3], [4, 5, 6]]\n * })\n * )\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const peel = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, sink) {\n let cause = undefined;\n const originalPull = yield* Channel.toPull(self.channel);\n const pull = Effect.catchCause(originalPull, cause_ => {\n cause = cause_;\n return Effect.failCause(cause_);\n });\n let stream = fromPull(Effect.succeed(pull));\n const leftover = yield* run(stream, sink);\n if (cause) return [leftover, empty];\n stream = fromPull(Effect.succeed(originalPull));\n return [leftover, stream];\n}));\n/**\n * Buffers up to `capacity` elements so a faster producer can progress\n * independently of a slower consumer.\n *\n * **Details**\n *\n * Finite buffers use the configured queue strategy: `\"suspend\"` applies\n * backpressure, while `\"dropping\"` and `\"sliding\"` may discard elements when\n * the buffer is full. This combinator destroys chunking; use `Stream.rechunk`\n * afterward if you need fixed chunk sizes.\n *\n * **Example** (Buffering stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3).pipe(\n * Stream.buffer({ capacity: 1 }),\n * Stream.runCollect\n * )\n * values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category buffering\n * @since 2.0.0\n */\nexport const buffer = /*#__PURE__*/dual(2, (self, options) => fromChannel(Channel.bufferArray(self.channel, options)));\n/**\n * Allows a faster producer to progress independently of a slower consumer by\n * buffering up to `capacity` chunks in a queue.\n *\n * **Details**\n *\n * Finite buffers use the configured queue strategy: `\"suspend\"` applies\n * backpressure, while `\"dropping\"` and `\"sliding\"` may discard chunks when the\n * buffer is full. This combinator preserves chunking and is best with\n * power-of-2 capacities.\n *\n * **Example** (Buffering stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.fromArrays([1, 2], [3, 4]).pipe(\n * Stream.bufferArray({ capacity: 2 }),\n * Stream.runCollect\n * )\n * result // => [ 1, 2, 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category buffering\n * @since 4.0.0\n */\nexport const bufferArray = /*#__PURE__*/dual(2, (self, options) => fromChannel(Channel.buffer(self.channel, options)));\n/**\n * Switches over to the stream produced by the provided function in case this\n * one fails. Allows recovery from all causes of failure, including\n * interruption if the stream is uninterruptible.\n *\n * **Example** (Catching stream causes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2).pipe(\n * Stream.concat(Stream.fail(\"Oops!\")),\n * Stream.concat(Stream.make(3, 4))\n * )\n *\n * const recovered = stream.pipe(\n * Stream.catchCause(() => Stream.make(999))\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(recovered)\n * values // => [ 1, 2, 999 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchCause = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.catchCause(cause => f(cause).channel), fromChannel));\n/**\n * Recovers from defects using the provided function.\n *\n * **Details**\n *\n * Typed failures and interruptions are not caught.\n *\n * **Example** (Recovering from a defect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.die(\"boom\").pipe(\n * Stream.catchDefect((defect) => Stream.succeed(`recovered: ${defect}`))\n * )\n *\n * const result = Effect.runSync(Stream.runCollect(stream))\n * result // => [\"recovered: boom\"]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchDefect = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.catchDefect(defect => f(defect).channel), fromChannel));\n/**\n * Runs an effect when the stream fails without changing its values or error,\n * unless the tap effect itself fails.\n *\n * **Example** (Tapping stream causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Stream } from \"effect\"\n *\n * const observations: Array<boolean> = []\n * const stream = Stream.make(1, 2).pipe(\n * Stream.concat(Stream.fail(\"boom\")),\n * Stream.tapCause((cause) => Effect.sync(() => observations.push(Cause.isReason(cause)))),\n * Stream.catch(() => Stream.succeed(0))\n * )\n *\n * const program = Effect.gen(function* () {\n * const result = yield* Stream.runCollect(stream)\n * result // => [1, 2, 0]\n * })\n *\n * await Effect.runPromise(program)\n * observations // => [false]\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const tapCause = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.tapCause(f), fromChannel));\nconst catch_ = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.catch(self.channel, error => f(error).channel)));\nexport {\n/**\n * Switches over to the stream produced by the provided function if this one fails.\n *\n * **Example** (Catching stream failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2).pipe(\n * Stream.concat(Stream.fail(\"Oops!\")),\n * Stream.catch(() => Stream.make(999))\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 1, 2, 999 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\ncatch_ as catch };\n/**\n * Peeks at errors effectfully without changing the stream unless the tap fails.\n *\n * **Example** (Effectfully peeking at errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const errors: Array<string> = []\n * const stream = Stream.make(1, 2).pipe(\n * Stream.concat(Stream.fail(\"boom\")),\n * Stream.tapError((error) => Effect.sync(() => errors.push(error))),\n * Stream.catch(() => Stream.make(999))\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 999]\n * })\n *\n * await Effect.runPromise(program)\n * errors // => [\"boom\"]\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const tapError = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.tapError(f), fromChannel));\n/**\n * Recovers from errors that match a predicate by switching to a recovery stream.\n *\n * **Details**\n *\n * When a failure matches the filter, the stream switches to the recovery\n * stream. Non-matching failures propagate downstream, so the error type is\n * preserved unless the filter narrows it.\n *\n * **Example** (Catching matching failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2).pipe(\n * Stream.concat(Stream.fail(42)),\n * Stream.catchIf(\n * (error): error is 42 => error === 42,\n * () => Stream.make(999)\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 1, 2, 999 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport 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))));\n/**\n * Recovers from errors that match a `Filter` by switching to a recovery\n * stream.\n *\n * **When to use**\n *\n * Use to recover from stream errors with a reusable `Filter` when matching can\n * also narrow or transform the error before choosing the recovery stream.\n *\n * **Details**\n *\n * Successful filter results are passed to `f`. Failed filter results go to\n * `orElse` when provided; otherwise the filter failure is re-failed.\n *\n * @see {@link catchIf} for predicate or refinement based recovery\n * @see {@link catchTag} for `_tag` based recovery from one tagged error\n * @see {@link catchTags} for `_tag` based recovery from multiple tagged errors\n * @see {@link catchCauseFilter} for filtering full causes\n *\n * @category error handling\n * @since 4.0.0\n */\nexport 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))));\n/**\n * Recovers from failures whose `_tag` matches the provided value by switching to\n * the stream returned by `f`.\n *\n * **When to use**\n *\n * Use when you need to handle a specific error case from a stream whose error\n * type is a tagged union with a readonly `_tag` field.\n *\n * **Example** (Catching tagged failures)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } from \"effect\"\n *\n * class HttpError extends Data.TaggedError(\"HttpError\")<{ message: string }> {}\n *\n * const stream = Stream.fail(new HttpError({ message: \"timeout\" }))\n *\n * const recovered = Stream.catchTag(stream, \"HttpError\", (error) =>\n * Stream.make(`Recovered: ${error.message}`)\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(recovered)\n * values // => [ 'Recovered: timeout' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchTag = /*#__PURE__*/dual(args => isStream(args[0]), (self, k, f, orElse) => {\n const pred = Array.isArray(k) ? e => hasProperty(e, \"_tag\") && k.includes(e._tag) : isTagged(k);\n return catchIf(self, pred, f, orElse);\n});\n/**\n * Switches to a recovery stream based on matching `_tag` handlers.\n *\n * **Example** (Catching tagged failures with handlers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * class NotFound {\n * readonly _tag = \"NotFound\"\n * constructor(readonly resource: string) {}\n * }\n *\n * class Unauthorized {\n * readonly _tag = \"Unauthorized\"\n * constructor(readonly user: string) {}\n * }\n *\n * const stream = Stream.fail(new NotFound(\"profile\"))\n *\n * const program = Effect.gen(function* () {\n * const result = yield* stream.pipe(\n * Stream.catchTags({\n * NotFound: () => Stream.succeed(\"fallback\"),\n * Unauthorized: () => Stream.succeed(\"login\")\n * }),\n * Stream.runCollect\n * )\n * result // => [ 'fallback' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchTags = /*#__PURE__*/dual(args => isStream(args[0]), (self, cases, orElse) => {\n let keys;\n return catchFilter(self, e => {\n keys ??= Object.keys(cases);\n return hasProperty(e, \"_tag\") && isString(e[\"_tag\"]) && keys.includes(e[\"_tag\"]) ? Result.succeed(e) : Result.fail(e);\n }, e => cases[e[\"_tag\"]](e), orElse);\n});\n/**\n * Catches a specific reason within a tagged error.\n *\n * **When to use**\n *\n * Use to handle nested error causes without removing the parent error\n * from the error channel.\n *\n * **Details**\n *\n * The handler receives the unwrapped reason.\n *\n * **Example** (Catching a tagged error reason)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } from \"effect\"\n *\n * class RateLimitError extends Data.TaggedError(\"RateLimitError\")<{\n * retryAfter: number\n * }> {}\n *\n * class QuotaExceededError extends Data.TaggedError(\"QuotaExceededError\")<{\n * limit: number\n * }> {}\n *\n * class AiError extends Data.TaggedError(\"AiError\")<{\n * reason: RateLimitError | QuotaExceededError\n * }> {}\n *\n * const stream = Stream.fail(\n * new AiError({ reason: new RateLimitError({ retryAfter: 60 }) })\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* stream.pipe(\n * Stream.catchReason(\"AiError\", \"RateLimitError\", (reason) =>\n * Stream.succeed(`retry: ${reason.retryAfter}`)\n * ),\n * Stream.runCollect\n * )\n * values // => [ 'retry: 60' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport 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))));\n/**\n * Catches multiple reasons within a tagged error using an object of handlers.\n *\n * **Example** (Catching tagged error reasons)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } from \"effect\"\n *\n * class RateLimitError extends Data.TaggedError(\"RateLimitError\")<{\n * retryAfter: number\n * }> {}\n *\n * class QuotaExceededError extends Data.TaggedError(\"QuotaExceededError\")<{\n * limit: number\n * }> {}\n *\n * class AiError extends Data.TaggedError(\"AiError\")<{\n * reason: RateLimitError | QuotaExceededError\n * }> {}\n *\n * const stream = Stream.fail(\n * new AiError({ reason: new RateLimitError({ retryAfter: 60 }) })\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* stream.pipe(\n * Stream.catchReasons(\"AiError\", {\n * RateLimitError: (reason) => Stream.succeed(`retry: ${reason.retryAfter}`),\n * QuotaExceededError: (reason) => Stream.succeed(`quota: ${reason.limit}`)\n * }),\n * Stream.runCollect\n * )\n * values // => [ 'retry: 60' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchReasons = /*#__PURE__*/dual(args => isStream(args[0]), (self, errorTag, cases, orElse) => {\n const handlers = Object.create(null);\n for (const key of Object.keys(cases)) {\n const handler = cases[key];\n handlers[key] = (reason, error) => handler(reason, error).channel;\n }\n const orElseHandler = orElse && ((reason, error) => orElse(reason, error).channel);\n return fromChannel(Channel.catchReasons(self.channel, errorTag, handlers, orElseHandler));\n});\n/**\n * Transforms the errors emitted by this stream using `f`.\n *\n * **Example** (Mapping stream errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.fail(\"bad\").pipe(\n * Stream.mapError((error) => `mapped: ${error}`),\n * Stream.catch((error) => Stream.make(`recovered from ${error}`)),\n * Stream.runCollect\n * )\n * result // => [ 'recovered from mapped: bad' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const mapError = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.mapError(self.channel, f)));\n/**\n * Recovers from stream failures by filtering the `Cause` and switching to a recovery stream.\n * Non-matching causes are re-emitted as failures.\n *\n * **Example** (Catching matching causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const failingStream = Stream.fail(\"NetworkError\")\n * const recovered = Stream.catchCauseIf(\n * failingStream,\n * (cause) => Cause.hasFails(cause),\n * (cause) => Stream.make(`Recovered: ${Cause.squash(cause)}`)\n * )\n *\n * const output = yield* Stream.runCollect(recovered)\n * output // => [ 'Recovered: NetworkError' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCauseIf = /*#__PURE__*/dual(3, (self, predicate, f) => fromChannel(Channel.catchCauseIf(self.channel, predicate, cause => f(cause).channel)));\n/**\n * Recovers from stream failures by filtering the `Cause` and switching to a\n * recovery stream.\n *\n * **When to use**\n *\n * Use when you need to recover a stream only from causes selected by a\n * `Filter`, while giving the recovery both the selected value and the original\n * `Cause`.\n *\n * **Details**\n *\n * The filter is applied to the full `Cause`. A successful filter result is\n * passed to `f` together with the original cause; a failed filter result\n * re-fails with the residual cause.\n *\n * @see {@link catchCauseIf} for predicate-based cause selection\n * @see {@link catchFilter} for filtering typed error values instead of full causes\n * @see {@link catchCause} for recovering from every cause without filtering\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCauseFilter = /*#__PURE__*/dual(3, (self, filter, f) => fromChannel(Channel.catchCauseFilter(self.channel, filter, (failure, cause) => f(failure, cause).channel)));\n/**\n * Switches to a fallback stream if this stream is empty.\n *\n * **Example** (Switching on empty streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.empty.pipe(\n * Stream.orElseIfEmpty(() => Stream.make(1, 2)),\n * Stream.runCollect\n * )\n * values // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElseIfEmpty = /*#__PURE__*/dual(2, (self, orElse) => fromChannel(Channel.orElseIfEmpty(self.channel, _ => toChannel(orElse()))));\n/**\n * Returns a stream that emits a fallback value when this stream fails.\n *\n * **Example** (Recovering with a fallback value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.fail(\"NetworkError\").pipe(\n * Stream.orElseSucceed((error) => `Recovered: ${error}`)\n * )\n *\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 'Recovered: NetworkError' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElseSucceed = /*#__PURE__*/dual(2, (self, f) => catch_(self, e => succeed(f(e))));\n/**\n * Turns typed failures into defects, making the stream infallible.\n *\n * **Example** (Turning failures into defects)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3).pipe(\n * Stream.orDie,\n * Stream.runCollect\n * )\n *\n * values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orDie = self => fromChannel(Channel.orDie(self.channel));\n/**\n * Ignores failures and ends the stream on error.\n *\n * **When to use**\n *\n * Use when you want a failing stream to end gracefully rather than propagate\n * the error.\n *\n * **Details**\n *\n * The `log` option controls whether the failure is logged before the stream\n * terminates.\n *\n * **Example** (Ignoring stream failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3).pipe(\n * Stream.concat(Stream.fail(\"boom\")),\n * Stream.ignore,\n * Stream.runCollect\n * )\n * values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * **Example** (Configuring ignore logging)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const values = yield* Stream.fail(\"boom\").pipe(\n * Stream.ignore({ log: false }),\n * Stream.runCollect\n * )\n * values // => []\n * }))\n *\n * ```\n *\n * @see {@link ignoreCause} for a variant that also ignores defects, not just typed failures\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const ignore = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignore(self.channel, options)));\n/**\n * Ignores the stream's failure cause, including defects, and ends the stream.\n *\n * **When to use**\n *\n * Use when you need to silently suppress a stream's entire failure cause,\n * including both typed errors and defects, rather than propagate it downstream.\n *\n * **Example** (Ignoring stream failure causes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2).pipe(\n * Stream.concat(Stream.die(\"boom\")),\n * Stream.ignoreCause({ log: false }),\n * Stream.runCollect\n * )\n * values // => [1, 2]\n * }))\n *\n * ```\n *\n * @see {@link ignore} to ignore only typed failures without suppressing defects\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const ignoreCause = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignoreCause(self.channel, options)));\n/**\n * Retries the stream according to the given schedule when it fails.\n *\n * **Details**\n *\n * This retries the entire stream, so will re-execute all of the stream's\n * acquire operations.\n *\n * The schedule is reset as soon as the first element passes through the\n * stream again.\n *\n * **Example** (Retrying stream failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1).pipe(\n * Stream.concat(Stream.fail(\"boom\")),\n * Stream.retry(Schedule.recurs(1)),\n * Stream.take(2),\n * Stream.runCollect\n * )\n *\n * values // => [ 1, 1 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const retry = /*#__PURE__*/dual(2, (self, policy) => fromChannel(Channel.retry(self.channel, policy)));\nconst retryWithoutReset = (self, schedule) => unwrap(Effect.map(Schedule.toStepWithMetadata(schedule), step => {\n let meta = Schedule.CurrentMetadata.defaultValue();\n const loop = () => catch_(provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)), error => unwrap(Pull.catchDone(Effect.map(step(error), meta_ => {\n meta = meta_;\n return unwrap(Effect.as(Effect.yieldNow, loop()));\n }), () => Effect.succeed(fail(error)))));\n return loop();\n}));\n/**\n * Applies an `ExecutionPlan` to a stream, retrying with step-provided resources\n * until it succeeds or the plan is exhausted.\n *\n * **Details**\n *\n * By default, a failing step can fallback even after emitting elements; set\n * `preventFallbackOnPartialStream` to fail instead of mixing partial output with\n * a later fallback.\n *\n * Attempts can be observed from outside the stream by passing\n * `options.onEvent`, which receives an `ExecutionPlan.Event` before each\n * attempt and after it settles; see `Effect.withExecutionPlan` for the handler\n * semantics. When a downstream consumer stops pulling early (for example\n * `Stream.take` outside the plan), the truncated attempt reports\n * `AttemptSuccess`: the consumer stopped, not the source.\n *\n * **Example** (Applying an execution plan)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, ExecutionPlan, Layer, Stream } from \"effect\"\n *\n * class Service extends Context.Service<Service>()(\"Service\", {\n * make: Effect.succeed({\n * stream: Stream.fail(\"A\") as Stream.Stream<number, string>\n * })\n * }) {\n * static Bad = Layer.succeed(Service, Service.of({ stream: Stream.fail(\"A\") }))\n * static Good = Layer.succeed(Service, Service.of({ stream: Stream.make(1, 2, 3) }))\n * }\n *\n * const plan = ExecutionPlan.make(\n * { provide: Service.Bad },\n * { provide: Service.Good }\n * )\n *\n * const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream))\n *\n * const program = Effect.gen(function*() {\n * const items = yield* stream.pipe(Stream.withExecutionPlan(plan), Stream.runCollect)\n * items // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 3.16.0\n */\nexport const withExecutionPlan = /*#__PURE__*/dual(args => isStream(args[0]), (self, policy, options) => suspend(() => {\n const preventFallbackOnPartialStream = options?.preventFallbackOnPartialStream ?? false;\n let i = 0;\n let meta = {\n attempt: 0,\n stepIndex: 0\n };\n const provideMeta = provideServiceEffect(ExecutionPlan.CurrentMetadata, Effect.sync(() => {\n meta = {\n attempt: meta.attempt + 1,\n stepIndex: i\n };\n return meta;\n }));\n const emitter = options?.onEvent === undefined ? undefined : internalExecutionPlan.makeEventEmitter(options.onEvent, () => meta);\n let attemptState;\n const instrument = emitter === undefined ? identity : attempt => onExit(onStart(attempt, Effect.map(emitter.begin, state => {\n attemptState = state;\n })), exit => Effect.suspend(() => {\n if (attemptState === undefined) return Effect.void;\n const state = attemptState;\n attemptState = undefined;\n return emitter.end(state, exit);\n }));\n let lastError = Option.none();\n const loop = suspend(() => {\n const step = policy.steps[i];\n if (!step) {\n return fail(Option.getOrThrow(lastError));\n }\n let nextStream = provideMeta(instrument(provide(self, step.provide)));\n let receivedElements = false;\n if (Option.isSome(lastError)) {\n const error = lastError.value;\n let attempted = false;\n const wrapped = nextStream;\n // ensure the schedule is applied at least once\n nextStream = suspend(() => {\n if (attempted) return wrapped;\n attempted = true;\n return fail(error);\n });\n nextStream = retryWithoutReset(nextStream, internalExecutionPlan.scheduleFromStep(step, false));\n } else {\n const schedule = internalExecutionPlan.scheduleFromStep(step, true);\n nextStream = schedule ? retryWithoutReset(nextStream, schedule) : nextStream;\n }\n return catch_(preventFallbackOnPartialStream ? onFirst(nextStream, _ => {\n receivedElements = true;\n return Effect.void;\n }) : nextStream, error => {\n i++;\n if (preventFallbackOnPartialStream && receivedElements) {\n return fail(error);\n }\n lastError = Option.some(error);\n return loop;\n });\n });\n return loop;\n}));\n/**\n * Takes the first `n` elements from this stream.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values return `Stream.empty` without evaluating the source stream.\n *\n * **Example** (Taking values from the left)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n * Stream.take(3),\n * Stream.runCollect\n * )\n * values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const take = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n return count === 0 ? empty : takeUntil(self, (_, i) => i === count - 1);\n});\n/**\n * Emits byte chunks until the configured limit would be exceeded, then drops\n * the crossing chunk and switches to a fallback stream.\n *\n * **Example** (Truncating at a byte limit)\n *\n * ```ts import.meta.vitest\n * import { ByteSize, Effect, Stream } from \"effect\"\n *\n * const program = Stream.make(\n * new Uint8Array([1, 2]),\n * new Uint8Array([3, 4, 5])\n * ).pipe(\n * Stream.limitBytes(ByteSize.bytes(4), () => Stream.empty),\n * Stream.runCollect,\n * Effect.map((chunks) => chunks.map((chunk) => [...chunk]))\n * )\n *\n * await Effect.runPromise(program) // => [[1, 2]]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const limitBytes = /*#__PURE__*/dual(3, (self, bytes, onLimitReached) => suspend(() => {\n const limit = ByteSize.fromInputUnsafe(bytes);\n let size = BigInt(0);\n let limitReached = false;\n return concat(takeWhile(self, chunk => {\n const nextSize = size + BigInt(chunk.length);\n if (nextSize > limit) {\n limitReached = true;\n return false;\n }\n size = nextSize;\n return true;\n }), suspend(() => limitReached ? onLimitReached() : empty));\n}));\n/**\n * Keeps the last `n` elements from this stream.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values return `Stream.empty` without evaluating the source stream.\n *\n * **Example** (Taking elements from the right)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.range(1, 6).pipe(\n * Stream.takeRight(3),\n * Stream.runCollect\n * )\n * values // => [ 4, 5, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const takeRight = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n if (count === 0) return empty;\n return mapAccumArray(self, MutableList.make, (list, arr) => {\n MutableList.appendAll(list, arr);\n if (list.length > count) {\n MutableList.takeNVoid(list, list.length - count);\n }\n return [list, emptyArr];\n }, {\n onHalt(list) {\n return MutableList.takeAll(list);\n }\n });\n});\n/**\n * Takes elements until the predicate matches.\n *\n * **Details**\n *\n * When `excludeLast` is `true`, the matching element is dropped.\n *\n * **Example** (Taking until a predicate matches)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(1, 5)\n *\n * const program = Effect.gen(function*() {\n * const inclusive = yield* stream.pipe(\n * Stream.takeUntil((n) => n % 3 === 0),\n * Stream.runCollect\n * )\n * inclusive // => [ 1, 2, 3 ]\n *\n * const exclusive = yield* stream.pipe(\n * Stream.takeUntil((n) => n % 3 === 0, { excludeLast: true }),\n * Stream.runCollect\n * )\n * exclusive // => [ 1, 2 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const takeUntil = /*#__PURE__*/dual(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let i = 0;\n let done = false;\n const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => {\n const index = chunk.findIndex(a => predicate(a, i++));\n if (index >= 0) {\n done = true;\n const arr = chunk.slice(0, options?.excludeLast ? index : index + 1);\n return Arr.isReadonlyArrayNonEmpty(arr) ? Effect.succeed(arr) : Cause.done();\n }\n return Effect.succeed(chunk);\n });\n return pump;\n})));\n/**\n * Takes stream elements until an effectful predicate returns `true`.\n *\n * **When to use**\n *\n * Use when the stopping condition needs an Effect or service and predicate\n * failure should fail the stream.\n *\n * **Example** (Taking until an effectful predicate matches)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.range(1, 5).pipe(\n * Stream.takeUntilEffect((n) => Effect.succeed(n % 3 === 0)),\n * Stream.runCollect\n * )\n * result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const takeUntilEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let i = 0;\n let done = false;\n return Effect.gen(function* () {\n if (done) return yield* Cause.done();\n const chunk = yield* pull;\n for (let j = 0; j < chunk.length; j++) {\n if (yield* predicate(chunk[j], i++)) {\n done = true;\n const arr = chunk.slice(0, options?.excludeLast ? j : j + 1);\n return Arr.isReadonlyArrayNonEmpty(arr) ? arr : yield* Cause.done();\n }\n }\n return chunk;\n });\n})));\n/**\n * Takes the longest initial prefix of elements that satisfy the predicate.\n *\n * **Example** (Taking while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(1, 5).pipe(\n * Stream.takeWhile((n) => n % 3 !== 0)\n * )\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(stream)\n * result // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const takeWhile = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let i = 0;\n let done = false;\n const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => {\n const out = [];\n for (let j = 0; j < chunk.length; j++) {\n if (!predicate(chunk[j], i++)) {\n done = true;\n break;\n }\n out.push(chunk[j]);\n }\n return Arr.isReadonlyArrayNonEmpty(out) ? Effect.succeed(out) : done ? Cause.done() : pump;\n });\n return pump;\n})));\n/**\n * Takes the longest initial prefix accepted by a `Filter` and emits the\n * filter's success values.\n *\n * **When to use**\n *\n * Use to keep the leading stream elements that a `Filter` accepts, emit the\n * filter's success values, and stop at the first filter failure.\n *\n * **Details**\n *\n * The stream stops at the first `Result.fail` returned by the filter.\n *\n * @see {@link takeWhile} for keeping original elements with a boolean predicate or refinement\n * @see {@link filterMap} for filtering across the whole stream instead of only the leading prefix\n * @see {@link dropWhileFilter} for dropping the accepted prefix and keeping the remaining original elements\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const takeWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let done = false;\n const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => {\n const out = [];\n for (let j = 0; j < chunk.length; j++) {\n const result = filter(chunk[j]);\n if (Result.isFailure(result)) {\n done = true;\n break;\n }\n out.push(result.success);\n }\n return Arr.isReadonlyArrayNonEmpty(out) ? Effect.succeed(out) : done ? Cause.done() : pump;\n });\n return pump;\n})));\n/**\n * Takes elements from the stream while the effectful predicate is `true`.\n *\n * **When to use**\n *\n * Use when the leading-prefix predicate needs an Effect or service and the\n * stream should stop before the first false result.\n *\n * **Example** (Effectfully taking while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.range(1, 5).pipe(\n * Stream.takeWhileEffect((n) => Effect.succeed(n % 3 !== 0)),\n * Stream.runCollect\n * )\n * result // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const takeWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => takeUntilEffect(self, (a, n) => Effect.map(predicate(a, n), b => !b), {\n excludeLast: true\n}));\n/**\n * Drops the first `n` elements from this stream.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values return the source stream unchanged.\n *\n * **Example** (Dropping values from the left)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n * const result = Stream.drop(stream, 2)\n *\n * const program = Effect.gen(function*() {\n * const items = yield* Stream.runCollect(result)\n * items // => [ 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const drop = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n if (count === 0) return self;\n return transformPull(self, (pull, _scope) => Effect.sync(() => {\n let dropped = 0;\n const pump = pull.pipe(Effect.flatMap(chunk => {\n if (dropped >= count) return Effect.succeed(chunk);\n dropped += chunk.length;\n if (dropped <= count) return pump;\n return Effect.succeed(chunk.slice(count - dropped));\n }));\n return pump;\n }));\n});\n/**\n * Drops elements until the specified predicate evaluates to `true`, then drops\n * that matching element.\n *\n * **Example** (Dropping until a predicate matches)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n * const result = Stream.dropUntil(stream, (n) => n >= 3)\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const output = yield* Stream.runCollect(result)\n * output // => [ 4, 5 ]\n * }))\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropUntil = /*#__PURE__*/dual(2, (self, predicate) => drop(dropWhile(self, (a, i) => !predicate(a, i)), 1));\n/**\n * Drops all elements of the stream until the specified effectful predicate\n * evaluates to `true`.\n *\n * **When to use**\n *\n * Use when dropping the leading prefix requires an Effect or service and the\n * first matching element should also be dropped.\n *\n * **Example** (Dropping until an effectful predicate matches)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.range(1, 5).pipe(\n * Stream.dropUntilEffect((n) => Effect.succeed(n % 3 === 0)),\n * Stream.runCollect\n * )\n * result // => [ 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropUntilEffect = /*#__PURE__*/dual(2, (self, predicate) => drop(dropWhileEffect(self, (a, i) => Effect.map(predicate(a, i), b => !b)), 1));\n/**\n * Drops elements from the stream while the specified predicate evaluates to `true`.\n *\n * **Example** (Dropping while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n * Stream.dropWhile((n) => n < 3),\n * Stream.runCollect\n * )\n * values // => [ 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropWhile = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let dropping = true;\n let index = 0;\n const filtered = Effect.flatMap(pull, arr => {\n const found = arr.findIndex(a => !predicate(a, index++));\n if (found === -1) return filtered;\n dropping = false;\n return Effect.succeed(arr.slice(found));\n });\n return Effect.suspend(() => dropping ? filtered : pull);\n})));\n/**\n * Drops elements while the filter succeeds.\n *\n * **When to use**\n *\n * Use when you need to remove a leading stream prefix based on a synchronous\n * `Filter` result while preserving the remaining original stream elements.\n *\n * **Details**\n *\n * `Result.succeed` drops the current element. The first `Result.fail` stops\n * dropping, emits that original element, and the rest of the source stream is\n * emitted without further filtering.\n *\n * @see {@link dropWhile} for boolean predicate prefix dropping\n * @see {@link takeWhileFilter} for keeping the accepted prefix as filter success values\n * @see {@link dropWhileEffect} for effectful predicate prefix dropping\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const dropWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let dropping = true;\n const filtered = Effect.flatMap(pull, arr => {\n const found = arr.findIndex(a => Result.isFailure(filter(a)));\n if (found === -1) return filtered;\n dropping = false;\n return Effect.succeed(arr.slice(found));\n });\n return Effect.suspend(() => dropping ? filtered : pull);\n})));\n/**\n * Drops elements while the specified effectful predicate evaluates to `true`.\n *\n * **Example** (Effectfully dropping while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n * Stream.dropWhileEffect((n) => Effect.succeed(n < 3)),\n * Stream.runCollect\n * )\n * result // => [ 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let dropping = true;\n let index = 0;\n const filtered = Effect.gen(function* () {\n while (true) {\n const arr = yield* pull;\n for (let i = 0; i < arr.length; i++) {\n const drop = yield* predicate(arr[i], index++);\n if (drop) continue;\n dropping = false;\n return arr.slice(i);\n }\n }\n });\n return Effect.suspend(() => dropping ? filtered : pull);\n})));\n/**\n * Drops the last specified number of elements from this stream.\n *\n * **Details**\n *\n * Keeps the last `n` elements in memory to drop them on completion. Finite\n * fractional values of `n` are rounded down. `NaN` and non-positive values\n * return the source stream unchanged.\n *\n * **Example** (Dropping values from the right)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n * Stream.dropRight(2),\n * Stream.runCollect\n * )\n * result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropRight = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n if (count === 0) return self;\n return transformPull(self, (pull, _scope) => Effect.sync(() => {\n const list = MutableList.make();\n const emit = Effect.flatMap(pull, arr => {\n MutableList.appendAllUnsafe(list, arr);\n const toTake = list.length - count;\n const items = MutableList.takeN(list, toTake);\n return Arr.isArrayNonEmpty(items) ? Effect.succeed(items) : emit;\n });\n return emit;\n }));\n});\n/**\n * Exposes the underlying chunks as a stream of non-empty arrays.\n *\n * **Example** (Exposing stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const chunks = yield* Stream.make(1, 2, 3, 4).pipe(\n * Stream.rechunk(2),\n * Stream.chunks,\n * Stream.runCollect\n * )\n * chunks // => [ [ 1, 2 ], [ 3, 4 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const chunks = self => self.channel.pipe(Channel.map(Arr.of), fromChannel);\n/**\n * Groups the stream into arrays of the specified size, preserving element order.\n *\n * **Details**\n *\n * Finite fractional sizes are rounded down. `NaN` and non-positive sizes are\n * treated as `1`.\n *\n * **Example** (Rechunking stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n * Stream.rechunk(2),\n * Stream.chunks,\n * Stream.runCollect\n * )\n * result // => [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const rechunk = /*#__PURE__*/dual(2, (self, target) => {\n target = Count.normalizeNonEmpty(target);\n return transformPull(self, (pull, _scope) => Effect.sync(() => {\n let chunk = Arr.empty();\n let index = 0;\n let current;\n let done = false;\n return Effect.suspend(function loop() {\n if (done) return Cause.done();else if (current === undefined) {\n return Effect.flatMap(pull, arr => {\n if (chunk.length === 0 && arr.length === target) {\n return Effect.succeed(arr);\n } else if (chunk.length + arr.length < target) {\n for (let i = 0; i < arr.length; i++) {\n chunk.push(arr[i]);\n }\n return loop();\n }\n current = arr;\n return loop();\n });\n }\n for (; index < current.length;) {\n chunk.push(current[index++]);\n if (chunk.length === target) {\n const result = chunk;\n chunk = [];\n return Effect.succeed(result);\n }\n }\n index = 0;\n current = undefined;\n return loop();\n }).pipe(Pull.catchDone(() => {\n if (chunk.length === 0) return Cause.done();\n const result = chunk;\n done = true;\n chunk = [];\n return Effect.succeed(result);\n }));\n }));\n});\n/**\n * Emits a sliding window of `n` elements.\n *\n * **Details**\n *\n * Finite fractional window sizes are rounded down. `NaN` and non-positive\n * sizes are treated as `1`.\n *\n * **Example** (Emitting sliding windows)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const result = yield* pipe(\n * Stream.make(1, 2, 3, 4, 5),\n * Stream.sliding(2),\n * Stream.runCollect\n * )\n * result // => [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ]\n * }))\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const sliding = /*#__PURE__*/dual(2, (self, chunkSize) => slidingSize(self, chunkSize, 1));\n/**\n * Emits sliding windows of `chunkSize` elements, advancing by `stepSize`.\n *\n * **Details**\n *\n * Finite fractional window and step sizes are rounded down. `NaN` and\n * non-positive sizes are treated as `1`.\n *\n * **Example** (Emitting sliding windows with a step size)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const chunks = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n * Stream.slidingSize(3, 2),\n * Stream.runCollect\n * )\n * chunks // => [ [ 1, 2, 3 ], [ 3, 4, 5 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const slidingSize = /*#__PURE__*/dual(3, (self, chunkSize, stepSize) => {\n const windowSize = Count.normalizeNonEmpty(chunkSize);\n const step = Count.normalizeNonEmpty(stepSize);\n return transformPull(self, (upstream, _scope) => Effect.sync(() => {\n let cause = null;\n const list = MutableList.make();\n let emitted = false;\n let skip = 0;\n const pull = Effect.matchCauseEffect(upstream, {\n onSuccess(arr) {\n MutableList.appendAllUnsafe(list, arr);\n if (skip > 0) {\n const length = list.length;\n MutableList.takeNVoid(list, skip);\n skip = Math.max(0, skip - length);\n }\n if (list.length < windowSize) return pull;\n emitted = true;\n const chunks = [];\n while (list.length >= windowSize) {\n if (windowSize === step) {\n chunks.push(MutableList.takeN(list, windowSize));\n } else {\n chunks.push(MutableList.toArrayN(list, windowSize));\n const length = list.length;\n MutableList.takeNVoid(list, step);\n skip = Math.max(0, step - length);\n }\n }\n return Effect.succeed(chunks);\n },\n onFailure(cause_) {\n if (emitted) MutableList.takeNVoid(list, windowSize - step);\n if (list.length === 0) return Effect.failCause(cause_);\n cause = cause_;\n return Effect.succeed(Arr.of(MutableList.takeAll(list)));\n }\n });\n return Effect.suspend(() => cause ? Effect.failCause(cause) : pull);\n }));\n});\n/**\n * Splits the stream into non-empty groups whenever the predicate matches.\n *\n * **Details**\n *\n * Matching elements act as delimiters and are not included in the output.\n *\n * **Example** (Splitting on matching values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.range(0, 9).pipe(\n * Stream.split((n) => n % 4 === 0),\n * Stream.runCollect\n * )\n * result // => [ [ 1, 2, 3 ], [ 5, 6, 7 ], [ 9 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const split = /*#__PURE__*/dual(2, (self, predicate) => mapAccumArray(self, Arr.empty, (acc, arr) => {\n const out = Arr.empty();\n for (let i = 0; i < arr.length; i++) {\n if (predicate(arr[i])) {\n if (Arr.isArrayNonEmpty(acc)) {\n out.push(acc);\n acc = [];\n }\n } else {\n acc.push(arr[i]);\n }\n }\n return [acc, out];\n}, {\n onHalt(arr) {\n return Arr.isArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n }\n}));\n/**\n * Combines elements from this stream and the specified stream by repeatedly\n * applying a stateful function that can pull from either side.\n *\n * **Details**\n *\n * Where possible, prefer `Stream.combineArray` for a more efficient\n * implementation.\n *\n * **Example** (Combining streams with state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.combine(\n * Stream.make(\"A\", \"B\", \"C\"),\n * Stream.make(1, 2, 3),\n * () => true,\n * (takeLeft, pullLeft, pullRight) =>\n * takeLeft\n * ? Effect.map(pullLeft, (value) => [`L:${value}`, false] as const)\n * : Effect.map(pullRight, (value) => [`R:${value}`, true] as const)\n * )\n *\n * const program = Effect.gen(function*() {\n * const output = yield* Stream.runCollect(stream)\n * output // => [ 'L:A', 'R:1', 'L:B', 'R:2', 'L:C', 'R:3' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport 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));\n/**\n * Combines two streams chunk-by-chunk with a stateful pull function.\n *\n * **When to use**\n *\n * Use to coordinate pulling chunks from two streams when each emitted chunk\n * depends on both sides and local state.\n *\n * **Details**\n *\n * The combining function receives the current state and pull functions for the\n * left and right streams. It returns the next non-empty chunk together with the\n * next state.\n *\n * **Example** (Combining stream chunks with state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2).pipe(\n * Stream.combineArray(\n * Stream.make(10, 20),\n * () => true,\n * (useLeft, pullLeft, pullRight) =>\n * Effect.gen(function*() {\n * const array = useLeft ? yield* pullLeft : yield* pullRight\n * return [array, !useLeft] as const\n * })\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 1, 2, 10, 20 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const combineArray = /*#__PURE__*/dual(4, (self, that, s, f) => fromChannel(Channel.combine(self.channel, that.channel, s, f)));\n/**\n * Maps elements statefully, emitting zero or more outputs per input.\n *\n * **Example** (Statefully mapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const totals = yield* Stream.make(0, 1, 2, 3, 4, 5, 6).pipe(\n * Stream.mapAccum(() => 0, (total, n) => {\n * const next = total + n\n * return [next, [next]] as const\n * }),\n * Stream.runCollect\n * )\n *\n * totals // => [0, 1, 3, 6, 10, 15, 21]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapAccum = /*#__PURE__*/dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => {\n const acc = Arr.empty();\n for (let index = 0; index < arr.length; index++) {\n const [newState, values] = f(state, arr[index]);\n state = newState;\n acc.push(...values);\n }\n return [state, Arr.isArrayNonEmpty(acc) ? Arr.of(acc) : emptyArr];\n}, options?.onHalt ? {\n onHalt(state) {\n const arr = options.onHalt(state);\n return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n }\n} : undefined)));\n/**\n * Maps over non-empty chunk arrays statefully, emitting zero or more values per chunk.\n *\n * **Details**\n *\n * The mapping function runs once per chunk and the state is threaded across chunks.\n *\n * **Example** (Statefully mapping stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const output = yield* Stream.make(1, 2, 3, 4, 5, 6).pipe(\n * Stream.rechunk(2),\n * Stream.mapAccumArray(() => 0, (sum: number, chunk) => {\n * const next = chunk.reduce((acc, n) => acc + n, sum)\n * return [next, [next]]\n * }),\n * Stream.runCollect\n * )\n * output // => [ 3, 10, 21 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapAccumArray = /*#__PURE__*/dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => {\n const [newState, values] = f(state, arr);\n state = newState;\n return [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : emptyArr];\n}, options?.onHalt ? {\n onHalt(state) {\n const arr = options.onHalt(state);\n return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n }\n} : undefined)));\nconst emptyArr = /*#__PURE__*/Arr.empty();\n/**\n * Maps each element statefully and effectfully, emitting zero or more output\n * values per input.\n *\n * **When to use**\n *\n * Use when stateful element mapping needs Effects or can fail while emitting\n * zero or more values per input element.\n *\n * **Details**\n *\n * The mapping effect receives the current state and element, then returns the\n * next state plus the values to emit. The state is threaded through the\n * stream.\n *\n * **Example** (Effectfully mapping stream values with state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.make(1, 1, 1).pipe(\n * Stream.mapAccumEffect(() => 0, (total, n) =>\n * Effect.succeed([total + n, [total + n]])\n * ),\n * Stream.runCollect\n * )\n *\n * result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport 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 ? {\n onHalt(state) {\n const arr = options.onHalt(state);\n return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n }\n} : undefined), fromChannel));\n/**\n * Maps each non-empty input chunk statefully and effectfully, emitting zero or\n * more output values per chunk.\n *\n * **When to use**\n *\n * Use when stateful mapping should process each emitted non-empty chunk with an\n * Effect instead of each element separately.\n *\n * **Details**\n *\n * The mapping effect receives the current state and chunk, then returns the\n * next state plus the values to emit. The state is threaded across chunks.\n *\n * **Example** (Effectfully mapping stream chunks with state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const totals = yield* Stream.make(1, 2, 3, 4).pipe(\n * Stream.rechunk(2),\n * Stream.mapAccumArrayEffect(() => 0, (total, chunk) =>\n * Effect.gen(function*() {\n * const next = chunk.reduce((sum, value) => sum + value, total)\n * return [next, [next]] as const\n * })\n * ),\n * Stream.runCollect\n * )\n * totals // => [ 3, 10 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapAccumArrayEffect = /*#__PURE__*/dual(args => isStream(args[0]), (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 ? {\n onHalt(state) {\n const arr = options.onHalt(state);\n return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n }\n} : undefined), fromChannel));\n/**\n * Accumulates state across the stream, emitting the initial state and each updated state.\n *\n * **Example** (Scanning stream state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3).pipe(\n * Stream.scan(0, (acc, n) => acc + n),\n * Stream.runCollect\n * )\n * values // => [ 0, 1, 3, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category accumulation\n * @since 2.0.0\n */\nexport const scan = /*#__PURE__*/dual(3, (self, initial, f) => suspend(() => {\n let isFirst = true;\n return fromChannel(Channel.mapAccum(self.channel, constant(initial), (state, arr) => {\n const states = Arr.empty();\n if (isFirst) {\n isFirst = false;\n states.push(state);\n }\n for (let index = 0; index < arr.length; index++) {\n state = f(state, arr[index]);\n states.push(state);\n }\n return [state, Arr.of(states)];\n }));\n}));\n/**\n * Accumulates state effectfully and emits the initial state plus each accumulated state.\n *\n * **Example** (Effectfully scanning stream state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const states = yield* Stream.make(1, 2, 3).pipe(\n * Stream.scanEffect(0, (sum, n) => Effect.succeed(sum + n)),\n * Stream.runCollect\n * )\n * states // => [ 0, 1, 3, 6 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category accumulation\n * @since 2.0.0\n */\nexport const scanEffect = /*#__PURE__*/dual(3, (self, initial, f) => self.channel.pipe(Channel.flattenArray, Channel.scanEffect(initial, f), Channel.map(Arr.of), fromChannel));\n/**\n * Drops earlier elements within the debounce window and emits only the latest element after the pause.\n *\n * **Example** (Debouncing stream elements)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3).pipe(Stream.debounce(Duration.zero))\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 3 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category rate limiting\n * @since 2.0.0\n */\nexport const debounce = /*#__PURE__*/dual(2, (self, duration) => transformPull(self, Effect.fnUntraced(function* (pull, scope) {\n const clock = yield* Clock;\n const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration));\n let lastArr;\n let cause;\n let emitAtMs = Infinity;\n const pullLatch = Latch.makeUnsafe();\n const emitLatch = Latch.makeUnsafe();\n const endLatch = Latch.makeUnsafe();\n yield* pull.pipe(pullLatch.whenOpen, Effect.flatMap(arr => {\n emitLatch.openUnsafe();\n lastArr = arr;\n emitAtMs = clock.currentTimeMillisUnsafe() + durationMs;\n return Effect.void;\n }), Effect.forever({\n disableYield: true\n }), Effect.onError(cause_ => {\n cause = cause_;\n emitAtMs = clock.currentTimeMillisUnsafe();\n emitLatch.openUnsafe();\n endLatch.openUnsafe();\n return Effect.void;\n }), Effect.forkIn(scope));\n const sleepLoop = Effect.suspend(function loop() {\n const now = clock.currentTimeMillisUnsafe();\n const timeMs = emitAtMs < now ? durationMs : Math.min(durationMs, emitAtMs - now);\n return Effect.flatMap(Effect.raceFirst(Effect.sleep(timeMs), endLatch.await), () => {\n const now = clock.currentTimeMillisUnsafe();\n if (now < emitAtMs) {\n return loop();\n } else if (lastArr) {\n emitLatch.closeUnsafe();\n pullLatch.closeUnsafe();\n const eff = Effect.succeed(Arr.of(Arr.lastNonEmpty(lastArr)));\n lastArr = undefined;\n return eff;\n } else if (cause) {\n return Effect.failCause(cause);\n }\n return loop();\n });\n });\n return Effect.suspend(() => {\n if (cause) {\n if (lastArr) {\n const eff = Effect.succeed(Arr.of(Arr.lastNonEmpty(lastArr)));\n lastArr = undefined;\n return eff;\n }\n return Effect.failCause(cause);\n }\n pullLatch.openUnsafe();\n return emitLatch.whenOpen(sleepLoop);\n });\n})));\n/**\n * Rate-limits stream chunks with an effectful cost function.\n *\n * **When to use**\n *\n * Use to throttle chunks when computing each chunk's cost requires an effect.\n *\n * **Details**\n *\n * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens,\n * and each chunk consumes the cost returned by the effectful `cost` function.\n *\n * If using the \"enforce\" strategy, arrays that do not meet the bandwidth\n * constraints are dropped. If using the \"shape\" strategy, arrays are delayed\n * until they can be emitted without exceeding the bandwidth constraints.\n *\n * Defaults to the \"shape\" strategy.\n *\n * **Example** (Throttling stream chunks effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(0, 5).pipe(\n * Stream.rechunk(1),\n * Stream.throttleEffect({\n * cost: (arr) => Effect.succeed(arr.length),\n * units: 1,\n * duration: 0,\n * strategy: \"shape\"\n * })\n * )\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const result = yield* Stream.runCollect(stream)\n * result // => [ 0, 1, 2, 3, 4, 5 ]\n * }))\n * ```\n *\n * @category rate limiting\n * @since 2.0.0\n */\nexport const throttleEffect = /*#__PURE__*/dual(2, (self, options) => {\n const burst = options.burst ?? 0;\n if (options.strategy === \"enforce\") {\n return throttleEnforceEffect(self, options.cost, options.units, options.duration, burst);\n }\n return throttleShapeEffect(self, options.cost, options.units, options.duration, burst);\n});\nconst throttleEnforceEffect = (self, cost, units, duration, burst) => transformPull(self, pull => Effect.clockWith(clock => {\n const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration));\n const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst;\n let tokens = units;\n let timestampMs = clock.currentTimeMillisUnsafe();\n return Effect.succeed(Effect.flatMap(pull, function loop(arr) {\n return Effect.flatMap(cost(arr), weight => {\n const currentMs = clock.currentTimeMillisUnsafe();\n const elapsed = currentMs - timestampMs;\n const cycles = elapsed / durationMs;\n const sum = tokens + cycles * units;\n const available = sum < 0 ? max : Math.min(sum, max);\n if (weight <= available) {\n tokens = available - weight;\n timestampMs = currentMs;\n return Effect.succeed(arr);\n }\n // Drop the array and continue\n return Effect.flatMap(pull, loop);\n });\n }));\n}));\nconst throttleShapeEffect = (self, cost, units, duration, burst) => transformPull(self, pull => Effect.clockWith(clock => {\n const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration));\n const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst;\n let tokens = units;\n let timestampMs = clock.currentTimeMillisUnsafe();\n return Effect.succeed(Effect.flatMap(pull, arr => Effect.flatMap(cost(arr), weight => {\n const currentMs = clock.currentTimeMillisUnsafe();\n const elapsed = currentMs - timestampMs;\n const cycles = elapsed / durationMs;\n const sum = tokens + cycles * units;\n const available = sum < 0 ? max : Math.min(sum, max);\n const remaining = available - weight;\n if (remaining >= 0) {\n tokens = remaining;\n timestampMs = currentMs;\n return Effect.succeed(arr);\n }\n // Calculate delay needed\n const waitCycles = -remaining / units;\n const delayMs = Math.max(0, waitCycles * durationMs);\n if (delayMs > 0) {\n return Effect.flatMap(Effect.sleep(delayMs), () => {\n tokens = remaining;\n timestampMs = currentMs;\n return Effect.succeed(arr);\n });\n }\n tokens = remaining;\n timestampMs = currentMs;\n return Effect.succeed(arr);\n })));\n}));\n/**\n * Rate-limits stream chunks with a synchronous cost function.\n *\n * **When to use**\n *\n * Use to throttle chunks when each chunk's cost can be computed synchronously.\n *\n * **Details**\n *\n * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens,\n * and each chunk consumes the cost returned by `cost`.\n *\n * If using the \"enforce\" strategy, arrays that do not meet the bandwidth\n * constraints are dropped. If using the \"shape\" strategy, arrays are delayed\n * until they can be emitted without exceeding the bandwidth constraints.\n *\n * Defaults to the \"shape\" strategy.\n *\n * **Example** (Throttling stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(0, 5).pipe(\n * Stream.rechunk(1),\n * Stream.throttle({\n * cost: (arr) => arr.length,\n * units: 1,\n * duration: 0,\n * strategy: \"shape\"\n * })\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 0, 1, 2, 3, 4, 5 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category rate limiting\n * @since 2.0.0\n */\nexport const throttle = /*#__PURE__*/dual(2, (self, options) => throttleEffect(self, {\n ...options,\n cost: arr => Effect.succeed(options.cost(arr))\n}));\n/**\n * Partitions the stream into non-empty arrays of the specified size.\n *\n * **Details**\n *\n * The final array may be smaller if there are not enough elements to fill it.\n * Finite fractional sizes are rounded down. `NaN` and non-positive sizes are\n * treated as `1`.\n *\n * **Example** (Grouping elements by size)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const grouped = yield* Stream.range(1, 8).pipe(\n * Stream.grouped(3),\n * Stream.runCollect\n * )\n * grouped // => [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const grouped = /*#__PURE__*/dual(2, (self, n) => chunks(rechunk(self, n)));\n/**\n * Partitions the stream into arrays, emitting when the chunk size is reached\n * or the duration passes.\n *\n * **Details**\n *\n * Finite fractional chunk sizes are rounded down. `NaN` and non-positive sizes\n * are treated as `1`.\n *\n * **Example** (Grouping elements by size or time)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3).pipe(\n * Stream.groupedWithin(2, \"5 seconds\"),\n * Stream.runCollect\n * )\n * values // => [ [ 1, 2 ], [ 3 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupedWithin = /*#__PURE__*/dual(3, (self, chunkSize, duration) => aggregateWithin(self, Sink.take(Count.normalizeNonEmpty(chunkSize)), Schedule.spaced(duration)));\n/**\n * Groups elements into keyed substreams using an effectful classifier.\n *\n * **Example** (Grouping elements into keyed substreams using an effectful classifier)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const grouped = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n * Stream.groupBy((n) =>\n * Effect.succeed([n % 2 === 0 ? \"even\" : \"odd\", n] as const)\n * ),\n * Stream.mapEffect(\n * Effect.fnUntraced(function*([key, stream]) {\n * return [key, yield* Stream.runCollect(stream)] as const\n * }),\n * { concurrency: \"unbounded\" }\n * ),\n * Stream.runCollect\n * )\n *\n * grouped // => [ [ 'odd', [ 1, 3, 5 ] ], [ 'even', [ 2, 4 ] ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupBy = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => groupByImpl(self, Effect.fnUntraced(function* (arr, queues, queueMap) {\n for (let i = 0; i < arr.length; i++) {\n const [key, value] = yield* f(arr[i]);\n const oentry = MutableHashMap.get(queueMap, key);\n const queue = Option.isSome(oentry) ? oentry.value : yield* Effect.scoped(RcMap.get(queues, key));\n yield* RcMap.touch(queues, key);\n yield* Queue.offer(queue, value);\n }\n}), options));\n/**\n * Groups elements by a key and emits a stream per key.\n *\n * **Example** (Grouping elements by key)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const grouped = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n * Stream.groupByKey((n) => n % 2 === 0 ? \"even\" : \"odd\"),\n * Stream.mapEffect(\n * ([key, stream]) =>\n * Stream.runCollect(stream).pipe(\n * Effect.map((values) => [key, values] as const)\n * ),\n * { concurrency: \"unbounded\" }\n * ),\n * Stream.runCollect\n * )\n * grouped // => [ [ 'odd', [ 1, 3, 5 ] ], [ 'even', [ 2, 4 ] ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupByKey = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => suspend(() => {\n const batch = MutableHashMap.empty();\n return groupByImpl(self, Effect.fnUntraced(function* (arr, queues, queueMap) {\n for (let i = 0; i < arr.length; i++) {\n const key = f(arr[i]);\n const ovalues = MutableHashMap.get(batch, key);\n if (Option.isNone(ovalues)) {\n MutableHashMap.set(batch, key, [arr[i]]);\n } else {\n ovalues.value.push(arr[i]);\n }\n }\n for (const [key, values] of batch) {\n const oentry = MutableHashMap.get(queueMap, key);\n const queue = Option.isSome(oentry) ? oentry.value : yield* Effect.scoped(RcMap.get(queues, key));\n yield* RcMap.touch(queues, key);\n yield* Queue.offerAll(queue, values);\n }\n MutableHashMap.clear(batch);\n }), options);\n}));\nconst groupByImpl = (self, f, options) => transformPullBracket(self, Effect.fnUntraced(function* (pull, scope, forkedScope) {\n const out = yield* Queue.unbounded();\n yield* Scope.addFinalizer(scope, Queue.shutdown(out));\n const queueMap = MutableHashMap.empty();\n const queues = yield* RcMap.make({\n lookup: key => Effect.acquireRelease(Queue.make({\n capacity: options?.bufferSize ?? 4096\n }).pipe(Effect.tap(queue => {\n MutableHashMap.set(queueMap, key, queue);\n return Queue.offer(out, [key, fromQueue(queue)]);\n })), queue => {\n MutableHashMap.remove(queueMap, key);\n return Queue.end(queue);\n }),\n idleTimeToLive: options?.idleTimeToLive ?? Duration.infinity\n }).pipe(Scope.provide(forkedScope));\n yield* Effect.whileLoop({\n while: constTrue,\n body: constant(Effect.flatMap(pull, arr => f(arr, queues, queueMap))),\n step: constVoid\n }).pipe(Effect.catchCause(cause => Queue.failCause(out, cause)), Effect.forkIn(scope));\n return Queue.takeAll(out);\n}));\n/**\n * Groups consecutive elements that have equal keys into non-empty arrays.\n *\n * **When to use**\n *\n * Use when you already have a stream ordered by the grouping key and want to\n * emit each consecutive run as a non-empty array while keeping later\n * non-adjacent runs separate.\n *\n * **Details**\n *\n * The key is computed with `f`; adjacent elements whose keys are equal by\n * `Equal.equals` are emitted as one `[key, group]`. Later non-adjacent runs\n * with the same key are emitted separately.\n *\n * @see {@link groupByKey} for grouping all elements with the same key across the stream\n * @see {@link groupBy} for custom grouped stream construction\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupAdjacentBy = /*#__PURE__*/dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let currentKey = undefined;\n let group;\n let toEmit = Arr.empty();\n const loop = pull.pipe(Effect.flatMap(chunk => {\n for (let i = 0; i < chunk.length; i++) {\n const item = chunk[i];\n const key = f(item);\n if (group === undefined) {\n currentKey = key;\n group = [item];\n continue;\n } else if (Equal.equals(key, currentKey)) {\n group.push(item);\n continue;\n }\n toEmit.push([currentKey, group]);\n currentKey = key;\n group = [item];\n }\n if (Arr.isArrayNonEmpty(toEmit)) {\n const out = toEmit;\n toEmit = [];\n return Effect.succeed(out);\n }\n return loop;\n }));\n let done = false;\n return Pull.catchDone(Effect.suspend(() => done ? Cause.done() : loop), () => {\n done = true;\n const out = group;\n group = undefined;\n return out && Arr.isArrayNonEmpty(out) ? Effect.succeed(Arr.of([currentKey, out])) : Cause.done();\n });\n})));\n/**\n * Applies a sink transducer to the stream and emits each sink result.\n *\n * **Example** (Transducing with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n * const result = yield* Stream.make(1, 2, 3, 4).pipe(\n * Stream.transduce(Sink.take(2)),\n * Stream.runCollect\n * )\n *\n * result // => [ [ 1, 2 ], [ 3, 4 ], [] ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category aggregation\n * @since 2.0.0\n */\nexport const transduce = /*#__PURE__*/dual(2, (self, sink) => transformPull(self, (upstream, scope) => Effect.sync(() => {\n let done;\n let leftover;\n const upstreamWithLeftover = Effect.suspend(() => {\n if (leftover !== undefined) {\n const chunk = leftover;\n leftover = undefined;\n return Effect.succeed(chunk);\n }\n return upstream;\n }).pipe(Effect.catch(error => {\n done = Exit.fail(error);\n return Cause.done();\n }));\n const pull = Effect.map(Effect.suspend(() => sink.transform(upstreamWithLeftover, scope)), ([value, leftover_]) => {\n leftover = leftover_;\n return Arr.of(value);\n });\n return Effect.suspend(() => done ? done : pull);\n})));\n/**\n * Aggregates elements using the provided sink and emits each sink result as a stream element.\n *\n * **Details**\n *\n * The stream runs the upstream and downstream in separate fibers, so the sink can keep\n * consuming input while downstream is busy processing the previous output.\n *\n * **Example** (Aggregating with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function* () {\n * const aggregated = yield* Stream.runCollect(\n * Stream.make(1, 2, 3, 4, 5, 6).pipe(\n * Stream.aggregate(\n * Sink.foldUntil(() => 0, 3, (sum, n) => Effect.succeed(sum + n))\n * )\n * )\n * )\n * aggregated // => [ 6, 15 ]\n * }))\n * ```\n *\n * @category aggregation\n * @since 2.0.0\n */\nexport const aggregate = /*#__PURE__*/dual(2, (self, sink) => aggregateWithin(self, sink, Schedule.forever));\n/**\n * Aggregates elements with a sink, emitting each result when the sink completes or the schedule triggers.\n *\n * **Details**\n *\n * The schedule can flush the current aggregation even if the sink has not finished.\n *\n * **Example** (Aggregating with a sink and schedule)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Sink, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function* () {\n * const aggregated = yield* Stream.runCollect(\n * Stream.make(1, 2, 3, 4, 5, 6).pipe(\n * Stream.aggregateWithin(\n * Sink.foldUntil(() => 0, 3, (sum, n) => Effect.succeed(sum + n)),\n * Schedule.forever\n * )\n * )\n * )\n * aggregated // => [ 6, 15 ]\n * }))\n * ```\n *\n * @category aggregation\n * @since 2.0.0\n */\nexport const aggregateWithin = /*#__PURE__*/dual(3, (self, sink, schedule) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_upstream, _, scope) {\n const pull = yield* Channel.toPullScoped(self.channel, _);\n const pullLatch = Latch.makeUnsafe(false);\n const scheduleStep = Symbol();\n const buffer = yield* Queue.make({\n capacity: 0\n });\n // upstream -> buffer\n yield* pull.pipe(pullLatch.whenOpen, Effect.flatMap(arr => {\n pullLatch.closeUnsafe();\n return Queue.offer(buffer, arr);\n }), Effect.forever,\n // don't disable autoYield to prevent choking the schedule\n Effect.catchCause(cause => Queue.failCause(buffer, cause)), Effect.forkIn(scope));\n // schedule -> buffer\n let lastOutput = Option.none();\n let leftover;\n let sinkHasInput = false;\n const step = yield* Schedule.toStepWithSleep(schedule);\n const stepLoop = Effect.suspend(function loop() {\n return Effect.flatMap(step(lastOutput), () => !sinkHasInput ? loop() : Queue.offer(buffer, scheduleStep));\n });\n const stepToBuffer = stepLoop.pipe(Effect.flatMap(() => Effect.never), Pull.catchDone(() => Cause.done()));\n // buffer -> sink\n const pullFromBuffer = Queue.take(buffer).pipe(Effect.flatMap(arr => {\n if (arr === scheduleStep) {\n return Cause.done();\n }\n sinkHasInput = true;\n return Effect.succeed(arr);\n }));\n const sinkUpstream = Effect.suspend(() => {\n if (leftover !== undefined) {\n const chunk = leftover;\n leftover = undefined;\n sinkHasInput = true;\n return Effect.succeed(chunk);\n }\n pullLatch.openUnsafe();\n return pullFromBuffer;\n });\n const catchSinkHalt = Effect.flatMap(([value, leftover_]) => {\n // ignore the last output if the upstream only pulled a halt\n if (!sinkHasInput && buffer.state._tag === \"Done\") return Cause.done();\n lastOutput = Option.some(value);\n leftover = leftover_;\n return Effect.succeed(Arr.of(value));\n });\n return Effect.suspend(() => {\n // if the buffer has exited and there is no more data to process\n if (buffer.state._tag === \"Done\" && leftover === undefined) {\n return buffer.state.exit;\n }\n sinkHasInput = leftover !== undefined;\n return Effect.succeed(Effect.suspend(() => sink.transform(sinkUpstream, scope)));\n }).pipe(Effect.flatMap(pull => Effect.raceFirst(catchSinkHalt(pull), stepToBuffer)));\n}))));\n/**\n * Creates a fixed-size tuple of streams that each emit\n * the same elements as the source stream.\n *\n * **Details**\n *\n * The source stream starts after all downstream streams have been subscribed.\n * With the default suspend strategy, the source can only advance `capacity`\n * chunks ahead of the slowest downstream stream. If a downstream stream is\n * interrupted, it unsubscribes from the broadcast so it no longer contributes\n * backpressure. Finite fractional values of `n` are rounded down. `NaN` and\n * non-positive values create no downstream streams.\n *\n * **Example** (Broadcasting to two consumers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * const [left, right] = yield* Stream.make(1, 2, 3).pipe(\n * Stream.broadcastN({ n: 2, capacity: 8 })\n * )\n *\n * const values = yield* Effect.all([\n * Stream.runCollect(left),\n * Stream.runCollect(right)\n * ], { concurrency: \"unbounded\" })\n *\n * values // => [ [ 1, 2, 3 ], [ 1, 2, 3 ] ]\n * })\n * )\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category broadcasting\n * @since 4.0.0\n */\nexport const broadcastN = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n const n = Count.normalize(options.n);\n const pubsub = yield* makePubSub(options);\n const streams = new Array(n);\n const parentScope = yield* Scope.Scope;\n for (let i = 0; i < n; i++) {\n const scope = Scope.forkUnsafe(parentScope);\n const subscription = yield* PubSub.subscribe(pubsub).pipe(Effect.provideService(Scope.Scope, scope));\n streams[i] = Channel.fromEffectTake(PubSub.take(subscription)).pipe(Channel.onExit(exit => Scope.close(scope, exit)), fromChannel);\n }\n yield* Channel.runForEach(self.channel, value => PubSub.publish(pubsub, value)).pipe(Effect.onExit(exit => PubSub.publish(pubsub, exit)), Effect.forkScoped);\n return streams;\n}));\nconst 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);\n/**\n * Creates a PubSub-backed stream that multicasts the source to all subscribers.\n *\n * **Details**\n *\n * The returned stream is scoped and uses the provided PubSub capacity and replay settings.\n *\n * **Example** (Broadcasting a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.scoped(\n * Effect.gen(function* () {\n * const broadcasted = yield* Stream.broadcast(Stream.fromArray([1, 2, 3]), {\n * capacity: 8,\n * replay: 3\n * })\n *\n * const [left, right] = yield* Effect.all([\n * Stream.runCollect(broadcasted),\n * Stream.runCollect(broadcasted)\n * ], { concurrency: \"unbounded\" })\n *\n * const result = [left, right] // => [[1, 2, 3], [1, 2, 3]]\n * })\n * )\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category broadcasting\n * @since 2.0.0\n */\nexport const broadcast = /*#__PURE__*/dual(2, (self, options) => Effect.map(toPubSubTake(self, options), fromPubSubTake));\n/**\n * Returns a new Stream that multicasts the original stream, subscribing when the first consumer starts.\n *\n * **Details**\n *\n * The upstream continues running while there is at least one consumer and is finalized after the last one exits.\n * If `idleTimeToLive` is set, the upstream is kept alive for that duration so a later subscriber can continue from\n * the next element instead of restarting.\n *\n * **Example** (Sharing a stream)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Ref, Stream } from \"effect\"\n *\n * const result = await Effect.runPromise(\n * Effect.scoped(\n * Effect.gen(function*() {\n * const firstReady = yield* Deferred.make<void>()\n * const secondReady = yield* Deferred.make<void>()\n * const acquisitions = yield* Ref.make(0)\n * const source = Stream.fromEffect(Ref.update(acquisitions, (n) => n + 1)).pipe(\n * Stream.drain,\n * Stream.concat(Stream.make(0)),\n * Stream.concat(\n * Stream.fromEffect(Effect.all([Deferred.await(firstReady), Deferred.await(secondReady)])).pipe(Stream.drain)\n * ),\n * Stream.concat(Stream.make(1, 2, 3))\n * )\n * const shared = yield* Stream.share(source, { capacity: 16, replay: 1 })\n * const consume = (ready: Deferred.Deferred<void>) =>\n * shared.pipe(\n * Stream.tap((value) => value === 0 ? Deferred.succeed(ready, void 0) : Effect.void),\n * Stream.filter((value) => value !== 0),\n * Stream.runCollect\n * )\n *\n * const values = yield* Effect.all([consume(firstReady), consume(secondReady)], { concurrency: \"unbounded\" })\n * return { values, acquisitions: yield* Ref.get(acquisitions) }\n * })\n * )\n * )\n * result // => { values: [[1, 2, 3], [1, 2, 3]], acquisitions: 1 }\n * ```\n *\n * @category broadcasting\n * @since 3.8.0\n */\nexport const share = /*#__PURE__*/dual(2, (self, options) => Effect.map(RcRef.make({\n acquire: broadcast(self, options),\n idleTimeToLive: options.idleTimeToLive\n}), ref => unwrap(RcRef.get(ref))));\n/**\n * Pipes this stream through a channel that consumes and emits chunked elements.\n *\n * **Details**\n *\n * The channel receives `NonEmptyReadonlyArray` chunks and can transform both the\n * output elements and error type.\n *\n * **Example** (Piping through a channel)\n *\n * ```ts import.meta.vitest\n * import { Array, Channel, Effect, Stream } from \"effect\"\n *\n * type NumberChunk = readonly [number, ...Array<number>]\n *\n * const doubleChunks = Channel.identity<NumberChunk, never, unknown>().pipe(\n * Channel.map((chunk) => Array.map(chunk, (n) => n * 2))\n * )\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.fromArray([1, 2, 3]).pipe(\n * Stream.rechunk(2),\n * Stream.pipeThroughChannel(doubleChunks),\n * Stream.runCollect\n * )\n * result // => [ 2, 4, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const pipeThroughChannel = /*#__PURE__*/dual(2, (self, channel) => fromChannel(Channel.pipeTo(self.channel, channel)));\n/**\n * Pipes values through the provided channel while preserving this stream's\n * failures alongside any channel failures.\n *\n * **Details**\n *\n * Upstream failures are not passed to the channel, so the resulting stream can\n * fail with either the original stream error or the channel error.\n *\n * **Example** (Piping through a channel with failures)\n *\n * ```ts import.meta.vitest\n * import { Array, Channel, Effect, Stream } from \"effect\"\n *\n * type NumberChunk = readonly [number, ...Array<number>]\n *\n * const stringifyChunks = Channel.identity<NumberChunk, \"StreamError\", unknown>().pipe(\n * Channel.map((chunk) => Array.map(chunk, String))\n * )\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * const result = yield* Stream.make(1, 2, 3).pipe(\n * Stream.rechunk(2),\n * Stream.pipeThroughChannelOrFail(stringifyChunks),\n * Stream.runCollect\n * )\n *\n * result // => [\"1\", \"2\", \"3\"]\n * }))\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const pipeThroughChannelOrFail = /*#__PURE__*/dual(2, (self, channel) => fromChannel(Channel.pipeToOrFail(self.channel, channel)));\n/**\n * Pipes the stream through `Sink.toChannel`, emitting only the sink leftovers.\n *\n * **Details**\n *\n * If the sink completes mid-chunk, the remaining elements become the output stream.\n *\n * **Example** (Piping through a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const leftovers = yield* Stream.make(1, 2, 3, 4).pipe(\n * Stream.pipeThrough(Sink.take(2)),\n * Stream.runCollect\n * )\n *\n * leftovers // => [ 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport 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));\n/**\n * Collects all elements into an array and emits it as a single element.\n *\n * **Example** (Collecting values into a stream element)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * const program = Effect.gen(function*() {\n * const collected = yield* stream.pipe(Stream.collect, Stream.runCollect)\n * collected[0] // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category accumulation\n * @since 4.0.0\n */\nexport const collect = self => fromEffect(runCollect(self));\n/**\n * Accumulates elements into a growing array, emitting the cumulative array for each input chunk.\n *\n * **Example** (Accumulating stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const accumulated = yield* Stream.runCollect(\n * Stream.fromArray([1, 2, 3]).pipe(\n * Stream.rechunk(1),\n * Stream.accumulate\n * )\n * )\n * accumulated // => [ [ 1 ], [ 1, 2 ], [ 1, 2, 3 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category accumulation\n * @since 2.0.0\n */\nexport const accumulate = self => mapAccumArray(self, Arr.empty, (acc, as) => {\n const combined = Arr.appendAll(acc, as);\n return [combined, [combined]];\n});\n/**\n * Emits only elements that differ from the previous one.\n *\n * **Example** (Emitting changed values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.fromIterable([1, 1, 2, 2, 3]).pipe(\n * Stream.changes,\n * Stream.runCollect\n * )\n *\n * values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const changes = self => changesWith(self, Equal.equals);\n/**\n * Returns a stream that only emits elements that are not equal to the previously emitted element, as determined by the specified predicate.\n *\n * **Example** (Emitting values that changed by equivalence)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"A\", \"a\", \"B\", \"b\", \"b\").pipe(\n * Stream.changesWith((left, right) => left.toLowerCase() === right.toLowerCase())\n * )\n *\n * await Effect.runPromise(\n * Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 'A', 'B' ]\n * })\n * )\n * ```\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const changesWith = /*#__PURE__*/dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let first = true;\n let last;\n return Effect.flatMap(pull, function loop(arr) {\n const out = [];\n let i = 0;\n if (first) {\n first = false;\n last = arr[0];\n i = 1;\n out.push(last);\n }\n for (; i < arr.length; i++) {\n const a = arr[i];\n if (f(a, last)) continue;\n last = a;\n out.push(a);\n }\n return Arr.isArrayNonEmpty(out) ? Effect.succeed(out) : Effect.flatMap(pull, loop);\n });\n})));\n/**\n * Emits only elements that differ from the previous element, using an effectful equality check.\n *\n * **Details**\n *\n * The predicate runs for each element after the first; returning `true` treats it as equal and skips it.\n *\n * **Example** (Effectfully emitting changed values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.make(1, 1, 2, 2, 3, 3).pipe(\n * Stream.changesWithEffect((a, b) => Effect.succeed(a === b))\n * )\n * const result = yield* Stream.runCollect(stream)\n * result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const changesWithEffect = /*#__PURE__*/dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n let first = true;\n let last;\n return Effect.flatMap(pull, Effect.fnUntraced(function* loop(arr) {\n const out = [];\n let i = 0;\n if (first) {\n first = false;\n last = arr[0];\n i = 1;\n out.push(last);\n }\n for (; i < arr.length; i++) {\n const a = arr[i];\n if (yield* f(a, last)) continue;\n last = a;\n out.push(a);\n }\n return Arr.isArrayNonEmpty(out) ? out : yield* Effect.flatMap(pull, Effect.fnUntraced(loop));\n }));\n})));\n/**\n * Decodes Uint8Array chunks into strings using TextDecoder with an optional encoding.\n *\n * **Example** (Decoding Uint8Array chunks into strings using TextDecoder with an optional encoding)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const encoder = new TextEncoder()\n * const stream = Stream.make(\n * encoder.encode(\"Hello\"),\n * encoder.encode(\" World\")\n * )\n *\n * const program = Effect.gen(function*() {\n * const decoded = yield* stream.pipe(\n * Stream.decodeText,\n * Stream.runCollect\n * )\n * decoded // => [ 'Hello', ' World' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeText = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => suspend(() => {\n const decoder = new TextDecoder(options?.encoding);\n return map(self, chunk => decoder.decode(chunk, {\n stream: true\n }));\n}));\n/**\n * Encodes a stream of strings into UTF-8 `Uint8Array` chunks.\n *\n * **Example** (Encoding a stream of strings into UTF-8 Uint8Array chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"Hello\", \" \", \"World\")\n * const program = Effect.gen(function*() {\n * const encoded = Stream.encodeText(stream)\n * const chunks = yield* Stream.runCollect(encoded)\n * const bytes = chunks.map((chunk) => [...chunk])\n * bytes // => [ [ 72, 101, 108, 108, 111 ], [ 32 ], [ 87, 111, 114, 108, 100 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category encoding\n * @since 2.0.0\n */\nexport const encodeText = self => suspend(() => {\n const encoder = new TextEncoder();\n return map(self, chunk => encoder.encode(chunk));\n});\n/**\n * Splits a stream of strings into lines, handling `\\n`, `\\r`, and `\\r\\n` delimiters across chunks.\n *\n * **Example** (Splitting streamed text into lines)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function* () {\n * const lines = yield* Stream.runCollect(\n * Stream.make(\"a\\nb\\r\\n\", \"c\\n\").pipe(Stream.splitLines)\n * )\n * lines // => [ 'a', 'b', 'c' ]\n * }))\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitLines = self => self.channel.pipe(Channel.pipeTo(Channel.splitLines()), fromChannel);\n/**\n * Inserts the provided element between emitted elements.\n *\n * **Example** (Interspersing stream elements)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const stream = Stream.make(1, 2, 3, 4).pipe(Stream.intersperse(0))\n * const result = yield* Stream.runCollect(stream)\n * result // => [1, 0, 2, 0, 3, 0, 4]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const intersperse = /*#__PURE__*/dual(2, (self, element) => mapArray(self, (arr, i) => {\n const out = i === 0 ? [] : [element];\n const lastIndex = arr.length - 1;\n for (let j = 0; j < arr.length; j++) {\n if (j === lastIndex) {\n out.push(arr[j]);\n } else {\n out.push(arr[j], element);\n }\n }\n return out;\n}));\n/**\n * Adds a start value, middle value, and end value around stream elements.\n *\n * **Details**\n *\n * The start and end values are always emitted, even when the stream is empty.\n *\n * **Example** (Interspersing stream affixes)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"a\", \"b\", \"c\").pipe(\n * Stream.intersperseAffixes({ start: \"[\", middle: \",\", end: \"]\" })\n * )\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(stream)\n * result // => [\"[\", \"a\", \",\", \"b\", \",\", \"c\", \"]\"]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const intersperseAffixes = /*#__PURE__*/dual(2, (self, options) => succeed(options.start).pipe(concat(intersperse(self, options.middle)), concat(succeed(options.end))));\n/**\n * Interleaves this stream with the specified stream by alternating pulls from\n * each stream; when one ends, the remaining values from the other stream are\n * emitted.\n *\n * **Example** (Interleaving streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.interleave(\n * Stream.make(2, 3),\n * Stream.make(5, 6, 7)\n * )\n *\n * const program = Effect.gen(function*() {\n * const collected = yield* Stream.runCollect(stream)\n * collected // => [ 2, 5, 3, 6, 7 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const interleave = /*#__PURE__*/dual(2, (self, that) => interleaveWith(self, that, fromIterable(Iterable.forever([true, false]))));\n/**\n * Interleaves two streams deterministically by following a boolean decider stream.\n *\n * **Details**\n *\n * The decider controls how many elements are pulled; if one side ends, pulls for\n * that side are ignored.\n *\n * **Example** (Interleaving two streams deterministically by following a boolean decider stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const left = Stream.make(1, 3, 5)\n * const right = Stream.make(2, 4, 6)\n * const decider = Stream.make(true, false, false, true, true)\n *\n * const values = yield* Stream.runCollect(\n * Stream.interleaveWith(left, right, decider)\n * )\n *\n * values // => [ 1, 2, 4, 3, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const interleaveWith = /*#__PURE__*/dual(3, (self, that, decider) => fromChannel(Channel.fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n const pullDecider = yield* Channel.toTransform(Channel.flattenArray(decider.channel))(upstream, scope);\n const retry = Symbol();\n let leftDone = false;\n let rightDone = false;\n const pullLeft = (yield* Channel.toTransform(Channel.flattenArray(self.channel))(upstream, scope)).pipe(Pull.catchDone(() => {\n leftDone = true;\n return Effect.succeed(retry);\n }));\n const pullRight = (yield* Channel.toTransform(Channel.flattenArray(that.channel))(upstream, scope)).pipe(Pull.catchDone(() => {\n rightDone = true;\n return Effect.succeed(retry);\n }));\n return Effect.gen(function* () {\n while (true) {\n if (leftDone && rightDone) {\n return yield* Cause.done();\n }\n const side = yield* pullDecider;\n if (side && leftDone) continue;\n if (!side && rightDone) continue;\n const elem = yield* side ? pullLeft : pullRight;\n if (elem === retry) continue;\n return Arr.of(elem);\n }\n });\n}))));\n/**\n * Interrupts the evaluation of this stream when the provided effect\n * completes. The given effect will be forked as part of this stream, and its\n * success will be discarded. This combinator will also interrupt any\n * in-progress element being pulled from upstream.\n *\n * **Details**\n *\n * If the effect completes with a failure before the stream completes, the\n * returned stream will emit that failure.\n *\n * **Example** (Interrupting when an effect completes)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const interrupt = yield* Deferred.make<void>()\n * const stream = Stream.make(1, 2, 3).pipe(\n * Stream.tap((value) =>\n * value === 2\n * ? Deferred.succeed(interrupt, void 0)\n * : Effect.void\n * ),\n * Stream.interruptWhen(Deferred.await(interrupt))\n * )\n *\n * const result = yield* Stream.runCollect(stream)\n * result // => [ 1 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptWhen = /*#__PURE__*/dual(2, (self, effect) => fromChannel(Channel.interruptWhen(self.channel, effect)));\n/**\n * Stops a stream after the current pull when an effect completes.\n *\n * **When to use**\n *\n * Use to stop before the next pull after an external signal completes.\n *\n * **Details**\n *\n * The effect is forked, its success value is discarded, and its failure fails\n * the stream.\n *\n * **Gotchas**\n *\n * This does not interrupt or truncate an in-progress pull. A pull may emit\n * multiple elements in a single chunk, in which case the entire chunk is\n * emitted. Use {@link interruptWhen} when the stream should be interrupted\n * immediately.\n *\n * **Example** (Halting a stream after an effect completes)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const halt = yield* Deferred.make<void>()\n * const values = yield* Stream.fromArray([1, 2, 3]).pipe(\n * Stream.tap((value) => value === 2 ? Deferred.succeed(halt, void 0) : Effect.void),\n * Stream.haltWhen(Deferred.await(halt)),\n * Stream.runCollect\n * )\n * values // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const haltWhen = /*#__PURE__*/dual(2, (self, effect) => fromChannel(Channel.haltWhen(self.channel, effect)));\n/**\n * Runs the provided finalizer when the stream exits, passing the exit value.\n *\n * **Example** (Running a finalizer on exit)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Stream } from \"effect\"\n *\n * const exits: Array<string> = []\n * const stream = Stream.make(1, 2, 3).pipe(\n * Stream.onExit((exit) =>\n * Exit.isSuccess(exit)\n * ? Effect.sync(() => exits.push(\"success\"))\n * : Effect.sync(() => exits.push(\"failure\"))\n * )\n * )\n *\n * await Effect.runPromise(Effect.gen(function*() {\n * yield* Stream.runCollect(stream)\n * }))\n * exits // => [\"success\"]\n * ```\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onExit = /*#__PURE__*/dual(2, (self, finalizer) => fromChannel(Channel.onExit(self.channel, finalizer)));\n/**\n * Runs the provided effect when the stream fails, passing the failure cause.\n *\n * **Gotchas**\n *\n * Note: Unlike `Effect.onError` there is no guarantee that the provided\n * effect will not be interrupted.\n *\n * **Example** (Running an effect on errors)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Stream } from \"effect\"\n *\n * const errors: Array<string> = []\n * const program = Effect.gen(function*() {\n * const stream = Stream.make(1, 2, 3).pipe(\n * Stream.concat(Stream.fail(\"boom\")),\n * Stream.onError((cause) => Effect.sync(() => errors.push(String(Cause.squash(cause)))))\n * )\n *\n * yield* Stream.runCollect(stream)\n * })\n *\n * await Effect.runPromise(Effect.exit(program))\n * errors // => [\"boom\"]\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const onError = /*#__PURE__*/dual(2, (self, cleanup) => fromChannel(Channel.onError(self.channel, cleanup)));\n/**\n * Runs the provided effect before this stream starts.\n *\n * **Example** (Running an effect on start)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n * const stream = Stream.fromArray([1, 2, 3]).pipe(\n * Stream.onStart(Effect.sync(() => events.push(\"started\")))\n * )\n *\n * const values = yield* Stream.runCollect(stream)\n * values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"started\"]\n * ```\n *\n * @category sequencing\n * @since 3.6.0\n */\nexport const onStart = /*#__PURE__*/dual(2, (self, onStart) => fromChannel(Channel.onStart(self.channel, onStart)));\n/**\n * Runs the provided effect with the first element emitted by the stream.\n *\n * **Example** (Running an effect on the first value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const first: Array<number> = []\n * await Effect.runPromise(Effect.gen(function* () {\n * yield* Stream.fromArray([1, 2, 3]).pipe(\n * Stream.onFirst((value) => Effect.sync(() => first.push(value))),\n * Stream.runDrain\n * )\n * }))\n * first // => [1]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const onFirst = /*#__PURE__*/dual(2, (self, onFirst) => fromChannel(Channel.onFirst(self.channel, arr => onFirst(arr[0]))));\n/**\n * Runs the provided effect when the stream ends successfully.\n *\n * **Example** (Running an effect on end)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.make(1, 2, 3).pipe(\n * Stream.onEnd(Effect.sync(() => events.push(\"ended\"))),\n * Stream.runCollect\n * )\n * values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"ended\"]\n * ```\n *\n * @category sequencing\n * @since 3.6.0\n */\nexport const onEnd = /*#__PURE__*/dual(2, (self, onEnd) => fromChannel(Channel.onEnd(self.channel, onEnd)));\n/**\n * Executes the provided finalizer after this stream's finalizers run.\n *\n * **Example** (Ensuring finalization)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const stream = Stream.fromArray([1, 2]).pipe(\n * Stream.ensuring(Effect.sync(() => events.push(\"cleanup\")))\n * )\n *\n * const program = Effect.gen(function*() {\n * const collected = yield* Stream.runCollect(stream)\n * collected // => [1, 2]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"cleanup\"]\n * ```\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => fromChannel(Channel.ensuring(self.channel, finalizer)));\n/**\n * Provides a layer or context to the stream, removing the corresponding\n * service requirements. Use `options.local` to build the layer every time; by\n * default, layers are shared between provide calls.\n *\n * **Example** (Providing stream requirements)\n *\n * ```ts import.meta.vitest\n * import { Console, Context, Effect, Layer, Stream } from \"effect\"\n *\n * class Env extends Context.Service<Env, { readonly name: string }>()(\"Env\") {}\n *\n * const layer = Layer.succeed(Env)({ name: \"Ada\" })\n *\n * const stream = Stream.fromEffect(\n * Effect.gen(function*() {\n * const env = yield* Effect.service(Env)\n * return `Hello, ${env.name}`\n * })\n * )\n *\n * const withEnv = stream.pipe(Stream.provide(layer))\n *\n * await Effect.runPromise(Stream.runCollect(withEnv)) // => [\"Hello, Ada\"]\n * ```\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provide = /*#__PURE__*/dual(args => isStream(args[0]), (self, layer, options) => fromChannel(Channel.provide(self.channel, layer, options)));\n/**\n * Provides multiple services to the stream using a context.\n *\n * **Example** (Providing multiple services to the stream using a context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Config extends Context.Service<Config, { readonly prefix: string }>()(\"Config\") {}\n * class Greeter extends Context.Service<Greeter, { greet: (name: string) => string }>()(\"Greeter\") {}\n *\n * const context = Context.make(Config, { prefix: \"Hello\" }).pipe(\n * Context.add(Greeter, { greet: (name: string) => `${name}!` })\n * )\n *\n * const stream = Stream.fromEffect(\n * Effect.gen(function*() {\n * const config = yield* Effect.service(Config)\n * const greeter = yield* Effect.service(Greeter)\n * return greeter.greet(config.prefix)\n * })\n * )\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(Stream.provideContext(stream, context))\n * result // => [ 'Hello!' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideContext = /*#__PURE__*/dual(2, (self, context) => fromChannel(Channel.provideContext(self.channel, context)));\n/**\n * Provides the stream with a single required service, eliminating that\n * requirement from its environment.\n *\n * **Example** (Providing a stream service)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Greeter extends Context.Service<Greeter, {\n * greet: (name: string) => string\n * }>()(\"Greeter\") {}\n *\n * const stream = Stream.fromEffect(\n * Effect.service(Greeter).pipe(\n * Effect.map((greeter) => greeter.greet(\"Ada\"))\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * const collected = yield* Stream.runCollect(\n * stream.pipe(\n * Stream.provideService(Greeter, {\n * greet: (name) => `Hello, ${name}`\n * })\n * )\n * )\n * collected // => [ 'Hello, Ada' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideService = /*#__PURE__*/dual(3, (self, key, service) => fromChannel(Channel.provideService(self.channel, key, service)));\n/**\n * Provides a service to the stream using an effect, removing the requirement and adding the effect's error and environment.\n *\n * **Example** (Providing a stream service effectfully)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class ApiConfig extends Context.Service<ApiConfig, { readonly baseUrl: string }>()(\"ApiConfig\") {}\n *\n * const stream = Stream.fromEffect(\n * Effect.gen(function*() {\n * const config = yield* Effect.service(ApiConfig)\n * return config.baseUrl\n * })\n * )\n *\n * const events: Array<string> = []\n * const withConfig = stream.pipe(\n * Stream.provideServiceEffect(\n * ApiConfig,\n * Effect.succeed({ baseUrl: \"https://example.com\" }).pipe(\n * Effect.tap(() => Effect.sync(() => events.push(\"loading\")))\n * )\n * )\n * )\n *\n * await Effect.runPromise(Stream.runCollect(withConfig)) // => [\"https://example.com\"]\n * events // => [\"loading\"]\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideServiceEffect = /*#__PURE__*/dual(3, (self, key, service) => fromChannel(Channel.provideServiceEffect(self.channel, key, service)));\n/**\n * Transforms the stream's required services by mapping the current context\n * to a new one.\n *\n * **Example** (Updating the stream context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Logger extends Context.Service<Logger, { prefix: string }>()(\"Logger\") {}\n * class Config extends Context.Service<Config, { name: string }>()(\"Config\") {}\n *\n * const stream = Stream.fromEffect(\n * Effect.gen(function*() {\n * const logger = yield* Effect.service(Logger)\n * const config = yield* Effect.service(Config)\n * return `${logger.prefix}${config.name}`\n * })\n * )\n *\n * const updated = stream.pipe(\n * Stream.updateContext((context: Context.Context<Logger>) =>\n * Context.add(context, Config, { name: \"World\" })\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * const values = yield* Stream.runCollect(updated)\n * values // => [ 'Hello World' ]\n * })\n *\n * await Effect.runPromise(\n * Effect.provideService(program, Logger, { prefix: \"Hello \" })\n * )\n * ```\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const updateContext = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.updateContext(self.channel, f)));\n/**\n * Updates a single service in the stream environment by applying a function.\n *\n * **Example** (Updating a stream service)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Counter extends Context.Service<Counter, { count: number }>()(\"Counter\") {}\n *\n * const stream = Stream.fromEffect(Effect.service(Counter)).pipe(\n * Stream.updateService(Counter, (counter) => ({ count: counter.count + 1 }))\n * )\n *\n * const program = Effect.gen(function*() {\n * const counters = yield* Stream.runCollect(stream)\n * const message = `Updated count: ${counters[0].count}` // => \"Updated count: 1\"\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Counter, { count: 0 }))\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const updateService = /*#__PURE__*/dual(3, (self, service, f) => updateContext(self, context => Context.add(context, service, f(Context.get(context, service)))));\n/**\n * Wraps the stream with a new span for tracing.\n *\n * **Example** (Wrapping a stream in a span)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.fromArray([1, 2, 3]).pipe(Stream.withSpan(\"numbers\"))\n *\n * await Effect.runPromise(\n * Effect.gen(function*() {\n * const values = yield* Stream.runCollect(stream)\n * values // => [ 1, 2, 3 ]\n * })\n * )\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withSpan = function () {\n const dataFirst = isStream(arguments[0]);\n const name = dataFirst ? arguments[1] : arguments[0];\n const options = addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]);\n if (dataFirst) {\n const self = arguments[0];\n return fromChannel(Channel.withSpan(self.channel, name, options));\n }\n return self => fromChannel(Channel.withSpan(self.channel, name, options));\n};\n/**\n * Provides the entry point for do-notation style stream composition.\n *\n * **Example** (Starting stream do notation)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe, Stream } from \"effect\"\n *\n * const program = pipe(\n * Stream.Do,\n * Stream.bind(\"value\", () => Stream.fromArray([1, 2])),\n * Stream.let(\"next\", ({ value }) => value + 1)\n * )\n *\n * const effect = Effect.gen(function*() {\n * const collected = yield* Stream.runCollect(program)\n * collected // => [ { value: 1, next: 2 }, { value: 2, next: 3 } ]\n * })\n *\n * await Effect.runPromise(effect)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const Do = /*#__PURE__*/succeed({});\nconst let_ = /*#__PURE__*/dual(3, (self, name, f) => map(self, a => ({\n ...a,\n [name]: f(a)\n})));\nexport {\n/**\n * Adds a computed field to the current Do-notation record.\n *\n * **Example** (Adding a computed field)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.Do.pipe(\n * Stream.let(\"x\", () => 2),\n * Stream.let(\"y\", ({ x }) => x * 3)\n * )\n *\n * const program = Effect.gen(function*() {\n * const records = yield* Stream.runCollect(stream)\n * records // => [ { x: 2, y: 6 } ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nlet_ as let };\n/**\n * Binds the result of a stream to a field in the do-notation record.\n *\n * **Example** (Binding a stream value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Stream.Do.pipe(\n * Stream.bind(\"a\", () => Stream.make(1, 2)),\n * Stream.bind(\"b\", ({ a }) => Stream.succeed(a + 1))\n * )\n *\n * const result = Stream.runCollect(program)\n *\n * await Effect.runPromise(result) // => [{ a: 1, b: 2 }, { a: 2, b: 3 }]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const bind = /*#__PURE__*/dual(args => isStream(args[0]), (self, tag, f, options) => flatMap(self, a => map(f(a), b => ({\n ...a,\n [tag]: b\n})), options));\n/**\n * Binds an Effect-produced value into the do-notation record for each stream element.\n *\n * **Example** (Binding an effect value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.Do.pipe(\n * Stream.bind(\"value\", () => Stream.make(1, 2)),\n * Stream.bindEffect(\"double\", ({ value }) => Effect.succeed(value * 2))\n * )\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Stream.runCollect(stream)\n * result // => [ { value: 1, double: 2 }, { value: 2, double: 4 } ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const bindEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, tag, f, options) => mapEffect(self, a => Effect.map(f(a), b => ({\n ...a,\n [tag]: b\n})), options));\n/**\n * Maps each element into a record keyed by the provided name.\n *\n * **Example** (Binding values to a record key)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3).pipe(Stream.bindTo(\"value\"))\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [{ value: 1 }, { value: 2 }, { value: 3 }]\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, a => ({\n [name]: a\n})));\n/**\n * Runs a stream with a sink and returns the sink result.\n *\n * **Example** (Running a stream with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const program = Stream.run(Stream.make(1, 2, 3), Sink.sum)\n *\n * await Effect.runPromise(program) // => 6\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport 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))));\n/**\n * Runs the stream and collects all elements into an array.\n *\n * **Example** (Collecting stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n *\n * const program = Effect.gen(function*() {\n * const collected = yield* Stream.runCollect(stream)\n * collected // => [ 1, 2, 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runCollect = self => Channel.runFold(self.channel, () => [], (acc, chunk) => {\n for (let i = 0; i < chunk.length; i++) {\n acc.push(chunk[i]);\n }\n return acc;\n});\n/**\n * Runs the stream and returns the number of elements emitted.\n *\n * **Example** (Counting stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n *\n * const program = Effect.gen(function* () {\n * const count = yield* Stream.runCount(stream)\n * count // => 5\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runCount = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => acc + chunk.length);\n/**\n * Runs the stream and returns the numeric sum of its elements.\n *\n * **Example** (Summing stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const total = yield* Stream.runSum(Stream.make(1, 2, 3))\n * total // => 6\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runSum = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => {\n for (let i = 0; i < chunk.length; i++) {\n acc += chunk[i];\n }\n return acc;\n});\n/**\n * Runs the stream and folds elements using a pure reducer.\n *\n * **Example** (Folding stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const total = yield* Stream.runFold(\n * Stream.make(1, 2, 3),\n * () => 0,\n * (acc, n) => acc + n\n * )\n * total // => 6\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runFold = /*#__PURE__*/dual(3, (self, initial, f) => Channel.runFold(self.channel, initial, (acc, arr) => {\n for (let i = 0; i < arr.length; i++) {\n acc = f(acc, arr[i]);\n }\n return acc;\n}));\n/**\n * Runs the stream and folds elements using an effectful reducer.\n *\n * **When to use**\n *\n * Use when reducing stream elements needs Effects, services, or failures in the\n * reducer.\n *\n * **Example** (Effectfully folding stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const total = yield* Stream.runFoldEffect(\n * Stream.make(1, 2, 3),\n * () => 0,\n * (acc, n) => Effect.succeed(acc + n)\n * )\n * total // => 6\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Channel.runFoldEffect(self.channel, initial, (acc, arr) => {\n let i = 0;\n let s = acc;\n return Effect.map(Effect.whileLoop({\n while: () => i < arr.length,\n body: () => f(s, arr[i]),\n step(z) {\n s = z;\n i++;\n }\n }), () => s);\n}));\n/**\n * Runs the stream and returns the first element as an `Option`.\n *\n * **Example** (Getting the first stream value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const head = yield* Stream.runHead(Stream.make(1, 2, 3))\n * Option.getOrThrow(head) // => 1\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runHead = self => Effect.map(Channel.runHead(self.channel), Option.map(Arr.getUnsafe(0)));\n/**\n * Runs the stream and returns the last element as an `Option`.\n *\n * **When to use**\n *\n * Use to consume a finite stream when only the final emitted element matters.\n *\n * **Details**\n *\n * `Option.some` contains the last emitted element. `Option.none` means the\n * stream completed without emitting.\n *\n * **Gotchas**\n *\n * The returned effect waits for the stream to complete before it can produce a\n * value.\n *\n * @see {@link runHead} for consuming only the first emitted element\n * @see {@link runCollect} for collecting every emitted element\n * @see {@link runDrain} for consuming the stream while discarding emitted elements\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runLast = self => Effect.map(Channel.runLast(self.channel), Option.map(Arr.lastNonEmpty));\n/**\n * Runs the provided effectful callback for each element of the stream.\n *\n * **Example** (Running an effect for each value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n * const values: Array<string> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Stream.runForEach(stream, (n) => Effect.sync(() => values.push(`Processing: ${n}`)))\n * })\n *\n * await Effect.runPromise(program)\n * values // => [\"Processing: 1\", \"Processing: 2\", \"Processing: 3\"]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runForEach = /*#__PURE__*/dual(2, (self, f) => Channel.runForEach(self.channel, arr => {\n let i = 0;\n return Effect.whileLoop({\n while: () => i < arr.length,\n body: () => f(arr[i++]),\n step: constVoid\n });\n}));\n/**\n * Runs the stream, applying the effectful predicate to each element and\n * stopping when it returns `false`.\n *\n * **Example** (Running effects while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const values: Array<number> = []\n * const program = Effect.gen(function*() {\n * const stream = Stream.make(1, 2, 3, 4, 5)\n *\n * yield* Stream.runForEachWhile(stream, (n) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => values.push(n))\n * return n < 3\n * })\n * )\n * })\n *\n * await Effect.runPromise(program)\n * values // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => Channel.runForEachWhile(self.channel, arr => {\n let done = false;\n let i = 0;\n return Effect.map(Effect.whileLoop({\n while: () => !done && i < arr.length,\n body: () => f(arr[i]),\n step(b) {\n i++;\n if (!b) done = true;\n }\n }), () => !done);\n}));\n/**\n * Consumes the stream in chunks, passing each non-empty array to the callback.\n *\n * **Example** (Consuming stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n * const chunks: Array<string> = []\n * const program = Effect.gen(function*() {\n * yield* Stream.runForEachArray(\n * stream,\n * (chunk) => Effect.sync(() => chunks.push(chunk.join(\", \")))\n * )\n * })\n *\n * await Effect.runPromise(program)\n * chunks // => [\"1, 2, 3, 4, 5\"]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runForEachArray = /*#__PURE__*/dual(2, (self, f) => Channel.runForEach(self.channel, f));\n/**\n * Runs the stream for its effects, discarding emitted elements.\n *\n * **Example** (Draining a stream run)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const values: Array<number> = []\n * const program = Effect.gen(function*() {\n * const stream = Stream.make(1, 2, 3).pipe(\n * Stream.mapEffect((n) => Effect.sync(() => values.push(n)))\n * )\n *\n * yield* Stream.runDrain(stream)\n * })\n *\n * await Effect.runPromise(program)\n * values // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runDrain = self => Channel.runDrain(self.channel);\n/**\n * Returns a scoped pull for manually consuming the stream's output chunks.\n *\n * **Details**\n *\n * The pull fails with `Cause.Done` when the stream ends and with the stream\n * error on failure.\n *\n * **Example** (Creating a scoped pull)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * const pull = yield* Stream.toPull(stream)\n * const chunk = yield* pull\n * chunk // => [ 1, 2, 3 ]\n * })\n * )\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toPull = self => Channel.toPull(self.channel);\n/**\n * Concatenates all emitted strings into a single string.\n *\n * **Example** (Joining strings from a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"Hello\", \" \", \"World\", \"!\")\n * const program = Effect.gen(function*() {\n * const text = yield* Stream.mkString(stream)\n * text // => \"Hello World!\"\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const mkString = self => Channel.runFold(self.channel, () => \"\", (acc, chunk) => acc + chunk.join(\"\"));\n/**\n * Concatenates the stream's `Uint8Array` chunks into a single `ArrayBuffer`.\n *\n * **Gotchas**\n *\n * This materializes the full content in memory. The source stream must not\n * reuse or mutate emitted buffers, which are retained until collection completes.\n *\n * **Example** (Joining byte chunks into an ArrayBuffer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Stream.make(\n * new Uint8Array([1, 2]),\n * new Uint8Array([3, 4])\n * ).pipe(\n * Stream.mkArrayBuffer,\n * Effect.map((buffer) => [...new Uint8Array(buffer)])\n * )\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const mkArrayBuffer = self => Effect.map(Channel.mkUint8Array(self.channel), bytes => bytes.buffer);\n/**\n * Concatenates the stream's `Uint8Array` chunks into a single `Uint8Array`.\n *\n * **Gotchas**\n *\n * This materializes the full content in memory. The source stream must not\n * reuse or mutate emitted buffers, which are retained until collection completes.\n *\n * **Example** (Joining Uint8Array chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(new Uint8Array([1, 2]), new Uint8Array([3, 4]))\n * const program = Effect.gen(function*() {\n * const bytes = yield* Stream.mkUint8Array(stream)\n * const values = Array.from(bytes) // => [1, 2, 3, 4]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const mkUint8Array = self => Channel.mkUint8Array(self.channel);\n/**\n * Converts the stream to a `ReadableStream` using the provided services.\n *\n * **When to use**\n *\n * Use when bridging to Web Streams and you already have the `Context` required\n * to run the stream outside an `Effect`.\n *\n * **Details**\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * **Example** (Converting to a ReadableStream with services)\n *\n * ```ts import.meta.vitest\n * import { Context, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n * const readableStream = Stream.toReadableStreamWith(stream, Context.empty())\n * const values = await Array.fromAsync(readableStream)\n * values // => [ 1, 2, 3, 4, 5 ]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toReadableStreamWith = /*#__PURE__*/dual(args => isStream(args[0]), (self, context, options) => {\n let currentResolve = undefined;\n let fiber = undefined;\n const latch = Latch.makeUnsafe(false);\n return new ReadableStream({\n start(controller) {\n fiber = Effect.runFork(Effect.provideContext(runForEachArray(self, chunk => latch.whenOpen(Effect.sync(() => {\n latch.closeUnsafe();\n for (let i = 0; i < chunk.length; i++) {\n controller.enqueue(chunk[i]);\n }\n currentResolve();\n currentResolve = undefined;\n }))), context));\n fiber.addObserver(exit => {\n if (exit._tag === \"Failure\") {\n controller.error(Cause.squash(exit.cause));\n } else {\n controller.close();\n }\n });\n },\n pull() {\n return new Promise(resolve => {\n currentResolve = resolve;\n latch.openUnsafe();\n });\n },\n cancel() {\n if (!fiber) return;\n return Effect.runPromise(Effect.asVoid(Fiber.interrupt(fiber)));\n }\n }, options?.strategy);\n});\n/**\n * Converts a stream to a `ReadableStream`.\n *\n * **Details**\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * **Example** (Converting a stream to a ReadableStream)\n *\n * ```ts import.meta.vitest\n * import { Stream } from \"effect\"\n *\n * const readableStream = Stream.toReadableStream(Stream.make(1, 2, 3))\n * const values = await Array.fromAsync(readableStream)\n * values // => [ 1, 2, 3 ]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toReadableStream = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => toReadableStreamWith(self, Context.empty(), options));\n/**\n * Creates an Effect that builds a ReadableStream from the stream.\n *\n * **When to use**\n *\n * Use when bridging to Web Streams from inside an `Effect` so the required\n * services can be captured from the current context.\n *\n * **Details**\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * **Example** (Creating a ReadableStream effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n *\n * const effect = Effect.gen(function*() {\n * const readableStream = yield* Stream.toReadableStreamEffect(stream)\n * readableStream instanceof ReadableStream // => true\n * })\n *\n * await Effect.runPromise(effect)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toReadableStreamEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => Effect.map(Effect.context(), context => toReadableStreamWith(self, context, options)));\n/**\n * Converts the stream to an `AsyncIterable` using the provided services.\n *\n * **When to use**\n *\n * Use when converting outside an Effect and you already have the `Context`\n * needed to run the stream.\n *\n * **Example** (Converting to an AsyncIterable with services)\n *\n * ```ts import.meta.vitest\n * import { Context, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n * const iterable = Stream.toAsyncIterableWith(stream, Context.empty())\n *\n * await Array.fromAsync(iterable) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toAsyncIterableWith = /*#__PURE__*/dual(2, (self, context) => ({\n [Symbol.asyncIterator]() {\n const runPromise = Effect.runPromiseWith(context);\n const runFork = Effect.runForkWith(context);\n const scope = Scope.makeUnsafe();\n let pull;\n let currentIter;\n let currentFiber;\n let closePromise;\n const close = exit => {\n if (closePromise) return closePromise;\n const fiber = currentFiber;\n closePromise = runPromise(Effect.as(Effect.andThen(fiber ? Fiber.interrupt(fiber) : Effect.void, Scope.close(scope, exit)), {\n done: true,\n value: undefined\n }));\n return closePromise;\n };\n const closeAndReportError = async exit => {\n try {\n await close(exit);\n } catch (error) {\n await runPromise(Effect.logError(\"Suppressed error while closing Stream async iterator\", error));\n }\n };\n return {\n async next() {\n if (closePromise) return closePromise;\n if (currentIter) {\n const next = currentIter.next();\n if (!next.done) return next;\n currentIter = undefined;\n }\n const fiber = runFork(pull ?? Effect.flatMap(Channel.toPullScoped(self.channel, scope), nextPull => {\n pull = nextPull;\n return nextPull;\n }));\n currentFiber = fiber;\n const exit = await runPromise(Fiber.await(fiber));\n if (currentFiber === fiber) {\n currentFiber = undefined;\n }\n if (Exit.isSuccess(exit)) {\n currentIter = exit.value[Symbol.iterator]();\n return currentIter.next();\n } else if (Pull.isDoneCause(exit.cause)) {\n return close(Exit.void);\n }\n if (closePromise && Cause.hasInterruptsOnly(exit.cause)) {\n return closePromise;\n }\n await closeAndReportError(exit);\n throw Cause.squash(exit.cause);\n },\n return() {\n return close(Exit.void);\n },\n async throw(error) {\n await closeAndReportError(Exit.die(error));\n throw error;\n }\n };\n }\n}));\n/**\n * Creates an effect that yields an `AsyncIterable` using the current services.\n *\n * **When to use**\n *\n * Use when the `AsyncIterable` should be created inside Effect with the current\n * context supplying the stream's services.\n *\n * **Example** (Creating an AsyncIterable effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * const program = Effect.gen(function*() {\n * const iterable = yield* Stream.toAsyncIterableEffect(stream)\n * return yield* Effect.promise(() => Array.fromAsync(iterable))\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 3.15.0\n */\nexport const toAsyncIterableEffect = self => Effect.map(Effect.context(), context => toAsyncIterableWith(self, context));\n/**\n * Converts a stream to an `AsyncIterable` for `for await...of` consumption.\n *\n * **Example** (Converting to an async iterable)\n *\n * ```ts import.meta.vitest\n * import { Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * await Array.fromAsync(Stream.toAsyncIterable(stream)) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 3.15.0\n */\nexport const toAsyncIterable = self => toAsyncIterableWith(self, Context.empty());\n/**\n * Runs the stream, publishing elements into the provided PubSub.\n *\n * **Details**\n *\n * `shutdownOnEnd` controls whether the PubSub is shut down when the stream ends.\n * It only shuts down when set to `true`.\n *\n * **Example** (Running a stream into a PubSub)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function* () {\n * const pubsub = yield* PubSub.unbounded<number>()\n * const subscription = yield* PubSub.subscribe(pubsub)\n *\n * yield* Stream.runIntoPubSub(Stream.fromIterable([1, 2]), pubsub)\n *\n * const first = yield* PubSub.take(subscription)\n * const second = yield* PubSub.take(subscription)\n *\n * first // => 1\n * second // => 2\n * }))\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runIntoPubSub = /*#__PURE__*/dual(args => isStream(args[0]), (self, pubsub, options) => Channel.runIntoPubSubArray(self.channel, pubsub, options));\n/**\n * Converts a stream to a PubSub of emitted values for concurrent consumption.\n *\n * **Details**\n *\n * `shutdownOnEnd` indicates whether the PubSub should be shut down when the\n * stream ends. By default this is `true`.\n *\n * **Example** (Converting a stream to a PubSub for concurrent consumption)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function* () {\n * const pubsub = yield* Stream.fromArray([1, 2]).pipe(\n * Stream.toPubSub({ capacity: 8 })\n * )\n * const subscription = yield* PubSub.subscribe(pubsub)\n * const first = yield* PubSub.take(subscription)\n *\n * first // => 1\n * }))\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toPubSub = /*#__PURE__*/dual(2, (self, options) => Channel.toPubSubArray(self.channel, options));\n/**\n * Converts a stream to a PubSub of `Take` values for concurrent consumption.\n *\n * **Details**\n *\n * `Take` values include the stream's end and failure signals.\n *\n * **Example** (Converting to a PubSub of takes)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n * const pubsub = yield* Stream.fromArray([1, 2, 3]).pipe(\n * Stream.toPubSubTake({ capacity: 8 })\n * )\n * const subscription = yield* PubSub.subscribe(pubsub)\n * const take = yield* PubSub.take(subscription)\n *\n * if (Array.isArray(take)) {\n * take // => [ 1, 2, 3 ]\n * }\n * })\n * await Effect.runPromise(Effect.scoped(program))\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toPubSubTake = /*#__PURE__*/dual(2, (self, options) => Channel.toPubSubTake(self.channel, options));\n/**\n * Creates a scoped dequeue that is fed by the stream for concurrent\n * consumption.\n *\n * **Details**\n *\n * Elements are offered to the queue as the stream runs. Stream completion is\n * signaled with `Cause.Done`, stream failures fail the queue, and the queue is\n * shut down when the surrounding scope closes.\n *\n * **Example** (Converting a stream to a Queue for concurrent consumption)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue, Stream } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n * const queue = yield* Stream.toQueue(Stream.fromIterable([1, 2, 3]), { capacity: 8 })\n * const chunk = yield* Queue.takeBetween(queue, 1, 3)\n * chunk // => [ 1, 2, 3 ]\n * })\n * await Effect.runPromise(Effect.scoped(program))\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toQueue = /*#__PURE__*/dual(2, (self, options) => Channel.toQueueArray(self.channel, options));\n/**\n * Runs the stream, offering each element to the provided queue and ending it\n * with `Cause.Done` when the stream completes.\n *\n * **Example** (Running a stream into a queue)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const queue = yield* Queue.bounded<number, Cause.Done>(4)\n *\n * yield* Effect.forkChild(\n * Stream.runIntoQueue(Stream.fromIterable([1, 2, 3]), queue)\n * )\n *\n * const values = [\n * yield* Queue.take(queue),\n * yield* Queue.take(queue),\n * yield* Queue.take(queue)\n * ]\n * const done = yield* Effect.flip(Queue.take(queue))\n *\n * values // => [ 1, 2, 3 ]\n * done._tag === \"Done\" // => true\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runIntoQueue = /*#__PURE__*/dual(2, (self, queue) => Channel.runIntoQueueArray(self.channel, queue));\n//# sourceMappingURL=Stream.js.map"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