@atproto/lex-server 0.0.9 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # @atproto/lex-server
2
2
 
3
+ ## 0.0.11
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`66b7295`](https://github.com/bluesky-social/atproto/commit/66b72950e8bcb39cac3382116bd282b3bb692f16)]:
8
+ - @atproto/lex-cbor@0.0.13
9
+
10
+ ## 0.0.10
11
+
12
+ ### Patch Changes
13
+
14
+ - [#4660](https://github.com/bluesky-social/atproto/pull/4660) [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Add `LexValue` schema validation
15
+
16
+ - [#4660](https://github.com/bluesky-social/atproto/pull/4660) [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Improve typing accuracy of `ReadableStream` values
17
+
18
+ - Updated dependencies [[`39dea03`](https://github.com/bluesky-social/atproto/commit/39dea03c417a1da069962560505427a7aa25ad7a), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`39dea03`](https://github.com/bluesky-social/atproto/commit/39dea03c417a1da069962560505427a7aa25ad7a), [`39dea03`](https://github.com/bluesky-social/atproto/commit/39dea03c417a1da069962560505427a7aa25ad7a), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`39dea03`](https://github.com/bluesky-social/atproto/commit/39dea03c417a1da069962560505427a7aa25ad7a), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df), [`ea5df64`](https://github.com/bluesky-social/atproto/commit/ea5df64db9e408d2b320f5f75eb2878aef6bc6df)]:
19
+ - @atproto/lex-schema@0.0.13
20
+ - @atproto/lex-data@0.0.12
21
+ - @atproto/lex-cbor@0.0.12
22
+ - @atproto/lex-json@0.0.12
23
+
3
24
  ## 0.0.9
4
25
 
5
26
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"lex-server.d.ts","sourceRoot":"","sources":["../src/lex-server.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,EACjB,qBAAqB,EACrB,yBAAyB,EACzB,iBAAiB,EACjB,IAAI,EACJ,UAAU,EACV,SAAS,EACT,KAAK,EACL,YAAY,EAGb,MAAM,qBAAqB,CAAA;AAG5B,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;AAElC;;;;;;GAMG;AACH,MAAM,MAAM,SAAS,GAAG,KAAK,GAAG,SAAS,GAAG,YAAY,CAAA;AAExD;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB,oDAAoD;IACpD,QAAQ,EAAE,MAAM,CAAA;IAChB,yCAAyC;IACzC,IAAI,EAAE,MAAM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import { LexError, LexValue, isPlainObject, ui8Concat } from '@atproto/lex-data'\nimport { lexParse, lexToJson } from '@atproto/lex-json'\nimport {\n InferMethodInput,\n InferMethodMessage,\n InferMethodOutput,\n InferMethodOutputBody,\n InferMethodOutputEncoding,\n InferMethodParams,\n Main,\n NsidString,\n Procedure,\n Query,\n Subscription,\n getMain,\n isNsidString,\n} from '@atproto/lex-schema'\nimport { drainWebsocket } from './lib/drain-websocket.js'\n\ntype Awaitable<T> = T | Promise<T>\n\n/**\n * Union type representing the supported Lexicon method types.\n *\n * - `Query`: Read-only methods invoked via HTTP GET\n * - `Procedure`: Methods that may modify state, invoked via HTTP POST\n * - `Subscription`: Real-time streaming methods over WebSocket\n */\nexport type LexMethod = Query | Procedure | Subscription\n\n/**\n * Network address for TCP or UDP connections.\n *\n * @example\n * ```typescript\n * const addr: NetAddr = {\n * hostname: '127.0.0.1',\n * port: 3000,\n * transport: 'tcp'\n * }\n * ```\n */\nexport type NetAddr = {\n /** The hostname or IP address of the connection. */\n hostname: string\n /** The port number of the connection. */\n port: number\n /** The transport protocol used. */\n transport: 'tcp' | 'udp'\n}\n\n/**\n * Unix domain socket address.\n *\n * @example\n * ```typescript\n * const addr: UnixAddr = {\n * path: '/var/run/app.sock',\n * transport: 'unix'\n * }\n * ```\n */\nexport type UnixAddr = {\n /** The filesystem path to the Unix socket. */\n path: string\n /** The transport protocol used. */\n transport: 'unix' | 'unixpacket'\n}\n\n/**\n * Union type for all supported address types.\n *\n * Can be a network address ({@link NetAddr}), Unix socket address ({@link UnixAddr}),\n * or `undefined` when the address is not available.\n */\nexport type Addr = NetAddr | UnixAddr | undefined\n\n/**\n * Metadata about the client connection for an incoming request.\n *\n * @typeParam A - The address type, defaults to {@link Addr}\n *\n * @example\n * ```typescript\n * const info: ConnectionInfo<NetAddr> = {\n * remoteAddr: { hostname: '192.168.1.1', port: 54321, transport: 'tcp' },\n * completed: new Promise((resolve) => socket.on('close', resolve))\n * }\n * ```\n */\nexport type ConnectionInfo<A extends Addr = Addr> = {\n /** The remote address of the client, if available. */\n remoteAddr: A\n /** Promise that resolves when the connection is fully closed. */\n completed: Promise<void>\n}\n\n/**\n * Function signature for handling HTTP requests in the XRPC router.\n *\n * This is the standard fetch-style handler that processes incoming requests\n * and returns responses. It is used both internally by the router and can\n * be used to integrate with other HTTP frameworks.\n *\n * @param request - The incoming HTTP request\n * @param connection - Optional connection metadata including remote address\n * @returns A promise resolving to the HTTP response\n *\n * @example\n * ```typescript\n * const handler: FetchHandler = async (request, connection) => {\n * console.log('Request from:', connection?.remoteAddr)\n * return new Response('Hello, World!')\n * }\n * ```\n */\nexport type FetchHandler = (\n request: Request,\n connection?: ConnectionInfo,\n) => Promise<Response>\n\n/**\n * Context object passed to XRPC method handlers.\n *\n * Contains all the information needed to process a request, including\n * parsed parameters, authentication credentials, and the raw request object.\n *\n * @typeParam Method - The Lexicon method type (Query, Procedure, or Subscription)\n * @typeParam Credentials - The type of authentication credentials, determined by the auth handler\n *\n * @example\n * ```typescript\n * const handler: LexRouterMethodHandler<MyMethod, UserCredentials> = async (ctx) => {\n * const { credentials, params, input, signal } = ctx\n * // credentials.userId is available if auth handler returns UserCredentials\n * // params contains validated query parameters\n * // input contains the request body (for procedures)\n * // signal can be used to abort long-running operations\n * return { body: { result: 'success' } }\n * }\n * ```\n */\nexport type LexRouterHandlerContext<Method extends LexMethod, Credentials> = {\n /** Authentication credentials returned by the auth handler. */\n credentials: Credentials\n /** Parsed and validated request input (body for procedures, undefined for queries). */\n input: InferMethodInput<Method, Body>\n /** Parsed and validated URL query parameters. */\n params: InferMethodParams<Method>\n /** The original HTTP request object. */\n request: Request\n /** Abort signal that is triggered when the request is cancelled. */\n signal: AbortSignal\n /** Connection metadata including remote address. */\n connection?: ConnectionInfo\n}\n\ntype AsOptionalPayloadOptions<T> = T extends undefined | void\n ? { encoding?: undefined; body?: undefined }\n : T\n\n/**\n * Return type for XRPC method handlers (queries and procedures).\n *\n * Handlers can return either:\n * - A raw {@link Response} object for full control over the HTTP response\n * - An object with `body`, optional `encoding`, and optional `headers`\n *\n * For JSON methods, the body is automatically serialized. For other encodings,\n * the body must be a valid {@link BodyInit} type.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n *\n * @example\n * ```typescript\n * // Return JSON body (most common)\n * return { body: { users: [...] } }\n *\n * // Return with custom headers\n * return {\n * body: { data: 'value' },\n * headers: { 'Cache-Control': 'max-age=3600' }\n * }\n *\n * // Return raw Response for full control\n * return new Response(binaryData, {\n * headers: { 'Content-Type': 'application/octet-stream' }\n * })\n * ```\n */\nexport type LexRouterHandlerOutput<Method extends Query | Procedure> =\n | Response\n | ({\n headers?: HeadersInit\n } & (InferMethodOutputEncoding<Method> extends 'application/json'\n ? {\n // Allow omitting body when output is JSON\n encoding?: 'application/json'\n body: InferMethodOutputBody<Method>\n }\n : AsOptionalPayloadOptions<InferMethodOutput<Method, BodyInit>>))\n\n/**\n * Handler function for XRPC query and procedure methods.\n *\n * Receives a context object with request details and credentials,\n * and returns either a Response or a structured output object.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const getProfile: LexRouterMethodHandler<GetProfileMethod, UserCredentials> = async (ctx) => {\n * const profile = await db.getProfile(ctx.params.actor)\n * return { body: profile }\n * }\n * ```\n */\nexport type LexRouterMethodHandler<\n Method extends Query | Procedure = Query | Procedure,\n Credentials = unknown,\n> = (\n ctx: LexRouterHandlerContext<Method, Credentials>,\n) => Awaitable<LexRouterHandlerOutput<Method>>\n\n/**\n * Configuration object for registering an XRPC method with authentication.\n *\n * Used when you need to specify both a handler and an auth function.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const config: LexRouterMethodConfig<GetProfileMethod, UserCredentials> = {\n * handler: async (ctx) => {\n * return { body: await getProfile(ctx.params.actor) }\n * },\n * auth: async ({ request }) => {\n * return verifyToken(request.headers.get('authorization'))\n * }\n * }\n * ```\n */\nexport type LexRouterMethodConfig<\n Method extends Query | Procedure = Query | Procedure,\n Credentials = unknown,\n> = {\n /** The handler function that processes the request. */\n handler: LexRouterMethodHandler<Method, Credentials>\n /** Authentication function that validates credentials before the handler runs. */\n auth: LexRouterAuth<Credentials, Method>\n}\n\n/**\n * Handler function for XRPC subscription methods (WebSocket streams).\n *\n * Returns an async iterable that yields messages to be sent over the WebSocket.\n * The connection remains open until the iterable completes or an error occurs.\n *\n * @typeParam Method - The Lexicon subscription method type\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const subscribeRepos: LexRouterSubscriptionHandler<SubscribeReposMethod> = async function* (ctx) {\n * const cursor = ctx.params.cursor ?? 0\n * for await (const event of eventStream.since(cursor)) {\n * if (ctx.signal.aborted) break\n * yield { $type: 'com.atproto.sync.subscribeRepos#commit', ...event }\n * }\n * }\n * ```\n */\nexport type LexRouterSubscriptionHandler<\n Method extends Subscription = Subscription,\n Credentials = unknown,\n> = (\n ctx: LexRouterHandlerContext<Method, Credentials>,\n) => AsyncIterable<InferMethodMessage<Method>>\n\n/**\n * Configuration object for registering an XRPC subscription with authentication.\n *\n * Used when you need to specify both a handler and an auth function for subscriptions.\n *\n * @typeParam Method - The Lexicon subscription method type\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const config: LexRouterSubscriptionConfig<SubscribeReposMethod, ServiceCredentials> = {\n * handler: async function* (ctx) {\n * for await (const event of eventStream) {\n * yield event\n * }\n * },\n * auth: async ({ request }) => {\n * return verifyServiceAuth(request)\n * }\n * }\n * ```\n */\nexport type LexRouterSubscriptionConfig<\n Method extends Subscription = Subscription,\n Credentials = unknown,\n> = {\n /** The handler function that yields subscription messages. */\n handler: LexRouterSubscriptionHandler<Method, Credentials>\n /** Authentication function that validates credentials before the handler runs. */\n auth: LexRouterAuth<Credentials, Method>\n}\n\n/**\n * Context object passed to authentication handlers.\n *\n * Contains the information needed to authenticate a request before\n * the main handler is invoked.\n *\n * @typeParam Method - The Lexicon method type\n *\n * @example\n * ```typescript\n * const authHandler: LexRouterAuth<UserCredentials> = async (ctx) => {\n * const token = ctx.request.headers.get('authorization')\n * if (!token) throw new LexError('AuthenticationRequired', 'Missing token')\n * return { userId: await verifyToken(token) }\n * }\n * ```\n */\nexport type LexRouterAuthContext<Method extends LexMethod = LexMethod> = {\n /** The Lexicon method definition being called. */\n method: Method\n /** Parsed and validated URL query parameters. */\n params: InferMethodParams<Method>\n /** The original HTTP request object. */\n request: Request\n /** Connection metadata including remote address. */\n connection?: ConnectionInfo\n}\n\n/**\n * Authentication handler function for XRPC methods.\n *\n * Called before the main handler to validate authentication credentials.\n * Should return the validated credentials or throw an error if authentication fails.\n *\n * @typeParam Credentials - The type of credentials to return on success\n * @typeParam Method - The Lexicon method type\n *\n * @example\n * ```typescript\n * // Simple token-based auth\n * const tokenAuth: LexRouterAuth<{ userId: string }> = async ({ request }) => {\n * const token = request.headers.get('authorization')?.replace('Bearer ', '')\n * if (!token) throw new LexError('AuthenticationRequired', 'Token required')\n * const userId = await verifyToken(token)\n * return { userId }\n * }\n *\n * // Using with serviceAuth for AT Protocol service authentication\n * import { serviceAuth } from '@atproto/lex-server'\n * const auth = serviceAuth({ audience: 'did:web:example.com', unique: checkNonce })\n * ```\n */\nexport type LexRouterAuth<\n Credentials = unknown,\n Method extends LexMethod = LexMethod,\n> = (ctx: LexRouterAuthContext<Method>) => Credentials | Promise<Credentials>\n\n/**\n * Context object passed to error handler callbacks.\n *\n * Used for logging and monitoring errors that occur during request handling.\n */\nexport type LexErrorHandlerContext = {\n /** The error that was thrown during handling. */\n error: unknown\n /** The original HTTP request that triggered the error. */\n request: Request\n /** The Lexicon method that was being executed. */\n method: LexMethod\n}\n\n/**\n * Function that upgrades an HTTP request to a WebSocket connection.\n *\n * This is platform-specific: Deno provides this natively, while Node.js\n * requires the `upgradeWebSocket` function from this package.\n *\n * @param request - The HTTP request to upgrade\n * @returns An object containing the WebSocket and the upgrade response\n *\n * @example\n * ```typescript\n * // In Node.js, use the provided upgradeWebSocket function\n * import { upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n * ```\n */\nexport type UpgradeWebSocket = (request: Request) => {\n /** The WebSocket instance for bidirectional communication. */\n socket: WebSocket\n /** The HTTP response to return (101 Switching Protocols). */\n response: Response\n}\n\n/**\n * Configuration options for the {@link LexRouter}.\n *\n * @example\n * ```typescript\n * const options: LexRouterOptions = {\n * upgradeWebSocket,\n * onHandlerError: async ({ error, request, method }) => {\n * console.error(`Error in ${method.nsid}:`, error)\n * await reportToSentry(error)\n * },\n * highWaterMark: 64 * 1024, // 64KB\n * lowWaterMark: 16 * 1024 // 16KB\n * }\n * ```\n */\nexport type LexRouterOptions = {\n /**\n * Function to upgrade HTTP requests to WebSocket connections.\n * Required for subscription methods. Defaults to Deno's built-in\n * upgradeWebSocket if available.\n */\n upgradeWebSocket?: UpgradeWebSocket\n /**\n * Callback invoked when an error occurs during request handling.\n * Useful for logging and error reporting. Not called for client-induced\n * errors (e.g., request abortion).\n */\n onHandlerError?: (ctx: LexErrorHandlerContext) => void | Promise<void>\n /**\n * High water mark for WebSocket backpressure (in bytes).\n * When buffered data exceeds this, the handler will wait before sending more.\n */\n highWaterMark?: number\n /**\n * Low water mark for WebSocket backpressure (in bytes).\n * The handler resumes sending when buffered data drops below this.\n */\n lowWaterMark?: number\n}\n\n/**\n * XRPC router for handling AT Protocol Lexicon methods.\n *\n * The router handles HTTP routing, parameter parsing, input validation,\n * authentication, and response serialization for XRPC methods. It supports\n * queries (GET), procedures (POST), and subscriptions (WebSocket).\n *\n * @example Setting up a basic XRPC server\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'\n * import { getProfile, createPost, subscribeRepos } from './lexicons'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n *\n * // Register a query handler (GET request)\n * router.add(getProfile, async (ctx) => {\n * const profile = await db.getProfile(ctx.params.actor)\n * return { body: profile }\n * })\n *\n * // Register a procedure handler with authentication (POST request)\n * router.add(createPost, {\n * handler: async (ctx) => {\n * const post = await db.createPost(ctx.credentials.did, ctx.input.body)\n * return { body: { uri: post.uri, cid: post.cid } }\n * },\n * auth: async ({ request }) => {\n * return verifyAccessToken(request)\n * }\n * })\n *\n * // Register a subscription handler (WebSocket)\n * router.add(subscribeRepos, async function* (ctx) {\n * for await (const event of eventStream.since(ctx.params.cursor)) {\n * if (ctx.signal.aborted) break\n * yield event\n * }\n * })\n *\n * // Start the server\n * const server = await serve(router, { port: 3000 })\n * console.log('XRPC server listening on port 3000')\n * ```\n *\n * @example Using with service authentication\n * ```typescript\n * import { LexRouter, serviceAuth } from '@atproto/lex-server'\n *\n * const router = new LexRouter()\n *\n * const auth = serviceAuth({\n * audience: 'did:web:api.example.com',\n * unique: async (nonce) => {\n * // Check and record nonce uniqueness\n * return await nonceStore.checkAndAdd(nonce)\n * }\n * })\n *\n * router.add(protectedMethod, {\n * handler: async (ctx) => {\n * // ctx.credentials contains { did, didDocument, jwt }\n * return { body: { callerDid: ctx.credentials.did } }\n * },\n * auth\n * })\n * ```\n */\nexport class LexRouter {\n /** Map of NSID strings to their fetch handlers. */\n readonly handlers: Map<NsidString, FetchHandler> = new Map()\n\n /**\n * Creates a new XRPC router.\n *\n * @param options - Router configuration options\n */\n constructor(readonly options: LexRouterOptions = {}) {}\n\n /**\n * Registers a subscription handler without authentication.\n *\n * @param ns - The Lexicon namespace definition for the subscription\n * @param handler - Async generator function that yields subscription messages\n * @returns This router instance for chaining\n */\n add<M extends Subscription>(\n ns: Main<M>,\n handler: LexRouterSubscriptionHandler<M, void>,\n ): this\n /**\n * Registers a subscription handler with authentication.\n *\n * @param ns - The Lexicon namespace definition for the subscription\n * @param config - Configuration object with handler and auth function\n * @returns This router instance for chaining\n */\n add<M extends Subscription, Credentials>(\n ns: Main<M>,\n config: LexRouterSubscriptionConfig<M, Credentials>,\n ): this\n /**\n * Registers a query or procedure handler without authentication.\n *\n * @param ns - The Lexicon namespace definition for the method\n * @param handler - Handler function that processes requests\n * @returns This router instance for chaining\n */\n add<M extends Query | Procedure>(\n ns: Main<M>,\n handler: LexRouterMethodHandler<M, void>,\n ): this\n /**\n * Registers a query or procedure handler with authentication.\n *\n * @param ns - The Lexicon namespace definition for the method\n * @param config - Configuration object with handler and auth function\n * @returns This router instance for chaining\n */\n add<M extends Query | Procedure, Credentials>(\n ns: Main<M>,\n config: LexRouterMethodConfig<M, Credentials>,\n ): this\n /**\n * Registers a Lexicon method handler.\n *\n * This is the unified overload that accepts any method type with optional authentication.\n *\n * @param ns - The Lexicon namespace definition\n * @param config - Handler function or configuration object\n * @returns This router instance for chaining\n *\n * @throws {TypeError} If a method with the same NSID is already registered\n *\n * @example\n * ```typescript\n * // Register without auth (credentials will be void)\n * router.add(myQuery, async (ctx) => {\n * return { body: { data: 'value' } }\n * })\n *\n * // Register with auth\n * router.add(myProcedure, {\n * handler: async (ctx) => {\n * console.log('Caller:', ctx.credentials.userId)\n * return { body: { success: true } }\n * },\n * auth: async ({ request }) => ({ userId: await verifyToken(request) })\n * })\n * ```\n */\n add<M extends LexMethod, Credentials = unknown>(\n ns: Main<M>,\n config: M extends Subscription\n ?\n | LexRouterSubscriptionHandler<M, Credentials>\n | LexRouterSubscriptionConfig<M, Credentials>\n : M extends Query | Procedure\n ?\n | LexRouterMethodHandler<M, Credentials>\n | LexRouterMethodConfig<M, Credentials>\n : never,\n ): this\n add<M extends LexMethod>(\n ns: Main<M>,\n config:\n | LexRouterSubscriptionHandler<any, any>\n | LexRouterSubscriptionConfig<any, any>\n | LexRouterMethodHandler<any, any>\n | LexRouterMethodConfig<any, any>,\n ) {\n const method = getMain(ns)\n if (this.handlers.has(method.nsid)) {\n throw new TypeError(`Method ${method.nsid} already registered`)\n }\n const methodConfig =\n typeof config === 'function'\n ? { handler: config, auth: undefined }\n : config\n\n const fetch: FetchHandler =\n method.type === 'subscription'\n ? this.buildSubscriptionHandler(\n method,\n methodConfig.handler as LexRouterSubscriptionHandler<any, any>,\n methodConfig.auth,\n )\n : this.buildMethodHandler(\n method,\n methodConfig.handler as LexRouterMethodHandler<any, any>,\n methodConfig.auth,\n )\n\n this.handlers.set(method.nsid, fetch)\n\n return this\n }\n\n private buildMethodHandler<Method extends Query | Procedure, Credentials>(\n method: Method,\n methodHandler: LexRouterMethodHandler<Method, Credentials>,\n auth?: LexRouterAuth<Credentials, Method>,\n ): FetchHandler {\n const getInput = (\n method.type === 'procedure'\n ? getProcedureInput.bind(method)\n : getQueryInput.bind(method)\n ) as (request: Request) => Promise<InferMethodInput<Method, Body>>\n\n return async (request, connection) => {\n // @NOTE CORS requests should be handled by a middleware before reaching\n // this point.\n if (\n (method.type === 'procedure' && request.method !== 'POST') ||\n (method.type === 'query' &&\n request.method !== 'GET' &&\n request.method !== 'HEAD')\n ) {\n return Response.json(\n { error: 'InvalidRequest', message: 'Method not allowed' },\n { status: 405 },\n )\n }\n\n try {\n const url = new URL(request.url)\n const params = method.parameters.fromURLSearchParams(url.searchParams)\n\n const credentials = auth\n ? await auth({ method, params, request, connection })\n : (undefined as Credentials)\n\n const input = await getInput(request)\n\n const output = await methodHandler({\n credentials,\n params,\n input,\n request,\n connection,\n signal: request.signal,\n })\n\n if (output instanceof Response) {\n return output\n }\n\n // @TODO add validation of output based on method.output.schema?\n\n if (output.body === undefined && output.encoding === undefined) {\n return new Response(null, { status: 200, headers: output.headers })\n }\n\n if (method.output?.encoding === 'application/json') {\n return Response.json(lexToJson(output.body as LexValue), {\n status: 200,\n headers: output.headers,\n })\n }\n\n const headers = new Headers(output.headers)\n headers.set('content-type', output.encoding!)\n return new Response(output.body as BodyInit | null | undefined, {\n status: 200,\n headers,\n })\n } catch (error) {\n return this.handleError(request, method, error)\n }\n }\n }\n\n private buildSubscriptionHandler<Method extends Subscription, Credentials>(\n method: Method,\n methodHandler: LexRouterSubscriptionHandler<Method, Credentials>,\n auth?: LexRouterAuth<Credentials, Method>,\n ): FetchHandler {\n const {\n onHandlerError,\n upgradeWebSocket = (globalThis as any).Deno?.upgradeWebSocket as\n | UpgradeWebSocket\n | undefined,\n } = this.options\n if (!upgradeWebSocket) {\n throw new TypeError(\n 'WebSocket upgrade not supported in this environment. Please provide an upgradeWebSocket option when creating the LexRouter.',\n )\n }\n\n return async (request, connection) => {\n if (request.method !== 'GET') {\n return Response.json(\n { error: 'InvalidRequest', message: 'Method not allowed' },\n { status: 405 },\n )\n }\n\n if (\n request.headers.get('connection')?.toLowerCase() !== 'upgrade' ||\n request.headers.get('upgrade')?.toLowerCase() !== 'websocket'\n ) {\n return Response.json(\n {\n error: 'InvalidRequest',\n message: 'XRPC subscriptions are only available over WebSocket',\n },\n {\n status: 426,\n headers: {\n Connection: 'Upgrade',\n Upgrade: 'websocket',\n },\n },\n )\n }\n\n if (request.signal.aborted) {\n return Response.json(\n { error: 'RequestAborted', message: 'The request was aborted' },\n { status: 499 },\n )\n }\n\n try {\n const { response, socket } = upgradeWebSocket(request)\n\n // @NOTE We are using a distinct signal than request.signal because that\n // signal may get aborted before the WebSocket is closed (this is the\n // case with Deno).\n const abortController = new AbortController()\n const { signal } = abortController\n const abort = () => abortController.abort()\n\n const onMessage = (event: unknown) => {\n const error = new LexError(\n 'InvalidRequest',\n 'XRPC subscriptions do not accept messages',\n { cause: event },\n )\n socket.send(encodeErrorFrame(error))\n socket.close(1008, error.error)\n }\n\n const onOpen = async () => {\n try {\n const url = new URL(request.url)\n const params = method.parameters.fromURLSearchParams(\n url.searchParams,\n )\n\n const credentials: Credentials = auth\n ? await auth({ method, params, request, connection })\n : (undefined as Credentials)\n\n signal.throwIfAborted()\n\n const iterable = methodHandler({\n credentials,\n params,\n input: undefined as InferMethodInput<Method, Body>,\n request,\n connection,\n signal,\n })\n\n const iterator = iterable[Symbol.asyncIterator]()\n\n signal.addEventListener('abort', async () => {\n // @NOTE will cause the process to crash if this throws\n await iterator.return?.()\n })\n\n while (!signal.aborted && socket.readyState === 1) {\n const result = await iterator.next()\n if (result.done) break\n\n // @TODO add validation of output based on method.output.schema?\n\n const data = encodeMessageFrame(method, result.value)\n\n socket.send(data)\n\n // Apply backpressure by waiting for the buffered data to drain\n // before generating the next message\n await drainWebsocket(socket, signal, this.options)\n }\n\n if (socket.readyState === 1) {\n socket.close(1000)\n }\n } catch (error) {\n // If the socket is still open, send an error frame before closing\n if (socket.readyState === 1) {\n const lexError =\n error instanceof LexError\n ? error\n : new LexError('InternalError', 'An internal error occurred')\n\n socket.send(encodeErrorFrame(lexError))\n\n socket.close(\n // https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1\n error instanceof LexError ? 1008 : 1011,\n lexError.error,\n )\n }\n\n // Only report unexpected processing errors\n if (onHandlerError && !isAbortReason(request.signal, error)) {\n await onHandlerError({ error, request, method })\n }\n } finally {\n abortController.abort()\n }\n }\n\n socket.addEventListener('error', abort)\n socket.addEventListener('close', abort)\n socket.addEventListener('open', onOpen)\n socket.addEventListener('message', onMessage)\n\n return response\n } catch (error) {\n return this.handleError(request, method, error)\n }\n }\n }\n\n private async handleError(\n request: Request,\n method: LexMethod,\n error: unknown,\n ) {\n // Only report unexpected processing errors\n const { onHandlerError } = this.options\n if (onHandlerError && !isAbortReason(request.signal, error)) {\n await onHandlerError({ error, request, method })\n }\n\n if (error instanceof LexError) {\n return error.toResponse()\n }\n\n return Response.json(\n { error: 'InternalError', message: 'An internal error occurred' },\n { status: 500 },\n )\n }\n\n /**\n * The main fetch handler for processing XRPC requests.\n *\n * Routes incoming requests to the appropriate method handler based on the\n * NSID in the URL path. Returns appropriate error responses for invalid\n * paths or unimplemented methods.\n *\n * This handler can be used directly with HTTP servers that support the\n * fetch API pattern, or converted to a Node.js request listener using\n * `toRequestListener()`.\n *\n * @param request - The incoming HTTP request\n * @param connection - Optional connection metadata\n * @returns A promise resolving to the HTTP response\n *\n * @example\n * ```typescript\n * // Use with Deno\n * Deno.serve(router.fetch)\n *\n * // Use with Bun\n * Bun.serve({ fetch: router.fetch })\n *\n * // Use with Node.js\n * import { toRequestListener } from '@atproto/lex-server/nodejs'\n * const listener = toRequestListener(router.fetch)\n * http.createServer(listener).listen(3000)\n * ```\n */\n fetch: FetchHandler = async (\n request: Request,\n connection?: ConnectionInfo,\n ): Promise<Response> => {\n const nsid = extractMethodNsid(request)\n\n const fetch = nsid\n ? (this.handlers as Map<unknown, FetchHandler>).get(nsid)\n : undefined\n if (fetch) return fetch(request, connection)\n\n if (!nsid || !isNsidString(nsid)) {\n return Response.json(\n {\n error: 'InvalidRequest',\n message: 'Invalid XRPC method path',\n },\n { status: 404 },\n )\n }\n\n return Response.json(\n {\n error: 'MethodNotImplemented',\n message: `XRPC method \"${nsid}\" not implemented on this server`,\n },\n { status: 501 },\n )\n }\n}\n\nfunction extractMethodNsid(request: Request): string | null {\n const { pathname } = new URL(request.url)\n if (!pathname.startsWith('/xrpc/')) return null\n if (pathname.includes('/', 6)) return null\n // We don't really need to validate the NSID here, the existence of the route\n // (which is looked up based on an NSID) is sufficient.\n return pathname.slice(6)\n}\n\nasync function getProcedureInput<M extends Procedure>(\n this: M,\n request: Request,\n): Promise<InferMethodInput<M, Body>> {\n const encodingRaw = request.headers\n .get('content-type')\n ?.split(';')[0]\n .trim()\n .toLowerCase()\n\n const encoding =\n encodingRaw ||\n // If the caller did not provide a content-type, but the method\n // expects an input, assume binary\n (request.body != null && this.input.encoding != null\n ? 'application/octet-stream'\n : undefined)\n\n if (!this.input.matchesEncoding(encoding)) {\n throw new LexError('InvalidRequest', `Invalid content-type: ${encoding}`)\n }\n\n if (this.input.encoding === 'application/json') {\n // @TODO limit size?\n const data = lexParse(await request.text())\n const body = this.input.schema ? this.input.schema.parse(data) : data\n return { encoding, body } as InferMethodInput<M, Body>\n } else if (this.input.encoding) {\n const body: Body = request\n return { encoding, body } as InferMethodInput<M, Body>\n } else {\n return undefined as InferMethodInput<M, Body>\n }\n}\n\nasync function getQueryInput<M extends Query>(\n this: M,\n request: Request,\n): Promise<InferMethodInput<M, Body>> {\n if (\n request.body ||\n request.headers.has('content-type') ||\n request.headers.has('content-length')\n ) {\n throw new LexError('InvalidRequest', 'GET requests must not have a body')\n }\n\n return undefined as InferMethodInput<M, Body>\n}\n\n// Pre-encoded frame header for error frames\nconst ERROR_FRAME_HEADER = /*#__PURE__*/ encode({ op: -1 })\n\nfunction encodeErrorFrame(error: LexError): Uint8Array {\n return ui8Concat([ERROR_FRAME_HEADER, encode(error.toJSON())])\n}\n\n// Pre-encoded frame header for message frames with unknown type\nconst UNKNOWN_MESSAGE_FRAME_HEADER = /*#__PURE__*/ encode({ op: 1 })\n\nfunction encodeMessageFrame(method: Subscription, value: LexValue): Uint8Array {\n if (isPlainObject(value) && typeof value.$type === 'string') {\n const { $type, ...rest } = value\n return ui8Concat([\n encode({\n op: 1,\n t:\n // If $type starts with `nsid#`, strip the NSID prefix\n $type.charCodeAt(0) !== 0x23 && // '#'\n $type.charCodeAt(method.nsid.length) === 0x23 && // '#'\n $type.startsWith(method.nsid)\n ? $type.slice(method.nsid.length)\n : $type,\n }),\n encode(rest),\n ])\n }\n\n return ui8Concat([UNKNOWN_MESSAGE_FRAME_HEADER, encode(value)])\n}\n\nfunction isAbortReason(signal: AbortSignal, error: unknown): boolean {\n if (!signal.aborted || signal.reason == null) return false\n return (\n error === signal.reason ||\n (error instanceof Error && error.cause === signal.reason)\n )\n}\n"]}
1
+ {"version":3,"file":"lex-server.js","sourceRoot":"","sources":["../src/lex-server.ts"],"names":[],"mappings":";;;AAAA,gDAA0C;AAC1C,gDAAgF;AAChF,gDAAuD;AACvD,oDAc4B;AAC5B,iEAAyD;AAkbzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmEG;AACH,MAAa,SAAS;IASC;IARrB,mDAAmD;IAC1C,QAAQ,GAAkC,IAAI,GAAG,EAAE,CAAA;IAE5D;;;;OAIG;IACH,YAAqB,UAA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KAAK,MAAM,CAAC,MAAM,CAAC,CAC1D,CAAA;AACH,CAAC","sourcesContent":["import { encode } from '@atproto/lex-cbor'\nimport { LexError, LexValue, isPlainObject, ui8Concat } from '@atproto/lex-data'\nimport { lexParse, lexToJson } from '@atproto/lex-json'\nimport {\n InferMethodInput,\n InferMethodMessage,\n InferMethodOutput,\n InferMethodOutputBody,\n InferMethodOutputEncoding,\n InferMethodParams,\n Main,\n NsidString,\n Procedure,\n Query,\n Subscription,\n getMain,\n isNsidString,\n} from '@atproto/lex-schema'\nimport { drainWebsocket } from './lib/drain-websocket.js'\n\ntype Awaitable<T> = T | Promise<T>\n\n/**\n * Union type representing the supported Lexicon method types.\n *\n * - `Query`: Read-only methods invoked via HTTP GET\n * - `Procedure`: Methods that may modify state, invoked via HTTP POST\n * - `Subscription`: Real-time streaming methods over WebSocket\n */\nexport type LexMethod = Query | Procedure | Subscription\n\n/**\n * Network address for TCP or UDP connections.\n *\n * @example\n * ```typescript\n * const addr: NetAddr = {\n * hostname: '127.0.0.1',\n * port: 3000,\n * transport: 'tcp'\n * }\n * ```\n */\nexport type NetAddr = {\n /** The hostname or IP address of the connection. */\n hostname: string\n /** The port number of the connection. */\n port: number\n /** The transport protocol used. */\n transport: 'tcp' | 'udp'\n}\n\n/**\n * Unix domain socket address.\n *\n * @example\n * ```typescript\n * const addr: UnixAddr = {\n * path: '/var/run/app.sock',\n * transport: 'unix'\n * }\n * ```\n */\nexport type UnixAddr = {\n /** The filesystem path to the Unix socket. */\n path: string\n /** The transport protocol used. */\n transport: 'unix' | 'unixpacket'\n}\n\n/**\n * Union type for all supported address types.\n *\n * Can be a network address ({@link NetAddr}), Unix socket address ({@link UnixAddr}),\n * or `undefined` when the address is not available.\n */\nexport type Addr = NetAddr | UnixAddr | undefined\n\n/**\n * Metadata about the client connection for an incoming request.\n *\n * @typeParam A - The address type, defaults to {@link Addr}\n *\n * @example\n * ```typescript\n * const info: ConnectionInfo<NetAddr> = {\n * remoteAddr: { hostname: '192.168.1.1', port: 54321, transport: 'tcp' },\n * completed: new Promise((resolve) => socket.on('close', resolve))\n * }\n * ```\n */\nexport type ConnectionInfo<A extends Addr = Addr> = {\n /** The remote address of the client, if available. */\n remoteAddr: A\n /** Promise that resolves when the connection is fully closed. */\n completed: Promise<void>\n}\n\n/**\n * Function signature for handling HTTP requests in the XRPC router.\n *\n * This is the standard fetch-style handler that processes incoming requests\n * and returns responses. It is used both internally by the router and can\n * be used to integrate with other HTTP frameworks.\n *\n * @param request - The incoming HTTP request\n * @param connection - Optional connection metadata including remote address\n * @returns A promise resolving to the HTTP response\n *\n * @example\n * ```typescript\n * const handler: FetchHandler = async (request, connection) => {\n * console.log('Request from:', connection?.remoteAddr)\n * return new Response('Hello, World!')\n * }\n * ```\n */\nexport type FetchHandler = (\n request: Request,\n connection?: ConnectionInfo,\n) => Promise<Response>\n\n/**\n * Context object passed to XRPC method handlers.\n *\n * Contains all the information needed to process a request, including\n * parsed parameters, authentication credentials, and the raw request object.\n *\n * @typeParam Method - The Lexicon method type (Query, Procedure, or Subscription)\n * @typeParam Credentials - The type of authentication credentials, determined by the auth handler\n *\n * @example\n * ```typescript\n * const handler: LexRouterMethodHandler<MyMethod, UserCredentials> = async (ctx) => {\n * const { credentials, params, input, signal } = ctx\n * // credentials.userId is available if auth handler returns UserCredentials\n * // params contains validated query parameters\n * // input contains the request body (for procedures)\n * // signal can be used to abort long-running operations\n * return { body: { result: 'success' } }\n * }\n * ```\n */\nexport type LexRouterHandlerContext<Method extends LexMethod, Credentials> = {\n /** Authentication credentials returned by the auth handler. */\n credentials: Credentials\n /** Parsed and validated request input (body for procedures, undefined for queries). */\n input: InferMethodInput<Method, Body>\n /** Parsed and validated URL query parameters. */\n params: InferMethodParams<Method>\n /** The original HTTP request object. */\n request: Request\n /** Abort signal that is triggered when the request is cancelled. */\n signal: AbortSignal\n /** Connection metadata including remote address. */\n connection?: ConnectionInfo\n}\n\ntype AsOptionalPayloadOptions<T> = T extends undefined | void\n ? { encoding?: undefined; body?: undefined }\n : T\n\n/**\n * Return type for XRPC method handlers (queries and procedures).\n *\n * Handlers can return either:\n * - A raw {@link Response} object for full control over the HTTP response\n * - An object with `body`, optional `encoding`, and optional `headers`\n *\n * For JSON methods, the body is automatically serialized. For other encodings,\n * the body must be a valid {@link BodyInit} type.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n *\n * @example\n * ```typescript\n * // Return JSON body (most common)\n * return { body: { users: [...] } }\n *\n * // Return with custom headers\n * return {\n * body: { data: 'value' },\n * headers: { 'Cache-Control': 'max-age=3600' }\n * }\n *\n * // Return raw Response for full control\n * return new Response(binaryData, {\n * headers: { 'Content-Type': 'application/octet-stream' }\n * })\n * ```\n */\nexport type LexRouterHandlerOutput<Method extends Query | Procedure> =\n | Response\n | ({\n headers?: HeadersInit\n } & (InferMethodOutputEncoding<Method> extends 'application/json'\n ? {\n // Allow omitting body when output is JSON\n encoding?: 'application/json'\n body: InferMethodOutputBody<Method>\n }\n : AsOptionalPayloadOptions<InferMethodOutput<Method, BodyInit>>))\n\n/**\n * Handler function for XRPC query and procedure methods.\n *\n * Receives a context object with request details and credentials,\n * and returns either a Response or a structured output object.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const getProfile: LexRouterMethodHandler<GetProfileMethod, UserCredentials> = async (ctx) => {\n * const profile = await db.getProfile(ctx.params.actor)\n * return { body: profile }\n * }\n * ```\n */\nexport type LexRouterMethodHandler<\n Method extends Query | Procedure = Query | Procedure,\n Credentials = unknown,\n> = (\n ctx: LexRouterHandlerContext<Method, Credentials>,\n) => Awaitable<LexRouterHandlerOutput<Method>>\n\n/**\n * Configuration object for registering an XRPC method with authentication.\n *\n * Used when you need to specify both a handler and an auth function.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const config: LexRouterMethodConfig<GetProfileMethod, UserCredentials> = {\n * handler: async (ctx) => {\n * return { body: await getProfile(ctx.params.actor) }\n * },\n * auth: async ({ request }) => {\n * return verifyToken(request.headers.get('authorization'))\n * }\n * }\n * ```\n */\nexport type LexRouterMethodConfig<\n Method extends Query | Procedure = Query | Procedure,\n Credentials = unknown,\n> = {\n /** The handler function that processes the request. */\n handler: LexRouterMethodHandler<Method, Credentials>\n /** Authentication function that validates credentials before the handler runs. */\n auth: LexRouterAuth<Credentials, Method>\n}\n\n/**\n * Handler function for XRPC subscription methods (WebSocket streams).\n *\n * Returns an async iterable that yields messages to be sent over the WebSocket.\n * The connection remains open until the iterable completes or an error occurs.\n *\n * @typeParam Method - The Lexicon subscription method type\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const subscribeRepos: LexRouterSubscriptionHandler<SubscribeReposMethod> = async function* (ctx) {\n * const cursor = ctx.params.cursor ?? 0\n * for await (const event of eventStream.since(cursor)) {\n * if (ctx.signal.aborted) break\n * yield { $type: 'com.atproto.sync.subscribeRepos#commit', ...event }\n * }\n * }\n * ```\n */\nexport type LexRouterSubscriptionHandler<\n Method extends Subscription = Subscription,\n Credentials = unknown,\n> = (\n ctx: LexRouterHandlerContext<Method, Credentials>,\n) => AsyncIterable<InferMethodMessage<Method>>\n\n/**\n * Configuration object for registering an XRPC subscription with authentication.\n *\n * Used when you need to specify both a handler and an auth function for subscriptions.\n *\n * @typeParam Method - The Lexicon subscription method type\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const config: LexRouterSubscriptionConfig<SubscribeReposMethod, ServiceCredentials> = {\n * handler: async function* (ctx) {\n * for await (const event of eventStream) {\n * yield event\n * }\n * },\n * auth: async ({ request }) => {\n * return verifyServiceAuth(request)\n * }\n * }\n * ```\n */\nexport type LexRouterSubscriptionConfig<\n Method extends Subscription = Subscription,\n Credentials = unknown,\n> = {\n /** The handler function that yields subscription messages. */\n handler: LexRouterSubscriptionHandler<Method, Credentials>\n /** Authentication function that validates credentials before the handler runs. */\n auth: LexRouterAuth<Credentials, Method>\n}\n\n/**\n * Context object passed to authentication handlers.\n *\n * Contains the information needed to authenticate a request before\n * the main handler is invoked.\n *\n * @typeParam Method - The Lexicon method type\n *\n * @example\n * ```typescript\n * const authHandler: LexRouterAuth<UserCredentials> = async (ctx) => {\n * const token = ctx.request.headers.get('authorization')\n * if (!token) throw new LexError('AuthenticationRequired', 'Missing token')\n * return { userId: await verifyToken(token) }\n * }\n * ```\n */\nexport type LexRouterAuthContext<Method extends LexMethod = LexMethod> = {\n /** The Lexicon method definition being called. */\n method: Method\n /** Parsed and validated URL query parameters. */\n params: InferMethodParams<Method>\n /** The original HTTP request object. */\n request: Request\n /** Connection metadata including remote address. */\n connection?: ConnectionInfo\n}\n\n/**\n * Authentication handler function for XRPC methods.\n *\n * Called before the main handler to validate authentication credentials.\n * Should return the validated credentials or throw an error if authentication fails.\n *\n * @typeParam Credentials - The type of credentials to return on success\n * @typeParam Method - The Lexicon method type\n *\n * @example\n * ```typescript\n * // Simple token-based auth\n * const tokenAuth: LexRouterAuth<{ userId: string }> = async ({ request }) => {\n * const token = request.headers.get('authorization')?.replace('Bearer ', '')\n * if (!token) throw new LexError('AuthenticationRequired', 'Token required')\n * const userId = await verifyToken(token)\n * return { userId }\n * }\n *\n * // Using with serviceAuth for AT Protocol service authentication\n * import { serviceAuth } from '@atproto/lex-server'\n * const auth = serviceAuth({ audience: 'did:web:example.com', unique: checkNonce })\n * ```\n */\nexport type LexRouterAuth<\n Credentials = unknown,\n Method extends LexMethod = LexMethod,\n> = (ctx: LexRouterAuthContext<Method>) => Credentials | Promise<Credentials>\n\n/**\n * Context object passed to error handler callbacks.\n *\n * Used for logging and monitoring errors that occur during request handling.\n */\nexport type LexErrorHandlerContext = {\n /** The error that was thrown during handling. */\n error: unknown\n /** The original HTTP request that triggered the error. */\n request: Request\n /** The Lexicon method that was being executed. */\n method: LexMethod\n}\n\n/**\n * Function that upgrades an HTTP request to a WebSocket connection.\n *\n * This is platform-specific: Deno provides this natively, while Node.js\n * requires the `upgradeWebSocket` function from this package.\n *\n * @param request - The HTTP request to upgrade\n * @returns An object containing the WebSocket and the upgrade response\n *\n * @example\n * ```typescript\n * // In Node.js, use the provided upgradeWebSocket function\n * import { upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n * ```\n */\nexport type UpgradeWebSocket = (request: Request) => {\n /** The WebSocket instance for bidirectional communication. */\n socket: WebSocket\n /** The HTTP response to return (101 Switching Protocols). */\n response: Response\n}\n\n/**\n * Configuration options for the {@link LexRouter}.\n *\n * @example\n * ```typescript\n * const options: LexRouterOptions = {\n * upgradeWebSocket,\n * onHandlerError: async ({ error, request, method }) => {\n * console.error(`Error in ${method.nsid}:`, error)\n * await reportToSentry(error)\n * },\n * highWaterMark: 64 * 1024, // 64KB\n * lowWaterMark: 16 * 1024 // 16KB\n * }\n * ```\n */\nexport type LexRouterOptions = {\n /**\n * Function to upgrade HTTP requests to WebSocket connections.\n * Required for subscription methods. Defaults to Deno's built-in\n * upgradeWebSocket if available.\n */\n upgradeWebSocket?: UpgradeWebSocket\n /**\n * Callback invoked when an error occurs during request handling.\n * Useful for logging and error reporting. Not called for client-induced\n * errors (e.g., request abortion).\n */\n onHandlerError?: (ctx: LexErrorHandlerContext) => void | Promise<void>\n /**\n * High water mark for WebSocket backpressure (in bytes).\n * When buffered data exceeds this, the handler will wait before sending more.\n */\n highWaterMark?: number\n /**\n * Low water mark for WebSocket backpressure (in bytes).\n * The handler resumes sending when buffered data drops below this.\n */\n lowWaterMark?: number\n}\n\n/**\n * XRPC router for handling AT Protocol Lexicon methods.\n *\n * The router handles HTTP routing, parameter parsing, input validation,\n * authentication, and response serialization for XRPC methods. It supports\n * queries (GET), procedures (POST), and subscriptions (WebSocket).\n *\n * @example Setting up a basic XRPC server\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'\n * import { getProfile, createPost, subscribeRepos } from './lexicons'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n *\n * // Register a query handler (GET request)\n * router.add(getProfile, async (ctx) => {\n * const profile = await db.getProfile(ctx.params.actor)\n * return { body: profile }\n * })\n *\n * // Register a procedure handler with authentication (POST request)\n * router.add(createPost, {\n * handler: async (ctx) => {\n * const post = await db.createPost(ctx.credentials.did, ctx.input.body)\n * return { body: { uri: post.uri, cid: post.cid } }\n * },\n * auth: async ({ request }) => {\n * return verifyAccessToken(request)\n * }\n * })\n *\n * // Register a subscription handler (WebSocket)\n * router.add(subscribeRepos, async function* (ctx) {\n * for await (const event of eventStream.since(ctx.params.cursor)) {\n * if (ctx.signal.aborted) break\n * yield event\n * }\n * })\n *\n * // Start the server\n * const server = await serve(router, { port: 3000 })\n * console.log('XRPC server listening on port 3000')\n * ```\n *\n * @example Using with service authentication\n * ```typescript\n * import { LexRouter, serviceAuth } from '@atproto/lex-server'\n *\n * const router = new LexRouter()\n *\n * const auth = serviceAuth({\n * audience: 'did:web:api.example.com',\n * unique: async (nonce) => {\n * // Check and record nonce uniqueness\n * return await nonceStore.checkAndAdd(nonce)\n * }\n * })\n *\n * router.add(protectedMethod, {\n * handler: async (ctx) => {\n * // ctx.credentials contains { did, didDocument, jwt }\n * return { body: { callerDid: ctx.credentials.did } }\n * },\n * auth\n * })\n * ```\n */\nexport class LexRouter {\n /** Map of NSID strings to their fetch handlers. */\n readonly handlers: Map<NsidString, FetchHandler> = new Map()\n\n /**\n * Creates a new XRPC router.\n *\n * @param options - Router configuration options\n */\n constructor(readonly options: LexRouterOptions = {}) {}\n\n /**\n * Registers a subscription handler without authentication.\n *\n * @param ns - The Lexicon namespace definition for the subscription\n * @param handler - Async generator function that yields subscription messages\n * @returns This router instance for chaining\n */\n add<M extends Subscription>(\n ns: Main<M>,\n handler: LexRouterSubscriptionHandler<M, void>,\n ): this\n /**\n * Registers a subscription handler with authentication.\n *\n * @param ns - The Lexicon namespace definition for the subscription\n * @param config - Configuration object with handler and auth function\n * @returns This router instance for chaining\n */\n add<M extends Subscription, Credentials>(\n ns: Main<M>,\n config: LexRouterSubscriptionConfig<M, Credentials>,\n ): this\n /**\n * Registers a query or procedure handler without authentication.\n *\n * @param ns - The Lexicon namespace definition for the method\n * @param handler - Handler function that processes requests\n * @returns This router instance for chaining\n */\n add<M extends Query | Procedure>(\n ns: Main<M>,\n handler: LexRouterMethodHandler<M, void>,\n ): this\n /**\n * Registers a query or procedure handler with authentication.\n *\n * @param ns - The Lexicon namespace definition for the method\n * @param config - Configuration object with handler and auth function\n * @returns This router instance for chaining\n */\n add<M extends Query | Procedure, Credentials>(\n ns: Main<M>,\n config: LexRouterMethodConfig<M, Credentials>,\n ): this\n /**\n * Registers a Lexicon method handler.\n *\n * This is the unified overload that accepts any method type with optional authentication.\n *\n * @param ns - The Lexicon namespace definition\n * @param config - Handler function or configuration object\n * @returns This router instance for chaining\n *\n * @throws {TypeError} If a method with the same NSID is already registered\n *\n * @example\n * ```typescript\n * // Register without auth (credentials will be void)\n * router.add(myQuery, async (ctx) => {\n * return { body: { data: 'value' } }\n * })\n *\n * // Register with auth\n * router.add(myProcedure, {\n * handler: async (ctx) => {\n * console.log('Caller:', ctx.credentials.userId)\n * return { body: { success: true } }\n * },\n * auth: async ({ request }) => ({ userId: await verifyToken(request) })\n * })\n * ```\n */\n add<M extends LexMethod, Credentials = unknown>(\n ns: Main<M>,\n config: M extends Subscription\n ?\n | LexRouterSubscriptionHandler<M, Credentials>\n | LexRouterSubscriptionConfig<M, Credentials>\n : M extends Query | Procedure\n ?\n | LexRouterMethodHandler<M, Credentials>\n | LexRouterMethodConfig<M, Credentials>\n : never,\n ): this\n add<M extends LexMethod>(\n ns: Main<M>,\n config:\n | LexRouterSubscriptionHandler<any, any>\n | LexRouterSubscriptionConfig<any, any>\n | LexRouterMethodHandler<any, any>\n | LexRouterMethodConfig<any, any>,\n ) {\n const method = getMain(ns)\n if (this.handlers.has(method.nsid)) {\n throw new TypeError(`Method ${method.nsid} already registered`)\n }\n const methodConfig =\n typeof config === 'function'\n ? { handler: config, auth: undefined }\n : config\n\n const fetch: FetchHandler =\n method.type === 'subscription'\n ? this.buildSubscriptionHandler(\n method,\n methodConfig.handler as LexRouterSubscriptionHandler<any, any>,\n methodConfig.auth,\n )\n : this.buildMethodHandler(\n method,\n methodConfig.handler as LexRouterMethodHandler<any, any>,\n methodConfig.auth,\n )\n\n this.handlers.set(method.nsid, fetch)\n\n return this\n }\n\n private buildMethodHandler<Method extends Query | Procedure, Credentials>(\n method: Method,\n methodHandler: LexRouterMethodHandler<Method, Credentials>,\n auth?: LexRouterAuth<Credentials, Method>,\n ): FetchHandler {\n const getInput = (\n method.type === 'procedure'\n ? getProcedureInput.bind(method)\n : getQueryInput.bind(method)\n ) as (request: Request) => Promise<InferMethodInput<Method, Body>>\n\n return async (request, connection) => {\n // @NOTE CORS requests should be handled by a middleware before reaching\n // this point.\n if (\n (method.type === 'procedure' && request.method !== 'POST') ||\n (method.type === 'query' &&\n request.method !== 'GET' &&\n request.method !== 'HEAD')\n ) {\n return Response.json(\n { error: 'InvalidRequest', message: 'Method not allowed' },\n { status: 405 },\n )\n }\n\n try {\n const url = new URL(request.url)\n const params = method.parameters.fromURLSearchParams(\n url.searchParams,\n ) as InferMethodParams<Method>\n\n const credentials = auth\n ? await auth({ method, params, request, connection })\n : (undefined as Credentials)\n\n const input = await getInput(request)\n\n const output = await methodHandler({\n credentials,\n params,\n input,\n request,\n connection,\n signal: request.signal,\n })\n\n if (output instanceof Response) {\n return output\n }\n\n // @TODO add validation of output based on method.output.schema?\n\n if (output.body === undefined && output.encoding === undefined) {\n return new Response(null, { status: 200, headers: output.headers })\n }\n\n if (method.output?.encoding === 'application/json') {\n return Response.json(lexToJson(output.body as LexValue), {\n status: 200,\n headers: output.headers,\n })\n }\n\n const headers = new Headers(output.headers)\n headers.set('content-type', output.encoding!)\n return new Response(output.body as BodyInit | null | undefined, {\n status: 200,\n headers,\n })\n } catch (error) {\n return this.handleError(request, method, error)\n }\n }\n }\n\n private buildSubscriptionHandler<Method extends Subscription, Credentials>(\n method: Method,\n methodHandler: LexRouterSubscriptionHandler<Method, Credentials>,\n auth?: LexRouterAuth<Credentials, Method>,\n ): FetchHandler {\n const {\n onHandlerError,\n upgradeWebSocket = (globalThis as any).Deno?.upgradeWebSocket as\n | UpgradeWebSocket\n | undefined,\n } = this.options\n if (!upgradeWebSocket) {\n throw new TypeError(\n 'WebSocket upgrade not supported in this environment. Please provide an upgradeWebSocket option when creating the LexRouter.',\n )\n }\n\n return async (request, connection) => {\n if (request.method !== 'GET') {\n return Response.json(\n { error: 'InvalidRequest', message: 'Method not allowed' },\n { status: 405 },\n )\n }\n\n if (\n request.headers.get('connection')?.toLowerCase() !== 'upgrade' ||\n request.headers.get('upgrade')?.toLowerCase() !== 'websocket'\n ) {\n return Response.json(\n {\n error: 'InvalidRequest',\n message: 'XRPC subscriptions are only available over WebSocket',\n },\n {\n status: 426,\n headers: {\n Connection: 'Upgrade',\n Upgrade: 'websocket',\n },\n },\n )\n }\n\n if (request.signal.aborted) {\n return Response.json(\n { error: 'RequestAborted', message: 'The request was aborted' },\n { status: 499 },\n )\n }\n\n try {\n const { response, socket } = upgradeWebSocket(request)\n\n // @NOTE We are using a distinct signal than request.signal because that\n // signal may get aborted before the WebSocket is closed (this is the\n // case with Deno).\n const abortController = new AbortController()\n const { signal } = abortController\n const abort = () => abortController.abort()\n\n const onMessage = (event: unknown) => {\n const error = new LexError(\n 'InvalidRequest',\n 'XRPC subscriptions do not accept messages',\n { cause: event },\n )\n socket.send(encodeErrorFrame(error))\n socket.close(1008, error.error)\n }\n\n const onOpen = async () => {\n try {\n const url = new URL(request.url)\n const params = method.parameters.fromURLSearchParams(\n url.searchParams,\n ) as InferMethodParams<Method>\n\n const credentials: Credentials = auth\n ? await auth({ method, params, request, connection })\n : (undefined as Credentials)\n\n signal.throwIfAborted()\n\n const iterable = methodHandler({\n credentials,\n params,\n input: undefined as InferMethodInput<Method, Body>,\n request,\n connection,\n signal,\n })\n\n const iterator = iterable[Symbol.asyncIterator]()\n\n signal.addEventListener('abort', async () => {\n // @NOTE will cause the process to crash if this throws\n await iterator.return?.()\n })\n\n while (!signal.aborted && socket.readyState === 1) {\n const result = await iterator.next()\n if (result.done) break\n\n // @TODO add validation of output based on method.output.schema?\n\n const data = encodeMessageFrame(method, result.value)\n\n socket.send(data)\n\n // Apply backpressure by waiting for the buffered data to drain\n // before generating the next message\n await drainWebsocket(socket, signal, this.options)\n }\n\n if (socket.readyState === 1) {\n socket.close(1000)\n }\n } catch (error) {\n // If the socket is still open, send an error frame before closing\n if (socket.readyState === 1) {\n const lexError =\n error instanceof LexError\n ? error\n : new LexError('InternalError', 'An internal error occurred')\n\n socket.send(encodeErrorFrame(lexError))\n\n socket.close(\n // https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1\n error instanceof LexError ? 1008 : 1011,\n lexError.error,\n )\n }\n\n // Only report unexpected processing errors\n if (onHandlerError && !isAbortReason(request.signal, error)) {\n await onHandlerError({ error, request, method })\n }\n } finally {\n abortController.abort()\n }\n }\n\n socket.addEventListener('error', abort)\n socket.addEventListener('close', abort)\n socket.addEventListener('open', onOpen)\n socket.addEventListener('message', onMessage)\n\n return response\n } catch (error) {\n return this.handleError(request, method, error)\n }\n }\n }\n\n private async handleError(\n request: Request,\n method: LexMethod,\n error: unknown,\n ) {\n // Only report unexpected processing errors\n const { onHandlerError } = this.options\n if (onHandlerError && !isAbortReason(request.signal, error)) {\n await onHandlerError({ error, request, method })\n }\n\n if (error instanceof LexError) {\n return error.toResponse()\n }\n\n return Response.json(\n { error: 'InternalError', message: 'An internal error occurred' },\n { status: 500 },\n )\n }\n\n /**\n * The main fetch handler for processing XRPC requests.\n *\n * Routes incoming requests to the appropriate method handler based on the\n * NSID in the URL path. Returns appropriate error responses for invalid\n * paths or unimplemented methods.\n *\n * This handler can be used directly with HTTP servers that support the\n * fetch API pattern, or converted to a Node.js request listener using\n * `toRequestListener()`.\n *\n * @param request - The incoming HTTP request\n * @param connection - Optional connection metadata\n * @returns A promise resolving to the HTTP response\n *\n * @example\n * ```typescript\n * // Use with Deno\n * Deno.serve(router.fetch)\n *\n * // Use with Bun\n * Bun.serve({ fetch: router.fetch })\n *\n * // Use with Node.js\n * import { toRequestListener } from '@atproto/lex-server/nodejs'\n * const listener = toRequestListener(router.fetch)\n * http.createServer(listener).listen(3000)\n * ```\n */\n fetch: FetchHandler = async (\n request: Request,\n connection?: ConnectionInfo,\n ): Promise<Response> => {\n const nsid = extractMethodNsid(request)\n\n const fetch = nsid\n ? (this.handlers as Map<unknown, FetchHandler>).get(nsid)\n : undefined\n if (fetch) return fetch(request, connection)\n\n if (!nsid || !isNsidString(nsid)) {\n return Response.json(\n {\n error: 'InvalidRequest',\n message: 'Invalid XRPC method path',\n },\n { status: 404 },\n )\n }\n\n return Response.json(\n {\n error: 'MethodNotImplemented',\n message: `XRPC method \"${nsid}\" not implemented on this server`,\n },\n { status: 501 },\n )\n }\n}\n\nfunction extractMethodNsid(request: Request): string | null {\n const { pathname } = new URL(request.url)\n if (!pathname.startsWith('/xrpc/')) return null\n if (pathname.includes('/', 6)) return null\n // We don't really need to validate the NSID here, the existence of the route\n // (which is looked up based on an NSID) is sufficient.\n return pathname.slice(6)\n}\n\nasync function getProcedureInput<M extends Procedure>(\n this: M,\n request: Request,\n): Promise<InferMethodInput<M, Body>> {\n const encodingRaw = request.headers\n .get('content-type')\n ?.split(';')[0]\n .trim()\n .toLowerCase()\n\n const encoding =\n encodingRaw ||\n // If the caller did not provide a content-type, but the method\n // expects an input, assume binary\n (request.body != null && this.input.encoding != null\n ? 'application/octet-stream'\n : undefined)\n\n if (!this.input.matchesEncoding(encoding)) {\n throw new LexError('InvalidRequest', `Invalid content-type: ${encoding}`)\n }\n\n if (this.input.encoding === 'application/json') {\n // @TODO limit size?\n const data = lexParse(await request.text())\n const body = this.input.schema ? this.input.schema.parse(data) : data\n return { encoding, body } as InferMethodInput<M, Body>\n } else if (this.input.encoding) {\n const body: Body = request\n return { encoding, body } as InferMethodInput<M, Body>\n } else {\n return undefined as InferMethodInput<M, Body>\n }\n}\n\nasync function getQueryInput<M extends Query>(\n this: M,\n request: Request,\n): Promise<InferMethodInput<M, Body>> {\n if (\n request.body ||\n request.headers.has('content-type') ||\n request.headers.has('content-length')\n ) {\n throw new LexError('InvalidRequest', 'GET requests must not have a body')\n }\n\n return undefined as InferMethodInput<M, Body>\n}\n\n// Pre-encoded frame header for error frames\nconst ERROR_FRAME_HEADER = /*#__PURE__*/ encode({ op: -1 })\n\nfunction encodeErrorFrame(error: LexError): Uint8Array {\n return ui8Concat([ERROR_FRAME_HEADER, encode(error.toJSON())])\n}\n\n// Pre-encoded frame header for message frames with unknown type\nconst UNKNOWN_MESSAGE_FRAME_HEADER = /*#__PURE__*/ encode({ op: 1 })\n\nfunction encodeMessageFrame(method: Subscription, value: LexValue): Uint8Array {\n if (isPlainObject(value) && typeof value.$type === 'string') {\n const { $type, ...rest } = value\n return ui8Concat([\n encode({\n op: 1,\n t:\n // If $type starts with `nsid#`, strip the NSID prefix\n $type.charCodeAt(0) !== 0x23 && // '#'\n $type.charCodeAt(method.nsid.length) === 0x23 && // '#'\n $type.startsWith(method.nsid)\n ? $type.slice(method.nsid.length)\n : $type,\n }),\n encode(rest),\n ])\n }\n\n return ui8Concat([UNKNOWN_MESSAGE_FRAME_HEADER, encode(value)])\n}\n\nfunction isAbortReason(signal: AbortSignal, error: unknown): boolean {\n if (!signal.aborted || signal.reason == null) return false\n return (\n error === signal.reason ||\n (error instanceof Error && error.cause === signal.reason)\n )\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"nodejs.d.ts","sourceRoot":"","sources":["../src/nodejs.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,eAAe,EAEf,MAAM,IAAI,UAAU,EACpB,aAAa,EACb,cAAc,EAEf,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;A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,SAAS;QAChB,UAAU,EAAE,KAAK;QACjB,YAAY,EAAE,KAAK;QACnB,QAAQ,EAAE,KAAK;KAChB,CAAC,CAAA;IAEF,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,YAAY,EAAE;QACjD,KAAK,EAAE,SAAS;QAChB,UAAU,EAAE,KAAK;QACjB,YAAY,EAAE,KAAK;QACnB,QAAQ,EAAE,KAAK;KAChB,CAAC,CAAA;IAEF,OAAO,MAAmC,CAAA;AAC5C,CAAC;AA0BD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AACI,KAAK,UAAU,KAAK,CAMzB,OAAqC,EACrC,OAA+C;IAE/C,MAAM,MAAM,GAAG,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;IAC7C,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IACtB,MAAM,IAAA,kBAAI,EAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IAC/B,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { once } from 'node:events'\nimport {\n IncomingHttpHeaders,\n IncomingMessage,\n RequestListener,\n Server as HttpServer,\n ServerOptions,\n ServerResponse,\n createServer as createHttpServer,\n} from 'node:http'\nimport { ListenOptions } from 'node:net'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport { createHttpTerminator } from 'http-terminator'\nimport { WebSocket as WebSocketPonyfill, WebSocketServer } from 'ws'\nimport { FetchHandler } from './lex-server.js'\n\n// @ts-expect-error\nSymbol.asyncDispose ??= Symbol.for('Symbol.asyncDispose')\n\nconst kResponseWs = Symbol.for('@atproto/lex-server:WebSocket')\n\nfunction isUpgradeRequest(request: Request, upgrade: string): boolean {\n return (\n request.method === 'GET' &&\n request.headers.get('connection')?.toLowerCase() === 'upgrade' &&\n request.headers.get('upgrade')?.toLowerCase() === upgrade\n )\n}\n\n/**\n * Upgrades an HTTP request to a WebSocket connection for Node.js.\n *\n * This function must be passed to the {@link LexRouter} constructor to enable\n * subscription (WebSocket) support on Node.js. It creates a WebSocket instance\n * and a placeholder response that signals the need for protocol upgrade.\n *\n * The actual upgrade is handled internally when the response is sent through\n * {@link sendResponse}.\n *\n * @param request - The incoming HTTP request to upgrade\n * @returns An object containing the WebSocket and upgrade response\n * @throws {TypeError} If the request is not a valid WebSocket upgrade request\n *\n * @example\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * // Pass to router for subscription support\n * const router = new LexRouter({ upgradeWebSocket })\n *\n * // Now you can add subscription handlers\n * router.add(subscribeRepos, async function* (ctx) {\n * for await (const event of eventStream) {\n * yield event\n * }\n * })\n * ```\n */\nexport function upgradeWebSocket(request: Request): {\n response: Response\n socket: WebSocket\n} {\n if (!isUpgradeRequest(request, 'websocket')) {\n throw new TypeError('upgradeWebSocket() expects a WebSocket upgrade')\n }\n\n // Placeholder response for WebSocket upgrade. The actual handling will happen\n // through the handleWebSocketUpgrade function. Headers set on the response\n // will be applied during the upgrade.\n const response = new Response(null, { status: 200 })\n\n // The Response constructor does not allow setting status 101, so we\n // define it directly. The purpose of this response is just to signal\n // that an upgrade is needed, and to carry any headers.\n Object.defineProperty(response, 'status', {\n value: 101,\n enumerable: false,\n configurable: false,\n writable: false,\n })\n\n // @ts-expect-error\n const socket: WebSocket = new WebSocketPonyfill(null, undefined, {\n autoPong: true,\n })\n\n // Attach the WebSocket to the response for later retrieval\n Object.defineProperty(response, kResponseWs, {\n value: socket,\n enumerable: false,\n configurable: false,\n writable: false,\n })\n\n return { response, socket }\n}\n\nconst kUpgradeEvent = Symbol.for('@atproto/lex-server:upgrade')\n\nfunction handleWebSocketUpgrade(\n req: IncomingMessage,\n response: Response,\n): void {\n const ws = (response as { [kResponseWs]?: WebSocketPonyfill })[kResponseWs]\n if (!ws) throw new TypeError('Response not created by upgradeWebSocket()')\n\n // Create a one time use WebSocketServer to handle the upgrade\n const wss = new WebSocketServer({\n autoPong: true,\n noServer: true,\n clientTracking: false,\n perMessageDeflate: true,\n // @ts-expect-error\n WebSocket: function () {\n // Return the websocket that was created earlier instead of a new instance\n return ws\n },\n })\n\n // Apply headers that might have been set on the response object during\n // handling. This will be called during wss.handleUpgrade().\n wss.on('headers', (headers) => {\n for (const [name, value] of response.headers) {\n headers.push(`${name}: ${value}`)\n }\n })\n\n wss.handleUpgrade(req, req.socket, Buffer.alloc(0), (_socket) => {\n // @TODO find a way to properly \"close\" the _socket when the server is\n // shutting down (might require replacing http-terminator with a local\n // implementation)\n\n req.emit(kUpgradeEvent, ws)\n })\n}\n\n/**\n * Sends a fetch API Response through a Node.js ServerResponse.\n *\n * Handles both regular HTTP responses and WebSocket upgrades. For WebSocket\n * upgrades (status 101), delegates to the WebSocket upgrade handler.\n *\n * This function is used internally by {@link toRequestListener} and\n * {@link createServer}, but can be used directly for custom integrations.\n *\n * @param req - The Node.js IncomingMessage\n * @param res - The Node.js ServerResponse to write to\n * @param response - The fetch API Response to send\n * @throws {TypeError} If headers have already been sent\n *\n * @example\n * ```typescript\n * import http from 'node:http'\n * import { sendResponse } from '@atproto/lex-server/nodejs'\n *\n * const server = http.createServer(async (req, res) => {\n * const response = new Response('Hello, World!', {\n * headers: { 'Content-Type': 'text/plain' }\n * })\n * await sendResponse(req, res, response)\n * })\n * ```\n */\nexport async function sendResponse(\n req: IncomingMessage,\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n // Invalid usage\n if (res.headersSent) {\n throw new TypeError('Response has already been sent')\n }\n\n if (response.status === 101) {\n return handleWebSocketUpgrade(req, response)\n }\n\n res.statusCode = response.status\n res.statusMessage = response.statusText\n\n for (const [key, value] of response.headers) {\n res.setHeader(key, value)\n }\n\n if (response.body != null && req.method !== 'HEAD') {\n const stream = Readable.fromWeb(response.body as any)\n await pipeline(stream, res)\n } else {\n await response.body?.cancel()\n res.end()\n }\n}\n\nfunction toRequest(req: IncomingMessage): Request {\n const host = req.headers.host ?? req.socket?.localAddress ?? 'localhost'\n const isEncrypted = (req.socket as any).encrypted === true\n const protocol = isEncrypted ? 'https' : 'http'\n const url = new URL(req.url ?? '/', `${protocol}://${host}`)\n const headers = toHeaders(req.headers)\n const body = toBody(req)\n const signal = requestSignal(req)\n\n return new Request(url, {\n signal,\n method: req.method,\n headers,\n body,\n referrer: headers.get('referrer') ?? headers.get('referer') ?? undefined,\n redirect: 'manual',\n // @ts-expect-error\n duplex: body ? 'half' : undefined,\n })\n}\n\nfunction requestSignal(req: IncomingMessage): AbortSignal {\n if (req.destroyed) return AbortSignal.abort()\n\n const abortController = new AbortController()\n\n const abort = (err?: Error | WebSocket) => {\n abortController.abort(err instanceof Error ? err : undefined)\n\n req.off('close', abort)\n req.off('error', abort)\n req.off('end', abort)\n req.off(kUpgradeEvent, abort)\n }\n\n req.on('close', abort)\n req.on('error', abort)\n req.on('end', abort)\n req.on(kUpgradeEvent, abort)\n\n return abortController.signal\n}\n\nfunction requestCompletion(req: IncomingMessage): Promise<void> {\n if (req.destroyed) return Promise.resolve()\n\n // Unlike the abort signal, we complete the promise only when the request\n // is fully done, accounting for websocket upgrade.\n return new Promise((resolve) => {\n const cleanup = () => {\n req.off('close', done)\n req.off('error', done)\n req.off('end', done)\n req.off(kUpgradeEvent, onUpgrade)\n }\n\n const onUpgrade = (ws: WebSocket) => {\n cleanup()\n ws.addEventListener('close', () => resolve())\n }\n\n const done = () => {\n resolve()\n cleanup()\n }\n\n req.on('close', done)\n req.on('error', done)\n req.on('end', done)\n req.on(kUpgradeEvent, onUpgrade)\n })\n}\n\nfunction toHeaders(headers: IncomingHttpHeaders): Headers {\n const result = new Headers()\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue\n if (Array.isArray(value)) {\n for (const v of value) result.append(key, v)\n } else {\n result.set(key, value)\n }\n }\n return result\n}\n\nfunction toBody(req: IncomingMessage): null | ReadableStream<Uint8Array> {\n if (\n req.method === 'GET' ||\n req.method === 'HEAD' ||\n req.method === 'OPTIONS'\n ) {\n return null\n }\n\n if (\n req.headers['content-type'] == null &&\n req.headers['transfer-encoding'] == null &&\n req.headers['content-length'] == null\n ) {\n return null\n }\n\n return Readable.toWeb(req) as ReadableStream<Uint8Array>\n}\n\n/**\n * Network address type for Node.js TCP connections.\n *\n * @example\n * ```typescript\n * const addr: NetAddr = {\n * transport: 'tcp',\n * hostname: '192.168.1.100',\n * port: 54321\n * }\n * ```\n */\nexport type NetAddr = {\n /** Always 'tcp' for Node.js HTTP connections. */\n transport: 'tcp'\n /** The IP address of the remote client. */\n hostname: string\n /** The port number of the remote client. */\n port: number\n}\n\n/**\n * Connection metadata for Node.js HTTP requests.\n *\n * Provides information about the client connection, including the remote\n * address and a promise that resolves when the connection is fully closed\n * (including WebSocket connections).\n */\nexport type NodeConnectionInfo = {\n /** Promise that resolves when the connection is fully closed. */\n completed: Promise<void>\n /** The remote address of the client, if available. */\n remoteAddr: NetAddr | undefined\n}\n\n/**\n * Interface for objects that can handle fetch-style requests.\n *\n * Used by {@link createServer} and {@link serve} to accept either\n * a fetch handler function or an object with a `fetch` method\n * (like {@link LexRouter}).\n */\nexport interface HandlerObject {\n /** The fetch handler method. */\n fetch: FetchHandler\n}\n\nasync function handleRequest(\n req: IncomingMessage,\n res: ServerResponse,\n fetchHandler: FetchHandler,\n) {\n const request = toRequest(req)\n const info = toConnectionInfo(req)\n const response = await fetchHandler(request, info)\n await sendResponse(req, res, response)\n}\n\nfunction toConnectionInfo(req: IncomingMessage): NodeConnectionInfo {\n const { socket } = req\n\n return {\n completed: requestCompletion(req),\n remoteAddr:\n socket.remoteAddress != null\n ? {\n transport: 'tcp',\n hostname: socket.remoteAddress,\n port: socket.remotePort!,\n }\n : undefined,\n }\n}\n\n/**\n * Converts a fetch-style handler to a Node.js request listener.\n *\n * The returned listener can be used with Node.js HTTP servers directly,\n * or as middleware in frameworks like Express (supports the `next` callback).\n *\n * @typeParam Request - The request class type (default: IncomingMessage)\n * @typeParam Response - The response class type (default: ServerResponse)\n * @param fetchHandler - The fetch-style handler function\n * @returns A Node.js RequestListener compatible with http.createServer\n *\n * @example Using as Express middleware\n * ```typescript\n * import express from 'express'\n * import { toRequestListener } from '@atproto/lex-server/nodejs'\n * import { LexRouter } from '@atproto/lex-server'\n *\n * const router = new LexRouter()\n * // Register handlers...\n *\n * const app = express()\n *\n * // Mount the XRPC router\n * app.use('/xrpc', toRequestListener(router.fetch))\n * ```\n */\nexport function toRequestListener<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n>(fetchHandler: FetchHandler) {\n return ((\n req: InstanceType<Request>,\n res: InstanceType<Response> & { req: InstanceType<Request> },\n next?: (err?: unknown) => void,\n ): void => {\n handleRequest(req, res, fetchHandler).catch((err) => {\n if (next) next(err)\n else {\n if (!res.headersSent) {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain; charset=utf-8')\n res.end('Internal Server Error')\n } else if (!res.writableEnded) {\n res.destroy()\n }\n }\n })\n }) satisfies RequestListener<Request, Response>\n}\n\n/**\n * Options for creating an XRPC server.\n *\n * Extends Node.js {@link ServerOptions} with additional options for graceful shutdown.\n */\nexport type CreateServerOptions<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n> = ServerOptions<Request, Response> & {\n /**\n * Timeout in milliseconds for graceful termination.\n *\n * When `terminate()` is called, the server will wait up to this duration\n * for active connections to complete before forcibly closing them.\n */\n gracefulTerminationTimeout?: number\n}\n\n/**\n * Extended HTTP server with graceful shutdown support.\n *\n * Extends the standard Node.js HttpServer with a `terminate()` method\n * for graceful shutdown and implements `AsyncDisposable` for use with\n * `await using`.\n *\n * @typeParam Request - The request class type\n * @typeParam Response - The response class type\n *\n * @example Graceful shutdown\n * ```typescript\n * const server = createServer(router)\n * server.listen(3000)\n *\n * process.on('SIGTERM', async () => {\n * console.log('Shutting down...')\n * await server.terminate()\n * console.log('Server stopped')\n * })\n * ```\n *\n * @example Using with await using\n * ```typescript\n * await using server = await serve(router, { port: 3000 })\n * // Server will be automatically terminated when scope exits\n * ```\n */\nexport interface Server<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n> extends HttpServer<Request, Response>,\n AsyncDisposable {\n /**\n * Gracefully terminates the server.\n *\n * Stops accepting new connections and waits for active connections\n * to complete (up to `gracefulTerminationTimeout`).\n *\n * @returns Promise that resolves when the server is fully stopped\n */\n terminate(): Promise<void>\n [Symbol.asyncDispose](): Promise<void>\n}\n\n/**\n * Creates an HTTP server configured for XRPC request handling.\n *\n * The server includes graceful shutdown support and can be used with\n * either a fetch handler function or an object with a `fetch` method\n * (like {@link LexRouter}).\n *\n * Note: This creates the server but does not start listening. Call\n * `server.listen()` to start the server, or use {@link serve} for\n * a combined create-and-listen operation.\n *\n * @typeParam Request - The request class type\n * @typeParam Response - The response class type\n * @param handler - A fetch handler or object with fetch method\n * @param options - Server configuration options\n * @returns An HTTP server with graceful shutdown support\n *\n * @example Basic usage\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { createServer, upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n * router.add(myMethod, myHandler)\n *\n * const server = createServer(router)\n * server.listen(3000, () => {\n * console.log('Server listening on port 3000')\n * })\n * ```\n *\n * @example With graceful termination timeout\n * ```typescript\n * const server = createServer(router, {\n * gracefulTerminationTimeout: 10000 // 10 seconds\n * })\n * ```\n */\nexport function createServer<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n>(\n handler: FetchHandler | HandlerObject,\n options: CreateServerOptions<Request, Response> = {},\n): Server<Request, Response> {\n const fetchHandler =\n typeof handler === 'function' ? handler : handler.fetch.bind(handler)\n\n const listener = toRequestListener(fetchHandler)\n const server = createHttpServer(options, listener)\n\n const terminator = createHttpTerminator({\n server: server as HttpServer,\n gracefulTerminationTimeout: options?.gracefulTerminationTimeout,\n })\n\n const terminate = async function terminate(this: Server<Request, Response>) {\n if (this !== server) {\n throw new TypeError('Server.terminate called with incorrect context')\n }\n // @TODO properly close all active WebSocket connections\n return terminator.terminate()\n }\n\n Object.defineProperty(server, 'terminate', {\n value: terminate,\n enumerable: false,\n configurable: false,\n writable: false,\n })\n\n Object.defineProperty(server, Symbol.asyncDispose, {\n value: terminate,\n enumerable: false,\n configurable: false,\n writable: false,\n })\n\n return server as Server<Request, Response>\n}\n\n/**\n * Combined options for creating and starting an XRPC server.\n *\n * Includes both server creation options and network listen options.\n *\n * @typeParam Request - The request class type\n * @typeParam Response - The response class type\n *\n * @example\n * ```typescript\n * const options: StartServerOptions = {\n * port: 3000,\n * host: '0.0.0.0',\n * gracefulTerminationTimeout: 10000\n * }\n * ```\n */\nexport type StartServerOptions<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n> = ListenOptions & CreateServerOptions<Request, Response>\n\n/**\n * Creates and starts an HTTP server, returning when it's ready to accept connections.\n *\n * This is a convenience function that combines {@link createServer} and `server.listen()`\n * into a single async operation. The returned promise resolves once the server\n * is actively listening.\n *\n * @typeParam Request - The request class type\n * @typeParam Response - The response class type\n * @param handler - A fetch handler or object with fetch method (like {@link LexRouter})\n * @param options - Combined server and listen options\n * @returns Promise resolving to the running server\n *\n * @example Basic usage\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n *\n * // Register handlers\n * router.add(getProfile, async (ctx) => {\n * return { body: await db.getProfile(ctx.params.actor) }\n * })\n *\n * // Start server on port 3000\n * const server = await serve(router, { port: 3000 })\n * console.log('Server listening on port 3000')\n *\n * // Graceful shutdown\n * process.on('SIGTERM', () => server.terminate())\n * process.on('SIGINT', () => server.terminate())\n * ```\n *\n * @example With all options\n * ```typescript\n * const server = await serve(router, {\n * port: 3000,\n * host: '0.0.0.0',\n * gracefulTerminationTimeout: 15000,\n * })\n * ```\n *\n * @example Using with await using (auto-cleanup)\n * ```typescript\n * async function main() {\n * await using server = await serve(router, { port: 3000 })\n *\n * // Server is running...\n * console.log('Server listening on port 3000')\n *\n * // Wait for termination signal\n * await Promise.race([\n * once(process, 'SIGINT'),\n * once(process, 'SIGTERM'),\n * ])\n *\n * // Server will be automatically terminated when scope exits\n * }\n * ```\n */\nexport async function serve<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n>(\n handler: FetchHandler | HandlerObject,\n options?: StartServerOptions<Request, Response>,\n): Promise<Server<Request, Response>> {\n const server = createServer(handler, options)\n server.listen(options)\n await once(server, 'listening')\n return server\n}\n"]}
1
+ {"version":3,"file":"nodejs.js","sourceRoot":"","sources":["../src/nodejs.ts"],"names":[],"mappings":";;AA6DA,4CAqCC;AAoED,oCA4BC;AAgND,8CAwBC;AA2GD,oCA2CC;AAuFD,sBAaC;AApqBD,6CAAkC;AAClC,yCAQkB;AAElB,6CAAsC;AACtC,mDAA+C;AAE/C,qDAAsD;AACtD,2BAAoE;AAGpE,mBAAmB;AACnB,MAAM,CAAC,YAAY,KAAK,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAA;AAEzD,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAA;AAE/D,SAAS,gBAAgB,CAAC,OAAgB,EAAE,OAAe;IACzD,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,KAAK;QACxB,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,WAAW,EAAE,KAAK,SAAS;QAC9D,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC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\n RequestListener,\n Server as HttpServer,\n ServerOptions,\n ServerResponse,\n createServer as createHttpServer,\n} from 'node:http'\nimport { ListenOptions } from 'node:net'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport type { ReadableStream as NodeReadableStream } from 'node:stream/web'\nimport { createHttpTerminator } from 'http-terminator'\nimport { WebSocket as WebSocketPonyfill, WebSocketServer } from 'ws'\nimport { FetchHandler } from './lex-server.js'\n\n// @ts-expect-error\nSymbol.asyncDispose ??= Symbol.for('Symbol.asyncDispose')\n\nconst kResponseWs = Symbol.for('@atproto/lex-server:WebSocket')\n\nfunction isUpgradeRequest(request: Request, upgrade: string): boolean {\n return (\n request.method === 'GET' &&\n request.headers.get('connection')?.toLowerCase() === 'upgrade' &&\n request.headers.get('upgrade')?.toLowerCase() === upgrade\n )\n}\n\n/**\n * Upgrades an HTTP request to a WebSocket connection for Node.js.\n *\n * This function must be passed to the {@link LexRouter} constructor to enable\n * subscription (WebSocket) support on Node.js. It creates a WebSocket instance\n * and a placeholder response that signals the need for protocol upgrade.\n *\n * The actual upgrade is handled internally when the response is sent through\n * {@link sendResponse}.\n *\n * @param request - The incoming HTTP request to upgrade\n * @returns An object containing the WebSocket and upgrade response\n * @throws {TypeError} If the request is not a valid WebSocket upgrade request\n *\n * @example\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * // Pass to router for subscription support\n * const router = new LexRouter({ upgradeWebSocket })\n *\n * // Now you can add subscription handlers\n * router.add(subscribeRepos, async function* (ctx) {\n * for await (const event of eventStream) {\n * yield event\n * }\n * })\n * ```\n */\nexport function upgradeWebSocket(request: Request): {\n response: Response\n socket: WebSocket\n} {\n if (!isUpgradeRequest(request, 'websocket')) {\n throw new TypeError('upgradeWebSocket() expects a WebSocket upgrade')\n }\n\n // Placeholder response for WebSocket upgrade. The actual handling will happen\n // through the handleWebSocketUpgrade function. Headers set on the response\n // will be applied during the upgrade.\n const response = new Response(null, { status: 200 })\n\n // The Response constructor does not allow setting status 101, so we\n // define it directly. The purpose of this response is just to signal\n // that an upgrade is needed, and to carry any headers.\n Object.defineProperty(response, 'status', {\n value: 101,\n enumerable: false,\n configurable: false,\n writable: false,\n })\n\n // @ts-expect-error\n const socket: WebSocket = new WebSocketPonyfill(null, undefined, {\n autoPong: true,\n })\n\n // Attach the WebSocket to the response for later retrieval\n Object.defineProperty(response, kResponseWs, {\n value: socket,\n enumerable: false,\n configurable: false,\n writable: false,\n })\n\n return { response, socket }\n}\n\nconst kUpgradeEvent = Symbol.for('@atproto/lex-server:upgrade')\n\nfunction handleWebSocketUpgrade(\n req: IncomingMessage,\n response: Response,\n): void {\n const ws = (response as { [kResponseWs]?: WebSocketPonyfill })[kResponseWs]\n if (!ws) throw new TypeError('Response not created by upgradeWebSocket()')\n\n // Create a one time use WebSocketServer to handle the upgrade\n const wss = new WebSocketServer({\n autoPong: true,\n noServer: true,\n clientTracking: false,\n perMessageDeflate: true,\n // @ts-expect-error\n WebSocket: function () {\n // Return the websocket that was created earlier instead of a new instance\n return ws\n },\n })\n\n // Apply headers that might have been set on the response object during\n // handling. This will be called during wss.handleUpgrade().\n wss.on('headers', (headers) => {\n for (const [name, value] of response.headers) {\n headers.push(`${name}: ${value}`)\n }\n })\n\n wss.handleUpgrade(req, req.socket, Buffer.alloc(0), (_socket) => {\n // @TODO find a way to properly \"close\" the _socket when the server is\n // shutting down (might require replacing http-terminator with a local\n // implementation)\n\n req.emit(kUpgradeEvent, ws)\n })\n}\n\n/**\n * Sends a fetch API Response through a Node.js ServerResponse.\n *\n * Handles both regular HTTP responses and WebSocket upgrades. For WebSocket\n * upgrades (status 101), delegates to the WebSocket upgrade handler.\n *\n * This function is used internally by {@link toRequestListener} and\n * {@link createServer}, but can be used directly for custom integrations.\n *\n * @param req - The Node.js IncomingMessage\n * @param res - The Node.js ServerResponse to write to\n * @param response - The fetch API Response to send\n * @throws {TypeError} If headers have already been sent\n *\n * @example\n * ```typescript\n * import http from 'node:http'\n * import { sendResponse } from '@atproto/lex-server/nodejs'\n *\n * const server = http.createServer(async (req, res) => {\n * const response = new Response('Hello, World!', {\n * headers: { 'Content-Type': 'text/plain' }\n * })\n * await sendResponse(req, res, response)\n * })\n * ```\n */\nexport async function sendResponse(\n req: IncomingMessage,\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n // Invalid usage\n if (res.headersSent) {\n throw new TypeError('Response has already been sent')\n }\n\n if (response.status === 101) {\n return handleWebSocketUpgrade(req, response)\n }\n\n res.statusCode = response.status\n res.statusMessage = response.statusText\n\n for (const [key, value] of response.headers) {\n res.setHeader(key, value)\n }\n\n if (response.body != null && req.method !== 'HEAD') {\n const stream = Readable.fromWeb(response.body as NodeReadableStream)\n await pipeline(stream, res)\n } else {\n await response.body?.cancel()\n res.end()\n }\n}\n\nfunction toRequest(req: IncomingMessage): Request {\n const host = req.headers.host ?? req.socket?.localAddress ?? 'localhost'\n const isEncrypted = (req.socket as any).encrypted === true\n const protocol = isEncrypted ? 'https' : 'http'\n const url = new URL(req.url ?? '/', `${protocol}://${host}`)\n const headers = toHeaders(req.headers)\n const body = toBody(req)\n const signal = requestSignal(req)\n\n return new Request(url, {\n signal,\n method: req.method,\n headers,\n body,\n referrer: headers.get('referrer') ?? headers.get('referer') ?? undefined,\n redirect: 'manual',\n // @ts-expect-error\n duplex: body ? 'half' : undefined,\n })\n}\n\nfunction requestSignal(req: IncomingMessage): AbortSignal {\n if (req.destroyed) return AbortSignal.abort()\n\n const abortController = new AbortController()\n\n const abort = (err?: Error | WebSocket) => {\n abortController.abort(err instanceof Error ? err : undefined)\n\n req.off('close', abort)\n req.off('error', abort)\n req.off('end', abort)\n req.off(kUpgradeEvent, abort)\n }\n\n req.on('close', abort)\n req.on('error', abort)\n req.on('end', abort)\n req.on(kUpgradeEvent, abort)\n\n return abortController.signal\n}\n\nfunction requestCompletion(req: IncomingMessage): Promise<void> {\n if (req.destroyed) return Promise.resolve()\n\n // Unlike the abort signal, we complete the promise only when the request\n // is fully done, accounting for websocket upgrade.\n return new Promise((resolve) => {\n const cleanup = () => {\n req.off('close', done)\n req.off('error', done)\n req.off('end', done)\n req.off(kUpgradeEvent, onUpgrade)\n }\n\n const onUpgrade = (ws: WebSocket) => {\n cleanup()\n ws.addEventListener('close', () => resolve())\n }\n\n const done = () => {\n resolve()\n cleanup()\n }\n\n req.on('close', done)\n req.on('error', done)\n req.on('end', done)\n req.on(kUpgradeEvent, onUpgrade)\n })\n}\n\nfunction toHeaders(headers: IncomingHttpHeaders): Headers {\n const result = new Headers()\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue\n if (Array.isArray(value)) {\n for (const v of value) result.append(key, v)\n } else {\n result.set(key, value)\n }\n }\n return result\n}\n\nfunction toBody(req: IncomingMessage): null | ReadableStream {\n if (\n req.method === 'GET' ||\n req.method === 'HEAD' ||\n req.method === 'OPTIONS'\n ) {\n return null\n }\n\n if (\n req.headers['content-type'] == null &&\n req.headers['transfer-encoding'] == null &&\n req.headers['content-length'] == null\n ) {\n return null\n }\n\n return Readable.toWeb(req) as ReadableStream\n}\n\n/**\n * Network address type for Node.js TCP connections.\n *\n * @example\n * ```typescript\n * const addr: NetAddr = {\n * transport: 'tcp',\n * hostname: '192.168.1.100',\n * port: 54321\n * }\n * ```\n */\nexport type NetAddr = {\n /** Always 'tcp' for Node.js HTTP connections. */\n transport: 'tcp'\n /** The IP address of the remote client. */\n hostname: string\n /** The port number of the remote client. */\n port: number\n}\n\n/**\n * Connection metadata for Node.js HTTP requests.\n *\n * Provides information about the client connection, including the remote\n * address and a promise that resolves when the connection is fully closed\n * (including WebSocket connections).\n */\nexport type NodeConnectionInfo = {\n /** Promise that resolves when the connection is fully closed. */\n completed: Promise<void>\n /** The remote address of the client, if available. */\n remoteAddr: NetAddr | undefined\n}\n\n/**\n * Interface for objects that can handle fetch-style requests.\n *\n * Used by {@link createServer} and {@link serve} to accept either\n * a fetch handler function or an object with a `fetch` method\n * (like {@link LexRouter}).\n */\nexport interface HandlerObject {\n /** The fetch handler method. */\n fetch: FetchHandler\n}\n\nasync function handleRequest(\n req: IncomingMessage,\n res: ServerResponse,\n fetchHandler: FetchHandler,\n) {\n const request = toRequest(req)\n const info = toConnectionInfo(req)\n const response = await fetchHandler(request, info)\n await sendResponse(req, res, response)\n}\n\nfunction toConnectionInfo(req: IncomingMessage): NodeConnectionInfo {\n const { socket } = req\n\n return {\n completed: requestCompletion(req),\n remoteAddr:\n socket.remoteAddress != null\n ? {\n transport: 'tcp',\n hostname: socket.remoteAddress,\n port: socket.remotePort!,\n }\n : undefined,\n }\n}\n\n/**\n * Converts a fetch-style handler to a Node.js request listener.\n *\n * The returned listener can be used with Node.js HTTP servers directly,\n * or as middleware in frameworks like Express (supports the `next` callback).\n *\n * @typeParam Request - The request class type (default: IncomingMessage)\n * @typeParam Response - The response class type (default: ServerResponse)\n * @param fetchHandler - The fetch-style handler function\n * @returns A Node.js RequestListener compatible with http.createServer\n *\n * @example Using as Express middleware\n * ```typescript\n * import express from 'express'\n * import { toRequestListener } from '@atproto/lex-server/nodejs'\n * import { LexRouter } from '@atproto/lex-server'\n *\n * const router = new LexRouter()\n * // Register handlers...\n *\n * const app = express()\n *\n * // Mount the XRPC router\n * app.use('/xrpc', toRequestListener(router.fetch))\n * ```\n */\nexport function toRequestListener<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n>(fetchHandler: FetchHandler) {\n return ((\n req: InstanceType<Request>,\n res: InstanceType<Response> & { req: InstanceType<Request> },\n next?: (err?: unknown) => void,\n ): void => {\n handleRequest(req, res, fetchHandler).catch((err) => {\n if (next) next(err)\n else {\n if (!res.headersSent) {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain; charset=utf-8')\n res.end('Internal Server Error')\n } else if (!res.writableEnded) {\n res.destroy()\n }\n }\n })\n }) satisfies RequestListener<Request, Response>\n}\n\n/**\n * Options for creating an XRPC server.\n *\n * Extends Node.js {@link ServerOptions} with additional options for graceful shutdown.\n */\nexport type CreateServerOptions<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n> = ServerOptions<Request, Response> & {\n /**\n * Timeout in milliseconds for graceful termination.\n *\n * When `terminate()` is called, the server will wait up to this duration\n * for active connections to complete before forcibly closing them.\n */\n gracefulTerminationTimeout?: number\n}\n\n/**\n * Extended HTTP server with graceful shutdown support.\n *\n * Extends the standard Node.js HttpServer with a `terminate()` method\n * for graceful shutdown and implements `AsyncDisposable` for use with\n * `await using`.\n *\n * @typeParam Request - The request class type\n * @typeParam Response - The response class type\n *\n * @example Graceful shutdown\n * ```typescript\n * const server = createServer(router)\n * server.listen(3000)\n *\n * process.on('SIGTERM', async () => {\n * console.log('Shutting down...')\n * await server.terminate()\n * console.log('Server stopped')\n * })\n * ```\n *\n * @example Using with await using\n * ```typescript\n * await using server = await serve(router, { port: 3000 })\n * // Server will be automatically terminated when scope exits\n * ```\n */\nexport interface Server<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n> extends HttpServer<Request, Response>,\n AsyncDisposable {\n /**\n * Gracefully terminates the server.\n *\n * Stops accepting new connections and waits for active connections\n * to complete (up to `gracefulTerminationTimeout`).\n *\n * @returns Promise that resolves when the server is fully stopped\n */\n terminate(): Promise<void>\n [Symbol.asyncDispose](): Promise<void>\n}\n\n/**\n * Creates an HTTP server configured for XRPC request handling.\n *\n * The server includes graceful shutdown support and can be used with\n * either a fetch handler function or an object with a `fetch` method\n * (like {@link LexRouter}).\n *\n * Note: This creates the server but does not start listening. Call\n * `server.listen()` to start the server, or use {@link serve} for\n * a combined create-and-listen operation.\n *\n * @typeParam Request - The request class type\n * @typeParam Response - The response class type\n * @param handler - A fetch handler or object with fetch method\n * @param options - Server configuration options\n * @returns An HTTP server with graceful shutdown support\n *\n * @example Basic usage\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { createServer, upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n * router.add(myMethod, myHandler)\n *\n * const server = createServer(router)\n * server.listen(3000, () => {\n * console.log('Server listening on port 3000')\n * })\n * ```\n *\n * @example With graceful termination timeout\n * ```typescript\n * const server = createServer(router, {\n * gracefulTerminationTimeout: 10000 // 10 seconds\n * })\n * ```\n */\nexport function createServer<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n>(\n handler: FetchHandler | HandlerObject,\n options: CreateServerOptions<Request, Response> = {},\n): Server<Request, Response> {\n const fetchHandler =\n typeof handler === 'function' ? handler : handler.fetch.bind(handler)\n\n const listener = toRequestListener(fetchHandler)\n const server = createHttpServer(options, listener)\n\n const terminator = createHttpTerminator({\n server: server as HttpServer,\n gracefulTerminationTimeout: options?.gracefulTerminationTimeout,\n })\n\n const terminate = async function terminate(this: Server<Request, Response>) {\n if (this !== server) {\n throw new TypeError('Server.terminate called with incorrect context')\n }\n // @TODO properly close all active WebSocket connections\n return terminator.terminate()\n }\n\n Object.defineProperty(server, 'terminate', {\n value: terminate,\n enumerable: false,\n configurable: false,\n writable: false,\n })\n\n Object.defineProperty(server, Symbol.asyncDispose, {\n value: terminate,\n enumerable: false,\n configurable: false,\n writable: false,\n })\n\n return server as Server<Request, Response>\n}\n\n/**\n * Combined options for creating and starting an XRPC server.\n *\n * Includes both server creation options and network listen options.\n *\n * @typeParam Request - The request class type\n * @typeParam Response - The response class type\n *\n * @example\n * ```typescript\n * const options: StartServerOptions = {\n * port: 3000,\n * host: '0.0.0.0',\n * gracefulTerminationTimeout: 10000\n * }\n * ```\n */\nexport type StartServerOptions<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n> = ListenOptions & CreateServerOptions<Request, Response>\n\n/**\n * Creates and starts an HTTP server, returning when it's ready to accept connections.\n *\n * This is a convenience function that combines {@link createServer} and `server.listen()`\n * into a single async operation. The returned promise resolves once the server\n * is actively listening.\n *\n * @typeParam Request - The request class type\n * @typeParam Response - The response class type\n * @param handler - A fetch handler or object with fetch method (like {@link LexRouter})\n * @param options - Combined server and listen options\n * @returns Promise resolving to the running server\n *\n * @example Basic usage\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n *\n * // Register handlers\n * router.add(getProfile, async (ctx) => {\n * return { body: await db.getProfile(ctx.params.actor) }\n * })\n *\n * // Start server on port 3000\n * const server = await serve(router, { port: 3000 })\n * console.log('Server listening on port 3000')\n *\n * // Graceful shutdown\n * process.on('SIGTERM', () => server.terminate())\n * process.on('SIGINT', () => server.terminate())\n * ```\n *\n * @example With all options\n * ```typescript\n * const server = await serve(router, {\n * port: 3000,\n * host: '0.0.0.0',\n * gracefulTerminationTimeout: 15000,\n * })\n * ```\n *\n * @example Using with await using (auto-cleanup)\n * ```typescript\n * async function main() {\n * await using server = await serve(router, { port: 3000 })\n *\n * // Server is running...\n * console.log('Server listening on port 3000')\n *\n * // Wait for termination signal\n * await Promise.race([\n * once(process, 'SIGINT'),\n * once(process, 'SIGTERM'),\n * ])\n *\n * // Server will be automatically terminated when scope exits\n * }\n * ```\n */\nexport async function serve<\n Request extends typeof IncomingMessage = typeof IncomingMessage,\n Response extends typeof ServerResponse<\n InstanceType<Request>\n > = typeof ServerResponse,\n>(\n handler: FetchHandler | HandlerObject,\n options?: StartServerOptions<Request, Response>,\n): Promise<Server<Request, Response>> {\n const server = createServer(handler, options)\n server.listen(options)\n await once(server, 'listening')\n return server\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/lex-server",
3
- "version": "0.0.9",
3
+ "version": "0.0.11",
4
4
  "license": "MIT",
5
5
  "description": "Request router for Atproto Lexicon protocols and schemas",
6
6
  "keywords": [
@@ -48,17 +48,17 @@
48
48
  "@atproto-labs/did-resolver": "^0.2.6",
49
49
  "@atproto/crypto": "^0.4.5",
50
50
  "@atproto/did": "^0.3.0",
51
- "@atproto/lex-cbor": "^0.0.11",
52
- "@atproto/lex-data": "^0.0.11",
53
- "@atproto/lex-json": "^0.0.11",
54
- "@atproto/lex-schema": "^0.0.12"
51
+ "@atproto/lex-cbor": "^0.0.13",
52
+ "@atproto/lex-data": "^0.0.12",
53
+ "@atproto/lex-json": "^0.0.12",
54
+ "@atproto/lex-schema": "^0.0.13"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@types/ws": "^8.18.1",
58
58
  "@vitest/coverage-v8": "4.0.16",
59
59
  "vitest": "^4.0.16",
60
- "@atproto/lex": "^0.0.15",
61
- "@atproto/lex-client": "^0.0.12"
60
+ "@atproto/lex": "^0.0.18",
61
+ "@atproto/lex-client": "^0.0.13"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "tsc --build tsconfig.build.json",
package/src/lex-server.ts CHANGED
@@ -676,7 +676,9 @@ export class LexRouter {
676
676
 
677
677
  try {
678
678
  const url = new URL(request.url)
679
- const params = method.parameters.fromURLSearchParams(url.searchParams)
679
+ const params = method.parameters.fromURLSearchParams(
680
+ url.searchParams,
681
+ ) as InferMethodParams<Method>
680
682
 
681
683
  const credentials = auth
682
684
  ? await auth({ method, params, request, connection })
@@ -798,7 +800,7 @@ export class LexRouter {
798
800
  const url = new URL(request.url)
799
801
  const params = method.parameters.fromURLSearchParams(
800
802
  url.searchParams,
801
- )
803
+ ) as InferMethodParams<Method>
802
804
 
803
805
  const credentials: Credentials = auth
804
806
  ? await auth({ method, params, request, connection })
package/src/nodejs.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  import { ListenOptions } from 'node:net'
12
12
  import { Readable } from 'node:stream'
13
13
  import { pipeline } from 'node:stream/promises'
14
+ import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
14
15
  import { createHttpTerminator } from 'http-terminator'
15
16
  import { WebSocket as WebSocketPonyfill, WebSocketServer } from 'ws'
16
17
  import { FetchHandler } from './lex-server.js'
@@ -185,7 +186,7 @@ export async function sendResponse(
185
186
  }
186
187
 
187
188
  if (response.body != null && req.method !== 'HEAD') {
188
- const stream = Readable.fromWeb(response.body as any)
189
+ const stream = Readable.fromWeb(response.body as NodeReadableStream)
189
190
  await pipeline(stream, res)
190
191
  } else {
191
192
  await response.body?.cancel()
@@ -279,7 +280,7 @@ function toHeaders(headers: IncomingHttpHeaders): Headers {
279
280
  return result
280
281
  }
281
282
 
282
- function toBody(req: IncomingMessage): null | ReadableStream<Uint8Array> {
283
+ function toBody(req: IncomingMessage): null | ReadableStream {
283
284
  if (
284
285
  req.method === 'GET' ||
285
286
  req.method === 'HEAD' ||
@@ -296,7 +297,7 @@ function toBody(req: IncomingMessage): null | ReadableStream<Uint8Array> {
296
297
  return null
297
298
  }
298
299
 
299
- return Readable.toWeb(req) as ReadableStream<Uint8Array>
300
+ return Readable.toWeb(req) as ReadableStream
300
301
  }
301
302
 
302
303
  /**