import type { RenderOptions, RenderToResponseOptions } from '../ssr/index'; import type { WorkerRpcHandlers, WorkerTaskHandler } from '../concurrency/index'; import type { BindingContext } from '../view/index'; /** * Repeated query parameters are represented as arrays. */ export interface ServerQuery { [key: string]: string | string[] | undefined; } /** * Lightweight request input accepted by `handle()`. */ export interface ServerRequestInit { /** * Request URL or path. * * Relative paths are resolved against `CreateServerOptions.baseUrl`. */ url: string | URL; /** * HTTP method. * @default 'GET' */ method?: string; /** * Request headers. */ headers?: HeadersInit; /** * Optional request body. */ body?: BodyInit | null; } /** * Shared response options used by server helpers. */ export interface ServerResponseInit extends ResponseInit { headers?: HeadersInit; } /** * HTML response options. */ export interface ServerHtmlResponseInit extends ServerResponseInit { /** * When `true`, the HTML string is assumed to be already safe and is returned * without additional sanitization. * @default false */ trusted?: boolean; } /** Attributes applied when serializing a `Set-Cookie` header. */ export interface ServerCookieOptions { domain?: string; httpOnly?: boolean; /** Lifetime in seconds; omit for a session cookie. */ maxAge?: number; path?: string; sameSite?: 'lax' | 'none' | 'strict'; secure?: boolean; } /** A single Server-Sent Events frame written to the response stream. */ export interface ServerSseEvent { data: string; event?: string; id?: string; /** Reconnection delay (ms) advertised to the client. */ retry?: number; } /** Options for opening a Server-Sent Events stream. */ export interface ServerSseOptions extends ServerResponseInit { /** Default reconnection delay (ms) sent once when the stream opens. */ retry?: number; } /** Maximum accepted request-body size, in bytes, per parsed content type. */ export interface ServerLimits { form?: number; json?: number; multipart?: number; text?: number; /** * Cap for any other (unrecognized) content type read as a raw `ArrayBuffer` * via `ctx.body()`. Unset means unbounded, so set this when accepting * arbitrary binary uploads to avoid buffering an unbounded body in memory. */ raw?: number; } /** Options for {@link ServerApp.listen}. */ export interface ServerListenOptions { hostname?: string; port?: number; /** Target runtime; `auto` detects Bun, Deno, or Node at call time. */ runtime?: 'auto' | 'bun' | 'deno' | 'node'; /** Abort signal that, once aborted, stops the server. */ signal?: AbortSignal; } /** Handle to a running server returned by {@link ServerApp.listen}. */ export interface ServerListenHandle { /** Every URL the server is listening on. */ addresses: string[]; /** Stop the server, resolving once it has fully shut down. */ close(): Promise; /** Alias of {@link ServerListenHandle.close}. */ stop(): Promise; /** Primary listen URL. */ url: string; } /** * SSR response options. */ export interface ServerRenderResponseOptions extends RenderOptions { /** * HTTP status to use for the response. * @default 200 */ status?: number; /** * Additional response headers. */ headers?: HeadersInit; } /** * Binary/text payloads accepted by server-side WebSocket peers and sessions. * * Use this for raw frames sent through `socket.send(...)`. */ export type ServerWebSocketData = string | Blob | ArrayBufferLike | ArrayBufferView; /** * Minimal runtime WebSocket peer shape consumed by server-side WebSocket sessions. */ export interface ServerWebSocketPeer { /** * Negotiated sub-protocol, when available. */ protocol?: string; /** * Current readyState, when the runtime exposes it. */ readyState?: number; /** * Remote URL, when the runtime exposes it. */ url?: string; /** * Send a raw payload to the connected peer. */ send(data: ServerWebSocketData): void; /** * Close the connection. */ close(code?: number, reason?: string): void; } /** * Wrapped WebSocket connection exposed to route handlers. */ export interface ServerWebSocketConnection extends ServerWebSocketPeer { /** * Serialize a value with `JSON.stringify()` and send it to the peer. */ sendJson(data: unknown): void; } /** * Request-scoped session surface attached to `ctx.session` by the * {@link ServerMiddleware} returned from `session()`. * * Session payload is read and written as plain properties — `ctx.session.userId` * — while lifecycle operations live behind `$`-prefixed members so they never * collide with arbitrary data keys. * * @example * ```ts * ctx.session.userId = user.id; // marks the session dirty and persists it * if (ctx.session.$isNew) ctx.session.role = 'guest'; * ctx.session.$destroy(); // clears data and expires the cookie * ``` */ export interface ServerSession { /** Current session id, or `null` until the session is first written to. */ readonly $id: string | null; /** `true` when no existing session was loaded from the incoming cookie. */ readonly $isNew: boolean; /** Shallow snapshot of the current session payload. */ readonly $data: Readonly>; /** * Rotate the session id while keeping the current payload. The previous id is * removed from the store on the next response (mitigates session fixation). */ $regenerate(): void; /** Clear the payload and expire the session cookie on the next response. */ $destroy(): void; /** Remove every key from the payload without destroying the session. */ $clear(): void; /** Arbitrary request-scoped session payload. */ [key: string]: unknown; } /** * Request/response context passed through the server pipeline. */ export interface ServerContext { /** * Normalized `Request` instance. */ request: Request; /** * Parsed URL for the current request. */ url: URL; /** * Uppercase HTTP method. */ method: string; /** * Pathname without query string. */ path: string; /** * Route params captured from `:param` path segments. */ params: Record; /** * Parsed query object. Repeated keys become arrays. */ query: ServerQuery; /** Parsed request cookies. */ cookies: Record; /** * Per-request mutable state bag for middleware communication. */ state: Record; /** * Request-scoped session, present only after the `session()` middleware runs. * * @see {@link ServerSession} */ session?: ServerSession; /** Parse the request body based on the request content-type. */ body(): Promise; /** * Create a raw `Response`. * * @example * ```ts * return ctx.response('Created', { status: 201 }); * ``` */ response(body?: BodyInit | null, init?: ServerResponseInit): Response; /** * Create a plain-text response. * * @example * ```ts * return ctx.text('ok'); * ``` */ text(body: string, init?: ServerResponseInit): Response; /** * Create a sanitized HTML response by default. * * @example * ```ts * return ctx.html('

Hello

'); * ``` */ html(body: string, init?: ServerHtmlResponseInit): Response; /** * Create a JSON response. * * @example * ```ts * return ctx.json({ ok: true }); * ``` */ json(data: unknown, init?: ServerResponseInit): Response; /** Create a response from a web ReadableStream. */ stream(body: ReadableStream, init?: ServerResponseInit): Response; /** Create a Server-Sent Events response. */ sse(source: AsyncIterable | Iterable, init?: ServerSseOptions): Response; /** Select the first accepted content type from the provided list. */ accepts(types: string[]): string | null; /** Append a Set-Cookie header to the current response context. */ setCookie(name: string, value: string, options?: ServerCookieOptions): void; /** * Create a redirect response. * * @example * ```ts * return ctx.redirect('/login', 302); * ``` */ redirect(location: string | URL, status?: number): Response; /** * Render a bQuery SSR template into an HTML response. * * @example * ```ts * return ctx.render('

', { title: 'Dashboard' }); * ``` */ render(template: string, data: BindingContext, options?: ServerRenderResponseOptions): Response; /** Render a template to a streaming response. */ renderStream(template: string, data: BindingContext, options?: ServerRenderResponseOptions): Response; /** Render a template via the SSR response helper. */ renderResponse(template: string, data: BindingContext, options?: RenderToResponseOptions): Promise; /** Run a one-off worker task from a handler. */ runTask(handler: WorkerTaskHandler, input: TInput, options?: import('../concurrency/index').RunTaskOptions): Promise; /** Run one named worker RPC method from a handler. */ callWorker(handlers: TRoutes, method: TMethod, input: Parameters[0], options?: import('../concurrency/index').CallWorkerMethodOptions): Promise>>; /** * `true` when the incoming request is a WebSocket upgrade handshake. */ isWebSocketRequest: boolean; } /** * Final request handler. */ export interface ServerHandler { (context: ServerContext): Response | Promise; } /** * WebSocket route lifecycle callbacks. */ export interface ServerWebSocketHandlerSet { /** * Requested sub-protocols for the handshake. */ protocols?: string | string[]; /** * Additional handshake headers used by compatible runtimes. */ headers?: HeadersInit; /** * Deserialize incoming WebSocket messages. * * Defaults to JSON.parse for string payloads with a raw-string fallback. */ deserialize?: (event: MessageEvent) => TReceive; /** * Called after the runtime accepts the upgrade. */ onOpen?: (socket: ServerWebSocketConnection, context: ServerContext) => void | Promise; /** * Called for each incoming message after deserialization. */ onMessage?: (data: TReceive, socket: ServerWebSocketConnection, context: ServerContext, event: MessageEvent) => void | Promise; /** * Called when the connection closes. */ onClose?: (event: CloseEvent, socket: ServerWebSocketConnection, context: ServerContext) => void | Promise; /** * Called when the runtime reports a socket error. */ onError?: (event: Event, socket: ServerWebSocketConnection, context: ServerContext) => void | Promise; } /** * WebSocket route definition or per-request factory. */ export type ServerWebSocketRouteHandler = ServerWebSocketHandlerSet | ((context: ServerContext) => ServerWebSocketHandlerSet | Promise>); /** * Runtime-agnostic WebSocket session returned by `handleWebSocket()`. */ export interface ServerWebSocketSession { /** * Request context captured during route matching and middleware execution. */ context: ServerContext; /** * Normalized requested sub-protocols. */ protocols: string[]; /** * Additional handshake headers requested by the route. */ headers?: HeadersInit; /** * Notify the session that the runtime accepted the connection. */ open(socket: ServerWebSocketPeer): Promise; /** * Deliver an incoming message event to the session. */ message(socket: ServerWebSocketPeer, event: MessageEvent): Promise; /** * Notify the session about a close event. */ close(socket: ServerWebSocketPeer, event: CloseEvent): Promise; /** * Notify the session about a socket error. */ error(socket: ServerWebSocketPeer, event: Event): Promise; } /** * Result type used by middleware and WebSocket handling. */ export type ServerResult = Response | ServerWebSocketSession | null; /** * Middleware continuation callback. */ export interface ServerNext { (): Promise; } /** * Express-inspired middleware for request pipelines. */ export interface ServerMiddleware { (context: ServerContext, next: ServerNext): Response | Promise; } /** * WebSocket middleware continuation callback. */ export interface ServerWebSocketNext { (): Promise; } /** * Middleware used by WebSocket routes. */ export interface ServerWebSocketMiddleware { (context: ServerContext, next: ServerWebSocketNext): ServerResult | Promise; } /** * Route definition used by `add()`. */ export interface ServerRoute { /** * Route path. Supports static segments, `:params`, and terminal `*`. */ path: string; /** * One or many HTTP methods. Omit for "all methods". */ method?: string | string[]; /** * Optional route-scoped middleware. */ middlewares?: ServerMiddleware[]; /** * Final route handler. */ handler: ServerHandler; } /** * Configures a server instance. */ export interface CreateServerOptions { /** * Base URL used to resolve relative request paths. * @default 'http://localhost' */ baseUrl?: string; /** * Global middleware applied to every request. */ middlewares?: ServerMiddleware[]; /** Body parsing limits by content type. */ limits?: ServerLimits; /** * Custom 404 handler. */ notFound?: ServerHandler; /** * Custom error handler. */ onError?: (error: unknown, context: ServerContext) => Response | Promise; } /** * Express-inspired app-like server handle. */ export interface ServerApp { /** * Register global middleware. */ use(middleware: ServerMiddleware): ServerApp; /** * Add a fully specified route. */ add(route: ServerRoute): ServerApp; /** * Register a GET route. */ get(path: string, handler: ServerHandler, middlewares?: ServerMiddleware[]): ServerApp; /** * Register a POST route. */ post(path: string, handler: ServerHandler, middlewares?: ServerMiddleware[]): ServerApp; /** * Register a PUT route. */ put(path: string, handler: ServerHandler, middlewares?: ServerMiddleware[]): ServerApp; /** * Register a PATCH route. */ patch(path: string, handler: ServerHandler, middlewares?: ServerMiddleware[]): ServerApp; /** * Register a DELETE route. */ delete(path: string, handler: ServerHandler, middlewares?: ServerMiddleware[]): ServerApp; /** * Register a route that matches any method. */ all(path: string, handler: ServerHandler, middlewares?: ServerMiddleware[]): ServerApp; /** * Register a WebSocket route. */ ws(path: string, handler: ServerWebSocketRouteHandler, middlewares?: ServerWebSocketMiddleware[]): ServerApp; /** * Handle a normalized request. */ handle(input: Request | string | URL | ServerRequestInit): Promise; /** Start a minimal runtime-native HTTP listener for this app. */ listen(options?: ServerListenOptions): Promise; /** * Resolve a WebSocket upgrade request into a runtime-agnostic session. * * Returns `null` when the request is not a WebSocket handshake or no matching * WebSocket route exists. Middleware may also short-circuit with a `Response`. */ handleWebSocket(input: Request | string | URL | ServerRequestInit): Promise; } //# sourceMappingURL=types.d.ts.map