(evaluate: LazyArg<Http.Server>, options: any): Effect.Effect<
{
readonly serve: {
<E, R>(
effect: Effect.Effect<HttpServerResponse, E, R>
): Effect.Effect<
void,
never,
Exclude<R, HttpServerRequest> | Scope.Scope
>
<E, R, App extends Effect.Effect<HttpServerResponse, any, any>>(
effect: Effect.Effect<HttpServerResponse, E, R>,
middleware: Middleware.HttpMiddleware.Applied<App, E, R>
): Effect.Effect<
void,
never,
Exclude<R, HttpServerRequest> | Scope.Scope
>
}
readonly address: HttpServer.Address
},
ServeError,
Scope.Scope
>Creates a scoped HttpServer from a Node http.Server, starts listening
with the supplied options, registers request and upgrade handling, and closes
the server during scope finalization with optional graceful-shutdown control.
export const const make: (
evaluate: LazyArg<Http.Server>,
options: any
) => Effect.Effect<
{
readonly serve: {
<E, R>(
effect: Effect.Effect<
HttpServerResponse,
E,
R
>
): Effect.Effect<
void,
never,
| Exclude<R, HttpServerRequest>
| Scope.Scope
>
<
E,
R,
App extends Effect.Effect<
HttpServerResponse,
any,
any
>
>(
effect: Effect.Effect<
HttpServerResponse,
E,
R
>,
middleware: Middleware.HttpMiddleware.Applied<
App,
E,
R
>
): Effect.Effect<
void,
never,
| Exclude<R, HttpServerRequest>
| Scope.Scope
>
}
readonly address: HttpServer.Address
},
ServeError,
Scope.Scope
>
Creates a scoped HttpServer from a Node http.Server, starts listening
with the supplied options, registers request and upgrade handling, and closes
the server during scope finalization with optional graceful-shutdown control.
make = import EffectEffect.const fnUntraced: <Effect.Effect<Scope.Scope, never, Scope.Scope> | Effect.Effect<void, ServeError, never>, {
readonly serve: {
<E, R>(effect: Effect.Effect<HttpServerResponse, E, R>): Effect.Effect<void, never, Exclude<R, HttpServerRequest> | Scope.Scope>;
<E, R, App extends Effect.Effect<HttpServerResponse, any, any>>(effect: Effect.Effect<HttpServerResponse, E, R>, middleware: Middleware.HttpMiddleware.Applied<App, E, R>): Effect.Effect<void, never, Exclude<R, HttpServerRequest> | Scope.Scope>;
};
readonly address: HttpServer.Address;
}, [evaluate: ...]>(body: (this: unassigned, evaluate: LazyArg<...>, options: any) => Generator<...>) => (evaluate: LazyArg<...>, options: any) => Effect.Effect<...> (+41 overloads)
fnUntraced(function*(
evaluate: LazyArg<Http.Server>evaluate: type LazyArg<A> = () => AA zero-argument function that produces a value when invoked.
When to use
Use to type a lazy value provider that should not run until called.
Example (Creating a lazy argument)
import { Function } from "effect"
const constNull: Function.LazyArg<null> = Function.constant(null)
LazyArg<import HttpHttp.type Http.Server = /*unresolved*/ anyServer>,
options: Net.ListenOptions & {
readonly disablePreemptiveShutdown?:
| boolean
| undefined
readonly gracefulShutdownTimeout?:
| Duration.Input
| undefined
}
options: import NetNet.type Net.ListenOptions = /*unresolved*/ anyListenOptions & {
readonly disablePreemptiveShutdown?: boolean | undefineddisablePreemptiveShutdown?: boolean | undefined
readonly gracefulShutdownTimeout?: Duration.Input | undefinedgracefulShutdownTimeout?: import DurationDuration.type Input =
| number
| bigint
| Duration.Duration
| readonly [seconds: number, nanos: number]
| `${number} nano`
| `${number} nanos`
| `${number} micro`
| `${number} micros`
| `${number} milli`
| `${number} millis`
| `${number} second`
| `${number} seconds`
| `${number} minute`
| `${number} minutes`
| `${number} hour`
| `${number} hours`
| `${number} day`
| `${number} days`
| `${number} week`
| `${number} weeks`
| "Infinity"
| "-Infinity"
| Duration.DurationObject
Valid input types that can be converted to a Duration.
When to use
Use when an API should accept any value that Effect can convert into a
Duration, including existing durations, millisecond numbers, nanosecond
bigints, high-resolution tuples, duration strings, infinity strings, or
duration objects.
Details
String inputs accept values like "10 seconds", "500 millis",
"Infinity", and "-Infinity". Finite fractional values that are
normalized to nanoseconds are rounded to the nearest nanosecond, with ties
away from zero.
Input | undefined
}
) {
const const scope: Scope.Scopeconst scope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
scope = yield* import EffectEffect.const scope: Effect<Scope, never, Scope>const scope: {
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;
}
Returns the current scope for resource management.
Example (Accessing the current scope)
import { Console, Effect } from "effect"
const program = Effect.gen(function*() {
const currentScope = yield* Effect.scope
yield* Console.log("Got scope for resource management")
// Use the scope to manually manage resources if needed
const resource = yield* Effect.acquireRelease(
Console.log("Acquiring resource").pipe(Effect.as("resource")),
() => Console.log("Releasing resource")
)
return resource
})
Effect.runPromise(Effect.scoped(program)).then(console.log)
// Output:
// Got scope for resource management
// Acquiring resource
// resource
// Releasing resource
scope
const const server: Http.Serverserver = evaluate: LazyArg<Http.Server>evaluate()
const const shutdown: Effect.Effect<
void,
never,
never
>
const shutdown: {
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;
}
shutdown = yield* 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<void>((resume: (
effect: Effect.Effect<void, never, never>
) => void
resume) => {
if (!const server: Http.Serverserver.listening) {
return resume: (
effect: Effect.Effect<void, never, never>
) => void
resume(import EffectEffect.const void: Effect.Effect<void, never, never>(alias) const void: {
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;
}
Returns an effect that succeeds with void.
void)
}
const server: Http.Serverserver.close((error: anyerror) => {
if (error: anyerror) {
resume: (
effect: Effect.Effect<void, never, never>
) => void
resume(import EffectEffect.const die: (
defect: unknown
) => Effect<never>
Creates an effect that terminates a fiber with a specified error.
When to use
Use when you need an Effect to report an unrecoverable defect instead of a
typed error.
Details
The die function is used to signal a defect, which represents a critical
and unexpected error in the code. When invoked, it produces an effect that
does not handle the error and instead terminates the fiber.
The error channel of the resulting effect is of type never, indicating that
it cannot recover from this failure.
Example (Failing on division by zero)
import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.die(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: Cannot divide by zero
// ...stack trace...
die(error: anyerror))
} else {
resume: (
effect: Effect.Effect<void, never, never>
) => void
resume(import EffectEffect.const void: Effect.Effect<void, never, never>(alias) const void: {
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;
}
Returns an effect that succeeds with void.
void)
}
})
}).Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<Effect.Effect<void, never, never>, never, never>>(this: Effect.Effect<void, never, never>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<Effect.Effect<void, never, never>, never, never>): Effect.Effect<Effect.Effect<void, never, never>, never, never> (+21 overloads)pipe(import EffectEffect.const cached: <A, E, R>(
self: Effect<A, E, R>
) => Effect<Effect<A, E, R>>
Returns an effect that lazily computes a result and caches it for subsequent
evaluations.
When to use
Use when you need an expensive or time-consuming operation to be evaluated
once and reused by later callers.
Details
This function wraps an effect and ensures that its result is computed only
once. Once the result is computed, it is cached, meaning that subsequent
evaluations of the same effect will return the cached result without
re-executing the logic.
Example (Memoizing an effect until invalidated)
import { Console, Effect } from "effect"
let i = 1
const expensiveTask = Effect.promise<string>(() => {
console.log("expensive task...")
return new Promise((resolve) => {
setTimeout(() => {
resolve(`result ${i++}`)
}, 100)
})
})
const program = Effect.gen(function*() {
console.log("non-cached version:")
yield* expensiveTask.pipe(Effect.andThen(Console.log))
yield* expensiveTask.pipe(Effect.andThen(Console.log))
console.log("cached version:")
const cached = yield* Effect.cached(expensiveTask)
yield* cached.pipe(Effect.andThen(Console.log))
yield* cached.pipe(Effect.andThen(Console.log))
})
Effect.runFork(program)
// Output:
// non-cached version:
// expensive task...
// result 1
// expensive task...
// result 2
// cached version:
// expensive task...
// result 3
// result 3
cached)
const const preemptiveShutdown: Effect.Effect<
void,
never,
never
>
const preemptiveShutdown: {
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;
}
preemptiveShutdown = options: Net.ListenOptions & {
readonly disablePreemptiveShutdown?:
| boolean
| undefined
readonly gracefulShutdownTimeout?:
| Duration.Input
| undefined
}
options.disablePreemptiveShutdown ?
import EffectEffect.const void: Effect.Effect<void, never, never>(alias) const void: {
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;
}
Returns an effect that succeeds with void.
void :
import EffectEffect.const timeoutOrElse: {
<A2, E2, R2>(options: {
readonly duration: Duration.Input
readonly orElse: LazyArg<Effect<A2, E2, R2>>
}): <A, E, R>(
self: Effect<A, E, R>
) => Effect<A | A2, E | E2, R | R2>
<A, E, R, A2, E2, R2>(
self: Effect<A, E, R>,
options: {
readonly duration: Duration.Input
readonly orElse: LazyArg<Effect<A2, E2, R2>>
}
): Effect<A | A2, E | E2, R | R2>
}
Applies a timeout to an effect, with a fallback effect executed if the timeout is reached.
When to use
Use when a timeout of an Effect should switch to a fallback effect.
Details
The fallback effect is created lazily by orElse and may introduce its own
success, failure, and requirement types.
Gotchas
If the timeout wins, the source effect is interrupted before the fallback is
run.
Example (Falling back on timeout)
import { Console, Effect } from "effect"
const slowQuery = Effect.gen(function*() {
yield* Console.log("Starting database query...")
yield* Effect.sleep("5 seconds")
return "Database result"
})
// Use cached data as fallback when timeout is reached
const program = Effect.timeoutOrElse(slowQuery, {
duration: "2 seconds",
orElse: () =>
Effect.gen(function*() {
yield* Console.log("Query timed out, using cached data")
return "Cached result"
})
})
Effect.runPromise(program).then(console.log)
// Output:
// Starting database query...
// Query timed out, using cached data
// Cached result
timeoutOrElse(const shutdown: Effect.Effect<
void,
never,
never
>
const shutdown: {
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;
}
shutdown, {
duration: Duration.Inputduration: options: Net.ListenOptions & {
readonly disablePreemptiveShutdown?:
| boolean
| undefined
readonly gracefulShutdownTimeout?:
| Duration.Input
| undefined
}
options.gracefulShutdownTimeout ?? import DurationDuration.const seconds: (
seconds: number
) => Duration
Creates a Duration from seconds.
Example (Creating durations from seconds)
import { Duration } from "effect"
const duration = Duration.seconds(30)
console.log(Duration.toMillis(duration)) // 30000
seconds(20),
orElse: LazyArg<
Effect.Effect<void, never, never>
>
orElse: () => import EffectEffect.const void: Effect.Effect<void, never, never>(alias) const void: {
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;
}
Returns an effect that succeeds with void.
void
})
yield* import ScopeScope.const addFinalizer: (
scope: Scope,
finalizer: Effect<unknown>
) => Effect<void>
Registers a finalizer effect on a scope.
Details
If the scope is open, the finalizer runs when the scope closes, regardless of
whether the scope closes successfully or with an error. If the scope is
already closed, the finalizer runs immediately.
Example (Adding finalizers)
import { Console, Effect, Exit, Scope } from "effect"
const program = Effect.gen(function*() {
const scope = yield* Scope.make()
// Add simple finalizers
yield* Scope.addFinalizer(scope, Console.log("Cleanup task 1"))
yield* Scope.addFinalizer(scope, Console.log("Cleanup task 2"))
yield* Scope.addFinalizer(scope, Effect.log("Cleanup task 3"))
// Do some work
yield* Console.log("Doing work...")
// Close the scope
yield* Scope.close(scope, Exit.void)
})
addFinalizer(const scope: Scope.Scopeconst scope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
scope, const shutdown: Effect.Effect<
void,
never,
never
>
const shutdown: {
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;
}
shutdown)
yield* 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<void, class ServeErrorclass ServeError {
name: string;
message: string;
stack: string;
cause: unknown;
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;
_tag: Tag;
}
Error wrapping a low-level failure from the HTTP server implementation.
ServeError>((resume: (
effect: Effect.Effect<void, ServeError, never>
) => void
resume) => {
function function (local function) onError(cause: Error): voidonError(cause: Error(parameter) cause: {
name: string;
message: string;
stack: string;
cause: unknown;
}
cause: Error) {
resume: (
effect: Effect.Effect<void, ServeError, never>
) => void
resume(import EffectEffect.const fail: <E>(
error: E
) => Effect<never, E>
Creates an Effect that represents a recoverable error.
When to use
Use to explicitly signal a recoverable error in an Effect.
Details
The error keeps propagating unless it is handled. You can handle tagged
errors with functions like
catchTag
or
catchTags
.
Example (Creating a failed effect)
import { Data, Effect } from "effect"
class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {}
// ┌─── Effect<never, OperationFailedError, never>
// ▼
const failure = Effect.fail(
new OperationFailedError()
)
fail(new new ServeError<{
readonly cause: unknown;
}>(args: {
readonly cause: unknown;
}): ServeError
Error wrapping a low-level failure from the HTTP server implementation.
ServeError({ cause: unknown(property) cause: {
name: string;
message: string;
stack: string;
cause: unknown;
}
cause })))
}
const server: Http.Serverserver.on("error", function (local function) onError(cause: Error): voidonError)
const server: Http.Serverserver.listen(options: Net.ListenOptions & {
readonly disablePreemptiveShutdown?:
| boolean
| undefined
readonly gracefulShutdownTimeout?:
| Duration.Input
| undefined
}
options, () => {
const server: Http.Serverserver.off("error", function (local function) onError(cause: Error): voidonError)
resume: (
effect: Effect.Effect<void, ServeError, never>
) => void
resume(import EffectEffect.const void: Effect.Effect<void, never, never>(alias) const void: {
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;
}
Returns an effect that succeeds with void.
void)
})
})
const const address: anyaddress = const server: Http.Serverserver.address()!
const const wss: Effect.Effect<
any,
never,
never
>
const wss: {
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;
}
wss = yield* 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 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(() => new import NodeWSNodeWS.WebSocketServer({ noServer: booleannoServer: true })),
(wss: anywss) =>
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<void>((resume: (
effect: Effect.Effect<void, never, never>
) => void
resume) => {
wss: anywss.close(() => resume: (
effect: Effect.Effect<void, never, never>
) => void
resume(import EffectEffect.const void: Effect.Effect<void, never, never>(alias) const void: {
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;
}
Returns an effect that succeeds with void.
void))
})
).Pipeable.pipe<Effect.Effect<any, never, Scope.Scope>, Effect.Effect<any, never, never>, Effect.Effect<Effect.Effect<any, never, never>, never, never>>(this: Effect.Effect<any, never, Scope.Scope>, ab: (_: Effect.Effect<any, never, Scope.Scope>) => Effect.Effect<any, never, never>, bc: (_: Effect.Effect<any, never, never>) => Effect.Effect<Effect.Effect<any, never, never>, never, never>): Effect.Effect<Effect.Effect<any, never, never>, never, never> (+21 overloads)pipe(
import ScopeScope.const provide: {
(value: Scope): <A, E, R>(
self: Effect<A, E, R>
) => Effect<A, E, Exclude<R, Scope>>
<A, E, R>(
self: Effect<A, E, R>,
value: Scope
): Effect<A, E, Exclude<R, Scope>>
}
Provides a concrete Scope to an effect.
When to use
Use to run an effect that requires Scope with a scope managed by the
caller.
Details
Providing the scope removes the Scope requirement from the effect context.
Example (Providing a scope)
import { Console, Effect, Scope } from "effect"
// An effect that requires a Scope
const program = Effect.gen(function*() {
const scope = yield* Scope.Scope
yield* Scope.addFinalizer(scope, Console.log("Cleanup"))
yield* Console.log("Working...")
})
// Provide a scope to the program
const withScope = Effect.gen(function*() {
const scope = yield* Scope.make()
yield* Scope.provide(scope)(program)
})
provide(const scope: Scope.Scopeconst scope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
scope),
import EffectEffect.const cached: <A, E, R>(
self: Effect<A, E, R>
) => Effect<Effect<A, E, R>>
Returns an effect that lazily computes a result and caches it for subsequent
evaluations.
When to use
Use when you need an expensive or time-consuming operation to be evaluated
once and reused by later callers.
Details
This function wraps an effect and ensures that its result is computed only
once. Once the result is computed, it is cached, meaning that subsequent
evaluations of the same effect will return the cached result without
re-executing the logic.
Example (Memoizing an effect until invalidated)
import { Console, Effect } from "effect"
let i = 1
const expensiveTask = Effect.promise<string>(() => {
console.log("expensive task...")
return new Promise((resolve) => {
setTimeout(() => {
resolve(`result ${i++}`)
}, 100)
})
})
const program = Effect.gen(function*() {
console.log("non-cached version:")
yield* expensiveTask.pipe(Effect.andThen(Console.log))
yield* expensiveTask.pipe(Effect.andThen(Console.log))
console.log("cached version:")
const cached = yield* Effect.cached(expensiveTask)
yield* cached.pipe(Effect.andThen(Console.log))
yield* cached.pipe(Effect.andThen(Console.log))
})
Effect.runFork(program)
// Output:
// non-cached version:
// expensive task...
// result 1
// expensive task...
// result 2
// cached version:
// expensive task...
// result 3
// result 3
cached
)
return import HttpServerHttpServer.const make: (options: {
readonly serve: (
httpEffect: Effect.Effect<
HttpServerResponse,
unknown,
HttpServerRequest | Scope.Scope
>,
middleware?: Middleware.HttpMiddleware
) => Effect.Effect<void, never, Scope.Scope>
readonly address: HttpServer.Address
}) => HttpServer.HttpServer["Service"]
Constructs an HttpServer service from a serving implementation and listening
address.
make({
address: HttpServer.Addressaddress: typeof const address: anyaddress === "string" ?
{
UnixAddress._tag: "UnixAddress"_tag: "UnixAddress",
UnixAddress.path: stringpath: const address: stringaddress
} :
{
TcpAddress._tag: "TcpAddress"_tag: "TcpAddress",
TcpAddress.hostname: stringhostname: const address: anyaddress.address === "::" ? "0.0.0.0" : const address: anyaddress.address,
TcpAddress.port: numberport: const address: anyaddress.port
},
serve: (
httpEffect: Effect.Effect<
HttpServerResponse,
unknown,
HttpServerRequest | Scope.Scope
>,
middleware?: Middleware.HttpMiddleware
) => Effect.Effect<void, never, Scope.Scope>
serve: import EffectEffect.const fnUntraced: <Effect.Effect<Scope.Scope, never, Scope.Scope> | Effect.Effect<void, never, never>, void, [httpApp: Effect.Effect<HttpServerResponse, unknown, Request.HttpServerRequest | Scope.Scope>, middleware: Middleware.HttpMiddleware | undefined]>(body: (this: unassigned, httpApp: Effect.Effect<HttpServerResponse, unknown, Request.HttpServerRequest | Scope.Scope>, middleware: Middleware.HttpMiddleware | undefined) => Generator<...>) => (httpApp: Effect.Effect<...>, middleware: Middleware.HttpMiddleware | undefined) => Effect.Effect<...> (+41 overloads)fnUntraced(function*(httpApp: Effect.Effect<
HttpServerResponse,
unknown,
Scope.Scope | Request.HttpServerRequest
>
(parameter) httpApp: {
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;
}
httpApp, middleware: Middleware.HttpMiddleware | undefinedmiddleware) {
const const serveScope: Scope.Scopeconst serveScope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
serveScope = yield* import EffectEffect.const scope: Effect<Scope, never, Scope>const scope: {
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;
}
Returns the current scope for resource management.
Example (Accessing the current scope)
import { Console, Effect } from "effect"
const program = Effect.gen(function*() {
const currentScope = yield* Effect.scope
yield* Console.log("Got scope for resource management")
// Use the scope to manually manage resources if needed
const resource = yield* Effect.acquireRelease(
Console.log("Acquiring resource").pipe(Effect.as("resource")),
() => Console.log("Releasing resource")
)
return resource
})
Effect.runPromise(Effect.scoped(program)).then(console.log)
// Output:
// Got scope for resource management
// Acquiring resource
// resource
// Releasing resource
scope
const const scope: Scope.Closeableconst scope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
scope = import ScopeScope.const forkUnsafe: (
scope: Scope,
finalizerStrategy?: "sequential" | "parallel"
) => Closeable
Creates a closeable child scope synchronously and registers it with a parent scope.
When to use
Use when a child scope must be created synchronously and the caller controls
both parent and child scope lifetimes.
Details
Closing the parent closes the child with the same exit value, and closing the
child detaches it from the parent. The optional finalizer strategy configures
the child scope and defaults to "sequential" when omitted.
Example (Creating a child scope synchronously)
import { Console, Effect, Exit, Scope } from "effect"
const program = Effect.gen(function*() {
const parentScope = Scope.makeUnsafe("sequential")
const childScope = Scope.forkUnsafe(parentScope, "parallel")
// Add finalizers to both scopes
yield* Scope.addFinalizer(parentScope, Console.log("Parent cleanup"))
yield* Scope.addFinalizer(childScope, Console.log("Child cleanup"))
// Close child first, then parent
yield* Scope.close(childScope, Exit.void)
yield* Scope.close(parentScope, Exit.void)
})
forkUnsafe(const serveScope: Scope.Scopeconst serveScope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
serveScope, "parallel")
const const handler: (
nodeRequest: Http.IncomingMessage,
nodeResponse: Http.ServerResponse
) => void
handler = yield* (const makeHandler: <
R,
E,
App extends Effect.Effect<
HttpServerResponse,
any,
any
> = Effect.Effect<HttpServerResponse, E, R>
>(
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,
nodeResponse: Http.ServerResponse
) => void,
never,
Exclude<
Effect.Services<App>,
HttpServerRequest | Scope.Scope
>
>
Creates a Node request event handler for an Effect HTTP application,
injecting a HttpServerRequest and interrupting the request fiber if the
client closes the response before it finishes.
makeHandler(httpApp: Effect.Effect<
HttpServerResponse,
unknown,
Scope.Scope | Request.HttpServerRequest
>
(parameter) httpApp: {
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;
}
httpApp, {
middleware?: | Middleware.HttpMiddleware.Applied<
Effect.Effect<
HttpServerResponse,
unknown,
Request.HttpServerRequest | Scope.Scope
>,
unknown,
Request.HttpServerRequest | Scope.Scope
>
| undefined
middleware: middleware: Middleware.HttpMiddleware | undefinedmiddleware as any,
scope: Scope.Closeable(property) scope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
scope
}) as 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, nodeResponse: Http.ServerResponsenodeResponse: import HttpHttp.type Http.ServerResponse = /*unresolved*/ anyServerResponse) => void>)
const const upgradeHandler: (
nodeRequest: Http.IncomingMessage,
socket: Duplex,
head: Buffer
) => void
upgradeHandler = yield* 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(const wss: Effect.Effect<
any,
never,
never
>
const wss: {
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;
}
wss, httpApp: Effect.Effect<
HttpServerResponse,
unknown,
Scope.Scope | Request.HttpServerRequest
>
(parameter) httpApp: {
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;
}
httpApp, {
middleware?: | Middleware.HttpMiddleware.Applied<
Effect.Effect<
HttpServerResponse,
unknown,
Request.HttpServerRequest | Scope.Scope
>,
unknown,
Request.HttpServerRequest | Scope.Scope
>
| undefined
middleware: middleware: Middleware.HttpMiddleware | undefinedmiddleware as any,
scope: Scope.Closeable(property) scope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
scope
})
yield* import ScopeScope.const addFinalizerExit: (
scope: Scope,
finalizer: (
exit: Exit<any, any>
) => Effect<unknown>
) => Effect<void>
Registers an exit-aware finalizer on a scope.
When to use
Use when cleanup needs to know whether the scope closed with success,
failure, or interruption.
Details
If the scope is open, the finalizer runs when the scope closes and receives
the scope's exit value. If the scope is already closed, the finalizer runs
immediately with the stored exit value.
Example (Adding an exit-aware finalizer)
import { Console, Effect, Exit, Scope } from "effect"
const withResource = Effect.gen(function*() {
const scope = yield* Scope.make()
// Add a finalizer for cleanup
yield* Scope.addFinalizerExit(
scope,
(exit) =>
Console.log(
`Cleaning up resource. Exit: ${
Exit.isSuccess(exit) ? "Success" : "Failure"
}`
)
)
// Use the resource
yield* Console.log("Using resource")
// Close the scope
yield* Scope.close(scope, Exit.void)
})
addFinalizerExit(const serveScope: Scope.Scopeconst serveScope: {
strategy: "sequential" | "parallel";
state: State.Open | State.Closed | State.Empty;
}
serveScope, () => {
const server: Http.Serverserver.off("request", const handler: (
nodeRequest: Http.IncomingMessage,
nodeResponse: Http.ServerResponse
) => void
handler)
const server: Http.Serverserver.off("upgrade", const upgradeHandler: (
nodeRequest: Http.IncomingMessage,
socket: Duplex,
head: Buffer
) => void
upgradeHandler)
return const preemptiveShutdown: Effect.Effect<
void,
never,
never
>
const preemptiveShutdown: {
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;
}
preemptiveShutdown
})
const server: Http.Serverserver.on("request", const handler: (
nodeRequest: Http.IncomingMessage,
nodeResponse: Http.ServerResponse
) => void
handler)
const server: Http.Serverserver.on("upgrade", const upgradeHandler: (
nodeRequest: Http.IncomingMessage,
socket: Duplex,
head: Buffer
) => void
upgradeHandler)
})
})
})