<
R,
E,
App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<
HttpServerResponse,
E,
R
>
>(
lazyWss: Effect.Effect<NodeWS.WebSocketServer>,
httpEffect: Effect.Effect<HttpServerResponse, E, R>,
options: {
readonly scope: Scope.Scope
readonly middleware?:
| Middleware.HttpMiddleware.Applied<App, E, R>
| undefined
}
): Effect.Effect<
(
nodeRequest: Http.IncomingMessage,
socket: Duplex,
head: Buffer
) => void,
never,
Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>
>Creates a Node upgrade event handler for an Effect HTTP application,
exposing the upgraded WebSocket as the request's upgrade effect and
interrupting the request fiber when the socket closes early.
export const const makeUpgradeHandler: <
R,
E,
App extends Effect.Effect<
HttpServerResponse,
any,
any
> = Effect.Effect<HttpServerResponse, E, R>
>(
lazyWss: Effect.Effect<NodeWS.WebSocketServer>,
httpEffect: Effect.Effect<
HttpServerResponse,
E,
R
>,
options: {
readonly scope: Scope.Scope
readonly middleware?:
| Middleware.HttpMiddleware.Applied<
App,
E,
R
>
| undefined
}
) => Effect.Effect<
(
nodeRequest: Http.IncomingMessage,
socket: Duplex,
head: Buffer
) => void,
never,
Exclude<
Effect.Services<App>,
HttpServerRequest | Scope.Scope
>
>
Creates a Node upgrade event handler for an Effect HTTP application,
exposing the upgraded WebSocket as the request's upgrade effect and
interrupting the request fiber when the socket closes early.
makeUpgradeHandler = <
function (type parameter) R in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
R,
function (type parameter) E in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
E,
function (type parameter) App in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
App extends import EffectEffect.interface Effect<out A, out E = never, out R = never>The Effect interface defines a value that lazily describes a workflow or
job. The workflow requires some context R, and may fail with an error of
type E, or succeed with a value of type A.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
Effect values model resourceful interaction with the outside world,
including synchronous, asynchronous, concurrent, and parallel interaction.
They use a fiber-based concurrency model, with built-in support for
scheduling, fine-grained interruption, structured concurrency, and high
scalability.
To run an Effect value, you need a Runtime, which is a type that is
capable of executing Effect values.
Effect<HttpServerResponse, any, any> = import EffectEffect.interface Effect<out A, out E = never, out R = never>The Effect interface defines a value that lazily describes a workflow or
job. The workflow requires some context R, and may fail with an error of
type E, or succeed with a value of type A.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
Effect values model resourceful interaction with the outside world,
including synchronous, asynchronous, concurrent, and parallel interaction.
They use a fiber-based concurrency model, with built-in support for
scheduling, fine-grained interruption, structured concurrency, and high
scalability.
To run an Effect value, you need a Runtime, which is a type that is
capable of executing Effect values.
Effect<HttpServerResponse, function (type parameter) E in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
E, function (type parameter) R in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
R>
>(
lazyWss: Effect.Effect<NodeWS.WebSocketServer>(parameter) lazyWss: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
lazyWss: import EffectEffect.interface Effect<out A, out E = never, out R = never>The Effect interface defines a value that lazily describes a workflow or
job. The workflow requires some context R, and may fail with an error of
type E, or succeed with a value of type A.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
Effect values model resourceful interaction with the outside world,
including synchronous, asynchronous, concurrent, and parallel interaction.
They use a fiber-based concurrency model, with built-in support for
scheduling, fine-grained interruption, structured concurrency, and high
scalability.
To run an Effect value, you need a Runtime, which is a type that is
capable of executing Effect values.
Effect<import NodeWSNodeWS.type NodeWS.WebSocketServer = /*unresolved*/ anyWebSocketServer>,
httpEffect: Effect.Effect<HttpServerResponse, E, R>(parameter) httpEffect: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
httpEffect: import EffectEffect.interface Effect<out A, out E = never, out R = never>The Effect interface defines a value that lazily describes a workflow or
job. The workflow requires some context R, and may fail with an error of
type E, or succeed with a value of type A.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
Effect values model resourceful interaction with the outside world,
including synchronous, asynchronous, concurrent, and parallel interaction.
They use a fiber-based concurrency model, with built-in support for
scheduling, fine-grained interruption, structured concurrency, and high
scalability.
To run an Effect value, you need a Runtime, which is a type that is
capable of executing Effect values.
Effect<HttpServerResponse, function (type parameter) E in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
E, function (type parameter) R in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
R>,
options: {
readonly scope: Scope.Scope
readonly middleware?:
| Middleware.HttpMiddleware.Applied<App, E, R>
| undefined
}
options: {
readonly scope: Scope.Scope(property) scope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
scope: import ScopeScope.Scope
readonly middleware?: | Middleware.HttpMiddleware.Applied<App, E, R>
| undefined
middleware?: import MiddlewareMiddleware.HttpMiddleware.interface HttpMiddleware.Applied<A extends Effect.Effect<HttpServerResponse, any, any>, E, R>Callable type representing middleware already specialized to a particular transformed app type.
Applied<function (type parameter) App in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
App, function (type parameter) E in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
E, function (type parameter) R in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
R> | undefined
}
): import EffectEffect.interface Effect<out A, out E = never, out R = never>The Effect interface defines a value that lazily describes a workflow or
job. The workflow requires some context R, and may fail with an error of
type E, or succeed with a value of type A.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
Effect values model resourceful interaction with the outside world,
including synchronous, asynchronous, concurrent, and parallel interaction.
They use a fiber-based concurrency model, with built-in support for
scheduling, fine-grained interruption, structured concurrency, and high
scalability.
To run an Effect value, you need a Runtime, which is a type that is
capable of executing Effect values.
Effect<
(nodeRequest: Http.IncomingMessagenodeRequest: import HttpHttp.type Http.IncomingMessage = /*unresolved*/ anyIncomingMessage, socket: Duplexsocket: import DuplexDuplex, head: Bufferhead: type Buffer = /*unresolved*/ anyBuffer) => void,
never,
type Exclude<T, U> = T extends U
? never
: T
Exclude from T those types that are assignable to U
Exclude<import EffectEffect.type Services<T> =
T extends Effect.Effect<
infer _A,
infer _E,
infer _R
>
? _R
: never
Extracts the required services type from an Effect.
When to use
Use to derive the context requirements of a generic or inferred Effect
without restating its R type parameter.
Services<function (type parameter) App in <R, E, App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>>(lazyWss: Effect.Effect<NodeWS.WebSocketServer>, httpEffect: Effect.Effect<HttpServerResponse, E, R>, options: {
readonly scope: Scope.Scope;
readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined;
}): Effect.Effect<(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void, never, Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>>
App>, HttpServerRequest | import ScopeScope.Scope>
> => {
const const handledApp: Effect.Effect<
void,
never,
| Request.HttpServerRequest
| Exclude<R, Scope.Scope>
>
const handledApp: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
handledApp = import HttpEffectHttpEffect.const toHandled: <E, R, EH, RH>(
self: Effect.Effect<HttpServerResponse, E, R>,
handleResponse: (
request: HttpServerRequest,
response: HttpServerResponse
) => Effect.Effect<unknown, EH, RH>,
middleware?:
| Middleware.HttpMiddleware
| undefined
) => Effect.Effect<
void,
never,
Exclude<R | RH | HttpServerRequest, Scope.Scope>
>
Runs an HTTP server effect, sends the produced response with the supplied handler, and converts failures into HTTP responses.
toHandled(httpEffect: Effect.Effect<HttpServerResponse, E, R>(parameter) httpEffect: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
httpEffect, const handleResponse: (
request: HttpServerRequest,
response: HttpServerResponse
) => Effect.Effect<void, HttpServerError>
handleResponse, options: {
readonly scope: Scope.Scope
readonly middleware?:
| Middleware.HttpMiddleware.Applied<App, E, R>
| undefined
}
options.middleware?: | Middleware.HttpMiddleware.Applied<App, E, R>
| undefined
middleware as any)
return import EffectEffect.const withFiber: <
A,
E = never,
R = never
>(
evaluate: (
fiber: Fiber<unknown, unknown>
) => Effect<A, E, R>
) => Effect<A, E, R>
Provides access to the current fiber within an effect computation.
Example (Reading the current fiber)
import { Effect } from "effect"
const program = Effect.withFiber((fiber) =>
Effect.succeed(`Fiber ID: ${fiber.id}`)
)
Effect.runPromise(program).then(console.log)
// Output: Fiber ID: 1
withFiber((parent: Fiber.Fiber<unknown, unknown>(parameter) parent: {
id: number;
currentOpCount: number;
getRef: <A>(ref: Context.Reference<A>) => A;
context: Context.Context<never>;
setContext: (context: Context.Context<never>) => void;
currentScheduler: Scheduler;
currentDispatcher: SchedulerDispatcher;
currentSpan: AnySpan | undefined;
currentLogLevel: LogLevel;
minimumLogLevel: LogLevel;
currentStackFrame: StackFrame | undefined;
maxOpsBeforeYield: number;
currentPreventYield: boolean;
addObserver: (cb: (exit: Exit<A, E>) => void) => () => void;
interruptUnsafe: (fiberId?: number | undefined, annotations?: Context.Context<never> | undefined) => void;
pollUnsafe: () => Exit<A, E> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
parent) => {
const const services: Context.Context<never>const services: {
mapUnsafe: ReadonlyMap<string, any>;
mutable: boolean;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
services = parent: Fiber.Fiber<unknown, unknown>(parameter) parent: {
id: number;
currentOpCount: number;
getRef: <A>(ref: Context.Reference<A>) => A;
context: Context.Context<never>;
setContext: (context: Context.Context<never>) => void;
currentScheduler: Scheduler;
currentDispatcher: SchedulerDispatcher;
currentSpan: AnySpan | undefined;
currentLogLevel: LogLevel;
minimumLogLevel: LogLevel;
currentStackFrame: StackFrame | undefined;
maxOpsBeforeYield: number;
currentPreventYield: boolean;
addObserver: (cb: (exit: Exit<A, E>) => void) => () => void;
interruptUnsafe: (fiberId?: number | undefined, annotations?: Context.Context<never> | undefined) => void;
pollUnsafe: () => Exit<A, E> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
parent.Fiber<unknown, unknown>.context: Context.Context<never>(property) Fiber<unknown, unknown>.context: {
mapUnsafe: ReadonlyMap<string, any>;
mutable: boolean;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
context
return import EffectEffect.const succeed: <A>(value: A) => Effect<A>Creates an Effect that always succeeds with a given value.
When to use
Use when an effect should complete successfully with a specific value without any errors
or external dependencies.
Example (Creating a successful effect)
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)
succeed(function function (local function) handler(nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer): voidhandler(
nodeRequest: Http.IncomingMessagenodeRequest: import HttpHttp.type Http.IncomingMessage = /*unresolved*/ anyIncomingMessage,
socket: Duplexsocket: import DuplexDuplex,
head: Bufferhead: type Buffer = /*unresolved*/ anyBuffer
) {
let let nodeResponse_: anynodeResponse_: import HttpHttp.type Http.ServerResponse = /*unresolved*/ anyServerResponse | undefined = var undefinedundefined
const const nodeResponse: () => anynodeResponse = () => {
if (let nodeResponse_: anynodeResponse_ === var undefinedundefined) {
let nodeResponse_: anynodeResponse_ = new import HttpHttp.ServerResponse(nodeRequest: Http.IncomingMessagenodeRequest)
let nodeResponse_: anynodeResponse_.assignSocket(socket: Duplexsocket as any)
let nodeResponse_: anynodeResponse_.on("finish", () => {
socket: Duplexsocket.end()
})
}
return let nodeResponse_: anynodeResponse_
}
const const upgradeEffect: Effect.Effect<
Socket.Socket,
never,
never
>
const upgradeEffect: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
upgradeEffect = import SocketSocket.const fromWebSocket: <RO>(
acquire: Effect.Effect<
globalThis.WebSocket,
Socket.SocketError,
RO
>,
options?:
| {
readonly closeCodeIsError?:
| ((code: number) => boolean)
| undefined
readonly openTimeout?:
| Duration.Input
| undefined
}
| undefined
) => Effect.Effect<
Socket.Socket,
never,
Exclude<RO, Scope.Scope>
>
Builds a Socket from a scoped WebSocket acquisition effect, waiting for the
socket to open, dispatching message handlers in fibers, and translating
open, read, and close events into SocketError values.
fromWebSocket(import EffectEffect.const flatMap: {
<A, B, E1, R1>(
f: (a: A) => Effect<B, E1, R1>
): <E, R>(
self: Effect<A, E, R>
) => Effect<B, E1 | E, R1 | R>
<A, E, R, B, E1, R1>(
self: Effect<A, E, R>,
f: (a: A) => Effect<B, E1, R1>
): Effect<B, E | E1, R | R1>
}
Chains effects to produce new Effect instances, useful for combining
operations that depend on previous results.
When to use
Use when you need to chain multiple effects, ensuring that each
step produces a new Effect while flattening any nested effects that may
occur.
Details
flatMap lets you sequence effects so that the result of one effect can be
used in the next step. It is similar to flatMap used with arrays but works
specifically with Effect instances, allowing you to avoid deeply nested
effect structures.
Since effects are immutable, flatMap always returns a new effect instead of
changing the original one.
Example (Choosing flatMap syntax variants)
import { Effect, pipe } from "effect"
const myEffect = Effect.succeed(1)
const transformation = (n: number) => Effect.succeed(n + 1)
const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation))
const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation)
const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation))
Example (Sequencing dependent effects)
import { Data, Effect, pipe } from "effect"
class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
// Function to apply a discount safely to a transaction amount
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, DiscountRateError> =>
discountRate === 0
? Effect.fail(new DiscountRateError())
: Effect.succeed(total - (total * discountRate) / 100)
// Simulated asynchronous task to fetch a transaction amount from database
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
// Chaining the fetch and discount application using `flatMap`
const finalAmount = pipe(
fetchTransactionAmount,
Effect.flatMap((amount) => applyDiscount(amount, 5))
)
Effect.runPromise(finalAmount).then(console.log)
// Output: 95
flatMap(
lazyWss: Effect.Effect<NodeWS.WebSocketServer>(parameter) lazyWss: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
lazyWss,
(wss: NodeWS.WebSocketServerwss) =>
import EffectEffect.const acquireRelease: <A, E, R, R2>(
acquire: Effect<A, E, R>,
release: (
a: A,
exit: Exit.Exit<unknown, unknown>
) => Effect<unknown, never, R2>,
options?: { readonly interruptible?: boolean }
) => Effect<A, E, R | R2 | Scope>
Constructs a scoped resource from an acquisition effect and a release
finalizer.
When to use
Use to acquire a scoped resource with an explicit release finalizer.
Details
If acquisition succeeds, the release finalizer is added to the current scope
and is guaranteed to run when that scope closes. The finalizer receives the
Exit value used to close the scope.
By default, acquisition is protected by an uninterruptible region. Pass
{ interruptible: true } to allow the acquisition effect to be interrupted.
Example (Acquiring and releasing a resource)
import { Console, Effect, Exit } from "effect"
// Simulate a resource that needs cleanup
interface FileHandle {
readonly path: string
readonly content: string
}
// Acquire a file handle
const acquire = Effect.gen(function*() {
yield* Console.log("Opening file")
return { path: "/tmp/file.txt", content: "file content" }
})
// Release the file handle
const release = (handle: FileHandle, exit: Exit.Exit<unknown, unknown>) =>
Console.log(
`Closing file ${handle.path} with exit: ${
Exit.isSuccess(exit) ? "success" : "failure"
}`
)
// Create a scoped resource
const resource = Effect.acquireRelease(acquire, release)
// Use the resource within a scope
const program = Effect.scoped(
Effect.gen(function*() {
const handle = yield* resource
yield* Console.log(`Using file: ${handle.path}`)
return handle.content
})
)
acquireRelease(
import EffectEffect.const callback: <A, E = never, R = never>(
register: (
this: Scheduler,
resume: (effect: Effect<A, E, R>) => void,
signal: AbortSignal
) => void | Effect<void, never, R>
) => Effect<A, E, R>
Creates an Effect from a callback-based asynchronous API.
When to use
Use when you need to integrate APIs that complete through callbacks instead
of returning a Promise.
Details
The registration function receives a resume callback and, when requested,
an AbortSignal. Call resume at most once with the effect that should
complete the fiber; later calls are ignored. Return an optional cleanup
effect from the registration function to run if the fiber is interrupted.
Example (Integrating callback APIs)
import { Effect } from "effect"
const delay = (ms: number) =>
Effect.callback<void>((resume) => {
const timeoutId = setTimeout(() => {
resume(Effect.void)
}, ms)
// Cleanup function for interruption
return Effect.sync(() => clearTimeout(timeoutId))
})
const program = delay(1000)
callback<module globalThisglobalThis.WebSocket>((resume: (
effect: Effect.Effect<WebSocket, never, never>
) => void
resume) =>
wss: NodeWS.WebSocketServerwss.handleUpgrade(nodeRequest: Http.IncomingMessagenodeRequest, socket: Duplexsocket, head: Bufferhead, (ws: anyws) => {
resume: (
effect: Effect.Effect<WebSocket, never, never>
) => void
resume(import EffectEffect.const succeed: <A>(value: A) => Effect<A>Creates an Effect that always succeeds with a given value.
When to use
Use when an effect should complete successfully with a specific value without any errors
or external dependencies.
Example (Creating a successful effect)
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)
succeed(ws: anyws as any))
})
),
(ws: WebSocketws) => import EffectEffect.const sync: <A>(
thunk: LazyArg<A>
) => Effect<A>
Creates an Effect that represents a synchronous side-effectful computation.
When to use
Use when you need to wrap a synchronous side-effectful operation that is not
expected to throw.
Details
The provided function is evaluated lazily when the effect runs.
Gotchas
The function must not throw. If it throws, the thrown value is treated as a
defect, not as a typed failure. Use try when throwing is expected.
Example (Capturing synchronous logging in an Effect)
import { Effect } from "effect"
const log = (message: string) =>
Effect.sync(() => {
console.log(message) // side effect
})
// ┌─── Effect<void, never, never>
// ▼
const program = log("Hello, World!")
sync(() => ws: WebSocketws.WebSocket.close(code?: number, reason?: string): voidThe WebSocket.close() method closes the already CLOSED, this method does nothing.
close())
)
))
const const map: Map<string, any>map = new var Map: MapConstructor
new <string, any>(iterable?: Iterable<readonly [string, any]> | null | undefined) => Map<string, any> (+3 overloads)
Map(const services: Context.Context<never>const services: {
mapUnsafe: ReadonlyMap<string, any>;
mutable: boolean;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
services.Context<never>.mapUnsafe: ReadonlyMap<string, any>mapUnsafe)
const map: Map<string, any>map.Map<string, any>.set(key: string, value: any): Map<string, any>Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
set(const HttpServerRequest: Context.Service<
Request.HttpServerRequest,
Request.HttpServerRequest
>
(alias) const HttpServerRequest: {
key: string;
Service: {
source: object;
url: string;
originalUrl: string;
method: HttpMethod;
cookies: ReadonlyRecord<string, string>;
multipart: Effect.Effect<Multipart.Persisted, Multipart.MultipartError, Scope.Scope | FileSystem.FileSystem | Path.Path>;
multipartStream: Stream.Stream<Multipart.Part, Multipart.MultipartError>;
upgrade: Effect.Effect<Socket.Socket, HttpServerError>;
modify: (options: { readonly url?: string; readonly headers?: Headers.Headers; readonly remoteAddress?: Option.Option<string> }) => HttpServerRequest;
headers: Headers.Headers;
remoteAddress: Option.Option<string>;
json: Effect.Effect<Schema.Json, E>;
text: Effect.Effect<string, E>;
urlParamsBody: Effect.Effect<UrlParams.UrlParams, E>;
arrayBuffer: Effect.Effect<ArrayBuffer, E>;
stream: Stream.Stream<Uint8Array, E>;
toString: () => string;
toJSON: () => unknown;
};
of: (this: void, self: Request.HttpServerRequest) => Request.HttpServerRequest;
context: (self: Request.HttpServerRequest) => Context.Context<Request.HttpServerRequest>;
use: (f: (service: Request.HttpServerRequest) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, Request.HttpServerRequest | R>;
useSync: (f: (service: Request.HttpServerRequest) => A) => Effect.Effect<A, never, Request.HttpServerRequest>;
Identifier: Identifier;
stack: string | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
Server-side representation of an incoming HTTP request.
Details
It extends HttpIncomingMessage with request metadata, parsed cookies,
multipart accessors, WebSocket upgrade support, and a modify method for
creating adjusted request views.
Service tag for the active server-side HTTP request.
When to use
Use to access the request currently being handled by HTTP server routes and
middleware.
HttpServerRequest.Key<HttpServerRequest, HttpServerRequest>.key: stringkey, new constructor ServerRequestImpl(source: Http.IncomingMessage, response: Http.ServerResponse | LazyArg<Http.ServerResponse>, upgradeEffect?: Effect.Effect<Socket.Socket, HttpServerError>, url?: any, headersOverride?: Headers.Headers, remoteAddressOverride?: Option.Option<string>): ServerRequestImplServerRequestImpl(nodeRequest: Http.IncomingMessagenodeRequest, const nodeResponse: () => anynodeResponse, const upgradeEffect: Effect.Effect<
Socket.Socket,
never,
never
>
const upgradeEffect: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
upgradeEffect))
const const fiber: Fiber.Fiber<void, never>const fiber: {
id: number;
currentOpCount: number;
getRef: <A>(ref: Context.Reference<A>) => A;
context: Context.Context<never>;
setContext: (context: Context.Context<never>) => void;
currentScheduler: Scheduler;
currentDispatcher: SchedulerDispatcher;
currentSpan: AnySpan | undefined;
currentLogLevel: LogLevel;
minimumLogLevel: LogLevel;
currentStackFrame: StackFrame | undefined;
maxOpsBeforeYield: number;
currentPreventYield: boolean;
addObserver: (cb: (exit: Exit<A, E>) => void) => () => void;
interruptUnsafe: (fiberId?: number | undefined, annotations?: Context.Context<never> | undefined) => void;
pollUnsafe: () => Exit<A, E> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
fiber = import FiberFiber.const runIn: {
(scope: Scope): <A, E>(
self: Fiber<A, E>
) => Fiber<A, E>
<A, E>(self: Fiber<A, E>, scope: Scope): Fiber<
A,
E
>
}
Adds a fiber to a Scope and returns the same fiber.
When to use
Use when a manually managed fiber should be interrupted when a Scope closes.
Details
When the scope is closed, the fiber is interrupted. If the scope is already
closed, the fiber is interrupted immediately.
Gotchas
This does not wait for the fiber to complete. It only registers the
interruption finalizer and returns the same fiber.
runIn(import EffectEffect.const runForkWith: <R>(
context: Context.Context<R>
) => <A, E>(
effect: Effect<A, E, R>,
options?: RunOptions | undefined
) => Fiber<A, E>
Runs an effect in the background with the provided services.
When to use
Use when an effect still requires services, you already have a Context, and
you want a background fiber.
Example (Running with services in the background)
import { Context, Effect } from "effect"
interface Logger {
log: (message: string) => void
}
const Logger = Context.Service<Logger>("Logger")
const services = Context.make(Logger, {
log: (message) => console.log(message)
})
const program = Effect.gen(function*() {
const logger = yield* Logger
logger.log("Hello from service!")
return "done"
})
const fiber = Effect.runForkWith(services)(program)
runForkWith(import ContextContext.const makeUnsafe: <Services = never>(
mapUnsafe: ReadonlyMap<string, any>
) => Context<Services>
Creates a Context from an existing service map.
When to use
Use when constructing a low-level Context from a trusted map whose lifecycle
you control.
Gotchas
This is unsafe because later mutation of the provided map can affect the
created Context. Prefer empty, make, add, or merge for normal
Context construction.
Example (Creating a context from a map)
import { Context } from "effect"
// Create a context from a Map (unsafe)
const map = new Map([
["Logger", { log: (msg: string) => console.log(msg) }]
])
const context = Context.makeUnsafe(map)
makeUnsafe<any>(const map: Map<string, any>map))(const handledApp: Effect.Effect<
void,
never,
| Request.HttpServerRequest
| Exclude<R, Scope.Scope>
>
const handledApp: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
handledApp), options: {
readonly scope: Scope.Scope
readonly middleware?:
| Middleware.HttpMiddleware.Applied<App, E, R>
| undefined
}
options.scope: Scope.Scope(property) scope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
scope)
socket: Duplexsocket.on("close", () => {
if (!socket: Duplexsocket.writableEnded) {
const fiber: Fiber.Fiber<void, never>const fiber: {
id: number;
currentOpCount: number;
getRef: <A>(ref: Context.Reference<A>) => A;
context: Context.Context<never>;
setContext: (context: Context.Context<never>) => void;
currentScheduler: Scheduler;
currentDispatcher: SchedulerDispatcher;
currentSpan: AnySpan | undefined;
currentLogLevel: LogLevel;
minimumLogLevel: LogLevel;
currentStackFrame: StackFrame | undefined;
maxOpsBeforeYield: number;
currentPreventYield: boolean;
addObserver: (cb: (exit: Exit<A, E>) => void) => () => void;
interruptUnsafe: (fiberId?: number | undefined, annotations?: Context.Context<never> | undefined) => void;
pollUnsafe: () => Exit<A, E> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
fiber.Fiber<void, never>.interruptUnsafe: (fiberId?: number | undefined, annotations?: Context.Context<never> | undefined) => voidinterruptUnsafe(parent: Fiber.Fiber<unknown, unknown>(parameter) parent: {
id: number;
currentOpCount: number;
getRef: <A>(ref: Context.Reference<A>) => A;
context: Context.Context<never>;
setContext: (context: Context.Context<never>) => void;
currentScheduler: Scheduler;
currentDispatcher: SchedulerDispatcher;
currentSpan: AnySpan | undefined;
currentLogLevel: LogLevel;
minimumLogLevel: LogLevel;
currentStackFrame: StackFrame | undefined;
maxOpsBeforeYield: number;
currentPreventYield: boolean;
addObserver: (cb: (exit: Exit<A, E>) => void) => () => void;
interruptUnsafe: (fiberId?: number | undefined, annotations?: Context.Context<never> | undefined) => void;
pollUnsafe: () => Exit<A, E> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
parent.Fiber<unknown, unknown>.id: numberid, class ClientAbortclass ClientAbort {
annotation: Context.Context<Cause.StackTrace | ClientAbort>;
key: Identifier;
of: (this: void, self: true) => true;
context: (self: true) => Context.Context<ClientAbort>;
use: (f: (service: true) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, ClientAbort | R>;
useSync: (f: (service: true) => A) => Effect.Effect<A, never, ClientAbort>;
Identifier: Identifier;
Service: Shape;
stack: string | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
Context annotation used to mark an interrupt as caused by the client aborting
the request.
Details
causeResponse uses this annotation to map a pure client abort to a 499
response instead of a server abort response.
ClientAbort.ClientAbort.annotation: Context.Context<Cause.StackTrace | ClientAbort>(property) ClientAbort.annotation: {
mapUnsafe: ReadonlyMap<string, any>;
mutable: boolean;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
annotation)
}
})
})
})
}