Thrown when a request body cannot be parsed as JSON.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Raised when a request body is not a form encoding the framework can parse:
a JSON body, a missing content-type, or a multipart/form-data type
carrying no boundary=.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Asserts that a target path is contained within a root by comparing canonical paths.
Brands a middleware function with the application's resolved error responder, so the kernel can reach it at the pre-pipeline sites.
Extracts a caller-facing message from an unknown thrown value.
Composes behaviours around a terminal handler — the ONE shared composer for the CQRS pipeline and all four non-HTTP ingress chains.
Returns the content type for a file based on its extension.
Formats a context as a W3C traceparent value.
Builds a cached, coalesced, time-bounded reachability probe.
Creates a custom capability token for third-party plugins.
Builds a path-exclusion predicate from a list of literals and patterns.
Decode a cursor token to its CursorPayload, or null when the
token is malformed.
Decodes a payload received from the wire back into its local form.
Encode a CursorPayload as a base64url-encoded JSON token.
Encodes a WebSocket payload for the wire.
Creates a failed Result.
Reads the error responder branded onto a middleware function, if any.
Extracts W3C trace context from web-standard headers.
Classifies a request content-type as one of the two form encodings.
Converts a nullable value to an Option.
Reads the status hint an error was branded with.
Checks if a relative path is lexically contained within a root.
Reports whether a value is thenable, by the same duck-typed test the
platform serve layers use rather than instanceof Promise.
Reports whether a set of request headers describes an RFC 6455 WebSocket upgrade.
Narrows an incoming message to a WorkerReadySignal.
Narrows an incoming message to a WorkerTaskReply.
Narrows an incoming message to a WorkerTaskRequest.
Build the "row after this one" keyset comparison as a portable
FilterExpression.
Mint the next-page cursor from the last row of a non-terminal page.
Returns the None option.
Creates a successful Result.
Parses one request body as a form — the ONE parse all three
IRequest.formData?() implementations share, and the function every
fallback path (a request without the optional accessor) calls directly.
Parses one request-body text as JSON, the ONE parse all three IRequest
json() implementations share (X37-1, M90f).
Parses a W3C traceparent value.
Replaces request.user deliberately, bypassing the single-write guard.
Replaces request.tenant deliberately, bypassing the single-write guard.
The sort a keyset walk actually runs under: the caller's orderBy followed
by every primary-key column it does not already carry, each ascending.
Resolves a probe's monotonic clock and timer surface from an injected
IRuntimeServices.
Resolves one entry of a registration option that accepts either an instance
or a RegistryFactory.
Returns a status the web Response constructor will accept, clamping an
unserveable one to 500 and reporting it through the logger capability when
one is reachable.
Responds to an error in the application's configured format.
Installs the single-write guard over request.user and request.tenant.
Reads the security metadata a middleware function was branded with.
Serializes any thrown value to a plain, serializable object.
Brands a request with a WebSocket upgrade intent for the HTTP adapter to act on after the framework handler returns.
Creates an Option holding a value.
Build the stable sort fingerprint embedded in every minted cursor.
Partitions a Workers env record by value type.
Unwraps a Result, returning the value or throwing the error.
Reads the WebSocket upgrade intent an adapter should act on, or undefined
when the pipeline did not ask for an upgrade.
Builds the ctx.state key under which the validated value for a target is
stored — the cross-package wire format between the writer
(validation-plugin's middleware) and any reader (e.g. decorator-plugin's
parameter resolvers). Both sides import this helper so the key can never
drift between the package that writes it and the one that reads it back.
Reads the validation metadata a middleware function was branded with.
Brands an error with the status it should be answered with.
Brands a middleware function with the security it enforces, so a documentation generator can read it without importing the plugin that produced it.
Brands a middleware function with the request part and schema it validates, so a documentation generator can read it without importing the plugin that produced it.
Options accepted when enqueueing a job.
-
delayMs: number
Delay before the job becomes available, in milliseconds.
-
headers: Readonly<Record<string, string>>
Transport headers to carry with the job, delivered to the processor as
IJob.headers. -
maxAttempts: number
Maximum attempts before the job is dead-lettered.
One immutable audit trail entry.
-
action: string
The action performed (e.g.
"user.delete"). -
after: Readonly<Record<string, unknown>>
Resource state after the action.
-
before: Readonly<Record<string, unknown>>
Resource state before the action.
-
metadata: Readonly<Record<string, unknown>>
Additional context (IP, request ID, …).
-
resource: string
The resource kind acted on (e.g.
"user"). -
resourceId: string
The specific resource instance, when applicable.
-
result: "success" | "failure"
Whether the action succeeded.
-
userId: string
The acting principal's ID.
The structural shape both behaviour contracts satisfy, and the element type
of composeBehaviorChain's behaviors array.
-
handle(): TResult | Promise<TResult>work: TWork,next: () => Promise<TResult>
Wraps the rest of the chain.
Bulkhead policy consumed by the ResiliencePlugin's bulkhead pattern.
-
maxConcurrent: number
Maximum concurrent in-flight executions.
-
maxQueue: number
Maximum queued executions once concurrency is saturated. Defaults to 0.
Options for createCachedProbe.
-
clearTimer: (handle: TimerHandle) => void
Cancels a timer created by
CachedProbeOptions.setTimer(e.g.IRuntimeServices.clearTimeout). -
fallback: T
Outcome recorded when the probe times out or rejects.
-
hrtime: () => number
Monotonic clock in milliseconds (e.g.
IRuntimeServices.hrtime()). Injected so the TTL is an interval, not a wall-clock reading. -
probe: () => Promise<T>
The reachability probe. Resolving
truemeans the backend is reachable; resolvingfalseor rejecting means it is not. -
setTimer: () => TimerHandlefn: () => void,ms: number
Timer used to bound each probe (e.g.
IRuntimeServices.setTimeout). -
timeoutMs: number
Per-probe timeout, in milliseconds. A probe that does not settle within this window resolves
CachedProbeOptions.fallback, which isfalse— unreachable — unless the caller widened it. -
ttlMs: number
How long to cache the last outcome, in milliseconds.
Circuit breaker policy consumed by the ResiliencePlugin's breaker pattern.
-
resetTimeout: number
Cooldown in milliseconds before an open breaker moves to half-open.
-
threshold: number
Failures within the
timeoutwindow that trip the breaker open. -
timeout: number
Rolling failure window in milliseconds; failures older than this (measured by the monotonic clock) are dropped before the threshold check.
Provides a service by constructing a class, injecting the listed tokens as constructor arguments.
-
inject: readonly string[]
Tokens resolved and passed as constructor arguments, in order.
-
useClass: Constructor<T>
The class to instantiate.
A command: a request that mutates state and returns a result.
A query: a request that returns data without side effects.
A CQRS request identified by a string type and carrying typed data.
-
data: TData
The request payload.
-
type: string
Request type name (e.g.
"CreateUser"). Used for routing.
The decoded contents of a cursor minted by encodeCursor: the
values of every ordered field (in orderBy order) plus the primary-key
column values (for tiebreaker lookups) plus a stable fingerprint of the
sort specification. The fingerprint is what a fingerprint mismatch on decode
detects.
-
keyValues: ReadonlyArray<CursorValue>
The primary-key column values (in key-column order), from the row the cursor was minted against. Used by
keysetPredicateas the tiebreaker fallback when a key column is absent fromorderBy. -
orderedValues: ReadonlyArray<CursorValue>
The value of every ordered field (in
orderBydeclaration order), from the row the cursor was minted against. Indexiis the value of the i-th entry ofObject.entries(orderBy). -
sortFingerprint: string
A stable fingerprint of the resolved sort specification: each ordered field paired with its direction, in order. A cursor minted under one sort and presented under another has a different fingerprint, so the caller is refused by name rather than served a silently wrong page.
A payload as it travels the backplane.
-
binary: boolean
True when
EncodedPayload.datais base64-encoded binary. -
data: string
The payload as a string.
Specification of one environment variable for
IEnvironmentApi.validate.
-
default: string | number | boolean
Default applied when the variable is absent.
-
required: boolean
Whether the variable must be present.
-
type: "string" | "number" | "boolean"
Expected primitive type (defaults to
'string').
A failed result carrying an error.
-
error: E
The error value.
-
success: false
Discriminant:
falsefor failure.
The minimal context an error responder needs to write a response: the
request-scoped state (where the responder itself is published), the response
builder to write to, and the request (for the Problem Details instance).
-
request: { readonly path: string; }
The request, when one exists (supplies the Problem Details
instance). -
response: IResponse
The response builder to write the error response to.
-
state: Map<string, unknown>
Request-scoped state; the responder is published under
ERROR_RESPONDER_STATE_KEY.
The initialization of an error response produced through the responder seam.
-
detail: string
An optional disclosure, kept verbatim by every format.
-
details: Readonly<Record<string, unknown>>
Optional structured details (e.g. a validation
errorsarray). -
status: number
The HTTP status code to answer with.
-
title: string
The framework-default
errormember. In a formatted response this is the Problem Detailsdetailwhen nodetailis supplied.
Provides a service via a factory function.
-
useFactory: () => T
Factory invoked to produce the instance.
Evaluation context for targeting rules.
-
attributes: Readonly<Record<string, string | number | boolean>>
Additional targeting attributes.
-
tenantId: string
The tenant the flag is evaluated for, when the request resolves one.
-
userId: string
The user the flag is evaluated for.
A parsed form body: the read-only view IRequest.formData?() resolves and
parseFormBody returns.
-
entries(): IterableIterator<[string, FormValue]>
Iterates every
[name, value]pair in wire order — the enumeration primitive for reading a form whose field names the reader does not know ahead of time (the hand-rollednew URLSearchParams(body)iteration this accessor replaces). -
get(name: string): FormValue | undefined
Returns the FIRST value for a name, or
undefinedwhen the name is absent — the web standard'sget, withundefined(narrowable) in place ofnull. -
getAll(name: string): readonly FormValue[]
Returns every value for a name in wire order — the web standard's
getAll, so a repeated field (multi-select, multi-file) keeps the order the client sent.
One file part of a form body: a field that declared a filename in its
Content-Disposition.
-
data: Uint8Array
The file bytes, synchronously.
-
filename: string
The client-provided file name (
Content-Dispositionfilename="…"). -
mimeType: string
MIME type reported by the part's
Content-Type, or its default.
Information about a WebSocket connection used for subscription operations.
-
connectionParams: Record<string, unknown>
The payload sent with
connection_init, if any. -
data: Map<string, unknown>
Per-connection application state.
-
headers: Headers
The upgrade request headers.
-
id: string
Unique connection identifier.
-
protocol: string
The negotiated subprotocol, when one was selected.
-
query: Readonly<Record<string, string>>
Query string parameters from the upgrade request.
The outcome of a GraphQL execution, carrying an HTTP status code for the transport layer to use.
-
result: GraphqlExecutionResult
The execution result (may contain errors).
-
status: number
The HTTP status code to return under
application/graphql-response+jsonnegotiation.
The execution result as specified by the GraphQL spec.
-
data: Record<string, unknown> | null
The data returned by the execution, or null if an error occurred.
-
errors: GraphqlFormattedError[]
Errors encountered during execution, or undefined if none.
Formatted GraphQL error as returned to the client.
-
extensions: Record<string, unknown>
Optional extensions for application-specific error codes.
-
locations: Array<{ line: number; column: number; }>
Optional locations in the query document.
-
message: string
Human-readable error message.
-
path: Array<string | number>
Optional path to the field where the error occurred.
Context for a subscription operation, carrying either an HTTP request context or a WebSocket connection info.
-
connection: GraphqlConnectionInfo
The WebSocket connection info (supplied by the WS path).
-
requestContext: IRequestContext
The HTTP request context (supplied by the SSE path).
Parameters for a GraphQL execution request.
-
extensions: Record<string, unknown>
Optional extensions carried with the request.
-
operationName: string
Operation name for documents with multiple operations.
-
query: string
The GraphQL query string.
-
variables: Record<string, unknown>
Variables as a record of unknown values (passed through verbatim).
A gRPC service definition that satisfies the plugin's expectations.
This is a structural constraint satisfied by generated descriptor objects
from @bufbuild/protobuf. It contains only the fields the plugin
needs to route requests and build reflection data.
-
method: Readonly<Record<string, TMethod>>
Methods keyed by their camelCase local name.
-
typeName: string
The fully qualified name of the service, e.g.
"package.ServiceName".
Opaque marker returned by IResponse terminal methods and
expected back from route handlers. It exists purely so the type system can
verify a handler produced a response; only the kernel creates values of
this type.
-
__handlerResult: true
Brand preventing accidental structural matches.
The outcome of one health check.
-
data: Readonly<Record<string, unknown>>
Optional diagnostic details (response times, versions, …).
-
status: HealthStatus
The reported health state.
The aggregated health report returned by IHealthService.check().
-
checks: Readonly<Record<string, Readonly<HealthCheckResult & { readonly latencyMs?: number; }>>>
Per-indicator results with optional latency measurements.
-
status: HealthStatus
Overall health status (worst of all participating indicators).
-
timestamp: string
ISO 8601 timestamp of when the check was performed.
How an error should be answered, as decided by the code that threw it.
-
detail: string
The caller-facing disclosure, served verbatim — required here, where
ErrorResponseInitleaves it optional, because a hint that omitted it would fall back to theError's own message. -
status: number
The HTTP status to answer with. Must be an integer in
400–599; a hint outside that range is treated as ABSENT and the error takes the ordinary masked-500path, because a hint says how an ERROR should be answered and a status the platform cannot serve would make the error handler itself throw.
A transaction handle that can also open entity data sources bound to itself.
-
createDataSource(entity: string): IDataSource
Open a data source for
entitybound to THIS transaction.
The application: registers plugins, owns the router and middleware pipeline, and manages the server lifecycle.
-
fetch(request: Request): Promise<Response>
Delegates a web-standard
Requestto the registeredIHttpAdapter.fetch. This works regardless of whetherstart()was called (Cloudflare Workers path:setHandlerruns atstart()time,fetchworks withoutlisten). -
middleware: IMiddlewareApi
The global middleware pipeline.
-
register(plugin: IPlugin): IApplication
Registers a plugin. Plugins register when the application starts, in dependency order.
-
router: IRouterApi
The application router.
-
services: IServiceRegistry
The application-scoped service registry.
-
start(options?: StartOptions): Promise<void>
Resolves plugins, builds the pipeline and router, and starts the server.
-
stop(): Promise<void>
Stops the server and runs shutdown hooks.
Immutable audit trail writer.
-
log(entry: AuditEntry): Promise<void>
Appends an entry to the audit trail. Entries are immutable once written.
Authentication service that coordinates strategies and provides credential verification for login flows.
-
authenticate(request: IRequest): Promise<IPrincipal | null>
Run configured passive strategies to authenticate a request.
-
verifyCredentials(credentials: { readonly identifier: string; readonly secret: string; }): Promise<IPrincipal | null>
Verify credentials for a login flow (e.g., username/password).
Authentication strategy interface. Implementations extract credentials
from a request and return a principal, or null if the strategy
does not apply.
-
authenticate(request: IRequest): Promise<IPrincipal | null>
Attempt to authenticate the request.
-
name: string
Strategy name for identification.
Key/value cache with per-entry TTL.
-
clear(): Promise<void>
Removes every entry (respecting the store's key prefix, if configured).
-
delete(key: string): Promise<boolean>
Removes a cached value.
-
get<T>(key: string): Promise<T | null>
Reads a cached value.
-
has(key: string): Promise<boolean>
Reports whether a live entry exists.
-
set<T>(): Promise<void>key: string,value: T,ttlSeconds?: number
Stores a value.
Circuit breaker protecting calls to an unreliable dependency.
-
execute<T>(fn: ResilientCall<T>): Promise<T>
Executes a call through the breaker.
-
state: CircuitState
The current circuit state.
CLI command registration surface: a plugin publishes commands here, and the
kernel registers each under CAPABILITIES.CLI_COMMAND as a
multi-provider token that any consumer can read with getAll.
-
register(): voidname: string,handler: CliCommandHandler
Registers a CLI command.
Registers and executes commands.
-
execute<TResult = unknown>(command: CqrsCommand): Promise<TResult>
Executes a command.
-
register<TCommand extends CqrsCommand, TResult>(): voidtype: string,handler: ICommandHandler<TCommand, TResult>
Registers a handler for a command type.
Handles one command type.
-
handle(command: TCommand): TResult | Promise<TResult>
Executes the command.
Type-safe configuration access. Values originate from environment
variables and .env files, validated at startup.
-
get<T>(key: string): T | undefined
Reads a configuration value.
-
getOrThrow<T>(key: string): T
Reads a required configuration value.
-
has(key: string): boolean
Reports whether a key is present.
Dependency injection container.
-
createScope(): IContainer
Creates a child scope. Scoped services resolve to one instance per scope; singletons are shared with the parent.
-
has(token: string): boolean
Reports whether a token is registered.
-
register<T>(): voidtoken: string,provider: Provider<T>,options?: ProviderOptions
Registers a provider under a token.
-
resolve<T>(token: string): T
Resolves an instance, constructing it (and its dependencies) as needed.
Monotonically increasing counter. observe / inc add a non-negative value.
-
inc(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Increments the counter.
Facade combining command and query buses.
-
commandBus: ICommandBus
The command bus.
-
queryBus: IQueryBus
The query bus.
The full database backend port: lifecycle plus data access.
-
beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
Begin a transaction, returning a handle that can open transaction-scoped data sources as well as commit and roll back.
-
createDataSource(entity: string): IDataSource
Open a non-transactional data source for the named entity.
-
rawQuery<T>(): Promise<T[]>sql: string,params?: unknown[]
Execute a raw query in the backend's own dialect.
The data-access seam a backend provides per entity.
-
count(): Promise<number>where: Record<string, unknown>,filter?: FilterExpression
Count entities matching a filter.
-
create(data: Partial<Record<string, unknown>>): Promise<Record<string, unknown>>
Insert a new entity.
-
delete(id: EntityKey): Promise<boolean>
Delete an entity by primary key.
-
findAll(query: NormalizedQuery): Promise<Record<string, unknown>[]>
Find every entity matching the normalized query.
-
findById(id: EntityKey): Promise<Record<string, unknown> | null>
Find a single entity by its primary key value.
-
findPage(query: NormalizedQuery): Promise<PageResult>
Find a page of entities by cursor pagination.
-
update(): Promise<Record<string, unknown>>id: EntityKey,data: Partial<Record<string, unknown>>
Update an existing entity by primary key.
Custom decorator registration surface (active only when the DecoratorPlugin is registered; inert otherwise).
-
register(): voidname: string,handler: DecoratorHandler
Registers a handler for a custom decorator.
DNS resolution, abstracted across runtimes.
-
resolveHost(hostname: string): Promise<readonly string[]>
Resolves a hostname to IP address literals.
-
resolveSrv(hostname: string): Promise<readonly SrvRecord[]>
Resolves
SRVrecords for a hostname.
A domain event.
-
aggregateId: string
ID of the aggregate that produced the event, when applicable.
-
data: T
The event payload.
-
id: string
Unique event ID.
-
occurredOn: Date
When the event occurred.
-
type: string
Event type name (e.g.
"UserCreated"). -
version: number
Aggregate version, for event-sourced aggregates.
Environment validation surface: plugins declare the environment variables they need, and the kernel validates them at startup, failing fast on violations.
-
validate(spec: Readonly<Record<string, EnvVarSpec>>): void
Declares and validates environment variables.
A request-scoped error responder: writes an error response in the application's configured format.
-
respond(): voidtarget: ErrorResponderTarget,init: ErrorResponseInit
Writes an error response in the configured format.
In-memory publish/subscribe event bus for domain events.
-
publish<T>(event: IDomainEvent<T>): Promise<void>
Publishes an event to every subscriber of its type.
-
publishBatch(events: IDomainEvent[]): Promise<void>
Publishes multiple events, each to its own subscribers.
-
subscribe<T>(): Unsubscribetype: string,handler: EventHandler<T>
Subscribes to an event type.
Feature flag evaluator. Evaluation is synchronous against the provider's cached state; providers refresh their state out of band.
-
isEnabled(): booleanflag: string,context?: FlagContext
Evaluates a flag.
-
isEnabledAsync(): Promise<boolean>flag: string,context?: FlagContext
Evaluates a flag, awaiting the backing provider when it can produce a more accurate answer asynchronously.
Runtime-agnostic file system operations. Absent on runtimes without file system access (edge platforms).
-
mkdir(): Promise<void>path: string,options?: { readonly recursive?: boolean; }
Creates a directory.
-
readFile(path: string): Promise<Uint8Array>
Reads a file.
-
readStream(): Promise<ReadableStream<Uint8Array>>path: string,options?: { readonly start?: number; readonly end?: number; }
Reads a file as a stream, optionally with byte range.
-
readdir(path: string): Promise<readonly string[]>
Lists directory entries.
-
realPath(path: string): Promise<string>
Resolves a path to its canonical absolute form, following symlinks.
-
rm(): Promise<void>path: string,options?: { readonly recursive?: boolean; }
Removes a file or directory.
-
stat(path: string): Promise<StatResult>
Returns file metadata.
-
writeFile(): Promise<void>path: string,data: Uint8Array
Writes a file, creating it if absent.
Gauge: arbitrary set / inc / dec. observe sets the value.
-
dec(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Decrements the gauge.
-
inc(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Increments the gauge.
-
set(): voidvalue: number,labels?: Readonly<Record<string, string>>
Sets the gauge to a specific value.
The GraphQL service contract.
-
cachedDocumentCount: number
Report the number of cached documents.
-
endpoint: string
The endpoint path where GraphQL is served.
-
execute(): Promise<GraphqlExecutionOutcome>params: GraphqlRequestParams,requestContext?: IRequestContext,method?: "GET" | "POST"
Execute a GraphQL request.
-
subscribe(): Promise<GraphqlSubscriptionOutcome>params: GraphqlRequestParams,context?: GraphqlOperationContext
Subscribe to a GraphQL operation (query, mutation, or subscription).
The service contract that applications use to register gRPC/Connect services.
Provided by the grpc-plugin under the CAPABILITIES.GRPC token.
-
addService<TDef extends GrpcServiceDefinition>(): voiddefinition: TDef,implementation?: unknown
Registers a gRPC service definition with an optional implementation.
-
available: boolean
Whether gRPC dispatch is available.
-
claims(request: Request): boolean
Whether this service claims a request — that is, whether the request path lies inside the configured
basePath. -
handleRequest(request: Request): Promise<Response>
Handles an incoming RPC request directly.
-
refuses(request: Request): Response | null
Whether this service refuses the request outright, decided from its HEADERS alone.
Health check registration surface.
-
register(): voidname: string,indicator: HealthIndicatorFn
Registers a health indicator.
A named health indicator contributing to /health, /live, and
/ready.
-
check(): Promise<HealthCheckResult>
Performs the health check.
-
name: string
Indicator name, unique per application.
Health service contract for registering and checking health indicators.
-
check(): Promise<HealthReport>
Runs all registered indicators and returns the aggregated report.
-
checkLive(): Promise<HealthReport>
Runs only the liveness indicator (the built-in "self" indicator).
-
checkReady(): Promise<HealthReport>
Runs all contributed indicators for readiness.
-
registerIndicator(): voidname: string,indicator: HealthIndicatorFn
Registers a health indicator.
Histogram: bucketed observation distribution plus sum and count.
-
buckets: readonly number[]
Upper bounds of the histogram buckets.
-
observe(): voidvalue: number,labels?: Readonly<Record<string, string>>
Records an observation (sample).
HTTP server adapter provided by the runtime plugin. No other plugin may create HTTP servers (AI_GUIDELINES §4.3).
-
close(handle: ServerHandle): Promise<void>
Stops the server gracefully.
-
fetch(request: Request): Response | Promise<Response>
The universal web-standard entry point. Accepts a web
Requestand returns a webResponse. May be called withoutlisten(e.g. Cloudflare Workers whereexport default { fetch: app.fetch }is the deploy path). -
listen(): Promise<ServerHandle>port: number,hostname?: string
Binds the adapter's
fetchto a real TCP socket. -
setHandler(handler: (request: IRequest) => IResponse | Promise<IResponse>): void
Installs the framework request handler. Called once at
start()time, after the middleware pipeline compiles and before anyfetchorlisten. -
setRpcHandler(handler: RpcFetchHandler): void
Installs a gRPC/Connect fetch handler.
-
setUpgradeRouter(router: WebSocketUpgradeRouter): void
Installs a WebSocket upgrade router. The adapter stores the router but does not consult it: since M70a the kernel's terminal handler resolves
IWebSocketServiceand callsrouteUpgradeitself, after the middleware pipeline has run without short-circuiting and before route matching — so an application catch-all cannot shadow an upgrade. What the adapter needs from this setter is the bare fact that a router was installed: Node attaches its rawupgradelistener only then.
Cross-cutting behaviour around one unit of non-HTTP ingress work.
-
handle(): void | Promise<void>ctx: IngressContext,next: () => Promise<void>
Wraps the rest of the chain around one work item.
A queued job delivered to a processor.
-
attempts: number
How many times this job has been attempted (1 on first delivery).
-
data: T
The job payload.
-
headers: Readonly<Record<string, string>>
Transport headers carried with the job, mirroring
MessageMetadata.headersso the two ingresses cannot drift on meaning:{}means the channel was read and carried nothing; absent means there was no channel. -
id: string
Queue-assigned job ID.
-
name: string
The job name it was enqueued under.
JWT sign/verify service.
-
decode<T = Readonly<Record<string, unknown>>>(token: string): T | null
Decodes a token without verifying it. Never trust the result for authorization decisions.
-
sign(): Promise<string>payload: Readonly<Record<string, unknown>>,options?: JwtSignOptions
Signs a payload into a JWT.
-
verify<T = Readonly<Record<string, unknown>>>(token: string): Promise<T>
Verifies a token's signature and validity window.
Lifecycle hook registration surface. Hooks run in registration order within each phase.
-
onBootstrap(fn: () => void | Promise<void>): void
Runs immediately before the server starts listening.
-
onClose(fn: () => void | Promise<void>): void
Runs after shutdown completes.
-
onError(fn: () => void | Promise<void>): voiderror: Error,ctx: IRequestContext
Runs when an error escapes middleware or a handler.
-
onInit(fn: () => void | Promise<void>): void
Runs after all plugins have registered.
-
onRegister(fn: () => void | Promise<void>): void
Runs during the owning plugin's registration.
-
onRequest(fn: (ctx: IRequestContext) => void | Promise<void>): void
Runs at the start of every request.
-
onResponse(fn: (ctx: IRequestContext) => void | Promise<void>): void
Runs after every response is produced.
-
onShutdown(fn: () => void | Promise<void>): void
Runs when shutdown begins — close connections, flush buffers here.
-
onStopping(fn: () => void | Promise<void>): void
Runs at the very start of
stop(), before the application begins refusing new requests.
Structured logger. All framework and application logging goes through
this interface — never console (AI_GUIDELINES §11.6).
-
child(bindings: LogMetadata): ILogger
Creates a child logger whose entries always include the bindings.
-
debug(): voidmessage: string,metadata?: LogMetadata
Logs at
debugseverity. -
error(): voidmessage: string,metadata?: LogMetadata
Logs at
errorseverity. -
fatal(): voidmessage: string,metadata?: LogMetadata
Logs at
fatalseverity. -
info(): voidmessage: string,metadata?: LogMetadata
Logs at
infoseverity. -
level: LogLevel
The minimum level this logger emits.
-
trace(): voidmessage: string,metadata?: LogMetadata
Logs at
traceseverity. -
warn(): voidmessage: string,metadata?: LogMetadata
Logs at
warnseverity.
Email sender.
-
isHealthy(): Promise<boolean | undefined>
Reports whether the mail transport is REACHABLE right now, distinct from whether the mailer was constructed. Optional: a mailer whose transport exposes no side-effect-free probe omits it, and so does an implementation that does not answer the question at all.
-
send(message: MailMessage): Promise<void>
Sends an email.
-
sendTemplate(): Promise<void>template: string,message: Omit<MailMessage, "html" | "text">,data: Readonly<Record<string, unknown>>
Renders a named template and sends the result.
Message broker for cross-service integration events.
-
connect(): Promise<void>
Opens the broker connection.
-
disconnect(): Promise<void>
Closes the broker connection.
-
isHealthy(): Promise<boolean>
Reports whether the broker's backend is reachable right now, for the plugin's health indicator.
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic.
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request to a topic and awaits a single correlated reply, providing brokered request-reply (RPC) over the message broker.
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder for a request topic. The handler's resolved value is sent back to the requesting caller, correlated to the originating request.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic.
Metadata captured by decorators, read by the DecoratorPlugin. Stored in plain maps — no reflection (ARCHITECTURE.md §12). The concrete metadata value shapes are owned by the decorator plugin.
-
controllers: Map<Constructor, Readonly<Record<string, unknown>>>
Controller metadata keyed by class.
-
routes: Map<>Constructor,ReadonlyArray<Readonly<Record<string, unknown>>>
Route metadata lists keyed by controller class.
-
services: Map<Constructor, Readonly<Record<string, unknown>>>
Service metadata keyed by class.
A registered metric.
-
help: string
Human-readable description.
-
name: string
Metric name (Prometheus naming conventions).
-
observe(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Records an observation.
-
type: MetricType
The metric instrument kind.
Metric registration surface.
-
register(): voidname: string,config: MetricConfig
Registers a metric.
Metrics service resolved via ctx.services.get<IMetricsService>('metrics').
-
counter(): ICountername: string,options?: MetricOptions
Gets or creates a counter.
-
gauge(): IGaugename: string,options?: MetricOptions
Gets or creates a gauge.
-
get(name: string): IMetric | undefined
Gets a metric by name.
-
histogram(): IHistogramname: string,options?: MetricOptions
Gets or creates a histogram.
-
summary(): ISummaryname: string,options?: MetricOptions
Gets or creates a summary.
Object form of middleware, for implementations that carry state.
Middleware pipeline registration surface exposed to plugins.
-
add(): voidmiddleware: MiddlewareFunction,options?: MiddlewareOptions
Adds middleware to the global pipeline.
Multi-tenancy service — exposes tenant context, repository creation, and cache-key helpers.
-
getCurrentTenant(ctx: IRequestContext): ITenant | undefined
Return the tenant resolved for this request context, or
undefined. -
getRepository<Entity, Id = string>(): ITenantRepository<Entity, Id>ctx: IRequestContext,entity: string
Create a tenant-scoped repository for the given entity type. Throws
TenantNotResolvedErrorif no tenant is resolved. -
getRepositoryFor<Entity, Id = string>(): ITenantRepository<Entity, Id>tenantId: string,entity: string
Create a tenant-scoped repository for the given entity type, scoped to the tenant id GIVEN — no
IRequestContextrequired. This is the entry point for non-HTTP work (an ingress behaviour, a queue processor, a scheduled job), where no request exists to resolve a tenant from; the caller reads the tenant id from the work item's own payload. Modelled onprefixCacheKey— this interface's other ctx-free, id-taking member. -
prefixCacheKey(): stringtenantId: string,key: string
Build a cache key that includes the tenant id, joined by the separator the plugin was configured with (
cache.separator, default':'). The separator is deliberately NOT a per-call argument: this method is the single home for separator resolution, so the middleware'sctx.stateprefix and a caller's key can never disagree.
Transport-neutral envelope for ONE unit of non-HTTP work.
-
attempt: number
1-based delivery attempt. Present for
'queue'(fromIJob.attempts) and'scheduler'(fromScheduledJob.attempts); ABSENT for'messaging'and'websocket'. Absent means "this ingress cannot tell you" — never "first try": brokers redeliver and none tracks a delivery count, so a fabricated1would lie on a fifth redelivery. -
headers: Readonly<Record<string, string>>
Transport headers, populated on the
'messaging'arm fromMessageMetadata.headersand on the'queue'arm fromIJob.headers.{}means the channel carried none; absent means there was no channel. -
kind: IngressKind
Which ingress path produced this work item — the discriminator a behaviour branches on.
-
name: string
The route the work is addressed by: the queue job name, the scheduler job name, the broker topic, or the WebSocket route path.
-
payload: TPayload
The native work item: an
IJob, aScheduledJob, the message payload, or the frame data.
Multi-channel notification dispatcher.
-
send(notification: NotificationMessage): Promise<void>
Dispatches a notification on every requested channel.
-
sendSettled(notification: NotificationMessage): Promise<readonly ChannelSendResult[]>
Dispatches a notification on every requested channel and reports the settled outcome of each, without throwing.
OpenAPI contribution surface. Schema values are unknown here; the
OpenAPI plugin narrows them (Zod schemas by default).
-
addSchema(): voidname: string,schema: unknown
Contributes a named schema to the generated OpenAPI document.
ORM adapter port — what the DatabasePlugin requires from any ORM integration.
-
beginTransaction(): Promise<ITransaction>
Begins a transaction.
-
connect(): Promise<void>
Opens the underlying connection (pool).
-
disconnect(): Promise<void>
Closes the underlying connection (pool).
-
isReady(): boolean
Reports whether the adapter is connected and usable.
Wraps a handler with cross-cutting logic (logging, timing, validation, etc.).
-
handle(): TResult | Promise<TResult>request: TRequest,next: () => Promise<TResult>
Wraps the next handler in the pipeline.
The plugin contract. Every framework capability implements this interface (AI_GUIDELINES §3.2).
-
consumes: readonly CapabilityToken[]
Capability tokens this plugin resolves lazily at runtime via
ctx.services.get. UnlikeIPlugin.dependencies, these are not required before this plugin registers and impose no ordering; but if no registered plugin provides one, the kernel emits a softwarn-level startup diagnostic (through the logger capability when one is registered), because the deferred lookups would otherwise fail only later, at request time. -
dependencies: readonly CapabilityToken[]
Capability tokens that must be provided before this plugin registers.
-
name: string
Unique plugin name, lowercase kebab-case.
-
optionalDependencies: readonly CapabilityToken[]
Capability tokens used when present, tolerated when absent.
-
priority: number
Registration priority within the same dependency level; lower first.
-
provides: readonly CapabilityToken[]
Capability tokens this plugin registers.
-
register(ctx: IPluginContext): void | Promise<void>
Registers the plugin's services, middleware, routes, and hooks.
-
version: string
Plugin semver, matching its
deno.jsonversion.
The registration context handed to IPlugin.register — every
extension point a plugin can touch.
-
app: IApplication
The owning application.
-
cli: ICliApi
CLI command registration.
-
config: IConfig
Configuration access (from the ConfigPlugin, when registered).
-
container: IContainer
DI container (from the DiPlugin, when registered).
-
decorators: IDecoratorApi
Custom decorator registration.
-
environment: IEnvironmentApi
Environment variable validation.
-
health: IHealthApi
Health check registration.
-
lifecycle: ILifecycleApi
Lifecycle hooks.
-
logger: ILogger
Logger (from the LoggerPlugin, when registered).
-
metadata: IMetadataStore
Decorator metadata store (from the DecoratorPlugin, when registered).
-
metrics: IMetricsApi
Metric registration.
-
middleware: IMiddlewareApi
Middleware pipeline.
-
openapi: IOpenApiApi
OpenAPI contributions.
-
options: Readonly<Record<string, unknown>>
Options the application passed to this plugin's factory.
-
router: IRouterApi
Route registration.
-
runtime: IRuntimeServices
Runtime services. Non-optional by contract: a runtime provider is mandatory and the kernel registers it first, so every other plugin can rely on it during registration (see ARCHITECTURE.md §7).
-
services: IServiceRegistry
Service registration and resolution.
The authenticated identity attached to a request by authentication middleware.
-
claims: Readonly<Record<string, unknown>>
Additional claims from the credential.
-
id: string
Stable subject identifier.
-
permissions: readonly string[]
Permission names held by the principal.
-
roles: readonly string[]
Role names held by the principal.
Registers and executes queries.
-
execute<TResult = unknown>(query: CqrsQuery): Promise<TResult>
Executes a query.
-
register<TQuery extends CqrsQuery, TResult>(): voidtype: string,handler: IQueryHandler<TQuery, TResult>
Registers a handler for a query type.
Handles one query type.
-
handle(query: TQuery): TResult | Promise<TResult>
Executes the query.
Background job queue.
-
add<T>(): Promise<string>name: string,data: T,options?: AddJobOptions
Enqueues a job.
-
addRecurring<T>(): Promise<void>name: string,data: T,options: RecurringOptions
Schedules a recurring job.
-
process<T>(): voidname: string,processor: JobProcessor<T>,options?: ProcessOptions
Registers a processor for a job name.
A publish/subscribe transport carrying RealtimeFrames between
application instances.
-
close(): Promise<void>
Closes the underlying transport and drops every handler.
-
connect(): Promise<void>
Opens the underlying transport. Idempotent.
-
isHealthy(): Promise<boolean>
Reports whether the transport's backend is reachable right now, for the plugin's health indicator.
-
origin: string
This instance's identity, stamped onto every frame it publishes.
-
publish(frame: RealtimeFrame): Promise<void>
Publishes a frame to every other subscribed instance.
-
subscribe(handler: RealtimeFrameHandler): Promise<() => void>
Registers a handler for frames arriving from other instances.
Runtime-agnostic view of an incoming HTTP request.
-
bytes(): Promise<Uint8Array>
Reads the body as raw bytes.
-
formData(): Promise<FormBody>
Reads the body as a form, for both
application/x-www-form-urlencodedandmultipart/form-datarequests. -
headers: Headers
Request headers (web-standard
Headers). -
ip: string
Client IP address, when derivable.
-
json<T = unknown>(): Promise<T>
Reads and parses the body as JSON.
-
method: HttpMethod
The HTTP method.
-
path: string
The URL path component (no query string).
-
raw: Request
The undisturbed web-standard
Request, preserved for WebSocket upgrade and gRPC dispatch after the middleware pipeline. -
signal: AbortSignal
An abort signal that fires when the underlying HTTP connection is severed (client disconnect, timeout). Populated by the HTTP adapter from the native
Request.signal; optional because injected / test requests may not carry one. -
tenant: ITenant
The resolved tenant, populated by the multi-tenancy middleware. Absent when no tenant could be resolved or multi-tenancy is not enabled.
-
text(): Promise<string>
Reads the body as text.
-
url: string
The full request URL.
-
user: IPrincipal
The authenticated principal, populated by authentication middleware. Absent when the request is unauthenticated.
Per-request context passed to middleware and route handlers. Each request gets a fresh context; request-scoped data lives here, never in globals.
-
id: string
Unique request ID (generated or propagated by middleware).
-
params: Readonly<Record<string, string>>
Path parameters extracted by the router (e.g.
:id). -
query: Readonly<Record<string, string>>
Query string parameters.
-
raw: Request
The undisturbed web-standard
Request, preserved for WebSocket upgrade and gRPC dispatch after the middleware pipeline. -
request: IRequest
The incoming request.
-
response: IResponse
The response builder.
-
services: IServiceRegistry
Service resolution (application-scoped plus request-scoped services).
-
signal: AbortSignal
An abort signal that fires when the underlying HTTP connection is severed (client disconnect, timeout). Populated by the kernel's request-context factory from the native
Request.signal; falls back to a non-aborting sentinel so handlers always have a live signal to listen on. -
startTime: number
High-resolution timestamp captured when the context was created.
-
state: Map<string, unknown>
Request-scoped state for passing data between middleware and handlers.
Resilience service registered under CAPABILITIES.RESILIENCE.
-
wrap<T>(): HardenedCall<T>fn: ResilientCall<T>,options?: WrapOptions
Wraps
fnwith the selected patterns and returns a hardened callable that reuses one shared pattern chain across invocations, so circuit-breaker and bulkhead state persist across calls.
Runtime-agnostic response builder. Configuration methods (status,
header) chain; terminal methods (json, text, send, redirect)
produce the HandlerResult a route handler returns.
-
appendHeader(): IResponsename: string,value: string
Appends a response header, preserving any existing values for the same name rather than replacing them (unlike
IResponse.header, which overwrites). This is the correct way to emit multiple headers of the same name — most notably severalSet-Cookieheaders (e.g. an access cookie plus a refresh cookie, or deleting several cookies at once). -
header(): IResponsename: string,value: string
Sets a response header.
-
html(body: string): HandlerResult
Sends an HTML response.
-
json<T>(body: T): HandlerResult
Sends a JSON response.
-
redirect(): HandlerResulturl: string,status?: number
Sends a redirect response.
-
send(body?: Uint8Array): HandlerResult
Sends a raw byte response.
-
snapshot(): ResponseSnapshot
Returns a snapshot of the current response state (status, headers, body). Enables middleware to inspect the response after
next()returns — required for transparent response caching. -
status(code: number): IResponse
Sets the response status code.
-
stream(body: ReadableStream<Uint8Array>): HandlerResult
Sends a streaming response body.
-
text(body: string): HandlerResult
Sends a plain-text response.
Router registration surface exposed to plugins and applications.
-
delete(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a DELETE route.
-
get(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a GET route.
-
group(): voidprefix: string,configure: (router: IRouterApi) => void
Creates a route group: routes registered inside the callback share the prefix and any group middleware.
-
head(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a HEAD route.
-
listRoutes(): readonly RouteInfo[]
Returns all registered routes for introspection.
-
options(): voidpath: string,route: RouteHandler | RouteDefinition
Registers an OPTIONS route.
-
patch(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a PATCH route.
-
post(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a POST route.
-
put(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a PUT route.
Runtime services — every runtime-specific operation the framework needs,
abstracted behind one interface. Registered under CAPABILITIES.RUNTIME
by the RuntimePlugin, which is mandatory in every application.
-
clearInterval(handle: TimerHandle): void
Cancels a
setInterval. -
clearTimeout(handle: TimerHandle): void
Cancels a
setTimeout. -
dns: IDnsResolver
DNS resolution; absent on runtimes with no resolver API (edge platforms).
-
env: Readonly<Record<string, string | undefined>>
Environment variables. Always read env through this, never
process.env. -
exit(code?: number): never
Terminates the process.
-
fs: IFileSystem
File system access; absent on runtimes without one (edge platforms).
-
hostname(): string
Returns the host name, when the runtime exposes one.
-
hrtime(): number
Returns a high-resolution monotonic timestamp in milliseconds, suitable for measuring durations.
-
now(): number
Returns the current wall-clock time in milliseconds since the epoch.
-
onSignal(): voidsignal: RuntimeSignal,handler: () => void
Registers a handler for a process-termination signal, so an application can run
app.stop()before the process dies. -
platform(): RuntimePlatform
Identifies the current runtime.
-
randomBytes(length: number): Uint8Array
Generates cryptographically secure random bytes.
-
setInterval(): TimerHandlefn: () => void,ms: number
Schedules a repeating callback.
-
setTimeout(): TimerHandlefn: () => void,ms: number
Schedules a one-shot callback.
-
subtle: SubtleCrypto
Web Crypto
SubtleCryptofor cryptographic operations. -
uuid(): string
Generates a UUID v4.
-
version(): string
Returns the runtime version string.
-
workers: IWorkerHost
Worker-thread spawning; absent on runtimes without threads (edge platforms).
In-process job scheduler.
-
cron<T = unknown>(): Promise<void>name: string,expression: string,handler: SchedulerJobHandler<T>,options?: ScheduleOptions<T>
Schedule a recurring job using a 5-field cron expression (UTC).
-
delay<T = unknown>(): Promise<void>name: string,delayMs: number,handler: SchedulerJobHandler<T>,options?: ScheduleOptions<T>
Schedule a one-shot delayed job.
-
every<T = unknown>(): Promise<void>name: string,intervalMs: number,handler: SchedulerJobHandler<T>,options?: ScheduleOptions<T>
Schedule a recurring job that fires every
intervalMsmilliseconds. -
getNextRun(name: string): Promise<number>
Return the next scheduled fire time as epoch milliseconds.
-
pause(name: string): Promise<void>
Pause a scheduled job without dropping its configuration.
-
remove(name: string): Promise<void>
Remove a scheduled job entirely.
-
resume(name: string): Promise<void>
Resume a paused job.
Secret manager backed by a provider (AWS KMS, GCP Secret Manager, Azure Key Vault, HashiCorp Vault, or environment variables in development).
-
get(name: string): Promise<string>
Retrieves a secret.
-
has(name: string): Promise<boolean>
Reports whether a secret exists.
-
rotate(): Promise<void>name: string,value: string
Rotates a secret to a new value.
Resolves logical service names to reachable instances, balances across them, and learns from reported call outcomes.
-
pick(): Promise<ServiceInstance | null>serviceName: string,options?: PickOptions
Chooses one instance, skipping ejected ones.
-
report(): voidinstance: ServiceInstance,outcome: ServiceOutcome
Reports how a call to an instance went.
-
resolve(serviceName: string): Promise<readonly ServiceInstance[]>
Lists every instance discovery knows for a service.
-
resolveUrl(): Promise<string | null>serviceName: string,path?: string,options?: PickOptions
Formats
IServiceDiscovery.pick's choice as an absolute URL. -
watch(): Promise<Unsubscribe>serviceName: string,listener: (instances: readonly ServiceInstance[]) => void
Subscribes to instance-list changes for a service.
Maps capability tokens to service instances.
-
get<T extends object>(token: CapabilityToken): T
Resolves a service by capability token.
-
getAll<T extends object>(token: CapabilityToken): readonly T[]
Resolves every provider registered for a multi-provider token.
-
has(token: CapabilityToken): boolean
Reports whether a capability is available.
-
register<T extends object>(): voidtoken: CapabilityToken,service: T,options?: RegisterOptions
Registers a service instance under a capability token.
-
registerFactory<T extends object>(): voidtoken: CapabilityToken,factory: ServiceFactory<T>,options?: RegisterOptions
Registers a lazy factory: the service is instantiated on first
getand cached for subsequent lookups. -
unregister(token: CapabilityToken): boolean
Removes a registration. On a multi-provider token this removes EVERY provider registered under it, not just the first.
Per-request session handle.
-
clear(): void
Removes every key, keeping the session and its id.
-
delete(key: string): boolean
Removes a key and marks the session for commit.
-
destroy(): void
Ends the session: clears the data, deletes any stored entry, and instructs the client to drop the cookie.
-
get<T = unknown>(key: string): T | undefined
Reads a value.
-
has(key: string): boolean
Reports whether a key is present.
-
id: string
The session identifier. Stable for the session's lifetime until
ISession.regenerateis called. -
isNew: boolean
Whether this session was created for this request rather than restored from a cookie.
truefor a first visit, and for a request whose cookie was missing, expired, or failed authentication. -
regenerate(): void
Issues a new session id while keeping the current data.
-
set<T>(): voidkey: string,value: T
Writes a value and marks the session for commit.
-
toJSON(): SessionData
Returns a plain snapshot of the current data.
Session service registered under CAPABILITIES.SESSION.
-
from(ctx: IRequestContext): ISession
Returns the session the middleware loaded for this request.
-
fromHeaders(headers: Headers): Promise<SessionView | null>
Opens a session from a
Headersobject alone — the headers-only read for non-HTTP entry points that have no request context to commit onto (a WebSocketonOpenhandler, an auth strategy reading a cookie).
Server-side session storage port.
-
close(): Promise<void>
Releases resources held by the store (timers, connections).
-
destroy(id: string): Promise<boolean>
Removes a stored session.
-
isHealthy(): Promise<boolean>
Reports the store's reachability, for the plugin's health indicator.
-
read(id: string): Promise<SessionData | null>
Reads a stored session payload.
-
write(): Promise<void>id: string,data: SessionData,ttlMs: number
Writes a session payload, replacing any existing one.
A span represents a single operation within a trace.
-
end(): void
Ends the span. Must be called exactly once.
-
recordException(error: Error): void
Records an exception on this span.
-
setAttribute(): thiskey: string,value: SpanAttributeValue
Sets a single attribute on the span.
-
setAttributes(attributes: Readonly<Record<string, SpanAttributeValue>>): this
Sets multiple attributes on the span.
-
setStatus(status: SpanStatus): void
Sets the status of the span.
-
spanContext(): SpanContext
Returns the span's context (traceId, spanId, traceFlags).
A live SSE connection backed by a ReadableStream.
-
close(): void
Closes the connection: clears the heartbeat, closes the stream controller, and marks the connection as closed. Idempotent.
-
comment(text: string): void
Enqueues a plain-text comment frame (
: <text>\n\n) — commonly used as a keep-alive heartbeat. -
id: string
Unique connection ID.
-
isOpen: boolean
Whether this connection is still open.
-
lastEventId: string | null
The client's
Last-Event-IDheader value, if present. -
result: HandlerResult
The
HandlerResultobtained fromctx.response.stream(). The handler returns this value so the kernel maps it to the correct web response. -
send(msg: SseMessage): void
Enqueues an encoded SSE frame for the connected client.
Service contract for the SSE hub — registered by the SsePlugin under
CAPABILITIES.SSE.
-
channel(name: string): SseChannel
Returns or creates a named channel.
-
channelCount: number
Number of channels the registry currently holds.
-
connectionCount: number
Current number of open connections.
-
open(ctx: IRequestContext): ISseConnection
Opens a new SSE connection for the given request context.
-
peek(name: string): SseChannel | undefined
Returns the named channel if one already exists, without creating it.
Service contract for server-side rendering (SSR).
-
render(ctx: IRequestContext): Promise<HandlerResult>
Renders an SSR document for the given request context.
Object storage abstraction.
-
delete(path: string): Promise<boolean>
Deletes an object.
-
exists(path: string): Promise<boolean>
Reports whether an object exists.
-
get(path: string): Promise<Uint8Array>
Retrieves an object.
-
getSignedUrl(): Promise<string>path: string,options: SignedUrlOptions
Creates a time-limited URL granting direct access to an object.
-
getStream(path: string): Promise<ReadableStream<Uint8Array>>
Retrieves an object as a streaming body for zero-copy downloads.
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
Stores an object.
Summary: per-quantile observations plus sum and count.
-
observe(): voidvalue: number,labels?: Readonly<Record<string, string>>
Records an observation (sample).
-
quantiles: readonly number[]
Configured quantiles.
Telemetry service — the primary API for creating spans.
-
activeSpanContext(): SpanContext | undefined
Reports the identifiers of the span that is active RIGHT NOW, so a signal emitted outside any span-creating call — a log record, most of all — can name the trace it belongs to.
-
withSpan<T>(): Promise<T>name: string,fn: (span: ISpan) => Promise<T>,options?: SpanOptions
Creates a span, runs the callback, and ends the span.
A resolved tenant.
-
id: string
Stable tenant identifier.
-
metadata: Readonly<Record<string, unknown>>
Tenant-specific configuration.
-
name: string
Display name.
Tenant-scoped repository — delegates CRUD to the data store the
multi-tenancy plugin was configured with (ITenantDataStore, declared in
that plugin), while threading the resolved tenant id.
-
create(data: Readonly<Record<string, unknown>>): Promise<Entity>
Create a new record.
-
delete(id: Id): Promise<boolean>
Delete a record by its identifier. Returns
trueif a record was deleted. -
find(filter: Readonly<Record<string, unknown>>): Promise<readonly Entity[]>
Find records matching a filter.
-
findAll(): Promise<readonly Entity[]>
Retrieve all records.
-
findById(id: Id): Promise<Entity | null>
Find a single record by its identifier.
-
update(): Promise<Entity | null>id: Id,data: Readonly<Record<string, unknown>>
Update an existing record by its identifier.
Resolves the tenant for an incoming request (by subdomain, header, path, or JWT claim, depending on the implementation).
-
resolve(request: IRequest): Promise<Option<ITenant>>
Resolves the request's tenant.
A database transaction handle.
-
commit(): Promise<void>
Commits the transaction.
-
rollback(): Promise<void>
Rolls the transaction back.
An adapter's explicit declaration of portable transaction isolation support.
-
transactionIsolationLevels: readonly TransactionIsolationLevel[]
The portable isolation levels this adapter honours.
Data validation service.
-
middleware(): MiddlewareFunctionschema: unknown,target: ValidationTarget
Creates middleware that validates one part of the request and stores the parsed value in request state.
-
validate<T>(): Result<T, readonly ValidationIssue[]>schema: unknown,data: unknown
Validates data against a schema.
View engine contract — renders a view component and its props to HTML.
-
render<P>(): string | Promise<string>component: Component<P>,props: P
Renders a view component with the given props to an HTML string.
A live WebSocket connection, as seen by application code.
-
close(): voidcode?: number,reason?: string
Closes the connection. Idempotent.
-
data: Map<string, unknown>
Per-connection application state, the socket-lifetime analogue of
IRequestContext.state. Use it to attach an authenticated user id, a tenant, or any value later handlers and broadcasts need. -
id: string
Unique connection ID (from
runtime.uuid()). -
isOpen: boolean
Whether the connection is still writable.
-
path: string
The path this connection was opened on.
-
readyState: WebSocketReadyState
Current lifecycle state.
-
send(data: string | Uint8Array): void
Sends a frame to this peer.
-
sendJson<T>(payload: T): void
Serializes a value to JSON and sends it as a text frame.
Service contract for the WebSocket hub — registered by the WebSocketPlugin
under CAPABILITIES.WEBSOCKET.
-
available: boolean
Whether the underlying HTTP adapter can perform WebSocket upgrades.
-
connectionCount: number
Current number of open connections across all routes.
-
peek(name: string): WebSocketRoom | undefined
Returns the named room if one already exists, without creating it.
-
room(name: string): WebSocketRoom
Returns the named room, creating it on first use.
-
roomCount: number
Current number of live rooms.
-
route(): voidpath: string,handlers: WebSocketHandlers,options?: WebSocketRouteOptions
Registers a WebSocket route. Paths match exactly; the query string is ignored for matching and exposed to
onOpeninstead. -
routeUpgrade(): Promise<WebSocketUpgradeDecision | null>request: Request,principal?: IPrincipal
Consults the internal upgrade router for an inbound request. Used by the kernel terminal handler to decide whether to upgrade after the middleware pipeline runs.
The runtime-native socket, normalized to the two operations the framework
needs. Implemented by each HTTP adapter's upgrader over its platform socket
(Deno.upgradeWebSocket's WebSocket, a ws socket on Node, Bun's
ServerWebSocket, the server half of a Workers WebSocketPair).
-
close(): voidcode?: number,reason?: string
Closes the socket.
-
readyState: WebSocketReadyState
Current lifecycle state of the underlying socket.
-
send(data: string | Uint8Array): void
Sends a frame to the peer. A
stringis sent as a text frame, aUint8Arrayas a binary frame.
Handle to one spawned worker thread, normalized across web Worker
(Deno/Bun) and node:worker_threads (Node).
-
onError(listener: (error: Error) => void): void
Registers a listener for worker-level errors (module evaluation failure, uncaught error in the worker).
-
onExit(listener: (code: number | null) => void): void
Registers a listener for the worker's THREAD ENDING, however it ended — a clean self-termination included. This is distinct from
onError, which reports a failure the worker survived long enough to report; a worker that simply stops raises no error at all. -
onMessage(listener: (message: unknown) => void): void
Registers a listener for messages from the worker.
-
postMessage(message: unknown): void
Posts a structured-clonable message to the worker.
-
terminate(): Promise<void>
Terminates the worker immediately.
Thread-spawning primitive provided by runtimes that support worker threads.
Absent on runtimes without them (e.g. Cloudflare Workers) — consumers MUST
degrade gracefully when it is not provided (see the WorkerPoolPlugin, which
fails run() with a typed error when no host exists).
-
availableParallelism(): number
Number of threads the host can usefully run in parallel.
-
reportsExit(): boolean
Reports whether handles from
spawnwill implementIWorkerHandle.onExit. -
spawn(specifier: string): IWorkerHandle
Spawns a module worker.
A pool of worker threads executing task modules off the event loop.
-
run<TInput, TOutput>(): Promise<TOutput>taskModule: string,input: TInput,options?: WorkerRunOptions
Runs a task on a pool worker for the given task module, creating the pool lazily on first use.
-
shutdown(): Promise<void>
Terminates every worker in every pool and rejects pending tasks. Called by the plugin's
onClosehook; safe to call more than once. -
stats(): readonly TaskPoolStats[]
Returns a snapshot of every pool created so far.
Options accepted when signing a JWT.
-
audience: string
Token audience.
-
expiresIn: string
Token lifetime (e.g.
"1h","7d"). -
issuer: string
Token issuer.
An outgoing email message.
-
bcc: readonly string[]
Blind-carbon-copy recipients.
-
cc: readonly string[]
Carbon-copy recipients.
-
from: string
Sender address; omitted to use the provider default.
-
html: string
HTML body.
-
subject: string
Subject line.
-
text: string
Plain-text body.
-
to: string | readonly string[]
Recipient address(es).
Transport metadata accompanying a delivered message.
-
headers: Readonly<Record<string, string>>
Transport headers read from the delivered message. First-party brokers populate this with
{}when their transport carried no headers. -
messageId: string
Broker-assigned message ID, when available.
-
timestamp: Date
Delivery timestamp, when available.
-
topic: string
The topic the message arrived on.
Configuration for registering a metric.
-
buckets: readonly number[]
Histogram bucket boundaries (histogram metrics only).
-
help: string
Human-readable description (Prometheus
HELP). -
labels: readonly string[]
Label names attachable to observations.
-
type: MetricType
The metric instrument kind.
Ergonomic options for the typed factory methods. type is injected by the
method name; help defaults to the metric name.
-
buckets: readonly number[]
Histogram bucket boundaries (histogram metrics only).
-
help: string
Human-readable description (Prometheus
HELP). Defaults to the metric name. -
labels: readonly string[]
Label names attachable to observations.
-
maxSamples: number
Summary only: bounded sample-window size.
-
quantiles: readonly number[]
Summary quantiles (summary metrics only).
Options accepted when adding middleware to the pipeline.
-
name: string
Diagnostic name shown in pipeline introspection.
-
priority: number
Execution priority — lower numbers run earlier. See ARCHITECTURE.md §10 for the conventional priority bands of first-party middleware.
A repository query with every option resolved to a concrete value — the
shape a IDataSource evaluates.
-
cursor: string
A keyset cursor position, or
undefinedwhen the query starts at the first page. Carried alongsideoffsetrather than replacing it: an offset says "skip this many from the start" and a cursor says "after this row", and the two are contradictory — a query carrying both is refused by name (§3.10). -
filter: FilterExpression
Optional portable expression conjoined with
where. -
limit: number
Maximum results, or
-1for unlimited. -
offset: number
Number of leading rows to skip.
-
orderBy: Record<string, OrderDirection>
Field-to-direction sort specification. Empty means no ordering.
-
select: readonly string[]
Field projection. Empty means all fields.
-
where: Record<string, unknown>
Filter conditions, matched by equality. Empty means no filter.
A notification dispatched across one or more channels.
-
body: string
Notification body.
-
channels: readonly string[]
Channel names to dispatch on (e.g.
['email', 'sms']). -
metadata: Readonly<Record<string, unknown>>
Channel-specific extras.
-
subject: string
Subject/title, for channels that support one.
-
to: Readonly<Record<string, string>>
Recipient addresses keyed by channel (e.g.
{ email: '…', phone: '…' }).
A successful result carrying a value.
-
success: true
Discriminant:
truefor success. -
value: T
The success value.
A single page of rows returned by IDataSource.findPage, plus the
cursor that continues to the next page (or null when the page is the last).
-
nextCursor: string | null
A cursor to fetch the next page, or
nullwhen the page is the last. -
rows: Record<string, unknown>[]
The rows in this page, already filtered, sorted, paginated and projected.
Per-call overrides for IServiceDiscovery.pick.
-
strategy: LoadBalanceStrategy
Overrides the plugin-configured strategy for this call only.
The clock-and-timer surface createCachedProbe runs on, bound to
a runtime.
-
clearTimer: (handle: TimerHandle) => void
Cancels a timer created by
ProbeTiming.setTimer— the runtime'sclearTimeout. -
hrtime: () => number
Monotonic clock in milliseconds — the runtime's
hrtime. Measures the cache TTL as an interval, never a wall-clock reading. -
setTimer: () => TimerHandlefn: () => void,ms: number
Timer used to bound each probe — the runtime's
setTimeout.
Options accepted when registering a processor.
-
concurrency: number
Jobs processed concurrently by this worker (default 1).
-
onFailed: () => void | Promise<void>job: IJob,error: unknown
Invoked once when a job has exhausted its attempts, immediately before it is dead-lettered — the only programmatic notice that work was permanently abandoned. It does NOT fire on an attempt that will be retried.
Options accepted when registering a provider.
-
scope: ServiceScope
Lifecycle scope (defaults to the container's default scope).
Object attributes accepted alongside the bytes when storing an object.
-
contentType: string
MIME type recorded on the stored object (e.g.
'image/png'). Omitted leaves the backend's own default, which isapplication/octet-streamon every provider that supports the field. -
metadata: Readonly<Record<string, string>>
Arbitrary user metadata recorded alongside the object. Keys and values are passed through to the backend unmodified; backends impose their own limits on size and on which characters a key may contain.
RBAC configuration for role hierarchy and permissions.
-
roles: Readonly<Record<string, RoleDefinition>>
Role definitions keyed by role name.
One broadcast crossing the backplane.
-
binary: boolean
True when
RealtimeFrame.datais base64-encoded binary. -
data: string
The payload, always a string.
-
exceptId: string
The connection excluded from this broadcast, by ID.
-
kind: RealtimeFrameKind
Which consumer the frame belongs to.
-
name: string
The room or channel name the frame addresses.
-
origin: string
The publishing instance's identity.
Options accepted when scheduling a recurring job.
-
cron: string
Cron expression controlling the schedule.
Options accepted when registering a service.
-
multi: boolean
Allow multiple providers for the same token; consumers retrieve them with
IServiceRegistry.getAll. -
override: boolean
Replace an existing registration. Without this flag, registering an already-registered token throws.
Options accepted by IMessageBroker.request.
-
timeoutMs: number
Reply wait budget in milliseconds. When no correlated reply arrives within this window,
requestrejects. Defaults to5000when omitted.
Retry configuration for a scheduled job.
-
backoff: SchedulerBackoff
Backoff strategy. Defaults to
'fixed'. -
delay: number
Base delay in milliseconds for the first retry.
-
limit: number
Maximum number of attempts before giving up (1-based minimum).
Retry policy consumed by the ResiliencePlugin's retry pattern.
-
backoff: BackoffStrategy
Backoff strategy applied to
delay. -
delay: number
Base backoff delay in milliseconds.
-
limit: number
Maximum total attempts (
1= a single attempt, no retry).
Role definition for RBAC configuration.
-
inherits: readonly string[]
Role names this role inherits from (transitive).
-
permissions: readonly string[]
Permissions granted by this role.
Options for a room broadcast.
-
except: IWebSocketConnection
A member to skip — typically the sender, so it does not echo to itself.
Full route definition, used when a route needs middleware or schemas in addition to its handler.
-
handler: RouteHandler
The route handler.
-
middleware: readonly MiddlewareFunction[]
Route-level middleware, executed before the handler.
-
schema: RouteSchema
Validation and OpenAPI schemas.
Route information returned by IRouterApi.listRoutes.
-
definition: RouteDefinition
The route definition including handler, middleware, and schema.
-
method: HttpMethod
HTTP method of the route.
-
owner: string
Name of the plugin that registered this route.
-
path: string
Route path pattern (router-style with
:paramsegments).
Validation/documentation schemas attached to a route. Schema values are
intentionally unknown here — the validation plugin narrows them (Zod
schemas by default) so common stays dependency-free.
-
body: unknown
Request body schema.
-
headers: unknown
Header schema.
-
params: unknown
Path parameter schema.
-
query: unknown
Query parameter schema.
-
response: Readonly<Record<number, unknown>>
Response schemas keyed by status code.
-
security: readonly SecurityRequirement[]
OpenAPI security requirements for this operation, overriding any document-level default. Each entry names a scheme declared in the document's
components.securitySchemesand lists the scopes it needs (empty for non-OAuth2 schemes such as HTTP bearer or API key). -
summary: string
OpenAPI operation summary.
-
tags: readonly string[]
OpenAPI tags.
What a middleware function enforces, for documentation generators.
-
authenticated: boolean
truewhen the middleware requires an authenticated principal;falsewhen it explicitly marks the route public.
What a validating middleware checks, branded onto the middleware function so a documentation generator can describe the route without importing the plugin that produced it.
-
schema: unknown
The schema it validates against, exactly as the caller supplied it.
-
target: ValidationTarget
Which part of the request the middleware validates.
A scheduled job instance handed to the handler.
-
attempts: number
Current attempt number (1-based).
-
data: T
Payload data supplied by the caller.
-
id: string
Unique job identifier.
-
name: string
Human-readable job name.
Options passed when scheduling a job.
-
data: T
Payload data handed to the handler.
-
retry: RetryOptions
Retry configuration. When absent the job runs once.
A plain, serializable representation of a thrown value.
-
cause: SerializedError
The serialized
cause, when the error carries one. -
classifiers: Readonly<Record<string, string | number | boolean>>
Safe scalar driver fields useful for error classification.
-
errors: readonly SerializedError[]
Serialized members of an
AggregateError, when present. -
message: string
The error's
message, or the stringified value for a non-Errorvalue. -
name: string
The error's
name(e.g.'Error','HttpError'), or'Error'for a non-Errorvalue. -
omittedErrorCount: number
Number of direct aggregate members omitted by the serialization budget.
-
stack: string
The error's
stack, when present.
One reachable instance of a service.
-
host: string
Hostname or IP literal. IPv6 literals arrive unbracketed.
-
id: string
Instance identity, unique within the service.
-
metadata: Readonly<Record<string, string>>
Free-form key/value metadata the backend carries.
-
port: number
TCP port.
-
secure: boolean
Whether the instance speaks TLS, deciding the
httpsscheme. -
serviceName: string
The logical service this instance belongs to.
-
tags: readonly string[]
Free-form labels the backend carries (Consul tags, for example).
-
weight: number
Relative selection weight for the
'weighted-random'strategy.
Options accepted when creating a signed URL.
-
expiresIn: number
URL validity in seconds.
An Option holding a value.
-
present: true
Discriminant:
truewhen a value is present. -
value: T
The contained value.
The return type of ISpan.spanContext.
-
spanId: string
16-character lowercase hex span ID.
-
traceFlags: string
2-character lowercase hex trace flags.
-
traceId: string
32-character lowercase hex trace ID.
Options for span creation.
-
attributes: Readonly<Record<string, SpanAttributeValue>>
Initial attributes to set on the span.
-
kind: SpanKind
The span kind (defaults to
'internal'). -
parentContext: TelemetryContext
Optional parent context for span parenting.
The two halves of a Workers env record.
-
bindings: Readonly<Record<string, object>>
Entries whose value is a non-null object — the platform bindings.
-
vars: Readonly<Record<string, string>>
Entries whose value is a string — safe for
IRuntimeServices.env.
One DNS SRV record, normalized across runtimes.
-
host: string
Target hostname. Trailing dots are left as the resolver returned them.
-
port: number
TCP port the service listens on.
-
priority: number
RFC 2782 priority — clients use the lowest-numbered tier first.
-
weight: number
RFC 2782 weight — relative share within one priority tier.
A named broadcast channel within the SSE hub.
-
add(conn: ISseConnection): void
Adds a connection to this channel's membership.
-
publish(msg: SseMessage): void
Publishes a message to every open member of this channel, skipping any connection whose
ISseConnection.isOpenisfalse. -
remove(conn: ISseConnection): void
Removes a connection from this channel's membership.
-
size: number
Number of currently open connections in this channel.
A single SSE event payload.
-
data: JsonValue
Event data. A
stringis written literally (split on\ninto multipledata:lines); any non-string isJSON.stringify-ed.undefinedis forbidden — use{}or omit the message instead. -
event: string
Event type name — sent as
event:field. -
id: string
Unique event identifier — sent as
id:field; enablesLast-Event-IDresume. -
retry: number
Reconnection time in milliseconds — sent as
retry:field.
Options for starting the application server.
-
hostname: string
Bind address (defaults to all interfaces).
-
port: number
TCP port to listen on.
File metadata returned by IFileSystem.stat.
-
isDirectory: boolean
Whether the path is a directory.
-
isFile: boolean
Whether the path is a regular file.
-
mtime: Date
Last modification time, when the runtime provides it.
-
size: number
Size in bytes.
Options accepted when subscribing to a topic.
-
queue: string
Consumer group / queue name for load-balanced delivery.
A snapshot of one task-module pool's state, returned by
IWorkerPool.stats.
-
busy: number
Workers currently executing a task.
-
completed: number
Tasks completed successfully since the pool was created.
-
failed: number
Tasks failed (error, crash, or timeout) since the pool was created.
-
queued: number
Tasks waiting in the pool's queue.
-
taskModule: string
The task-module specifier this pool executes.
-
workers: number
Workers currently alive in the pool.
Opaque handle representing the parent context for span creation.
-
_opaque: TELEMETRY_CONTEXT_OPAQUE
Internal marker — consumers must not inspect this type.
-
spanId: string
16-character lowercase hex parent span ID (W3C format).
-
traceFlags: string
2-character lowercase hex trace flags (W3C format).
-
traceId: string
32-character lowercase hex trace ID (W3C format).
-
tracestate: string
Raw
tracestateheader value, if present.
Optional controls for opening a transaction.
-
isolation: TransactionIsolationLevel
Requested isolation level; omitted preserves the adapter default.
A single validation failure.
-
code: string
Machine-readable failure code, when the validator provides one.
-
message: string
Human-readable description of the failure.
-
path: string
Dot-path of the offending field (e.g.
"address.zip").
Payload of a WebSocket close, normalized across runtimes.
-
code: number
The RFC 6455 close code (e.g.
1000normal,1001going away). -
reason: string
The close reason; an empty string when the peer supplied none.
Details of the upgrade request that opened a connection, handed to
WebSocketHandlers.onOpen.
-
headers: Headers
The upgrade request headers — read these to authenticate the peer.
-
path: string
The URL path component (no query string).
-
protocol: string
The negotiated subprotocol, when one was selected.
-
query: Readonly<Record<string, string>>
Query string parameters.
-
url: string
The full upgrade request URL.
-
user: IPrincipal
The authenticated principal, when one authenticated the upgrade. Populated by threading
ctx.request.userthroughIWebSocketService.routeUpgrade; omitted when the upgrade was not authenticated. Read this inonOpento identify the peer rather than re-deriving it from the headers.
The callbacks an HTTP adapter drives once it has completed a handshake. The WebSocket plugin builds one sink per accepted upgrade and hands it to the adapter inside the accept decision; the adapter binds its native socket events to these methods.
-
onClose(event: WebSocketCloseEvent): void
Called once, when the socket closes for any reason.
-
onError(error: Error): void
Called when the socket reports a transport-level error. A socket that errors is also expected to close, so implementations must tolerate
WebSocketEventSink.onClosearriving afterwards. -
onMessage(data: string | Uint8Array): void
Called for every inbound frame.
-
onOpen(transport: IWebSocketTransport): void
Called once, when the socket is live and writable.
The lifecycle callbacks an application supplies per WebSocket route.
-
onClose(): void | Promise<void>conn: IWebSocketConnection,event: WebSocketCloseEvent
Called once, when the connection closes for any reason.
-
onError(): void | Promise<void>conn: IWebSocketConnection,error: Error
Called on a transport error, and on a rejected promise from any other callback.
-
onMessage(): void | Promise<void>conn: IWebSocketConnection,data: string | Uint8Array
Called for every inbound frame.
-
onOpen(): void | Promise<void>conn: IWebSocketConnection,context: WebSocketConnectionContext
Called once per connection, after the handshake completes.
A named broadcast group of connections — the bidirectional analogue of the SSE plugin's channels.
-
add(conn: IWebSocketConnection): void
Adds a connection to this room.
-
broadcast(): voiddata: string | Uint8Array,options?: RoomBroadcastOptions
Sends a frame to every open member, skipping any closed member and any member named by
options.except. -
broadcastJson<T>(): voidpayload: T,options?: RoomBroadcastOptions
Serializes a value to JSON once and broadcasts it as a text frame.
-
name: string
The room name.
-
remove(conn: IWebSocketConnection): void
Removes a connection from this room.
-
size: number
Number of currently open members.
Per-route configuration supplied alongside the handlers.
-
guards: readonly WebSocketUpgradeGuard[]
Guards evaluated before this route's WebSocket handshake is accepted.
-
heartbeat: boolean
Whether this route participates in the shared heartbeat sweep.
-
protocols: readonly string[]
Subprotocols this route accepts. When non-empty, the first client-requested protocol appearing in this list is echoed back and any request whose
Sec-WebSocket-Protocolmatches none of them is rejected with 400. When omitted, no protocol is negotiated and none is echoed.
The WebSocket upgrade intent the kernel terminal handler brands onto an
IRequest under UPGRADE_INTENT, for the HTTP adapter
to act on once the middleware pipeline has run without short-circuiting.
-
protocol: string | undefined
The negotiated subprotocol to echo back, when one was selected.
-
sink: import("./services/websocket.ts").WebSocketEventSink
The sink the adapter binds its native socket events into.
Serialized shape of an error crossing the thread boundary in a
WorkerTaskReply.
-
message: string
The remote error's
message. -
name: string
The remote error's
name. -
stack: string
The remote error's
stack, when available.
Posted once by the worker side (defineWorkerTask) after its message
handler is wired; the pool dispatches tasks only to ready workers.
-
__hewp: 1
Protocol marker.
-
kind: "ready"
Discriminant.
Options for one IWorkerPool.run call.
-
timeoutMs: number
Per-call task timeout in milliseconds, overriding the pool's configured timeout.
0disables the timeout for this call.
A task outcome posted by the worker back to the pool.
-
__hewp: 1
Protocol marker.
-
error: WorkerErrorShape
The serialized error when
okisfalse. -
id: number
Correlation id echoed from the request.
-
kind: "reply"
Discriminant.
-
ok: boolean
Whether the task handler returned normally.
-
result: unknown
The handler's return value when
okistrue.
A task dispatch posted by the pool to a worker.
-
__hewp: 1
Protocol marker.
-
id: number
Correlation id, unique per pool.
-
input: unknown
Structured-clonable task input.
-
kind: "task"
Discriminant.
Options selecting which resilience patterns wrap a protected call.
-
bulkhead: boolean | BulkheadPolicy
Bulkhead layer:
trueuses the default, a policy overrides. -
circuitBreaker: boolean | CircuitBreakerPolicy
Circuit breaker layer:
trueuses the default, a policy overrides. -
retry: boolean | RetryPolicy
Retry layer:
trueuses the default, a policy overrides. -
timeout: number
Per-attempt timeout in milliseconds; absent disables the timeout layer.
Backoff strategy applied to a RetryPolicy's base delay.
A capability token: a lowercase kebab-case string that identifies a capability, not a concrete type.
| { readonly channel: string; readonly ok: false; readonly error: SerializedError; }
The settled outcome of dispatching a notification on a single channel.
Circuit breaker states.
A CLI command implementation.
A view component: a pure function from a props bag to something the engine
can render to a string — a JSX node (@hono/hono/jsx), an
HtmlEscapedString (the html tagged template), or a plain string
(a by-name template adapted per §3.6 of the M92 plan).
A constructable class reference.
A scalar value retained by a portable keyset cursor.
Handler invoked when a custom decorator is applied; receives the metadata the decorator captured.
A primary key value: a scalar string, a scalar number, or a composite
key expressed as a readonly record of named columns to values.
Handles one event type.
| { readonly type: "comparison"; readonly field: string | readonly string[]; readonly operator: "contains"; readonly value: string; }
| { readonly type: "comparison"; readonly field: string | readonly string[]; readonly operator: "gt" | "gte" | "lt" | "lte"; readonly value: string | number | Date; }
| { readonly type: "comparison"; readonly field: string | readonly string[]; readonly operator: "in"; readonly value: readonly unknown[]; }
A comparison of one entity field against a scalar value or value list.
| { readonly type: "and" | "or"; readonly filters: readonly FilterExpression[]; }
A portable filter tree evaluated by every repository backend.
Operators supported by a portable repository filter comparison.
The two request encodings a form body can carry.
One form value: a plain field string, or a FormFile.
| { kind: "single"; status: number; result: GraphqlExecutionResult; }
| { kind: "stream"; status: number; stream: AsyncIterable<GraphqlExecutionResult>; }
Discriminated outcome of a subscription operation.
The serving status returned by the health bridge. These values map onto the gRPC v1 Health response enum.
The hardened callable returned by IResilienceService.wrap.
Function form of a health indicator.
Health state reported by a health indicator.
| "HEAD"
| "POST"
| "PUT"
| "PATCH"
| "DELETE"
| "OPTIONS"
HTTP request methods supported by the router.
The ingress path a unit of non-HTTP work arrived on.
Processes jobs of one name.
| number
| boolean
| null
| readonly JsonValue[]
| { readonly [key: string]: JsonValue | undefined; }
A value JSON.stringify can serialize.
| "init"
| "bootstrap"
| "active"
| "shutdown"
| "close"
Application lifecycle phases, in execution order.
How IServiceDiscovery.pick chooses among healthy instances.
Log severity levels, ordered from most to least severe.
Structured metadata attached to a log entry.
Handles messages delivered on a subscription.
Metric instrument kinds supported by the metrics capability.
A middleware function: pre-process, call next(), post-process. May
short-circuit by returning a response without calling next().
Continues the middleware pipeline. Not calling it short-circuits the pipeline (the caller must have produced a response).
Sort direction for a single field.
One exclusion entry: an exact path, or a pattern tested against the path.
Union of the well-known priority values in PLUGIN_PRIORITY.
Any provider form accepted by IContainer.register.
Receives frames published by other instances.
Which kind of broadcast group a RealtimeFrame addresses.
A factory that constructs a registry entry from the service registry.
Responder for a request topic. Its resolved value is sent back to the caller as the reply, correlated to the originating request.
A call protected by the resilience patterns.
| { readonly streaming: true; readonly status: number; readonly headers: Headers; readonly body: ReadableStream<Uint8Array>; readonly responseInit?: ResponseSnapshotInit | undefined; }
Discriminated union representing the possible shapes of an IResponse snapshot.
When streaming is false, body is a buffered Uint8Array | string | null.
When streaming is true, body is a live ReadableStream<Uint8Array>.
Native-response initialization data attached to a snapshot by the kernel
when its headers have not needed a mutable Headers instance.
-
headers: HeadersInit
Header input accepted directly by the web-standard
Responseconstructor.
A route handler: receives the request context and returns a response via the context's response builder.
A fetch handler that attempts to handle a gRPC/Connect request.
Returns a Response if the request was handled as RPC,
otherwise returns null so the adapter falls through to normal
Hono handling.
JavaScript runtimes the framework can execute on.
A process-termination signal an application can shut down gracefully on.
Backoff strategy for retry delays.
Handler invoked when a scheduled job fires.
A single OpenAPI security requirement: a map of security-scheme name to the scopes that scheme must grant. Scopes are meaningful only for OAuth2 and OpenID Connect schemes; every other scheme type takes an empty array.
Opaque handle for a running HTTP server, created and consumed only by the runtime's HTTP adapter.
A factory invoked lazily on the first lookup of a token registered with
IServiceRegistry.registerFactory.
How a call to an instance went, as reported by the caller.
Service lifecycle scopes.
Arbitrary serializable session payload.
A read-only projection of a session: its identifier and payload, with no mutation surface.
-
data: Readonly<SessionData>
The session payload, exactly as stored.
-
id: string
The session identifier.
| number
| boolean
| ReadonlyArray<string | number | boolean>
Attribute value — a span attribute can be a primitive or an array of primitives.
The kind of span. Maps to OTel SpanKind at the implementation boundary.
Span status — whether the span completed successfully or not.
Union of all standard capability token values.
Opaque handle returned by runtime timer methods. Its concrete shape is
runtime-specific (a number on Deno, an object on Node); consumers only
ever pass it back to clearTimeout/clearInterval.
| "read-committed"
| "repeatable-read"
| "serializable"
Portable transaction isolation levels.
Removes a subscription when called.
The request part a validation middleware targets.
The result of a route-scoped WebSocket upgrade guard.
Lifecycle state of a WebSocket, normalized across runtimes to names rather than the numeric codes the web API uses.
| { readonly accept: false; readonly status: number; }
What an HTTP adapter should do with an inbound upgrade request, as decided
by the WebSocketUpgradeRouter.
A route-scoped predicate evaluated before a WebSocket handshake is accepted.
Consulted by an HTTP adapter for every inbound WebSocket upgrade request.
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
The ctx.state key under which http-security-plugin's
ipSecurityMiddleware publishes the resolved client IP, and from which
auth-plugin's rateLimitMiddleware reads it back.
The brand under which an errorHandler middleware function carries its
resolved IErrorResponder.
The ctx.state key under which an application's resolved error responder is
published.
Key under which an Error carries its HttpStatusHint.
Well-known plugin registration priorities. Lower numbers register first.
-
HIGH: number
Logging, configuration — capabilities most plugins consume.
-
HIGHEST: number
Runtime and other must-run-first infrastructure.
-
LOW: number
Plugins that want most capabilities available before they register.
-
LOWEST: number
Observers that must register after everything else.
-
NORMAL: number
Default band for ordinary capability plugins.
-
OPENAPI: number
OpenAPI plugin — generates spec after routes are registered.
Key under which a MiddlewareFunction carries its
RouteSecurityMetadata.
Opaque marker symbol for TelemetryContext.
The W3C header carrying a trace parent. @since 0.2.0
The W3C header carrying vendor trace state. @since 0.2.0
Key under which the kernel terminal handler brands an IRequest
with a WebSocket upgrade intent.
Key under which a MiddlewareFunction carries its
RouteValidationMetadata.
Usage
import * as Shared_types__interfaces__and_capability_tokens_for_the_Setu_TS_framework__This_package_has_zero_dependencies_and_no_runtime_behavior_beyond_constants_and_pure_type_utilities___Every_export_here_is_public_API_and_documented_in_PUBLIC_API_md__AI_GUIDELINES__10__ from "common/src/index.ts";