@atproto/lex-server 0.0.8 → 0.0.9

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/dist/nodejs.d.ts CHANGED
@@ -1,34 +1,312 @@
1
1
  import { IncomingMessage, Server as HttpServer, ServerOptions, ServerResponse } from 'node:http';
2
2
  import { ListenOptions } from 'node:net';
3
3
  import { FetchHandler } from './lex-server.js';
4
+ /**
5
+ * Upgrades an HTTP request to a WebSocket connection for Node.js.
6
+ *
7
+ * This function must be passed to the {@link LexRouter} constructor to enable
8
+ * subscription (WebSocket) support on Node.js. It creates a WebSocket instance
9
+ * and a placeholder response that signals the need for protocol upgrade.
10
+ *
11
+ * The actual upgrade is handled internally when the response is sent through
12
+ * {@link sendResponse}.
13
+ *
14
+ * @param request - The incoming HTTP request to upgrade
15
+ * @returns An object containing the WebSocket and upgrade response
16
+ * @throws {TypeError} If the request is not a valid WebSocket upgrade request
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * import { LexRouter } from '@atproto/lex-server'
21
+ * import { upgradeWebSocket } from '@atproto/lex-server/nodejs'
22
+ *
23
+ * // Pass to router for subscription support
24
+ * const router = new LexRouter({ upgradeWebSocket })
25
+ *
26
+ * // Now you can add subscription handlers
27
+ * router.add(subscribeRepos, async function* (ctx) {
28
+ * for await (const event of eventStream) {
29
+ * yield event
30
+ * }
31
+ * })
32
+ * ```
33
+ */
4
34
  export declare function upgradeWebSocket(request: Request): {
5
35
  response: Response;
6
36
  socket: WebSocket;
7
37
  };
38
+ /**
39
+ * Sends a fetch API Response through a Node.js ServerResponse.
40
+ *
41
+ * Handles both regular HTTP responses and WebSocket upgrades. For WebSocket
42
+ * upgrades (status 101), delegates to the WebSocket upgrade handler.
43
+ *
44
+ * This function is used internally by {@link toRequestListener} and
45
+ * {@link createServer}, but can be used directly for custom integrations.
46
+ *
47
+ * @param req - The Node.js IncomingMessage
48
+ * @param res - The Node.js ServerResponse to write to
49
+ * @param response - The fetch API Response to send
50
+ * @throws {TypeError} If headers have already been sent
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * import http from 'node:http'
55
+ * import { sendResponse } from '@atproto/lex-server/nodejs'
56
+ *
57
+ * const server = http.createServer(async (req, res) => {
58
+ * const response = new Response('Hello, World!', {
59
+ * headers: { 'Content-Type': 'text/plain' }
60
+ * })
61
+ * await sendResponse(req, res, response)
62
+ * })
63
+ * ```
64
+ */
8
65
  export declare function sendResponse(req: IncomingMessage, res: ServerResponse, response: Response): Promise<void>;
66
+ /**
67
+ * Network address type for Node.js TCP connections.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const addr: NetAddr = {
72
+ * transport: 'tcp',
73
+ * hostname: '192.168.1.100',
74
+ * port: 54321
75
+ * }
76
+ * ```
77
+ */
9
78
  export type NetAddr = {
79
+ /** Always 'tcp' for Node.js HTTP connections. */
10
80
  transport: 'tcp';
81
+ /** The IP address of the remote client. */
11
82
  hostname: string;
83
+ /** The port number of the remote client. */
12
84
  port: number;
13
85
  };
86
+ /**
87
+ * Connection metadata for Node.js HTTP requests.
88
+ *
89
+ * Provides information about the client connection, including the remote
90
+ * address and a promise that resolves when the connection is fully closed
91
+ * (including WebSocket connections).
92
+ */
14
93
  export type NodeConnectionInfo = {
94
+ /** Promise that resolves when the connection is fully closed. */
15
95
  completed: Promise<void>;
96
+ /** The remote address of the client, if available. */
16
97
  remoteAddr: NetAddr | undefined;
17
98
  };
99
+ /**
100
+ * Interface for objects that can handle fetch-style requests.
101
+ *
102
+ * Used by {@link createServer} and {@link serve} to accept either
103
+ * a fetch handler function or an object with a `fetch` method
104
+ * (like {@link LexRouter}).
105
+ */
18
106
  export interface HandlerObject {
107
+ /** The fetch handler method. */
19
108
  fetch: FetchHandler;
20
109
  }
110
+ /**
111
+ * Converts a fetch-style handler to a Node.js request listener.
112
+ *
113
+ * The returned listener can be used with Node.js HTTP servers directly,
114
+ * or as middleware in frameworks like Express (supports the `next` callback).
115
+ *
116
+ * @typeParam Request - The request class type (default: IncomingMessage)
117
+ * @typeParam Response - The response class type (default: ServerResponse)
118
+ * @param fetchHandler - The fetch-style handler function
119
+ * @returns A Node.js RequestListener compatible with http.createServer
120
+ *
121
+ * @example Using as Express middleware
122
+ * ```typescript
123
+ * import express from 'express'
124
+ * import { toRequestListener } from '@atproto/lex-server/nodejs'
125
+ * import { LexRouter } from '@atproto/lex-server'
126
+ *
127
+ * const router = new LexRouter()
128
+ * // Register handlers...
129
+ *
130
+ * const app = express()
131
+ *
132
+ * // Mount the XRPC router
133
+ * app.use('/xrpc', toRequestListener(router.fetch))
134
+ * ```
135
+ */
21
136
  export declare function toRequestListener<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse>(fetchHandler: FetchHandler): (req: InstanceType<Request>, res: InstanceType<Response> & {
22
137
  req: InstanceType<Request>;
23
138
  }, next?: (err?: unknown) => void) => void;
139
+ /**
140
+ * Options for creating an XRPC server.
141
+ *
142
+ * Extends Node.js {@link ServerOptions} with additional options for graceful shutdown.
143
+ */
24
144
  export type CreateServerOptions<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse> = ServerOptions<Request, Response> & {
145
+ /**
146
+ * Timeout in milliseconds for graceful termination.
147
+ *
148
+ * When `terminate()` is called, the server will wait up to this duration
149
+ * for active connections to complete before forcibly closing them.
150
+ */
25
151
  gracefulTerminationTimeout?: number;
26
152
  };
153
+ /**
154
+ * Extended HTTP server with graceful shutdown support.
155
+ *
156
+ * Extends the standard Node.js HttpServer with a `terminate()` method
157
+ * for graceful shutdown and implements `AsyncDisposable` for use with
158
+ * `await using`.
159
+ *
160
+ * @typeParam Request - The request class type
161
+ * @typeParam Response - The response class type
162
+ *
163
+ * @example Graceful shutdown
164
+ * ```typescript
165
+ * const server = createServer(router)
166
+ * server.listen(3000)
167
+ *
168
+ * process.on('SIGTERM', async () => {
169
+ * console.log('Shutting down...')
170
+ * await server.terminate()
171
+ * console.log('Server stopped')
172
+ * })
173
+ * ```
174
+ *
175
+ * @example Using with await using
176
+ * ```typescript
177
+ * await using server = await serve(router, { port: 3000 })
178
+ * // Server will be automatically terminated when scope exits
179
+ * ```
180
+ */
27
181
  export interface Server<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse> extends HttpServer<Request, Response>, AsyncDisposable {
182
+ /**
183
+ * Gracefully terminates the server.
184
+ *
185
+ * Stops accepting new connections and waits for active connections
186
+ * to complete (up to `gracefulTerminationTimeout`).
187
+ *
188
+ * @returns Promise that resolves when the server is fully stopped
189
+ */
28
190
  terminate(): Promise<void>;
29
191
  [Symbol.asyncDispose](): Promise<void>;
30
192
  }
193
+ /**
194
+ * Creates an HTTP server configured for XRPC request handling.
195
+ *
196
+ * The server includes graceful shutdown support and can be used with
197
+ * either a fetch handler function or an object with a `fetch` method
198
+ * (like {@link LexRouter}).
199
+ *
200
+ * Note: This creates the server but does not start listening. Call
201
+ * `server.listen()` to start the server, or use {@link serve} for
202
+ * a combined create-and-listen operation.
203
+ *
204
+ * @typeParam Request - The request class type
205
+ * @typeParam Response - The response class type
206
+ * @param handler - A fetch handler or object with fetch method
207
+ * @param options - Server configuration options
208
+ * @returns An HTTP server with graceful shutdown support
209
+ *
210
+ * @example Basic usage
211
+ * ```typescript
212
+ * import { LexRouter } from '@atproto/lex-server'
213
+ * import { createServer, upgradeWebSocket } from '@atproto/lex-server/nodejs'
214
+ *
215
+ * const router = new LexRouter({ upgradeWebSocket })
216
+ * router.add(myMethod, myHandler)
217
+ *
218
+ * const server = createServer(router)
219
+ * server.listen(3000, () => {
220
+ * console.log('Server listening on port 3000')
221
+ * })
222
+ * ```
223
+ *
224
+ * @example With graceful termination timeout
225
+ * ```typescript
226
+ * const server = createServer(router, {
227
+ * gracefulTerminationTimeout: 10000 // 10 seconds
228
+ * })
229
+ * ```
230
+ */
31
231
  export declare function createServer<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse>(handler: FetchHandler | HandlerObject, options?: CreateServerOptions<Request, Response>): Server<Request, Response>;
232
+ /**
233
+ * Combined options for creating and starting an XRPC server.
234
+ *
235
+ * Includes both server creation options and network listen options.
236
+ *
237
+ * @typeParam Request - The request class type
238
+ * @typeParam Response - The response class type
239
+ *
240
+ * @example
241
+ * ```typescript
242
+ * const options: StartServerOptions = {
243
+ * port: 3000,
244
+ * host: '0.0.0.0',
245
+ * gracefulTerminationTimeout: 10000
246
+ * }
247
+ * ```
248
+ */
32
249
  export type StartServerOptions<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse> = ListenOptions & CreateServerOptions<Request, Response>;
250
+ /**
251
+ * Creates and starts an HTTP server, returning when it's ready to accept connections.
252
+ *
253
+ * This is a convenience function that combines {@link createServer} and `server.listen()`
254
+ * into a single async operation. The returned promise resolves once the server
255
+ * is actively listening.
256
+ *
257
+ * @typeParam Request - The request class type
258
+ * @typeParam Response - The response class type
259
+ * @param handler - A fetch handler or object with fetch method (like {@link LexRouter})
260
+ * @param options - Combined server and listen options
261
+ * @returns Promise resolving to the running server
262
+ *
263
+ * @example Basic usage
264
+ * ```typescript
265
+ * import { LexRouter } from '@atproto/lex-server'
266
+ * import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'
267
+ *
268
+ * const router = new LexRouter({ upgradeWebSocket })
269
+ *
270
+ * // Register handlers
271
+ * router.add(getProfile, async (ctx) => {
272
+ * return { body: await db.getProfile(ctx.params.actor) }
273
+ * })
274
+ *
275
+ * // Start server on port 3000
276
+ * const server = await serve(router, { port: 3000 })
277
+ * console.log('Server listening on port 3000')
278
+ *
279
+ * // Graceful shutdown
280
+ * process.on('SIGTERM', () => server.terminate())
281
+ * process.on('SIGINT', () => server.terminate())
282
+ * ```
283
+ *
284
+ * @example With all options
285
+ * ```typescript
286
+ * const server = await serve(router, {
287
+ * port: 3000,
288
+ * host: '0.0.0.0',
289
+ * gracefulTerminationTimeout: 15000,
290
+ * })
291
+ * ```
292
+ *
293
+ * @example Using with await using (auto-cleanup)
294
+ * ```typescript
295
+ * async function main() {
296
+ * await using server = await serve(router, { port: 3000 })
297
+ *
298
+ * // Server is running...
299
+ * console.log('Server listening on port 3000')
300
+ *
301
+ * // Wait for termination signal
302
+ * await Promise.race([
303
+ * once(process, 'SIGINT'),
304
+ * once(process, 'SIGTERM'),
305
+ * ])
306
+ *
307
+ * // Server will be automatically terminated when scope exits
308
+ * }
309
+ * ```
310
+ */
33
311
  export declare function serve<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse>(handler: FetchHandler | HandlerObject, options?: StartServerOptions<Request, Response>): Promise<Server<Request, Response>>;
34
312
  //# sourceMappingURL=nodejs.d.ts.map
@@ -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;AAKxC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAe9C,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,GAAG;IAClD,QAAQ,EAAE,QAAQ,CAAA;IAClB,MAAM,EAAE,SAAS,CAAA;CAClB,CAkCA;AAyCD,wBAAsB,YAAY,CAChC,GAAG,EAAE,eAAe,EACpB,GAAG,EAAE,cAAc,EACnB,QAAQ,EAAE,QAAQ,GACjB,OAAO,CAAC,IAAI,CAAC,CAwBf;AA4GD,MAAM,MAAM,OAAO,GAAG;IACpB,SAAS,EAAE,KAAK,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;CACb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;;;;;;;;;GA4DG;AACH,wBAAsB,KAAK,CACzB,OAAO,SAAS,OAAO,eAAe,GAAG,OAAO,eAAe,EAC/D,QAAQ,SAAS,OAAO,cAAc,CACpC,YAAY,CAAC,OAAO,CAAC,CACtB,GAAG,OAAO,cAAc,EAEzB,OAAO,EAAE,YAAY,GAAG,aAAa,EACrC,OAAO,CAAC,EAAE,kBAAkB,CAAC,OAAO,EAAE,QAAQ,CAAC,GAC9C,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAKpC"}
package/dist/nodejs.js CHANGED
@@ -19,6 +19,36 @@ function isUpgradeRequest(request, upgrade) {
19
19
  request.headers.get('connection')?.toLowerCase() === 'upgrade' &&
20
20
  request.headers.get('upgrade')?.toLowerCase() === upgrade);
21
21
  }
22
+ /**
23
+ * Upgrades an HTTP request to a WebSocket connection for Node.js.
24
+ *
25
+ * This function must be passed to the {@link LexRouter} constructor to enable
26
+ * subscription (WebSocket) support on Node.js. It creates a WebSocket instance
27
+ * and a placeholder response that signals the need for protocol upgrade.
28
+ *
29
+ * The actual upgrade is handled internally when the response is sent through
30
+ * {@link sendResponse}.
31
+ *
32
+ * @param request - The incoming HTTP request to upgrade
33
+ * @returns An object containing the WebSocket and upgrade response
34
+ * @throws {TypeError} If the request is not a valid WebSocket upgrade request
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * import { LexRouter } from '@atproto/lex-server'
39
+ * import { upgradeWebSocket } from '@atproto/lex-server/nodejs'
40
+ *
41
+ * // Pass to router for subscription support
42
+ * const router = new LexRouter({ upgradeWebSocket })
43
+ *
44
+ * // Now you can add subscription handlers
45
+ * router.add(subscribeRepos, async function* (ctx) {
46
+ * for await (const event of eventStream) {
47
+ * yield event
48
+ * }
49
+ * })
50
+ * ```
51
+ */
22
52
  function upgradeWebSocket(request) {
23
53
  if (!isUpgradeRequest(request, 'websocket')) {
24
54
  throw new TypeError('upgradeWebSocket() expects a WebSocket upgrade');
@@ -80,6 +110,33 @@ function handleWebSocketUpgrade(req, response) {
80
110
  req.emit(kUpgradeEvent, ws);
81
111
  });
82
112
  }
113
+ /**
114
+ * Sends a fetch API Response through a Node.js ServerResponse.
115
+ *
116
+ * Handles both regular HTTP responses and WebSocket upgrades. For WebSocket
117
+ * upgrades (status 101), delegates to the WebSocket upgrade handler.
118
+ *
119
+ * This function is used internally by {@link toRequestListener} and
120
+ * {@link createServer}, but can be used directly for custom integrations.
121
+ *
122
+ * @param req - The Node.js IncomingMessage
123
+ * @param res - The Node.js ServerResponse to write to
124
+ * @param response - The fetch API Response to send
125
+ * @throws {TypeError} If headers have already been sent
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * import http from 'node:http'
130
+ * import { sendResponse } from '@atproto/lex-server/nodejs'
131
+ *
132
+ * const server = http.createServer(async (req, res) => {
133
+ * const response = new Response('Hello, World!', {
134
+ * headers: { 'Content-Type': 'text/plain' }
135
+ * })
136
+ * await sendResponse(req, res, response)
137
+ * })
138
+ * ```
139
+ */
83
140
  async function sendResponse(req, res, response) {
84
141
  // Invalid usage
85
142
  if (res.headersSent) {
@@ -211,6 +268,32 @@ function toConnectionInfo(req) {
211
268
  : undefined,
212
269
  };
213
270
  }
271
+ /**
272
+ * Converts a fetch-style handler to a Node.js request listener.
273
+ *
274
+ * The returned listener can be used with Node.js HTTP servers directly,
275
+ * or as middleware in frameworks like Express (supports the `next` callback).
276
+ *
277
+ * @typeParam Request - The request class type (default: IncomingMessage)
278
+ * @typeParam Response - The response class type (default: ServerResponse)
279
+ * @param fetchHandler - The fetch-style handler function
280
+ * @returns A Node.js RequestListener compatible with http.createServer
281
+ *
282
+ * @example Using as Express middleware
283
+ * ```typescript
284
+ * import express from 'express'
285
+ * import { toRequestListener } from '@atproto/lex-server/nodejs'
286
+ * import { LexRouter } from '@atproto/lex-server'
287
+ *
288
+ * const router = new LexRouter()
289
+ * // Register handlers...
290
+ *
291
+ * const app = express()
292
+ *
293
+ * // Mount the XRPC router
294
+ * app.use('/xrpc', toRequestListener(router.fetch))
295
+ * ```
296
+ */
214
297
  function toRequestListener(fetchHandler) {
215
298
  return ((req, res, next) => {
216
299
  handleRequest(req, res, fetchHandler).catch((err) => {
@@ -229,6 +312,44 @@ function toRequestListener(fetchHandler) {
229
312
  });
230
313
  });
231
314
  }
315
+ /**
316
+ * Creates an HTTP server configured for XRPC request handling.
317
+ *
318
+ * The server includes graceful shutdown support and can be used with
319
+ * either a fetch handler function or an object with a `fetch` method
320
+ * (like {@link LexRouter}).
321
+ *
322
+ * Note: This creates the server but does not start listening. Call
323
+ * `server.listen()` to start the server, or use {@link serve} for
324
+ * a combined create-and-listen operation.
325
+ *
326
+ * @typeParam Request - The request class type
327
+ * @typeParam Response - The response class type
328
+ * @param handler - A fetch handler or object with fetch method
329
+ * @param options - Server configuration options
330
+ * @returns An HTTP server with graceful shutdown support
331
+ *
332
+ * @example Basic usage
333
+ * ```typescript
334
+ * import { LexRouter } from '@atproto/lex-server'
335
+ * import { createServer, upgradeWebSocket } from '@atproto/lex-server/nodejs'
336
+ *
337
+ * const router = new LexRouter({ upgradeWebSocket })
338
+ * router.add(myMethod, myHandler)
339
+ *
340
+ * const server = createServer(router)
341
+ * server.listen(3000, () => {
342
+ * console.log('Server listening on port 3000')
343
+ * })
344
+ * ```
345
+ *
346
+ * @example With graceful termination timeout
347
+ * ```typescript
348
+ * const server = createServer(router, {
349
+ * gracefulTerminationTimeout: 10000 // 10 seconds
350
+ * })
351
+ * ```
352
+ */
232
353
  function createServer(handler, options = {}) {
233
354
  const fetchHandler = typeof handler === 'function' ? handler : handler.fetch.bind(handler);
234
355
  const listener = toRequestListener(fetchHandler);
@@ -258,6 +379,67 @@ function createServer(handler, options = {}) {
258
379
  });
259
380
  return server;
260
381
  }
382
+ /**
383
+ * Creates and starts an HTTP server, returning when it's ready to accept connections.
384
+ *
385
+ * This is a convenience function that combines {@link createServer} and `server.listen()`
386
+ * into a single async operation. The returned promise resolves once the server
387
+ * is actively listening.
388
+ *
389
+ * @typeParam Request - The request class type
390
+ * @typeParam Response - The response class type
391
+ * @param handler - A fetch handler or object with fetch method (like {@link LexRouter})
392
+ * @param options - Combined server and listen options
393
+ * @returns Promise resolving to the running server
394
+ *
395
+ * @example Basic usage
396
+ * ```typescript
397
+ * import { LexRouter } from '@atproto/lex-server'
398
+ * import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'
399
+ *
400
+ * const router = new LexRouter({ upgradeWebSocket })
401
+ *
402
+ * // Register handlers
403
+ * router.add(getProfile, async (ctx) => {
404
+ * return { body: await db.getProfile(ctx.params.actor) }
405
+ * })
406
+ *
407
+ * // Start server on port 3000
408
+ * const server = await serve(router, { port: 3000 })
409
+ * console.log('Server listening on port 3000')
410
+ *
411
+ * // Graceful shutdown
412
+ * process.on('SIGTERM', () => server.terminate())
413
+ * process.on('SIGINT', () => server.terminate())
414
+ * ```
415
+ *
416
+ * @example With all options
417
+ * ```typescript
418
+ * const server = await serve(router, {
419
+ * port: 3000,
420
+ * host: '0.0.0.0',
421
+ * gracefulTerminationTimeout: 15000,
422
+ * })
423
+ * ```
424
+ *
425
+ * @example Using with await using (auto-cleanup)
426
+ * ```typescript
427
+ * async function main() {
428
+ * await using server = await serve(router, { port: 3000 })
429
+ *
430
+ * // Server is running...
431
+ * console.log('Server listening on port 3000')
432
+ *
433
+ * // Wait for termination signal
434
+ * await Promise.race([
435
+ * once(process, 'SIGINT'),
436
+ * once(process, 'SIGTERM'),
437
+ * ])
438
+ *
439
+ * // Server will be automatically terminated when scope exits
440
+ * }
441
+ * ```
442
+ */
261
443
  async function serve(handler, options) {
262
444
  const server = createServer(handler, options);
263
445
  server.listen(options);
@@ -1 +1 @@
1
- {"version":3,"file":"nodejs.js","sourceRoot":"","sources":["../src/nodejs.ts"],"names":[],"mappings":";;AA8BA,4CAqCC;AAyCD,oCA4BC;AAsJD,8CAwBC;AAsBD,oCA2CC;AASD,sBAaC;AA7YD,6CAAkC;AAClC,yCAQkB;AAElB,6CAAsC;AACtC,mD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AAA;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\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\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\nexport type NetAddr = {\n transport: 'tcp'\n hostname: string\n port: number\n}\n\nexport type NodeConnectionInfo = {\n completed: Promise<void>\n remoteAddr: NetAddr | undefined\n}\n\nexport interface HandlerObject {\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\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\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 gracefulTerminationTimeout?: number\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 terminate(): Promise<void>\n [Symbol.asyncDispose](): Promise<void>\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\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\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":";;AA4DA,4CAqCC;AAoED,oCA4BC;AAgND,8CAwBC;AA2GD,oCA2CC;AAuFD,sBAaC;AAnqBD,6CAAkC;AAClC,yCAQkB;AAElB,6CAAsC;AACtC,mDAA+C;AAC/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,C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AA;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"]}