### Provide Dependencies to Effect - Effect.js Source: https://effect.website/docs/ai/getting-started Demonstrates how to provide dependencies to an Effect program using Layer.succeed and Effect.provide. This example shows setting up a mock Database service and running a program that depends on it. ```typescript import { Context, Effect, Layer } from "effect" class Database extends Context.Tag("Database") Effect.Effect> }>() {} const DatabaseLive = Layer.succeed( Database, { // Simulate a database query query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([])) } ) // ┌─── Effect // ▼ const program = Effect.gen(function*() { const database = yield* Database const result = yield* database.query("SELECT * FROM users") return result }) // ┌─── Effect // ▼ const runnable = Effect.provide(program, DatabaseLive) Effect.runPromise(runnable).then(console.log) ``` -------------------------------- ### Install @effect/ai with Bun Source: https://effect.website/docs/ai/getting-started Installs the base package for core abstractions and the OpenAI provider integration using Bun. It also ensures the core Effect package is installed. ```bash # Install the base package for the core abstractions (always required) bun add @effect/ai # Install one (or more) provider integrations bun add @effect/ai-openai # Also add the core Effect package (if not already installed) bun add effect ``` -------------------------------- ### Configure and Provide OpenAI Client Source: https://effect.website/docs/ai/getting-started Demonstrates how to instantiate an OpenAI model and provide the necessary client dependencies to an Effect program using the pipe pattern. ```typescript const Gpt4o = OpenAiLanguageModel.model("gpt-4o"); const main = generateDadJoke.pipe( Effect.provide(Gpt4o) ); ``` -------------------------------- ### Inject Services with Effect.provide Source: https://effect.website/docs/ai/getting-started Shows how to satisfy program dependencies by providing a service implementation to an effect using Effect.provide. ```typescript const program = Effect.gen(function*() { const database = yield* Database const result = yield* database.query("SELECT * FROM users") return result }) const runnable = Effect.provide(program, DatabaseLive) Effect.runPromise(runnable).then(console.log) ``` -------------------------------- ### Initialize LLM Models with Effect Source: https://effect.website/docs/ai/getting-started Demonstrates how to instantiate OpenAI and Anthropic model clients using the Effect library's model configuration patterns. ```typescript const Gpt4o = model("gpt-4o"); const Claude37 = model("claude-3-7-sonnet-latest"); ``` -------------------------------- ### POST /effect/provide Source: https://effect.website/docs/ai/getting-started Injects required dependencies into an Effect, allowing it to execute by satisfying its environmental requirements. ```APIDOC ## POST /effect/provide ### Description Provides necessary dependencies (Layers, Context, or Runtime) to an Effect, effectively removing its environmental requirements so it can be executed. ### Method POST ### Endpoint /effect/provide ### Parameters #### Request Body - **effect** (Object) - Required - The Effect instance to be executed. - **layer** (Object) - Required - The dependency layer (e.g., OpenAiClient) to provide to the effect. ### Request Example { "effect": "generateDadJoke", "layer": "OpenAiClient" } ### Response #### Success Response (200) - **status** (string) - Confirmation that dependencies were provided and the effect is ready for execution. #### Response Example { "status": "success", "message": "Dependencies injected successfully." } ``` -------------------------------- ### GET Request Handling Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README Example of defining a GET route to respond with 'Hello World!' on the homepage. ```APIDOC ## GET / HTTP Request ### Description This endpoint handles GET requests to the root path ('/') and responds with 'Hello World!'. ### Method GET ### Endpoint / ### Request Example (No specific request body for this example) ### Response #### Success Response (200) - **body** (string) - 'Hello World!' ### Response Example ``` Hello World! ``` ### Code Snippet ```typescript router.pipe( HttpRouter.get( "/", HttpServerResponse.text("Hello World") ) ) ``` ``` -------------------------------- ### Dependency Injection with Effect Framework Source: https://effect.website/docs/ai/getting-started Shows how to instantiate a language model and provide dependencies to an Effect using the pipeable architecture. ```TypeScript const Gpt4o = OpenAiLanguageModel("gpt-4o"); const main = generateDadJoke.pipe( Effect.provide(layer) ); ``` -------------------------------- ### Dependency Injection with Effect Layers Source: https://effect.website/docs/ai/getting-started Shows how to define a service using Context.Tag and provide its implementation via Layer.succeed to an Effect program. ```typescript import { Context, Effect, Layer } from "effect"; class Database extends Context.Tag("Database") Effect.Effect> }>() {} const DatabaseLive = Layer.succeed(Database, { query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([])) }); const program = Effect.gen(function*() { const database = yield* Database; return yield* database.query("SELECT * FROM users"); }); const runnable = Effect.provide(program, DatabaseLive); Effect.runPromise(runnable).then(console.log); ``` -------------------------------- ### Define and use a database service with Effect Source: https://effect.website/docs/ai/getting-started Demonstrates how to define a service using Context.Tag and provide a live implementation using Layer.succeed, followed by executing an Effect program. ```typescript import { Context, Effect, Layer } from "effect" class Database extends Context.Tag("Database") Effect.Effect> }>() {} const DatabaseLive = Layer.succeed(Database, { query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([])) }) const program = Effect.gen(function*() { const database = yield* Database const result = yield* database.query("SELECT * FROM users") return result }) const runnable = Effect.provide(program, DatabaseLive) Effect.runPromise(runnable).then(console.log) ``` -------------------------------- ### Create and provide an OpenAI Model Source: https://effect.website/docs/ai/getting-started Shows how to instantiate an OpenAI language model using the factory pattern and provide it to an Effect program to generate text. ```typescript import { OpenAiLanguageModel } from "@effect/ai-openai" import { LanguageModel } from "@effect/ai" import { Effect } from "effect" // Create the model const Gpt4o = OpenAiLanguageModel.model("gpt-4o") // Provide the model to an Effect program const program = LanguageModel.generateText({ prompt: "Generate a dad joke" }).pipe(Effect.provide(Gpt4o)) ``` -------------------------------- ### Initialize Cross-Platform Path Module Source: https://effect.website/docs/platform/introduction A basic setup example for importing the Path module from @effect/platform to handle file paths in a cross-platform compatible manner. ```typescript import { Path } from "@effect/platform"; import { Effect } from "effect"; ``` -------------------------------- ### Deno Project Setup and 'Hello, World!' Source: https://effect.website/docs/getting-started/installation Guides through setting up a new Effect project for Deno. It includes creating a project directory, initializing Deno, adding the 'effect' npm package as a dependency, and running a simple 'Hello, World!' program using `deno run`. This verifies the Deno environment is correctly configured for Effect. ```bash mkdir hello-effect cd hello-effect denO init denO add npm:effect ``` ```typescript import { Effect, Console } from "effect" const program = Console.log("Hello, World!") Effect.runSync(program) ``` ```bash deno run main.ts ``` -------------------------------- ### Install @effect/ai with Yarn Source: https://effect.website/docs/ai/getting-started Installs the base package for core abstractions and the OpenAI provider integration using Yarn. It also ensures the core Effect package is installed. ```bash # Install the base package for the core abstractions (always required) yarn add @effect/ai # Install one (or more) provider integrations yarn add @effect/ai-openai # Also add the core Effect package (if not already installed) yarn add effect ``` -------------------------------- ### Initialize Deno Project Source: https://effect.website/llms-full.txt Commands to create a new project directory, navigate into it, and initialize a Deno project. It also includes adding the 'effect' npm package as a dependency. ```shell mkdir hello-effect cd hello-effect ``` ```shell deno init ``` ```shell deno add npm:effect ``` -------------------------------- ### Install @effect/ai with pnpm Source: https://effect.website/docs/ai/getting-started Installs the base package for core abstractions and the OpenAI provider integration using pnpm. It also ensures the core Effect package is installed. ```bash # Install the base package for the core abstractions (always required) pnpm add @effect/ai # Install one (or more) provider integrations pnpm add @effect/ai-openai # Also add the core Effect package (if not already installed) pnpm add effect ``` -------------------------------- ### Bun Project Setup and 'Hello, World!' Source: https://effect.website/docs/getting-started/installation Details the process of creating a new Effect project for Bun. It covers directory creation, Bun initialization (which generates `tsconfig.json`), ensuring `strict` mode is enabled in `tsconfig.json`, adding the 'effect' package, and running a 'Hello, World!' program. This confirms the Bun environment is properly set up for Effect development. ```bash mkdir hello-effect cd hello-effect bun init ``` ```json { "compilerOptions": { "strict": true } } ``` ```bash bun add effect ``` ```typescript import { Effect, Console } from "effect" const program = Console.log("Hello, World!") Effect.runSync(program) ``` ```bash bun index.ts ``` -------------------------------- ### Install @effect/ai with npm Source: https://effect.website/docs/ai/getting-started Installs the base package for core abstractions and the OpenAI provider integration using npm. It also ensures the core Effect package is installed. ```bash # Install the base package for the core abstractions (always required) npm install @effect/ai # Install one (or more) provider integrations npm install @effect/ai-openai # Also add the core Effect package (if not already installed) npm install effect ``` -------------------------------- ### Initialize Deno Project Source: https://effect.website/llms-small.txt Initializes a new Deno project in the current directory. This command sets up the necessary files and configurations for Deno. ```sh deno init ``` -------------------------------- ### Generate Dad Joke with Effect AI Source: https://effect.website/docs/ai/getting-started An example demonstrating how to use the `LanguageModel` service from the `@effect/ai` package to generate a dad joke. This snippet requires importing `LanguageModelLanguageModel` and `Effect` from the 'effect' package. ```typescript import { LanguageModelLanguageModel } from "@effect/ai" import { Effect } from "effect" // Example usage would go here, demonstrating the dad joke generation. ``` -------------------------------- ### Provide Model to Multiple Programs using Effect.gen (TypeScript) Source: https://effect.website/docs/ai/getting-started This snippet demonstrates how to provide a single LanguageModel instance to multiple functions within an Effect.gen block. It shows the reusability of the Model by passing it to a function that generates text based on a prompt. The example utilizes Effect.gen for composing asynchronous operations. ```typescript import { import OpenAiLanguageModelOpenAiLanguageModel } from "@effect/ai-openai" import { import LanguageModelLanguageModel } from "@effect/ai" import { import Effect@since ― 2.0.0@since ― 2.0.0@since ― 2.0.0Effect } from "effect" const const generateDadJoke: Effect.Effect, AiError, LanguageModel.LanguageModel>generateDadJoke = import Effect@since ― 2.0.0@since ― 2.0.0@since ― 2.0.0Effect.const gen: , AiError, LanguageModel.LanguageModel>>, LanguageModel.GenerateTextResponse<{}>>(f: (resume: Effect.Adapter) => Generator, AiError, LanguageModel.LanguageModel>>, LanguageModel.GenerateTextResponse<{}>, never>) => Effect.Effect<...> (+1 overload)Provides a way to write effectful code using generator functions, simplifying control flow and error handling. When to Use Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage. The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end. Example import { Effect } from "effect" const addServiceCharge = (amount: number) => amount + 1 const applyDiscount = ( total: number, discountRate: number): Effect.Effect => discountRate === 0 ? Effect.fail(new Error("Discount rate cannot be zero")) : Effect.succeed(total - (total * discountRate) / 100) const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) export const program = Effect.gen(function* () { const transactionAmount = yield* fetchTransactionAmount const discountRate = yield* fetchDiscountRate const discountedAmount = yield* applyDiscount( transactionAmount, discountRate ) const finalAmount = addServiceCharge(discountedAmount) return `Final amount to charge: ${finalAmount}`}) @since ― 2.0.0gen(function*() { const const response: LanguageModel.GenerateTextResponse<{}>response = yield* import LanguageModelLanguageModel.const generateText: <{ prompt: string;}, {}>(options: { prompt: string;} & LanguageModel.GenerateTextOptions<{}>) => Effect.Effect, AiError, LanguageModel.LanguageModel>Generate text using a language model.@example import { LanguageModel } from "@effect/ai" import { Effect } from "effect" const program = Effect.gen(function* () { const response = yield* LanguageModel.generateText({ prompt: "Write a haiku about programming", toolChoice: "none" }) console.log(response.text) console.log(response.usage.totalTokens) return response }) @since ― 1.0.0generateText({ prompt: string & RawInputThe prompt input to use to generate text.prompt: "Generate a dad joke" }) var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream. A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module. Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information. Example using the global console: console.log('hello world');// Prints: hello world, to stdoutconsole.log('hello %s', 'world');// Prints: hello world, to stdoutconsole.error(new Error('Whoops, something bad happened'));// Prints error message and stack trace to stderr:// Error: Whoops, something bad happened// at [eval]:5:15// at Script.runInThisContext (node:vm:132:18)// at Object.runInThisContext (node:vm:309:38)// at node:internal/process/execution:77:19// at [eval]-wrapper:6:22// at evalScript (node:internal/process/execution:76:60)// at node:internal/main/eval_string:23:3 const name = 'Will Robinson';console.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr Example using the Console class: ``` -------------------------------- ### API Setup and Annotations Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README This section details how to initialize the HttpApi and apply various annotations for OpenAPI documentation, including schema definitions, descriptions, licenses, and summaries. ```APIDOC ## API Setup and Annotations ### Description Initializes the HttpApi with a base path and applies OpenAPI annotations to define schemas, descriptions, licenses, and summaries for the API. ### Method N/A (Initialization and Configuration) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body for this configuration step." } ``` ### Response #### Success Response (N/A) N/A #### Response Example ```json { "example": "No response body for this configuration step." } ``` ### Code Example ```typescript import { HttpApi, OpenApi } from "@effect/platform"; import { Schema } from "effect"; const api = HttpApi.make("api") // Provide additional schemas .annotate(HttpApi.AdditionalSchemas, [ Schema.String.annotations({ identifier: "MyString" }) ]) // Add a description .annotate(OpenApi.Description, "my description") // Set license information .annotate(OpenApi.License, { name: "MIT", url: "http://example.com" }) // Provide a summary .annotate(OpenApi.Summary, "my summary"); ``` ### Notes - The `HttpApi.make("api")` call initializes the API with a base path. - `Schema.String.annotations({ identifier: "MyString" })` defines a schema with a specific identifier. - OpenAPI annotations are used to enrich the API documentation. ``` -------------------------------- ### Provide Dependencies to Effect with Layer Source: https://effect.website/docs/ai/getting-started The `provide` function in Effect allows supplying necessary environment dependencies to an effect, removing its external requirements. Dependencies can be provided via Layers, Context, Runtime, or ManagedRuntime. This enables modular environment setup for effects like database connections or logging services. ```typescript import { Context, Effect, Layer } from "effect" class Database extends Context.Tag("Database") Effect.Effect> }>() {} const DatabaseLive = Layer.succeed( Database, { // Simulate a database query query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([])) } ) // ┌─── Effect // ▼ const program = Effect.gen(function*() { const database = yield* Database const result = yield* database.query("SELECT * FROM users") return result }) // ┌─── Effect // ▼ const runnable = Effect.provide(program, DatabaseLive) Effect.runPromise(runnable).then(console.log) // Output: // timestamp=... level=INFO fiber=#0 message="Executing query: SELECT * FROM users" // [] ``` -------------------------------- ### Hello World Example Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README A simple 'Hello World' example demonstrating the basic structure of defining and implementing an HTTP API endpoint. ```APIDOC ## Hello World ### Description This example demonstrates the fundamental steps for creating a "Hello World" HTTP API. ### Defining and Implementing an API This involves defining the API structure and providing the implementation for the endpoints. ### Serving The Auto Generated Swagger Documentation Details on how to serve the automatically generated Swagger documentation for your API. ### Deriving a Client Information on how to generate a client for your defined API to facilitate consumption. ``` -------------------------------- ### Set Up HTTP Server and Routing Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README This code initializes an application using a router and pipes it to the `HttpServer.serve` method. It then starts the server, listening for incoming requests on port 3000. This is a fundamental setup for any Node.js web server application. ```typescript const app = router.pipe(HttpServer.serve()) listen(app, 3000) ``` -------------------------------- ### Install Project Dependencies with Deno Source: https://effect.website/llms-small.txt Installs project dependencies for a React + Vite application using Deno. This command handles the setup and installation of necessary packages for the project. ```sh cd hello-effect denp install ``` -------------------------------- ### Initialize Deno Project and Add Effect Dependency Source: https://context7_llms Sets up a new project directory for Deno and initializes it. It then adds the 'effect' package as a dependency using Deno's package management. ```shell mkdir hello-effect cd hello-effect denp init denp add npm:effect ``` -------------------------------- ### Effect.gen Example without Interruption Source: https://effect.website/docs/concurrency/basic-concurrency Demonstrates the usage of `Effect.gen` for writing effectful code that runs without interruption. This example logs the start and completion of a task, showcasing a typical workflow. ```typescript import { Effect } from "effect" const program: Effect.Effect = Effect.gen(function* () { console.log('Program started') const result = yield* Effect.succeed('Task completed') console.log('Program finished') return result }) Effect.runPromiseExit(program).then(exit => { console.log(exit) }) ``` -------------------------------- ### Define GET route for homepage Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README This snippet demonstrates how to define a GET route for the homepage ('/'). When a GET request is received at this endpoint, the application will respond with the text 'Hello World'. This is a fundamental example of setting up routing in the application. ```typescript // respond with "hello world" when a GET request is made to the homepage HttpRouter.get("/", HttpServerResponse.text("Hello World")) ``` -------------------------------- ### Start Server and Listen Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README This code sets up an application by piping the router's request handling through an HTTP server and then starts the server listening on port 3000. ```typescript const app = router.pipe(HttpServer.serve()) listen(app, 3000) ``` -------------------------------- ### Stream.intersperseAffixes Source: https://effect.website/docs/stream/operations Provides control over different affixes at the start, between elements, and at the end of the stream. ```APIDOC ## POST /api/stream/intersperseAffixes ### Description This endpoint allows you to add custom affixes (start, middle, and end) to a stream. It's useful for formatting stream output or creating structured data representations. ### Method POST ### Endpoint /api/stream/intersperseAffixes ### Parameters #### Request Body - **start** (string) - Required - The affix to be added at the beginning of the stream. - **middle** (string) - Required - The affix to be added between elements of the stream. - **end** (string) - Required - The affix to be added at the end of the stream. ### Request Example ```json { "start": "[", "middle": "|", "end": "]" } ``` ### Response #### Success Response (200) - **stream** (Stream) - The modified stream with affixes applied. #### Response Example ```json { "stream": "[1|2|3]" } ``` ``` -------------------------------- ### Access Raw Request in Node.js with @effect/platform-node Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README This TypeScript code snippet demonstrates how to obtain the raw Node.js incoming message object from an @effect/platform request. It imports necessary modules from '@effect/platform' and '@effect/platform-node'. The example defines an HTTP router that logs the raw request when a GET request is made to the root path. It relies on a 'listen.js' file for server setup. ```typescript import { HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "@effect/platform" import { NodeHttpServer, NodeHttpServerRequest } from "@effect/platform-node" import { Effect } from "effect" import { listen } from "./listen.js" const router = HttpRouter.empty.pipe( HttpRouter.get( "/", Effect.gen(function* () { const req = yield* HttpServerRequest.HttpServerRequest const raw = NodeHttpServerRequest.toIncomingMessage(req) console.log(raw) return HttpServerResponse.empty() }) ) ) listen(HttpServer.serve(router), 3000) ``` -------------------------------- ### Install @effect/platform with Bun Source: https://context7_llms Installs the beta version of the @effect/platform package using Bun. ```sh bun add @effect/platform ``` -------------------------------- ### Install @effect/platform with Deno Source: https://context7_llms Installs the beta version of the @effect/platform package using Deno. ```sh deno add npm:@effect/platform ``` -------------------------------- ### GET /hello-world Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README This endpoint provides a simple 'Hello, World!' greeting. It's a basic example demonstrating how to define a GET request within the Effect-TS API structure. ```APIDOC ## GET /hello-world ### Description Provides a 'Hello, World!' greeting. ### Method GET ### Endpoint /hello-world ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **greeting** (string) - The 'Hello, World!' message. #### Response Example ```json { "greeting": "Hello, World!" } ``` ``` -------------------------------- ### Set up and launch an HTTP server with Effect-TS Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README This code snippet demonstrates the setup and launch of an HTTP server using Effect-TS. It involves providing API layers, configuring server options like port, and piping the runtime to run the main process. Dependencies include Layer, HttpServer, MyApiLive, NodeHttpServer, and NodeRuntime. ```typescript Layer.provide( Layer.provide(MyApiLive), HttpServer.withLogAddress, Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })) ) Layer.launch(HttpLive).pipe( NodeRuntime.runMain ) ``` -------------------------------- ### POST /language-model/generate Source: https://effect.website/docs/ai/getting-started Generates text based on a provided prompt using the configured language model. ```APIDOC ## POST /language-model/generate ### Description Generates text using a language model based on the provided prompt and configuration options. ### Method POST ### Endpoint /language-model/generate ### Parameters #### Request Body - **prompt** (string) - Required - The text prompt to send to the language model. - **toolChoice** (string) - Optional - Specifies tool usage behavior (e.g., "none"). ### Request Example { "prompt": "Write a haiku about programming", "toolChoice": "none" } ### Response #### Success Response (200) - **text** (string) - The generated text response. - **usage** (object) - Token usage statistics including totalTokens. #### Response Example { "text": "Code flows like a stream,\nLogic built in silent lines,\nDigital dreams wake.", "usage": { "totalTokens": 25 } } ``` -------------------------------- ### Start Development Server Source: https://effect.website/docs/getting-started/installation Commands to launch the Vite development server. ```npm npm run dev ``` ```pnpm pnpm run dev ``` ```yarn yarn run dev ``` ```bun bun run dev ``` ```deno deno run dev ``` -------------------------------- ### POST /language-model/generate Source: https://effect.website/docs/ai/getting-started Generates text content using a configured language model provider such as OpenAI. ```APIDOC ## POST /language-model/generate ### Description Generates text based on a prompt using a specified model (e.g., gpt-4o). The response is handled as an Effect containing a GenerateTextResponse. ### Method POST ### Endpoint /language-model/generate ### Parameters #### Request Body - **model** (string) - Required - The identifier of the model to use (e.g., "gpt-4o"). - **prompt** (string) - Required - The input text for the language model. ### Request Example { "model": "gpt-4o", "prompt": "Tell me a dad joke." } ### Response #### Success Response (200) - **text** (string) - The concatenated text output from the model. #### Response Example { "text": "Why don't scientists trust atoms? Because they make up everything!" } ``` -------------------------------- ### Custom Console Instance Source: https://effect.website/docs/stream/operations Shows how to create a custom `Console` instance with specific output streams. ```APIDOC ## Custom Console Instance ### Description This section details how to create a custom `Console` object, allowing you to direct output to specific streams (e.g., files or custom stream objects) instead of the default stdout and stderr. ### Method `new console.Console(stdout[, stderr][, ignoreErrors])` ### Endpoint N/A (Built-in module constructor) ### Parameters - **stdout** (WritableStream) - Required - The stream to write log output to. - **stderr** (WritableStream) - Optional - The stream to write error output to. If not provided, stdout is used for errors. - **ignoreErrors** (boolean) - Optional - If true, errors writing to the streams will be ignored. Defaults to false. ### Request Example ```javascript const out = getStreamSomehow(); // Assume this returns a writable stream const err = getStreamSomehow(); // Assume this returns a writable stream const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints to 'out' stream myConsole.error(new Error('Whoops, something bad happened')); // Prints to 'err' stream ``` ### Response #### Success Response - Custom `Console` object is created and ready for use. #### Response Example ```json { "message": "Custom console created successfully." } ``` ``` -------------------------------- ### Debouncing Streams Source: https://effect.website/docs/stream/operations Explanation and example of using the `Stream.debounce` function to control the frequency of stream emissions. ```APIDOC ## Debouncing Streams Debouncing is a technique used to prevent a function from firing too frequently, which is particularly useful when a stream emits values rapidly but only the last value after a pause is needed. The `Stream.debounce` function achieves this by delaying the emission of values until a specified time period has passed without any new values. If a new value arrives during the waiting period, the timer resets, and only the latest value will eventually be emitted after a pause. ### Example (Debouncing a Stream of Rapidly Emitted Values) ```typescript import { Stream, Effect } from "effect" // Helper function to log with elapsed time since the last log let last = Date.now() const log = (message: string) => Effect.sync(() => { const end = Date.now() console.log(`${message} (elapsed: ${end - last}ms)`) last = end }) const stream = Stream.fromIterable([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) const debouncedStream = Stream.debounce(stream, 100) // Wait for 100ms pause Effect.runFork(Stream.runForEach(debouncedStream, log)) ``` ### Method `Stream.debounce` ### Parameters #### Query Parameters - **stream** (Stream) - The input stream. - **duration** (number) - The time in milliseconds to wait for a pause in emissions. ### Response #### Success Response (200) - **Emitted value** (any) - The last value emitted after the specified pause. #### Response Example (Output will vary based on execution time, but will show only the last number after a pause) ``` 10 (elapsed: 123ms) ``` ``` -------------------------------- ### AI Module Source: https://effect.website/docs/data-types/datetime Documentation for the AI module, including introduction, getting started, execution planning, and tool use. ```APIDOC ## AI Module Documentation ### Description This section covers the AI module, detailing its introduction, getting started guide, execution planning for LLM interactions, and how to utilize tools. ### Endpoints - `/docs/ai/introduction/` - `/docs/ai/getting-started/` - `/docs/ai/planning-llm-interactions/` - `/docs/ai/tool-use/` ``` -------------------------------- ### Install Project Dependencies Source: https://context7_llms Installs the necessary packages for a newly created Vite project. This command should be run after navigating into the project directory. ```sh cd hello-effect npm install ``` ```sh cd hello-effect pnpm install ``` ```sh cd hello-effect yarn install ``` ```sh cd hello-effect bun install ``` ```sh cd hello-effect denO install ``` -------------------------------- ### Create Effect App with npm, pnpm, Yarn, Bun, Deno Source: https://context7_llms Quickly set up a new Effect application using `create-effect-app`. This command handles all necessary configurations. Supports multiple package managers for installation. ```shell npx create-effect-app@latest ``` ```shell pnpm create effect-app@latest ``` ```shell yarn create effect-app@latest ``` ```shell bunx create-effect-app@latest ``` ```shell deno init --npm effect-app@latest ``` -------------------------------- ### Represent structured data output Source: https://effect.website/docs/stream/operations An example of a JSON-like object structure representing a chunk of data with an identifier and a list of values. ```json { "_id": "Chunk", "values": [ 1, 0, 2, 3, 0, 4, 5 ] } ``` -------------------------------- ### Get Head of Array and Fetch Data with Effect Source: https://context7_llms Combines getting the head of an array and fetching data using Effect. This example demonstrates mixing Either and Effect, running a program, and logging the result. ```typescript import { Either } from "effect" import { Effect } from "effect" // Function to get the head of an array, returning Either const head = (array: ReadonlyArray): Either.Either => array.length > 0 ? Either.right(array[0]) : Either.left("empty array") // Simulated fetch function that returns Effect const fetchData = (): Effect.Effect => { const success = Math.random() > 0.5 return success ? Effect.succeed("some data") : Effect.fail("Failed to fetch data") } // Mixing Either and Effect const program = Effect.all([head([1, 2, 3]), fetchData()]) Effect.runPromise(program).then(console.log) /* Example Output: [ 1, 'some data' ] */ ``` -------------------------------- ### Define API Endpoints with HttpApiEndpoint (GET /users) Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README Defines a GET endpoint for retrieving all users. It specifies the HTTP method, path, and expected response structure using schemas. This example is part of a larger CRUD API definition. ```typescript const getUsers = HttpApiEndpoint.get("GetUsers", "/users").pipe( HttpApiEndpoint.withResponseSchema(User.array) ) ``` -------------------------------- ### unwrapOr with Neverthrow Source: https://effect.website/docs/additional-resources/effect-vs-neverthrow This example demonstrates how to use `unwrapOr` with the Neverthrow library to get the unwrapped value or a default if the result is an Err. ```APIDOC ## POST /unwrapOr/neverthrow ### Description Provides a default value if the Neverthrow Result is an Err. ### Method POST ### Endpoint /unwrapOr/neverthrow ### Parameters #### Query Parameters - **defaultValue** (number) - Required - The default value to return if the result is an Err. #### Request Body - **result** (object) - Required - The Neverthrow Result object. - **_tag** (string) - Required - Tag indicating if it's 'Err' or 'Ok'. - **error** (string) - Optional - The error message if _tag is 'Err'. - **value** (any) - Optional - The value if _tag is 'Ok'. ### Request Example ```json { "result": { "_tag": "Err", "error": "Oh no" }, "defaultValue": 10 } ``` ### Response #### Success Response (200) - **unwrappedValue** (any) - The unwrapped value or the default value. #### Response Example ```json { "unwrappedValue": 10 } ``` ``` -------------------------------- ### Create Effect App CLI commands (Shell) Source: https://effect.website/llms-full.txt Provides various ways to initiate a new Effect application using the `create-effect-app` CLI. This includes interactive setup and non-interactive usage with specific template and configuration options. ```shell npx create-effect-app@latest ``` ```shell pnpm create effect-app@latest ``` ```shell yarn create effect-app@latest ``` ```shell bunx create-effect-app@latest ``` ```shell deno init --npm effect-app@latest ``` ```shell npx create-effect-app --template basic --eslint my-effect-app ``` ```shell create-effect-app (-t, --template basic | cli | monorepo) [--changesets] [--flake] [--eslint] [--workflows] [] create-effect-app (-e, --example http-server) [] ``` -------------------------------- ### Node.js Console Logging and Custom Console Instances Source: https://effect.website/docs/platform/command Shows how to use the global console for standard logging and how to instantiate a custom Console class to direct output to specific streams. ```JavaScript console.log('hello world'); console.log('hello %s', 'world'); console.error(new Error('Whoops, something bad happened')); const myConsole = new console.Console(outStream, errStream); myConsole.log('hello world'); myConsole.warn(`Danger ${name}! Danger!`); ``` -------------------------------- ### Install Effect AI Packages (Bun) Source: https://effect.website/llms-full.txt Installs the base Effect AI package, OpenAI provider integration, and the core Effect package using Bun. ```shell # Install the base package for the core abstractions (always required) bun add @effect/ai # Install one (or more) provider integrations bun add @effect/ai-openai # Also add the core Effect package (if not already installed) bun add effect ``` -------------------------------- ### Interrupt Effect with Effect.interrupt Source: https://effect.website/llms-small.txt Illustrates how to explicitly interrupt a running Effect fiber using `Effect.interrupt`. In this example, the program starts, logs 'start', and then encounters `Effect.interrupt`, causing the fiber to terminate before reaching the 'done' log. The interruption is visible in the `Cause` of the `Exit` type. ```typescript import { Effect } from "effect" const program = Effect.gen(function* () { console.log("start") yield* Effect.sleep("2 seconds") yield* Effect.interrupt console.log("done") return "some result" }) Effect.runPromiseExit(program).then(console.log) /* Output: start { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Interrupt', fiberId: { _id: 'FiberId', _tag: 'Runtime', id: 0, startTimeMillis: ... } } } */ ``` -------------------------------- ### Configuring OpenAI Client Layer Source: https://effect.website/docs/ai/getting-started Shows how to instantiate an OpenAiClient Layer using layerConfig. This approach allows for secure configuration management using Effect's Config system and supports dependency injection for the HttpClient. ```typescript import { OpenAiClient } from "@effect/ai-openai" import { Config, Layer } from "effect" const OpenAi = OpenAiClient.layerConfig({ apiKey: Config.redacted("OPENAI_API_KEY") }) ``` -------------------------------- ### Provide Dependencies with Effect.provide Source: https://effect.website/docs/ai/getting-started Explains how to supply required environments or services to an Effect using Layers, enabling modular and testable dependency injection. ```typescript class Database extends Context.Tag("Database") Effect.Effect> }>() {} const DatabaseLive = Layer.succeed( Database, { query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([])) } ); ``` -------------------------------- ### GET /user* Source: https://github.com/Effect-TS/effect/blob/main/packages/platform/README This endpoint matches any request path starting with '/user'. It captures the full URL and returns it in the response. ```APIDOC ## GET /user* ### Description This endpoint matches any request path starting with '/user' (e.g., '/user', '/users', etc.). It captures the full URL and returns it in the response. ### Method GET ### Endpoint /user* ### Parameters #### Path Parameters - **None** #### Query Parameters - **None** #### Request Body - **None** ### Request Example ```json { "example": "No request body needed for this example." } ``` ### Response #### Success Response (200) - **url** (string) - The full URL of the incoming request. #### Response Example ```json { "url": "/users/some_id" } ``` ### Error Handling - **404 Not Found**: If the route does not match. - **500 Internal Server Error**: If there is an issue processing the request. ``` -------------------------------- ### Custom Console Instance Source: https://effect.website/docs/stream/operations Illustrates how to create a custom Console instance with specific output and error streams. ```APIDOC ## Console API - Custom Instance ### Description This section explains how to create and use a custom `console.Console` instance, allowing redirection of output and error streams. ### Method - `new console.Console(stdout[, stderr][, ignoreErrors])` ### Endpoint N/A (Built-in Node.js module) ### Parameters - `stdout` (WritableStream): The stream to which logging output will be written. - `stderr` (WritableStream): The stream to which error output will be written. - `ignoreErrors` (boolean, optional): If true, errors writing to the `stdout` or `stderr` streams will be ignored. ### Request Example ```javascript const out = getStreamSomehow(); // Assume this returns a WritableStream const err = getStreamSomehow(); // Assume this returns a WritableStream const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.error(new Error('Whoops, something bad happened')); const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); ``` ### Response #### Success Response (Custom Streams) - Logs are written to the specified `stdout` and `stderr` streams. #### Response Example ``` // Output to 'out' stream: hello world // Output to 'err' stream: [Error: Whoops, something bad happened] Danger Will Robinson! Danger! ``` ``` -------------------------------- ### Run Development Server with Different Package Managers Source: https://context7_llms This snippet shows commands to run the development server using various package managers like npm, pnpm, Yarn, Bun, and Deno. It's a common task for starting a project. ```sh npm run dev ``` ```sh pnpm run dev ``` ```sh yarn run dev ``` ```sh bun run dev ``` ```sh deno run dev ``` -------------------------------- ### Initialize Bun Project and Configure TypeScript Source: https://effect.website/llms-full.txt Commands to create a new project directory and initialize a Bun project. It includes adding the 'effect' package and verifying the 'strict' setting in tsconfig.json. ```shell mkdir hello-effect cd hello-effect ``` ```shell bun init ``` ```json { "compilerOptions": { "strict": true } } ``` ```shell bun add effect ```