Askr documentation
Generated API snapshot

@askrjs/server

Exports from the declarations published in @askrjs/server. Signatures reflect the published artifact.

Exports

This entrypoint publishes 84 exports. Use the anchored symbol rows for direct links. Type-only exports are labeled separately from runtime values.

acceptedtype

accepted: (value?: JsonValue, init?: ResponseInit) => Response

Builds a `202 Accepted` response; JSON-serializes `value` if given, otherwise an empty body.

acceptstype

accepts: (value: string, expected: string) => boolean

AccessDeniedHandlertype

AccessDeniedHandler: (decision: Extract<AuthDecision, {
  allowed: false;
}>, context: ServerContext) => Response | Promise<Response>

Handler invoked to produce a response when an auth decision denies access.

ApiRoutetype

ApiRoute: any

A single registered route: a path/method pattern paired with a handler (or WebSocket upgrade handler).

path
path: string;
method
method?: string | readonly string[];
handler
handler: Handler<RouteParams>;
upgrade
upgrade?: WebSocketHandler<RouteParams>;

ApiRouteOptionstype

ApiRouteOptions: any

Per-route configuration shared by {@link ApiRoute}.

auth
auth?: AuthRequirement;
middleware
middleware?: readonly Middleware<RouteParams>[];
maxRequestBytes
maxRequestBytes?: number;

AuthCredentialstype

AuthCredentials: any

Email/password credentials submitted to the register or authenticate endpoints.

email
email: string;
password
password: string;

AuthRouteErrortype

AuthRouteError: typeof AuthRouteError

Error thrown from `register`/`authenticate`/etc. callbacks to short-circuit an auth route with a specific status.

status
readonly status: 401 | 409 | 429;

AuthRouteOptionstype

AuthRouteOptions: any

Configuration for {@link registerAuthRoutes}.

issuer
issuer: TokenIssuer<P>;
cookie
cookie: CookieOptions & { name: string; };
principalSchema
principalSchema: Schema;
register
register(context: ServerContext, credentials: AuthCredentials): P | Promise<P>;
authenticate
authenticate(context: ServerContext, credentials: AuthCredentials): P | null | Promise<P | null>;
allowAttempt
allowAttempt(context: ServerContext, operation: "register" | "authenticate", normalizedEmail: string): boolean | Promise<boolean>;
revoke
revoke?(context: ServerContext): void | Promise<void>;
redirect
redirect?: (context: ServerContext, operation: "register" | "authenticate", principal: P) => string | undefined;

badtype

bad: (detail?: string, init?: ResponseInit) => Response

Alias for {@link badRequest}.

badRequesttype

badRequest: (detail?: string, init?: ResponseInit) => Response

Builds a `400 Bad Request` Problem Details response.

bindtype

bind: <T extends object = Record<string, unknown>>(context: BindContext) => Promise<T>

Merges a request's body, query string, and path parameters into a single object, in that precedence order (path parameters win, then query string, then body). Supports JSON, URL-encoded, and multipart/form-data bodies; unrecognized content types yield an empty body.

BindContexttype

BindContext: any

Minimal request context required by {@link bind} to gather body, query, and path values.

request
request: Request;
params
params: Params;
url
url: URL;
query
query: URLSearchParams;

BindingErrortype

BindingError: typeof BindingError

Error thrown when request data cannot be bound, e.g. an unreadable or malformed body.

field
readonly field?: string | undefined;
status
readonly status = 400;

challengetype

challenge: (options?: ChallengeOptions) => Response

Builds a `401`/`407` Problem Details response with a `WWW-Authenticate` (or `Proxy-Authenticate` for `407`) challenge header.

ChallengeOptionstype

ChallengeOptions: any

Options for building a `WWW-Authenticate` challenge response via {@link ServerContext.challenge}.

scheme
scheme?: string;
realm
realm?: string;
status
status?: 401 | 407;
detail
detail?: string;
init
init?: ResponseInit;

conflicttype

conflict: (detail?: string, init?: ResponseInit) => Response

Builds a `409 Conflict` Problem Details response.

contentTypetype

contentType: (value: string | null) => string | undefined

createCspNoncetype

createCspNonce: () => CspNonceProvider

Creates a {@link CspNonceProvider} that lazily generates a cryptographically random, URL-safe base64 nonce per {@link ServerContext} and caches it for the lifetime of that context, so repeated calls within the same request return the same value.

createdtype

created: (value?: JsonValue, init?: ResponseInit) => Response

Builds a `201 Created` response; JSON-serializes `value` if given, otherwise an empty body.

createEventStreamtype

createEventStream: (options?: EventStreamOptions) => EventStream

Creates a Server-Sent Events stream backed by a `text/event-stream` `Response`, with bounded backpressure-aware writes, optional heartbeat comments, and automatic closing when `options.signal` aborts or `close()` is called.

createRoutertype

createRouter: () => Router

Creates an empty, mutable {@link Router} with chainable HTTP-method route builders (`get`, `post`, `put`, `patch`, `delete`, `options`, `head`, `trace`, `connect`, `ws`) and a `use` method for registering middleware.

createServerApptype

createServerApp: { (router: Router): ServerApp; (options?: ServerAppOptions): ServerApp; }

Creates a transport-neutral server application that dispatches Web `Request`s to a router's routes and middleware, returning Web `Response`s. Accepts either a bare {@link Router} or a full {@link ServerAppOptions} object (which may itself reference a router). Builds a path matcher from the combined routes, validates request-size limits, and wraps dispatch with auth resolution, telemetry, and error handling (payload-too-large, malformed path parameters, binding errors, and a fallback `onError`). Creates a transport-neutral server application. See the {@link Router} overload for details.

const app = createServerApp(router);
export default { fetch: app.fetch };

CspNonceProvidertype

CspNonceProvider: (context: ServerContext) => string

A function that returns a CSP nonce for a given request context, stable across calls for the same context.

DEFAULT_MAX_REQUEST_BYTEStype

DEFAULT_MAX_REQUEST_BYTES: 1048576

Default maximum request body size, in bytes (1 MiB), used when no limit is configured.

defineRoutestype

defineRoutes: (definition: (route: RouteBuilder) => void) => ApiRoute[]

Builds a flat list of {@link ApiRoute}s by invoking `definition` with a {@link RouteBuilder}. Useful for defining a set of routes without a full {@link Router} (e.g. to compose into one).

errortype

error: (status?: number, detail?: string, init?: ResponseInit) => Response

Builds a Problem Details error response with a configurable status (default `500`).

EventStreamtype

EventStream: any

A live Server-Sent Events stream, backed by a streaming `Response`.

response
readonly response: Response;
closed
readonly closed: Promise<void>;
send
Queues an event in order. Await or otherwise handle the returned promise before producing without bound. Rejects with `QuotaExceededError` when the pending-write limit is full.
comment
Queues an SSE comment in order. Rejects with `QuotaExceededError` when the pending-write limit is full.
close
close(): Promise<void>;

EventStreamOptionstype

EventStreamOptions: any

Options for {@link createEventStream}.

signal
Aborting this signal closes the stream.
heartbeatInterval
If set, sends a `heartbeat` comment on this interval (in ms) to keep the connection alive.
highWaterMark
Backpressure threshold for the underlying `ReadableStream` and maximum number of unresolved `send()`/`comment()` calls admitted at once. Defaults to 16.
headers
headers?: HeadersInit;

forbiddentype

forbidden: (detail?: string, init?: ResponseInit) => Response

Builds a `403 Forbidden` Problem Details response.

formatServerSentEventtype

formatServerSentEvent: (event: ServerSentEvent) => string

Serializes a {@link ServerSentEvent} to the `text/event-stream` wire format, escaping multi-line data/comment fields and validating that `event`/`id` contain no line breaks.

Handlertype

Handler: {
  bivarianceHack(context: ServerContext<RouteParams>): Response | Promise<Response>;
}["bivarianceHack"]

A route handler function that produces a response for a given {@link ServerContext}.

internalServerErrortype

internalServerError: (detail?: string, init?: ResponseInit) => Response

Builds a `500 Internal Server Error` Problem Details response.

jsontype

json: (value: JsonValue, init?: ResponseInit) => Response

Builds a `200 OK`-shaped JSON response, serializing `value` and setting the JSON content type.

JsonValuetype

JsonValue: unknown

A value that can be serialized as JSON.

methodNotAllowedtype

methodNotAllowed: (allow?: string | readonly string[], init?: ResponseInit) => Response

Builds a `405 Method Not Allowed` Problem Details response, setting the `Allow` header if given.

Middlewaretype

Middleware: {
  bivarianceHack(context: ServerContext<RouteParams>, next: Next): Response | Promise<Response>;
}["bivarianceHack"]

A middleware function that may short-circuit or delegate to `next` to produce a response.

Nexttype

Next: () => Response | Promise<Response>

Continuation function passed to a {@link Middleware}, invoking the next handler in the chain.

noContenttype

noContent: (init?: ResponseInit) => Response

Builds a `204 No Content` response with an empty body.

notFoundtype

notFound: (detail?: string, init?: ResponseInit) => Response

Builds a `404 Not Found` Problem Details response.

notImplementedtype

notImplemented: (detail?: string, init?: ResponseInit) => Response

Builds a `501 Not Implemented` Problem Details response.

oktype

ok: (value?: JsonValue, init?: ResponseInit) => Response

Builds a `200 OK` response; JSON-serializes `value` if given, otherwise an empty body.

Paramstype

Params: Record<string, string>

A map of route path parameter names to their string values.

PathParamstype

PathParams: string extends Path ? Params : { [Name in PathParameterNames<Path>]: string; }

Infers a {@link Params}-shaped object type from a route path pattern, extracting the names of `{param}` and `{*param}` segments as required string keys.

PayloadTooLargeErrortype

PayloadTooLargeError: typeof PayloadTooLargeError

Error thrown when a request body exceeds the configured maximum size.

status
readonly status = 413;

ProbeHandlertype

ProbeHandler: (context: ServerContext) => ProbeResult | Promise<ProbeResult>

A health-check handler used for liveness/readiness/startup probes.

ProbeOptionstype

ProbeOptions: any

Optional handlers for the built-in `livez`/`readyz`/`startupz`/`targetz` health probe routes.

livez
livez?: ProbeHandler;
readyz
readyz?: ProbeHandler;
startupz
startupz?: ProbeHandler;
targetz
targetz?: ProbeHandler;

ProbeResulttype

ProbeResult: boolean | Response | void

Result of a health probe: `true`/`false` for pass/fail, a `Response` to return as-is, or `void` for pass.

problemtype

problem: (status: number, detail?: string, options?: ProblemOptions & { init?: ResponseInit; }) => Response

Builds an RFC 9457 `application/problem+json` response, defaulting `type` to `about:blank` and `title` to a standard reason phrase for the given `status` (falling back to "HTTP Error").

Problemtype

Problem: any

An RFC 9457 Problem Details object, as produced by {@link ServerContext.problem}.

type
type: string;
title
title: string;
status
status: number;
detail
detail?: string;
instance
instance?: string;

ProblemOptionstype

ProblemOptions: any

Optional fields used to customize a {@link Problem} response.

type
type?: string;
title
title?: string;
instance
instance?: string;
extensions
extensions?: Record<string, unknown>;

readRequestBytestype

readRequestBytes: (request: Request, maximum?: number) => Promise<Uint8Array>

Reads a request body into memory as raw bytes, enforcing a maximum size. The result is cached per-request so subsequent reads (e.g. for JSON, text, or form data) reuse the same buffered bytes instead of re-reading the stream.

readRequestFormDatatype

readRequestFormData: (request: Request, maximum?: number) => Promise<FormData>

Reads a request body and parses it as `multipart/form-data`, enforcing a maximum size.

readRequestTexttype

readRequestText: (request: Request, maximum?: number) => Promise<string>

Reads and decodes a request body as UTF-8 text, enforcing a maximum size.

redirecttype

redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response

Builds a redirect response with an empty body and a `Location` header. Defaults to `302 Found`.

registerAuthRoutestype

registerAuthRoutes: <Dependencies, P extends Principal>(api: Pick<ApiDefinition<Dependencies>, "group">, options: AuthRouteOptions<P>) => void

Registers a standard set of authentication routes (`POST /auth/v1/accounts`, `GET/POST /auth/v1/session`, `DELETE /auth/v1/session`) on an OpenAPI-style API/group, handling registration, login, session lookup, and logout with CSRF protection via a same-origin `Origin` header check, per-attempt rate limiting, and cookie-based token storage.

RequestStatetype

RequestState: Record<string, unknown>

Arbitrary per-request state bag attached to a {@link ServerContext}.

RouteBuildertype

RouteBuilder: any

Chainable, per-HTTP-method route registration methods, one per method plus `ws` for WebSockets.

route
route<const Path extends string>(method: string | readonly string[], path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
get
get<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
post
post<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
put
put<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
patch
patch<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
delete
delete<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
options
options<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
head
head<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
trace
trace<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
connect
connect<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;
ws
ws<const Path extends string>(path: Path, handler: WebSocketHandler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

Routertype

Router: any

A mutable collection of routes and middleware, built with chainable per-method registration methods (each returning the router itself for chaining) and a `use` method for middleware.

routes
readonly routes: readonly ApiRoute[];
middleware
readonly middleware: readonly Middleware[];
use
use(...middleware: Middleware[]): Router;
route
route<const Path extends string>(method: string | readonly string[], path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
get
get<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
post
post<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
put
put<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
patch
patch<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
delete
delete<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
options
options<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
head
head<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
trace
trace<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
connect
connect<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;
ws
ws<const Path extends string>(path: Path, handler: WebSocketHandler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

safeRedirecttype

safeRedirect: (fallback: string, options?: SafeRedirectOptions) => (value: unknown) => string

Creates a validator that resolves an untrusted redirect target to a safe, same-origin, relative path — or to `fallback` if the value is unsafe (absolute, protocol-relative, contains a scheme, control characters, `..` traversal, backslashes, or an unwanted hash).

SafeRedirectOptionstype

SafeRedirectOptions: any

Options for {@link safeRedirect}.

allowHash
Allow redirect targets that include a URL fragment (`#...`). Defaults to disallowed.

ServerApptype

ServerApp: any

A configured server application, as returned by {@link createServerApp }.

fetch
fetch(request: Request, dispatchOptions?: ServerDispatchOptions): Promise<Response>;

ServerAppOptionstype

ServerAppOptions: any

Options accepted by {@link createServerApp } to configure a server application.

router
router?: Router;
routes
routes?: readonly ApiRoute[];
middleware
middleware?: readonly Middleware[];
onError
onError?: (error: unknown, context: ServerContext) => Response | Promise<Response>;
onAccessDenied
onAccessDenied?: AccessDeniedHandler;
auth
auth?: AuthResolver;
fallback
fallback?: Handler;
websocket
websocket?: WebSocketAdapter;
probes
probes?: ProbeOptions;
telemetry
telemetry?: ServerTelemetry;
maxRequestBytes
maxRequestBytes?: number;

ServerContexttype

ServerContext: any

The per-request context passed to handlers and middleware, bundling the incoming request, parsed URL/params/query, auth state, and a family of response-building helper methods (`json`, `ok`, `notFound`, `problem`, `setCookie`, `upgrade`, etc.).

request
request: Request;
url
url: URL;
params
params: RouteParams;
headers
headers: Headers;
query
query: URLSearchParams;
state
state: RequestState;
auth
auth: AuthContext;
signal
signal: AbortSignal;
sse
sse(options?: Omit<EventStreamOptions, "signal">): EventStream;
telemetry
telemetry?: ServerTelemetry;
bind
bind<T extends object = Record<string, unknown>>(): Promise<T>;
json
json(value: JsonValue, init?: ResponseInit): Response;
text
text(value: string, init?: ResponseInit): Response;
redirect
redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): Response;
ok
ok(value?: JsonValue, init?: ResponseInit): Response;
created
created(value?: JsonValue, init?: ResponseInit): Response;
accepted
accepted(value?: JsonValue, init?: ResponseInit): Response;
noContent
noContent(init?: ResponseInit): Response;
badRequest
badRequest(message?: string, init?: ResponseInit): Response;
bad
bad(message?: string, init?: ResponseInit): Response;
unauthorized
unauthorized(message?: string, init?: ResponseInit): Response;
forbidden
forbidden(message?: string, init?: ResponseInit): Response;
notFound
notFound(message?: string, init?: ResponseInit): Response;
conflict
conflict(message?: string, init?: ResponseInit): Response;
unprocessableEntity
unprocessableEntity(message?: string, init?: ResponseInit): Response;
tooManyRequests
tooManyRequests(message?: string, init?: ResponseInit): Response;
methodNotAllowed
methodNotAllowed(allow?: string | readonly string[], init?: ResponseInit): Response;
error
error(status?: number, message?: string, init?: ResponseInit): Response;
internalServerError
internalServerError(message?: string, init?: ResponseInit): Response;
serverError
serverError(message?: string, init?: ResponseInit): Response;
notImplemented
notImplemented(message?: string, init?: ResponseInit): Response;
serviceUnavailable
serviceUnavailable(message?: string, init?: ResponseInit): Response;
problem
problem(status: number, detail?: string, options?: ProblemOptions): Response;
challenge
challenge(options?: ChallengeOptions): Response;
setCookie
setCookie(response: Response, name: string, value: string, options?: CookieOptions): Response;
clearCookie
clearCookie(response: Response, name: string, options?: CookieOptions): Response;
upgrade
upgrade(handler: WebSocketHandler): Response | Promise<Response>;

ServerDispatchOptionstype

ServerDispatchOptions: any

Per-request options passed to {@link ServerApp.fetch}.

websocket
websocket?: WebSocketAdapter;

serverErrortype

serverError: (detail?: string, init?: ResponseInit) => Response

Alias for {@link internalServerError}.

ServerSentEventtype

ServerSentEvent: any

A single Server-Sent Event; `data` is JSON-serialized unless already a string.

data
data?: unknown;
event
event?: string;
id
id?: string;
retry
retry?: number;

ServerTelemetrytype

ServerTelemetry: any

Telemetry hooks that a {@link ServerAppOptions.telemetry} implementation provides. Each `work`-wrapping method should run `work` inside an appropriately named span, propagating its return value.

request
request<T>(fields: ServerTelemetryFields, work: () => T): T;
routeMatch
routeMatch<T>(fields: ServerTelemetryFields, work: () => T): T;
loader
loader?<T>(fields: ServerTelemetryFields, work: () => T): T;
action
action<T>(fields: ServerTelemetryFields, work: () => T): T;
apiOperation
apiOperation<T>(fields: ServerTelemetryFields, work: () => T): T;
queryPrefetch
queryPrefetch?<T>(fields: ServerTelemetryFields, work: () => T): T;
ssrRender
ssrRender?<T>(fields: ServerTelemetryFields, work: () => T): T;
log
log(level: "debug" | "info" | "warn" | "error", event: ServerTelemetryOperation, fields?: ServerTelemetryFields): void;
traceId
traceId(): string | undefined;
extract
extract?<Carrier>(carrier: Carrier, getter: { keys(value: Carrier): string[]; get(value: Carrier, key: string): string | string[] | undefined; }): unknown;
withContext
withContext?<T>(context: unknown, work: () => T): T;

ServerTelemetryFieldstype

ServerTelemetryFields: any

Contextual fields attached to a telemetry span or log entry.

requestId
requestId?: string;
traceId
traceId?: string;
route
route?: string;
action
action?: string;
operation
operation?: string;
status
status?: number;
durationMs
durationMs?: number;

ServerTelemetryOperationtype

ServerTelemetryOperation: "askr.request" | "askr.route.match" | "askr.loader" | "askr.action" | "askr.api.operation" | "askr.query.prefetch" | "askr.ssr.render" | "askr.vite.document"

Identifies the kind of operation a {@link ServerTelemetry} call is instrumenting.

serviceUnavailabletype

serviceUnavailable: (detail?: string, init?: ResponseInit) => Response

Builds a `503 Service Unavailable` Problem Details response.

texttype

text: (value: string, init?: ResponseInit) => Response

Builds a plain-text response, setting the `text/plain; charset=utf-8` content type.

TokenIssuertype

TokenIssuer: any

Issues auth tokens for a principal, used by {@link registerAuthRoutes} to mint session tokens.

issue
issue(principal: Omit<P, "id"> & { subject: string; }): Promise<string>;

tooManyRequeststype

tooManyRequests: (detail?: string, init?: ResponseInit) => Response

Builds a `429 Too Many Requests` Problem Details response.

unauthorizedtype

unauthorized: (detail?: string, init?: ResponseInit) => Response

Builds a `401 Unauthorized` Problem Details response.

unprocessableEntitytype

unprocessableEntity: (detail?: string, init?: ResponseInit) => Response

Builds a `422 Unprocessable Entity` Problem Details response.

WebSocketAdaptertype

WebSocketAdapter: any

Adapter that performs the transport-specific work of upgrading a request to a WebSocket.

upgrade
upgrade(request: Request, handler: WebSocketHandler, context: ServerContext): Response | Promise<Response>;

WebSocketCloseEventtype

WebSocketCloseEvent: any

Details of a WebSocket close event, mirroring the DOM `CloseEvent` fields used here.

code
readonly code: number;
reason
readonly reason: string;
wasClean
readonly wasClean: boolean;

WebSocketHandlertype

WebSocketHandler: {
  bivarianceHack(socket: WebSocketLike, context: ServerContext<RouteParams>): void | Promise<void>;
}["bivarianceHack"]

Handler invoked with a live {@link WebSocketLike} once a connection has been upgraded.

WebSocketLiketype

WebSocketLike: any

Transport-neutral interface for an upgraded WebSocket connection.

send
send(data: string | ArrayBufferLike | ArrayBufferView): void;
close
close(code?: number, reason?: string): void;
onMessage
onMessage(listener: (data: string | Uint8Array) => void): () => void;
onClose
onClose(listener: (event: WebSocketCloseEvent) => void): () => void;
onError
onError(listener: (error: unknown) => void): () => void;