### Padding strings at the start example Source: https://effect.website/docs/v4/api/effect/String Example showing how to use String.padStart to pad a string at the start with spaces or a custom fill string. ```typescript import { pipe, String } from "effect" pipe("a", String.padStart(5)) // => " a" pipe("a", String.padStart(5, "_")) // => "____a" ``` -------------------------------- ### Example: Starting do notation with Option.bindTo Source: https://effect.website/docs/v4/api/effect/Option Example of starting do notation with `Option.bindTo`, then using `Option.bind` and `Option.let` to build a record with named values. ```typescript import { Option, pipe } from "effect" pipe( Option.some(2), Option.bindTo("x"), Option.bind("y", () => Option.some(3)), Option.let("sum", ({ x, y }) => x + y) ) // => Option.some({ x: 2, y: 3, sum: 5 }) ``` -------------------------------- ### make example Source: https://effect.website/docs/v4/api/effect/ConfigProvider Example of creating a simple in-memory provider using make. The get callback joins the path and looks up a value in a record. ```typescript import { ConfigProvider, Effect } from "effect" const data: Record = { host: "localhost", port: "5432" } const provider = ConfigProvider.make((path) => { const key = path.join(".") const value = data[key] return Effect.succeed( value !== undefined ? ConfigProvider.makeValue(value) : undefined ) }) Effect.runSync(provider.load(["host"])) // => ConfigProvider.makeValue("localhost") ``` -------------------------------- ### Prompt LLM agents to install @effect/tsgo Source: https://effect.website/docs/v4/getting-started/devtools Use this prompt to instruct LLM agents to perform the installation of @effect/tsgo. It points them to the CLI setup and install readme. ```text Install and enable https://github.com/Effect-TS/tsgo in this project using npx @effect/tsgo setup --help ``` -------------------------------- ### Stream.fromChannel example Source: https://effect.website/docs/v4/api/effect/Stream Creates a stream from an array-emitting channel. The example uses Channel.succeed([1,2,3]) and collects the stream to get [1,2,3]. ```typescript import { Channel, Effect, Stream } from "effect" const channel = Channel.succeed([1, 2, 3] as const) const stream = Stream.fromChannel(channel) await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3] ``` -------------------------------- ### Stream.fromEffect example Source: https://effect.website/docs/v4/api/effect/Stream Creates a stream from an effect. The example uses Effect.succeed(42) and collects the stream to get [42]. ```typescript import { Effect, Stream } from "effect" const stream = Stream.fromEffect(Effect.succeed(42)) await Effect.runPromise(Stream.runCollect(stream)) // => [42] ``` -------------------------------- ### Stream.fromArrays example Source: https://effect.website/docs/v4/api/effect/Stream Creates a stream from multiple arrays. The example passes [1,2] and [3,4] and collects the stream to get [1,2,3,4]. ```typescript import { Effect, Stream } from "effect" const program = Effect.gen(function*() { const stream = Stream.fromArrays([1, 2], [3, 4]) const values = yield* Stream.runCollect(stream) values // => [1, 2, 3, 4] }) ``` -------------------------------- ### Starting stream do notation with Stream.Do Source: https://effect.website/docs/v4/api/effect/Stream Example of starting stream do-notation with `Stream.Do`, binding a value, and using `Stream.let` to compute a new field. The output shows the collected results. ```typescript import { Effect, pipe, Stream } from "effect" const program = pipe( Stream.Do, Stream.bind("value", () => Stream.fromArray([1, 2])), Stream.let("next", ({ value }) => value + 1) ) const effect = Effect.gen(function*() { const collected = yield* Stream.runCollect(program) collected // => [ { value: 1, next: 2 }, { value: 2, next: 3 } ] }) await Effect.runPromise(effect) ``` -------------------------------- ### Depth-first traversal example Source: https://effect.website/docs/v4/api/effect/Graph Example of depth-first traversal. Creates a directed graph with three nodes and two edges, then traverses from node 0 to get indices [0, 1, 2]. Without start nodes, the iterator is empty. ```typescript import { Graph } from "effect" const graph = Graph.directed((mutable) => { const a = Graph.addNode(mutable, "A") const b = Graph.addNode(mutable, "B") const c = Graph.addNode(mutable, "C") Graph.addEdge(mutable, a, b, 1) Graph.addEdge(mutable, b, c, 1) }) // Start from a specific node Array.from(Graph.indices(Graph.dfs(graph, { start: [0] }))) // => [0, 1, 2] Array.from(Graph.indices(Graph.dfs(graph))) // => [] ``` -------------------------------- ### Start development server with npm, pnpm, yarn, bun, or deno Source: https://effect.website/docs/v4/getting-started/installation Start the development server using your package manager. After running, press `o` to open the application in your browser and verify the counter increments when the button is clicked. ```bash npm run dev ``` ```bash pnpm run dev ``` ```bash yarn run dev ``` ```bash bun run dev ``` ```bash deno run dev ``` -------------------------------- ### Breadth-first traversal example Source: https://effect.website/docs/v4/api/effect/Graph Example of breadth-first traversal. Creates a directed graph with three nodes and two edges, then traverses from node 0 to get indices [0, 1, 2]. Without start nodes, the iterator is empty. ```typescript import { Graph } from "effect" const graph = Graph.directed((mutable) => { const a = Graph.addNode(mutable, "A") const b = Graph.addNode(mutable, "B") const c = Graph.addNode(mutable, "C") Graph.addEdge(mutable, a, b, 1) Graph.addEdge(mutable, b, c, 1) }) // Start from a specific node Array.from(Graph.indices(Graph.bfs(graph, { start: [0] }))) // => [0, 1, 2] Array.from(Graph.indices(Graph.bfs(graph))) // => [] ``` -------------------------------- ### Command.withExamples Source: https://effect.website/docs/v4/api/effect/cli/Command Sets usage examples for a command. Examples are exposed in structured `HelpDoc` data and rendered by the default formatter in an `EXAMPLES` section. ```APIDOC ## Command.withExamples ### Description Sets usage examples for a command. Examples are exposed in structured `HelpDoc` data and rendered by the default formatter in an `EXAMPLES` section. ### Signature ```ts declare const withExamples: { (examples: readonly Array): (self: Command) => Command; (self: Command, examples: readonly Array): Command; } ``` ### Parameters - `examples` (readonly Array) - The usage examples to set for the command. ### Returns A new command with the usage examples set. ### Example ```ts import { Command } from "effect/cli" const login = Command.make("login").pipe( Command.withExamples([ { command: "myapp login", description: "Log in with browser OAuth" }, { command: "myapp login --token sbp_abc123", description: "Log in with a token" } ]) ) login.examples.map((example) => example.command) // => ["myapp login", "myapp login --token sbp_abc123"] ``` ``` -------------------------------- ### Install dependencies with Bun (after configuration) Source: https://effect.website/docs/v4/getting-started/devtools Runs bun install to install dependencies and execute the prepare script that patches Oxlint. ```bash bun install ``` -------------------------------- ### Ending batch mutation Source: https://effect.website/docs/v4/api/effect/HashMap Example of ending batch mutation: starts with an existing map, begins mutation, performs multiple operations, and ends mutation to get the final immutable result. ```typescript import { HashMap } from "effect" // Start with an existing map const original = HashMap.make(["x", 10], ["y", 20]) // Begin mutation for batch operations const mutable = HashMap.beginMutation(original) // Perform multiple efficient operations HashMap.set(mutable, "z", 30) HashMap.remove(mutable, "x") HashMap.set(mutable, "w", 40) // End mutation to get final immutable result HashMap.endMutation(mutable) // => HashMap.make(["y", 20], ["z", 30], ["w", 40]) ``` -------------------------------- ### Stream.fromPubSub: Create stream from PubSub Source: https://effect.website/docs/v4/api/effect/Stream Creates a stream from a PubSub subscription using Stream.fromPubSub. The example creates an unbounded PubSub with replay 3, forks a fiber to collect the first three values, publishes 1, 2, 3, and joins the fiber to get [1, 2, 3]. ```typescript import { Effect, Fiber, PubSub, Stream } from "effect" const program = Effect.gen(function*() { const pubsub = yield* PubSub.unbounded({ replay: 3 }) const fiber = yield* Stream.fromPubSub(pubsub).pipe( Stream.take(3), Stream.runCollect, Effect.forkChild ) yield* PubSub.publish(pubsub, 1) yield* PubSub.publish(pubsub, 2) yield* PubSub.publish(pubsub, 3) const values = yield* Fiber.join(fiber) values // => [1, 2, 3] }) ``` -------------------------------- ### Add usage examples with withExamples Source: https://effect.website/docs/v4/api/effect/cli/Command Demonstrates adding usage examples to a command with `withExamples`. The examples are stored in the `examples` property and can be accessed programmatically. ```typescript import { Command } from "effect/cli" const login = Command.make("login").pipe( Command.withExamples([ { command: "myapp login", description: "Log in with browser OAuth" }, { command: "myapp login --token sbp_abc123", description: "Log in with a token" } ]) ) login.examples.map((example) => example.command) // => ["myapp login", "myapp login --token sbp_abc123"] ``` -------------------------------- ### Function.constVoid example Source: https://effect.website/docs/v4/api/effect/Function Example of using Function.constVoid to get a thunk that returns undefined. ```typescript import { Function } from "effect" Function.constVoid() // => undefined ``` -------------------------------- ### Stream.onStart: Run effect on start Source: https://effect.website/docs/v4/api/effect/Stream Runs an effect before the stream starts. The effect pushes "started" into an events array, and after collecting the stream, the values are [1, 2, 3] and events is ["started"]. ```typescript import { Effect, Stream } from "effect" const events: Array = [] const program = Effect.gen(function*() { const stream = Stream.fromArray([1, 2, 3]).pipe( Stream.onStart(Effect.sync(() => events.push("started"))) ) const values = yield* Stream.runCollect(stream) values // => [1, 2, 3] }) await Effect.runPromise(program) events // => ["started"] ``` -------------------------------- ### Adding Affixes to a Stream with Stream.intersperseAffixes Source: https://effect.website/docs/v4/stream/operations Provides control over different affixes at the start, between elements, and at the end of the stream. The example adds '[' at the start, '|' between elements, and ']' at the end. ```ts import { Stream, Effect } from "effect" // Create a stream and add affixes: // - `[` at the start // - `|` between elements // - `]` at the end const stream = Stream.make(1, 2, 3, 4, 5).pipe( Stream.intersperseAffixes({ start: "[", middle: "|", end: "]", }), ) await Effect.runPromise(Stream.runCollect(stream)) // => ["[", 1, "|", 2, "|", 3, "|", 4, "|", 5, "]"] ``` -------------------------------- ### Function.constUndefined example Source: https://effect.website/docs/v4/api/effect/Function Example of using Function.constUndefined to get a thunk that returns undefined. ```typescript import { Function } from "effect" Function.constUndefined() // => undefined ``` -------------------------------- ### Create project directory Source: https://effect.website/docs/v4/getting-started/installation Creates a new directory named 'hello-effect' and navigates into it. ```bash mkdir hello-effect cd hello-effect ``` -------------------------------- ### Function.constTrue example Source: https://effect.website/docs/v4/api/effect/Function Example of using Function.constTrue to get a thunk that returns true. ```typescript import { Function } from "effect" Function.constTrue() // => true ``` -------------------------------- ### Install dependencies with npm (after configuration) Source: https://effect.website/docs/v4/getting-started/devtools Runs npm install to install dependencies and execute the prepare script that patches Oxlint. ```bash npm install ``` -------------------------------- ### Stream.as example Source: https://effect.website/docs/v4/api/effect/Stream Example of using `Stream.as` to replace each element of a stream with a constant value. The output is collected and shown as `[ 'x', 'x', 'x' ]`. ```typescript import { Effect, Stream } from "effect" const program = Effect.gen(function*() { const values = yield* Stream.make(1, 2, 3).pipe( Stream.as("x"), Stream.runCollect ) values // => [ 'x', 'x', 'x' ] }) await Effect.runPromise(program) ``` -------------------------------- ### Stream.zip example Source: https://effect.website/docs/v4/api/effect/Stream Example of using `Stream.zip` to zip two streams point-wise. The result is collected and logged as an array of tuples. ```typescript import { Effect, Stream } from "effect" const stream1 = Stream.make(1, 2, 3) const stream2 = Stream.make("a", "b", "c") const zipped = Stream.zip(stream1, stream2) const program = Effect.gen(function*() { const result = yield* Stream.runCollect(zipped) result // => [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ] }) await Effect.runPromise(program) ``` -------------------------------- ### Function.constNull example Source: https://effect.website/docs/v4/api/effect/Function Example of using Function.constNull to get a thunk that returns null. ```typescript import { Function } from "effect" Function.constNull() // => null ``` -------------------------------- ### Install dependencies with Yarn (after configuration) Source: https://effect.website/docs/v4/getting-started/devtools Runs yarn install to install dependencies and execute the prepare script that patches Oxlint. ```bash yarn install ``` -------------------------------- ### Function.constFalse example Source: https://effect.website/docs/v4/api/effect/Function Example of using Function.constFalse to get a thunk that returns false. ```typescript import { Function } from "effect" Function.constFalse() // => false ``` -------------------------------- ### Install dependencies with pnpm (after configuration) Source: https://effect.website/docs/v4/getting-started/devtools Runs pnpm install to install dependencies and execute the prepare script that patches Oxlint. ```bash pnpm install ``` -------------------------------- ### Stream.zipLatest example Source: https://effect.website/docs/v4/api/effect/Stream Example of using `Stream.zipLatest` to combine two streams with the latest value. The result is collected and logged as an array of tuples. ```typescript import { Effect, Stream } from "effect" const program = Effect.gen(function*() { const result = yield* Stream.zipLatest( Stream.make(1), Stream.make("a") ).pipe(Stream.runCollect) result // => [ [ 1, 'a' ] ] }) await Effect.runPromise(program) ``` -------------------------------- ### Stream.onStart Source: https://effect.website/docs/v4/api/effect/Stream Runs an effect before the stream starts. ```APIDOC ## Stream.onStart ### Description Runs the provided effect before this stream starts. The effect is executed before any elements are emitted. ### Signature ```typescript declare const onStart: { (onStart: Effect): (self: Stream) => Stream; (self: Stream, onStart: Effect): Stream; } ``` ### Parameters - **onStart** (Effect) - Required - The effect to run before the stream starts. ### Returns - **Stream** - A new stream that runs the effect before starting. ### Example ```typescript import { Effect, Stream } from "effect" const events: Array = [] const program = Effect.gen(function*() { const stream = Stream.fromArray([1, 2, 3]).pipe( Stream.onStart(Effect.sync(() => events.push("started"))) ) const values = yield* Stream.runCollect(stream) values // => [1, 2, 3] }) await Effect.runPromise(program) events // => ["started"] ``` ``` -------------------------------- ### Get record values Source: https://effect.website/docs/v4/api/effect/Record Example of using `Record.values` to get the values of a record as an array. ```typescript import { Record } from "effect" Record.values({ a: 1, b: 2, c: 3 }) // => [1, 2, 3] ``` -------------------------------- ### Install project dependencies with npm, pnpm, yarn, bun, or deno Source: https://effect.website/docs/v4/getting-started/installation Navigate into the newly created project directory and install the project dependencies using the corresponding package manager. ```bash cd hello-effect npm install ``` ```bash cd hello-effect pnpm install ``` ```bash cd hello-effect yarn install ``` ```bash cd hello-effect bun install ``` ```bash cd hello-effect deno install ``` -------------------------------- ### Stream.toQueue example Source: https://effect.website/docs/v4/api/effect/Stream Converts a stream to a queue for concurrent consumption. The example creates a queue with capacity 8, takes between 1 and 3 elements, and logs the resulting chunk as [1, 2, 3]. The program must be run within a scope because the queue is scoped. ```typescript import { Effect, Queue, Stream } from "effect" const program = Effect.gen(function* () { const queue = yield* Stream.toQueue(Stream.fromIterable([1, 2, 3]), { capacity: 8 }) const chunk = yield* Queue.takeBetween(queue, 1, 3) chunk // => [ 1, 2, 3 ] }) await Effect.runPromise(Effect.scoped(program)) ``` -------------------------------- ### Get record keys Source: https://effect.website/docs/v4/api/effect/Record Example of using `Record.keys` to get the keys of a record as an array. ```typescript import { Record } from "effect" Record.keys({ a: 1, b: 2, c: 3 }) // => ["a", "b", "c"] ``` -------------------------------- ### Full example: Composing AppConfigLive and DatabaseLive Source: https://effect.website/docs/v4/requirements-management/layers Defines Config, Logger, and Database services, creates their layers, merges ConfigLive and LoggerLive into AppConfigLive, then provides AppConfigLive and ConfigLive to DatabaseLive to create MainLive. Finally runs a query using the composed layer, outputting the result. ```ts import { Effect, Context, Layer } from "effect" // Declaring a service key for the Config service class Config extends Context.Service< Config, { readonly getConfig: Effect.Effect<{ readonly logLevel: string readonly connection: string }> } >()("Config") {} // Layer const ConfigLive = Layer.succeed(Config, { getConfig: Effect.succeed({ logLevel: "INFO", connection: "mysql://username:password@hostname:port/database_name", }), }) // Declaring a service key for the Logger service class Logger extends Context.Service< Logger, { readonly log: (message: string) => Effect.Effect } >()("Logger") {} // Layer const LoggerLive = Layer.effect( Logger, Effect.gen(function* () { const config = yield* Config return { log: (message) => Effect.gen(function* () { const { logLevel } = yield* config.getConfig console.log(`[${logLevel}] ${message}`) }), } }), ) // Declaring a service key for the Database service class Database extends Context.Service< Database, { readonly query: (sql: string) => Effect.Effect } >()("Database") {} // Layer const DatabaseLive = Layer.effect( Database, Effect.gen(function* () { const config = yield* Config const logger = yield* Logger return { query: (sql: string) => Effect.gen(function* () { yield* logger.log(`Executing query: ${sql}`) const { connection } = yield* config.getConfig return { result: `Results from ${connection}` } }), } }), ) // Layer const AppConfigLive = Layer.merge(ConfigLive, LoggerLive) // Layer const MainLive = DatabaseLive.pipe( // provides the config and logger to the database Layer.provide(AppConfigLive), // provides the config to AppConfigLive Layer.provide(ConfigLive), ) await Effect.runPromise( Effect.provide( Database.pipe(Effect.andThen((db) => db.query("SELECT * FROM users"))), MainLive, ), ) // => { result: "Results from mysql://username:password@hostname:port/database_name" } ``` -------------------------------- ### orElseResult Example Source: https://effect.website/docs/v4/api/effect/cli/Param Example of using `Param.orElseResult` to get a `Result` indicating which parameter succeeded. ```typescript import { Param } from "effect/cli" const configSource = Param.File(Param.flagKind, "config").pipe( Param.orElseResult(() => Param.String(Param.flagKind, "config-url")) ) // Returns Result configSource.kind // => "flag" ``` -------------------------------- ### Creating an execution plan example Source: https://effect.website/docs/v4/api/effect/ExecutionPlan Example showing how to create an ExecutionPlan with two steps, the first with attempts set to 2, and then accessing the steps length. ```typescript import { Context, ExecutionPlan } from "effect" const ThePlan = ExecutionPlan.make( { provide: Context.empty(), attempts: 2 }, { provide: Context.empty() } ) ThePlan.steps.length // => 2 ``` -------------------------------- ### Example: Publishing and subscribing to messages Source: https://effect.website/docs/v4/api/effect/PubSub Example demonstrating how to create a bounded PubSub with a dropping strategy, publish messages, and subscribe to consume them. The example creates a PubSub with capacity 2, publishes three messages (the third is dropped), and then takes the two messages that were successfully published. The result is an array of the published messages and the taken messages. ```typescript import { Effect, PubSub } from "effect" const program = Effect.scoped(Effect.gen(function*() { // Create a bounded PubSub with capacity 10 const pubsub = yield* PubSub.bounded(10) // Subscribe and consume messages const subscription = yield* PubSub.subscribe(pubsub) // Publish messages yield* PubSub.publish(pubsub, "Hello") yield* PubSub.publish(pubsub, "World") const message1 = yield* PubSub.take(subscription) const message2 = yield* PubSub.take(subscription) return [message1, message2] })) const actual = await Effect.runPromise(program) actual // => ["Hello", "World"] ``` -------------------------------- ### Example: Using String.length Source: https://effect.website/docs/v4/api/effect/String Example showing how to use `String.length` to get the length of a string. ```typescript import { String } from "effect" String.length("abc") // => 3 ``` -------------------------------- ### Stream.aggregateWithin example Source: https://effect.website/docs/v4/api/effect/Stream Example of using `Stream.aggregateWithin` with a sink and a schedule (`Schedule.forever`). The output is `[ 6, 15 ]`. ```typescript import { Effect, Schedule, Sink, Stream } from "effect" await Effect.runPromise(Effect.gen(function* () { const aggregated = yield* Stream.runCollect( Stream.make(1, 2, 3, 4, 5, 6).pipe( Stream.aggregateWithin( Sink.foldUntil(() => 0, 3, (sum, n) => Effect.succeed(sum + n)), Schedule.forever ) ) ) aggregated // => [ 6, 15 ] })) ``` -------------------------------- ### size example Source: https://effect.website/docs/v4/api/effect/HashSet Example of using HashSet.size to get the number of elements in various HashSets. ```typescript import { HashSet } from "effect" HashSet.size(HashSet.empty()) // => 0 HashSet.size(HashSet.make("a", "b")) // => 2 HashSet.size(HashSet.fromIterable(["x", "y", "z", "x", "y"])) // => 3 ``` -------------------------------- ### Creating a TestClock Example Source: https://effect.website/docs/v4/api/effect/testing/TestClock Example demonstrating how to create a TestClock with default settings and custom warning delay, then use it to adjust time and read the current time in milliseconds. ```typescript import { Effect } from "effect" import { TestClock } from "effect/testing" const program = Effect.gen(function*() { // Create a TestClock with default settings const testClock = yield* TestClock.make() // Create a TestClock with custom warning delay const customTestClock = yield* TestClock.make({ warningDelay: "10 seconds" }) // Use the TestClock to control time in tests yield* testClock.adjust("1 hour") const currentTime = testClock.currentTimeMillisUnsafe() currentTime // => 3_600_000 }) await Effect.runPromise(Effect.scoped(program)) ``` -------------------------------- ### scan example Source: https://effect.website/docs/v4/api/effect/Stream Example of using Stream.scan to accumulate state, emitting the initial state and each updated state. The output is [ 0, 1, 3, 6 ]. ```typescript import { Effect, Stream } from "effect" const program = Effect.gen(function*() { const values = yield* Stream.make(1, 2, 3).pipe( Stream.scan(() => 0, (acc, n) => acc + n), Stream.runCollect ) values // => [ 0, 1, 3, 6 ] }) await Effect.runPromise(program) ``` -------------------------------- ### Stream.fromEffectSchedule example Source: https://effect.website/docs/v4/api/effect/Stream Repeats an effect with a schedule. The example uses Schedule.recurs(2) to repeat the effect twice, resulting in three "ping" values. ```typescript import { Effect, Schedule, Stream } from "effect" const stream = Stream.fromEffectSchedule(Effect.succeed("ping"), Schedule.recurs(2)) await Effect.runPromise(Stream.runCollect(stream)) // => ["ping", "ping", "ping"] ``` -------------------------------- ### startsWith example Source: https://effect.website/docs/v4/api/effect/String Example usage of String.startsWith with pipe. Checks if a string starts with a given substring. ```typescript import { pipe, String } from "effect" pipe("hello world", String.startsWith("hello")) // => true pipe("hello world", String.startsWith("world")) // => false ``` -------------------------------- ### Stream.onStart signature Source: https://effect.website/docs/v4/api/effect/Stream Signature for the `onStart` combinator. It runs an effect before the stream starts. ```typescript declare const onStart: { (onStart: Effect): (self: Stream) => Stream; (self: Stream, onStart: Effect): Stream; } ``` -------------------------------- ### Accessing and providing FileSystem Source: https://effect.website/docs/v4/api/effect/FileSystem Shows how to create a custom FileSystem using makeNoop, access the service via Effect.gen, and provide it using Effect.provideService. The example returns the file contents if the file exists. ```typescript import { Effect, FileSystem } from "effect" const customFs = FileSystem.makeNoop({ exists: () => Effect.succeed(true), readFileString: () => Effect.succeed("contents") }) // Access the FileSystem service const program = Effect.gen(function*() { const fs = yield* FileSystem.FileSystem const exists = yield* fs.exists("./data.txt") return exists ? yield* fs.readFileString("./data.txt") : undefined }) const withCustomFs = Effect.provideService( program, FileSystem.FileSystem, customFs ) Effect.runSync(withCustomFs) // => "contents" ``` -------------------------------- ### Getting chunk size with Chunk.size Source: https://effect.website/docs/v4/api/effect/Chunk Example of using Chunk.size to get the number of elements in a chunk. ```typescript import { Chunk } from "effect" Chunk.size(Chunk.make(1, 2, 3)) // => 3 ``` -------------------------------- ### Stream.zipFlatten example Source: https://effect.website/docs/v4/api/effect/Stream Example of using `Stream.zipFlatten` to zip two streams and flatten the left tuple. The result is collected and logged as an array of flattened tuples. ```typescript import { Effect, Stream } from "effect" const program = Effect.gen(function*() { const stream1 = Stream.make( [1, "a"] as const, [2, "b"] as const, [3, "c"] as const ) const stream2 = Stream.make("x", "y", "z") const result = yield* Stream.zipFlatten(stream1, stream2).pipe(Stream.runCollect) result // => [ [ 1, 'a', 'x' ], [ 2, 'b', 'y' ], [ 3, 'c', 'z' ] ] }) await Effect.runPromise(program) ``` -------------------------------- ### Launching an application layer Source: https://effect.website/docs/v4/api/effect/Layer Example of launching an application layer. It creates a server layer, launches it in a forked fiber, waits for it to start, then interrupts the fiber and returns the recorded events. ```typescript import { Context, Deferred, Effect, Fiber, Layer, Ref } from "effect" class HttpServer extends Context.Service()("HttpServer") {} const program = Effect.gen(function*() { const events = yield* Ref.make>([]) const started = yield* Deferred.make() const serverLayer = Layer.effect(HttpServer, Effect.gen(function*() { yield* Ref.update(events, (events) => [...events, "Starting HTTP server..."]) yield* Deferred.succeed(started, undefined) return { port: 3000 } })) const fiber = yield* Effect.forkChild(Layer.launch(serverLayer)) yield* Deferred.await(started) yield* Fiber.interrupt(fiber) return yield* Ref.get(events) }) await Effect.runPromise(program) // => ["Starting HTTP server..."] ``` -------------------------------- ### Running effects around request resolution with RequestResolver.around Source: https://effect.website/docs/v4/api/effect/RequestResolver Shows how to wrap a request resolver with setup and cleanup effects using RequestResolver.around. The before effect runs before each batch and returns a value passed to the after effect. The example logs batch start and completion events and resolves a single request. ```typescript import { Effect, Exit, Request, RequestResolver } from "effect" interface GetDataRequest extends Request.Request { readonly _tag: "GetDataRequest" } const GetDataRequest = Request.tagged("GetDataRequest") const events: Array = [] const resolver = RequestResolver.make((entries) => Effect.sync(() => { for (const entry of entries) { entry.completeUnsafe(Exit.succeed("data")) } }) ) // Add setup and cleanup around request execution const resolverWithAround = RequestResolver.around( resolver, (entries) => Effect.gen(function*() { events.push(`Starting batch of ${entries.length} requests`) return entries.length }), (entries, initialSize) => Effect.sync(() => { events.push(`Batch completed with ${entries.length} requests (started with ${initialSize})`) }) ) const program = Effect.request(GetDataRequest(), resolverWithAround) const result = await Effect.runPromise(program) events // => ["Starting batch of 1 requests", "Batch completed with 1 requests (started with 1)"] result // => "data" ``` -------------------------------- ### Stream.transduce example Source: https://effect.website/docs/v4/api/effect/Stream Example of using `Stream.transduce` with a sink that takes 2 elements at a time. The output is `[ [ 1, 2 ], [ 3, 4 ], [] ]`. ```typescript import { Effect, Sink, Stream } from "effect" const program = Effect.gen(function* () { const result = yield* Stream.make(1, 2, 3, 4).pipe( Stream.transduce(Sink.take(2)), Stream.runCollect ) result // => [ [ 1, 2 ], [ 3, 4 ], [] ] }) await Effect.runPromise(program) ``` -------------------------------- ### Stream.cross example Source: https://effect.website/docs/v4/api/effect/Stream Example of using `Stream.cross` to compute the cartesian product of two streams. The result is collected and logged as an array of tuples. ```typescript import { Effect, Stream } from "effect" const program = Effect.gen(function*() { const left = Stream.make(1, 2) const right = Stream.make("a", "b") const values = yield* Stream.runCollect(Stream.cross(left, right)) values // => [ [ 1, 'a' ], [ 1, 'b' ], [ 2, 'a' ], [ 2, 'b' ] ] }) await Effect.runPromise(program) ``` -------------------------------- ### Working with file handles example Source: https://effect.website/docs/v4/api/effect/FileSystem This example demonstrates creating a mock File handle and using it in an Effect program. It shows how to implement the required methods and then run a program that reads, writes, syncs, and returns statistics. The output shows the size in bytes, bytes read, and the buffer contents. ```typescript import { ByteSize, Effect, FileSystem, Option } from "effect" const file: FileSystem.File = { [FileSystem.FileTypeId]: FileSystem.FileTypeId, stat: Effect.succeed({ size: ByteSize.bytes(5) } as FileSystem.File.Info), seek: () => Effect.succeed(BigInt(0)), sync: Effect.void, read: (buffer) => Effect.sync(() => { buffer.set([1, 2, 3, 4, 5]) return 5 }), readAlloc: () => Effect.succeed(Option.none()), truncate: () => Effect.void, write: (buffer) => Effect.succeed(buffer.length), writeAll: () => Effect.void } const program = Effect.gen(function*() { const stats = yield* file.stat const buffer = new Uint8Array(5) const bytesRead = yield* file.read(buffer) yield* file.writeAll(new TextEncoder().encode("Hello")) yield* file.sync return { size: stats.size, bytesRead, buffer: Array.from(buffer) } }) const result = Effect.runSync(program) ByteSize.toBigInt(result.size) // => 5n result.bytesRead // => 5 result.buffer // => [1, 2, 3, 4, 5] ``` -------------------------------- ### accumulate example Source: https://effect.website/docs/v4/api/effect/Stream Example of using Stream.accumulate to accumulate elements into a growing array. The output is [ [ 1 ], [ 1, 2 ], [ 1, 2, 3 ] ]. ```typescript import { Effect, Stream } from "effect" const program = Effect.gen(function*() { const accumulated = yield* Stream.runCollect( Stream.fromArray([1, 2, 3]).pipe( Stream.rechunk(1), Stream.accumulate ) ) accumulated // => [ [ 1 ], [ 1, 2 ], [ 1, 2, 3 ] ] }) await Effect.runPromise(program) ``` -------------------------------- ### Stream.buffer Source: https://effect.website/docs/v4/stream/operations Documentation for the Stream.buffer operator, including its signature, buffering options, and an example. ```APIDOC ## Stream.buffer ### Description Buffers elements from a stream to handle speed mismatches between producer and consumer. The producer can continue working independently from the consumer up to a specified capacity. ### Signature `Stream.buffer(options: { capacity: number | "unbounded", strategy?: "sliding" | "dropping" }): Stream` ### Parameters - **capacity** (number | "unbounded") - Required - Maximum number of elements to buffer. Use `"unbounded"` for unlimited buffering. - **strategy** ("sliding" | "dropping") - Optional - Buffering strategy when the queue is full. Defaults to bounded queue behavior. ### Buffering Options | **Buffering Type** | **Configuration** | **Description** | | ------------------- | -------------------------------------------- | ------------------------------------------------------------- | | **Bounded Queue** | `{ capacity: number }` | Limits the queue to a fixed size. | | **Unbounded Queue** | `{ capacity: "unbounded" }` | Allows an unlimited number of buffered items. | | **Sliding Queue** | `{ capacity: number, strategy: "sliding" }` | Keeps the most recent items, discarding older ones when full. | | **Dropping Queue** | `{ capacity: number, strategy: "dropping" }` | Keeps the earliest items, discarding new ones when full. | ### Example ```ts import { Stream, Console, Schedule, Effect } from "effect" const stream = Stream.range(1, 10).pipe( // Log each element before buffering Stream.tap((n) => Console.log(`before buffering: ${n}`)), // Buffer with a capacity of 4 elements Stream.buffer({ capacity: 4 }), // Log each element after buffering Stream.tap((n) => Console.log(`after buffering: ${n}`)), // Add a 5-second delay between each emission Stream.schedule(Schedule.spaced("5 seconds")), ) Effect.runPromise(Stream.runCollect(stream)).then(console.log) ``` ``` -------------------------------- ### Creating a single-valued pure stream Source: https://effect.website/docs/v4/api/effect/Stream Example of creating a single-valued pure stream. ```typescript import { Effect, Stream } from "effect" await Effect.runPromise(Stream.runCollect(Stream.succeed(3))) // => [3] ``` -------------------------------- ### Stream.toReadableStreamWith example Source: https://effect.website/docs/v4/api/effect/Stream Converts a stream to a ReadableStream using an empty context. The example produces the values [1, 2, 3, 4, 5]. ```typescript import { Context, Stream } from "effect" const stream = Stream.make(1, 2, 3, 4, 5) const readableStream = Stream.toReadableStreamWith(stream, Context.empty()) const values = await Array.fromAsync(readableStream) values // => [ 1, 2, 3, 4, 5 ] ``` -------------------------------- ### Array.dropWhile example Source: https://effect.website/docs/v4/api/effect/Array Example of using Array.dropWhile to drop elements from the start while they are less than 4, resulting in [4, 5]. ```typescript import { Array } from "effect" Array.dropWhile([1, 2, 3, 4, 5], (x) => x < 4) // => [4, 5] ```