@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/CHANGELOG.md +16 -0
- package/dist/errors.d.ts +94 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +94 -0
- package/dist/errors.js.map +1 -1
- package/dist/lex-server.d.ts +479 -0
- package/dist/lex-server.d.ts.map +1 -1
- package/dist/lex-server.js +103 -0
- package/dist/lex-server.js.map +1 -1
- package/dist/lib/www-authenticate.d.ts +66 -0
- package/dist/lib/www-authenticate.d.ts.map +1 -1
- package/dist/lib/www-authenticate.js +28 -0
- package/dist/lib/www-authenticate.js.map +1 -1
- package/dist/nodejs.d.ts +278 -0
- package/dist/nodejs.d.ts.map +1 -1
- package/dist/nodejs.js +182 -0
- package/dist/nodejs.js.map +1 -1
- package/dist/service-auth.d.ts +151 -9
- package/dist/service-auth.d.ts.map +1 -1
- package/dist/service-auth.js +41 -2
- package/dist/service-auth.js.map +1 -1
- package/package.json +8 -8
- package/src/errors.ts +94 -0
- package/src/lex-server.test.ts +3 -2
- package/src/lex-server.ts +480 -0
- package/src/lib/www-authenticate.ts +66 -0
- package/src/nodejs.ts +278 -0
- package/src/service-auth.ts +151 -9
package/dist/lex-server.d.ts
CHANGED
|
@@ -1,83 +1,562 @@
|
|
|
1
1
|
import { InferMethodInput, InferMethodMessage, InferMethodOutput, InferMethodOutputBody, InferMethodOutputEncoding, InferMethodParams, Main, NsidString, Procedure, Query, Subscription } from '@atproto/lex-schema';
|
|
2
2
|
type Awaitable<T> = T | Promise<T>;
|
|
3
|
+
/**
|
|
4
|
+
* Union type representing the supported Lexicon method types.
|
|
5
|
+
*
|
|
6
|
+
* - `Query`: Read-only methods invoked via HTTP GET
|
|
7
|
+
* - `Procedure`: Methods that may modify state, invoked via HTTP POST
|
|
8
|
+
* - `Subscription`: Real-time streaming methods over WebSocket
|
|
9
|
+
*/
|
|
3
10
|
export type LexMethod = Query | Procedure | Subscription;
|
|
11
|
+
/**
|
|
12
|
+
* Network address for TCP or UDP connections.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* const addr: NetAddr = {
|
|
17
|
+
* hostname: '127.0.0.1',
|
|
18
|
+
* port: 3000,
|
|
19
|
+
* transport: 'tcp'
|
|
20
|
+
* }
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
4
23
|
export type NetAddr = {
|
|
24
|
+
/** The hostname or IP address of the connection. */
|
|
5
25
|
hostname: string;
|
|
26
|
+
/** The port number of the connection. */
|
|
6
27
|
port: number;
|
|
28
|
+
/** The transport protocol used. */
|
|
7
29
|
transport: 'tcp' | 'udp';
|
|
8
30
|
};
|
|
31
|
+
/**
|
|
32
|
+
* Unix domain socket address.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```typescript
|
|
36
|
+
* const addr: UnixAddr = {
|
|
37
|
+
* path: '/var/run/app.sock',
|
|
38
|
+
* transport: 'unix'
|
|
39
|
+
* }
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
9
42
|
export type UnixAddr = {
|
|
43
|
+
/** The filesystem path to the Unix socket. */
|
|
10
44
|
path: string;
|
|
45
|
+
/** The transport protocol used. */
|
|
11
46
|
transport: 'unix' | 'unixpacket';
|
|
12
47
|
};
|
|
48
|
+
/**
|
|
49
|
+
* Union type for all supported address types.
|
|
50
|
+
*
|
|
51
|
+
* Can be a network address ({@link NetAddr}), Unix socket address ({@link UnixAddr}),
|
|
52
|
+
* or `undefined` when the address is not available.
|
|
53
|
+
*/
|
|
13
54
|
export type Addr = NetAddr | UnixAddr | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* Metadata about the client connection for an incoming request.
|
|
57
|
+
*
|
|
58
|
+
* @typeParam A - The address type, defaults to {@link Addr}
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```typescript
|
|
62
|
+
* const info: ConnectionInfo<NetAddr> = {
|
|
63
|
+
* remoteAddr: { hostname: '192.168.1.1', port: 54321, transport: 'tcp' },
|
|
64
|
+
* completed: new Promise((resolve) => socket.on('close', resolve))
|
|
65
|
+
* }
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
14
68
|
export type ConnectionInfo<A extends Addr = Addr> = {
|
|
69
|
+
/** The remote address of the client, if available. */
|
|
15
70
|
remoteAddr: A;
|
|
71
|
+
/** Promise that resolves when the connection is fully closed. */
|
|
16
72
|
completed: Promise<void>;
|
|
17
73
|
};
|
|
74
|
+
/**
|
|
75
|
+
* Function signature for handling HTTP requests in the XRPC router.
|
|
76
|
+
*
|
|
77
|
+
* This is the standard fetch-style handler that processes incoming requests
|
|
78
|
+
* and returns responses. It is used both internally by the router and can
|
|
79
|
+
* be used to integrate with other HTTP frameworks.
|
|
80
|
+
*
|
|
81
|
+
* @param request - The incoming HTTP request
|
|
82
|
+
* @param connection - Optional connection metadata including remote address
|
|
83
|
+
* @returns A promise resolving to the HTTP response
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```typescript
|
|
87
|
+
* const handler: FetchHandler = async (request, connection) => {
|
|
88
|
+
* console.log('Request from:', connection?.remoteAddr)
|
|
89
|
+
* return new Response('Hello, World!')
|
|
90
|
+
* }
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
18
93
|
export type FetchHandler = (request: Request, connection?: ConnectionInfo) => Promise<Response>;
|
|
94
|
+
/**
|
|
95
|
+
* Context object passed to XRPC method handlers.
|
|
96
|
+
*
|
|
97
|
+
* Contains all the information needed to process a request, including
|
|
98
|
+
* parsed parameters, authentication credentials, and the raw request object.
|
|
99
|
+
*
|
|
100
|
+
* @typeParam Method - The Lexicon method type (Query, Procedure, or Subscription)
|
|
101
|
+
* @typeParam Credentials - The type of authentication credentials, determined by the auth handler
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```typescript
|
|
105
|
+
* const handler: LexRouterMethodHandler<MyMethod, UserCredentials> = async (ctx) => {
|
|
106
|
+
* const { credentials, params, input, signal } = ctx
|
|
107
|
+
* // credentials.userId is available if auth handler returns UserCredentials
|
|
108
|
+
* // params contains validated query parameters
|
|
109
|
+
* // input contains the request body (for procedures)
|
|
110
|
+
* // signal can be used to abort long-running operations
|
|
111
|
+
* return { body: { result: 'success' } }
|
|
112
|
+
* }
|
|
113
|
+
* ```
|
|
114
|
+
*/
|
|
19
115
|
export type LexRouterHandlerContext<Method extends LexMethod, Credentials> = {
|
|
116
|
+
/** Authentication credentials returned by the auth handler. */
|
|
20
117
|
credentials: Credentials;
|
|
118
|
+
/** Parsed and validated request input (body for procedures, undefined for queries). */
|
|
21
119
|
input: InferMethodInput<Method, Body>;
|
|
120
|
+
/** Parsed and validated URL query parameters. */
|
|
22
121
|
params: InferMethodParams<Method>;
|
|
122
|
+
/** The original HTTP request object. */
|
|
23
123
|
request: Request;
|
|
124
|
+
/** Abort signal that is triggered when the request is cancelled. */
|
|
24
125
|
signal: AbortSignal;
|
|
126
|
+
/** Connection metadata including remote address. */
|
|
25
127
|
connection?: ConnectionInfo;
|
|
26
128
|
};
|
|
27
129
|
type AsOptionalPayloadOptions<T> = T extends undefined | void ? {
|
|
28
130
|
encoding?: undefined;
|
|
29
131
|
body?: undefined;
|
|
30
132
|
} : T;
|
|
133
|
+
/**
|
|
134
|
+
* Return type for XRPC method handlers (queries and procedures).
|
|
135
|
+
*
|
|
136
|
+
* Handlers can return either:
|
|
137
|
+
* - A raw {@link Response} object for full control over the HTTP response
|
|
138
|
+
* - An object with `body`, optional `encoding`, and optional `headers`
|
|
139
|
+
*
|
|
140
|
+
* For JSON methods, the body is automatically serialized. For other encodings,
|
|
141
|
+
* the body must be a valid {@link BodyInit} type.
|
|
142
|
+
*
|
|
143
|
+
* @typeParam Method - The Lexicon method type (Query or Procedure)
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* ```typescript
|
|
147
|
+
* // Return JSON body (most common)
|
|
148
|
+
* return { body: { users: [...] } }
|
|
149
|
+
*
|
|
150
|
+
* // Return with custom headers
|
|
151
|
+
* return {
|
|
152
|
+
* body: { data: 'value' },
|
|
153
|
+
* headers: { 'Cache-Control': 'max-age=3600' }
|
|
154
|
+
* }
|
|
155
|
+
*
|
|
156
|
+
* // Return raw Response for full control
|
|
157
|
+
* return new Response(binaryData, {
|
|
158
|
+
* headers: { 'Content-Type': 'application/octet-stream' }
|
|
159
|
+
* })
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
31
162
|
export type LexRouterHandlerOutput<Method extends Query | Procedure> = Response | ({
|
|
32
163
|
headers?: HeadersInit;
|
|
33
164
|
} & (InferMethodOutputEncoding<Method> extends 'application/json' ? {
|
|
34
165
|
encoding?: 'application/json';
|
|
35
166
|
body: InferMethodOutputBody<Method>;
|
|
36
167
|
} : AsOptionalPayloadOptions<InferMethodOutput<Method, BodyInit>>));
|
|
168
|
+
/**
|
|
169
|
+
* Handler function for XRPC query and procedure methods.
|
|
170
|
+
*
|
|
171
|
+
* Receives a context object with request details and credentials,
|
|
172
|
+
* and returns either a Response or a structured output object.
|
|
173
|
+
*
|
|
174
|
+
* @typeParam Method - The Lexicon method type (Query or Procedure)
|
|
175
|
+
* @typeParam Credentials - The type of authentication credentials
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* ```typescript
|
|
179
|
+
* const getProfile: LexRouterMethodHandler<GetProfileMethod, UserCredentials> = async (ctx) => {
|
|
180
|
+
* const profile = await db.getProfile(ctx.params.actor)
|
|
181
|
+
* return { body: profile }
|
|
182
|
+
* }
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
37
185
|
export type LexRouterMethodHandler<Method extends Query | Procedure = Query | Procedure, Credentials = unknown> = (ctx: LexRouterHandlerContext<Method, Credentials>) => Awaitable<LexRouterHandlerOutput<Method>>;
|
|
186
|
+
/**
|
|
187
|
+
* Configuration object for registering an XRPC method with authentication.
|
|
188
|
+
*
|
|
189
|
+
* Used when you need to specify both a handler and an auth function.
|
|
190
|
+
*
|
|
191
|
+
* @typeParam Method - The Lexicon method type (Query or Procedure)
|
|
192
|
+
* @typeParam Credentials - The type of authentication credentials
|
|
193
|
+
*
|
|
194
|
+
* @example
|
|
195
|
+
* ```typescript
|
|
196
|
+
* const config: LexRouterMethodConfig<GetProfileMethod, UserCredentials> = {
|
|
197
|
+
* handler: async (ctx) => {
|
|
198
|
+
* return { body: await getProfile(ctx.params.actor) }
|
|
199
|
+
* },
|
|
200
|
+
* auth: async ({ request }) => {
|
|
201
|
+
* return verifyToken(request.headers.get('authorization'))
|
|
202
|
+
* }
|
|
203
|
+
* }
|
|
204
|
+
* ```
|
|
205
|
+
*/
|
|
38
206
|
export type LexRouterMethodConfig<Method extends Query | Procedure = Query | Procedure, Credentials = unknown> = {
|
|
207
|
+
/** The handler function that processes the request. */
|
|
39
208
|
handler: LexRouterMethodHandler<Method, Credentials>;
|
|
209
|
+
/** Authentication function that validates credentials before the handler runs. */
|
|
40
210
|
auth: LexRouterAuth<Credentials, Method>;
|
|
41
211
|
};
|
|
212
|
+
/**
|
|
213
|
+
* Handler function for XRPC subscription methods (WebSocket streams).
|
|
214
|
+
*
|
|
215
|
+
* Returns an async iterable that yields messages to be sent over the WebSocket.
|
|
216
|
+
* The connection remains open until the iterable completes or an error occurs.
|
|
217
|
+
*
|
|
218
|
+
* @typeParam Method - The Lexicon subscription method type
|
|
219
|
+
* @typeParam Credentials - The type of authentication credentials
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```typescript
|
|
223
|
+
* const subscribeRepos: LexRouterSubscriptionHandler<SubscribeReposMethod> = async function* (ctx) {
|
|
224
|
+
* const cursor = ctx.params.cursor ?? 0
|
|
225
|
+
* for await (const event of eventStream.since(cursor)) {
|
|
226
|
+
* if (ctx.signal.aborted) break
|
|
227
|
+
* yield { $type: 'com.atproto.sync.subscribeRepos#commit', ...event }
|
|
228
|
+
* }
|
|
229
|
+
* }
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
42
232
|
export type LexRouterSubscriptionHandler<Method extends Subscription = Subscription, Credentials = unknown> = (ctx: LexRouterHandlerContext<Method, Credentials>) => AsyncIterable<InferMethodMessage<Method>>;
|
|
233
|
+
/**
|
|
234
|
+
* Configuration object for registering an XRPC subscription with authentication.
|
|
235
|
+
*
|
|
236
|
+
* Used when you need to specify both a handler and an auth function for subscriptions.
|
|
237
|
+
*
|
|
238
|
+
* @typeParam Method - The Lexicon subscription method type
|
|
239
|
+
* @typeParam Credentials - The type of authentication credentials
|
|
240
|
+
*
|
|
241
|
+
* @example
|
|
242
|
+
* ```typescript
|
|
243
|
+
* const config: LexRouterSubscriptionConfig<SubscribeReposMethod, ServiceCredentials> = {
|
|
244
|
+
* handler: async function* (ctx) {
|
|
245
|
+
* for await (const event of eventStream) {
|
|
246
|
+
* yield event
|
|
247
|
+
* }
|
|
248
|
+
* },
|
|
249
|
+
* auth: async ({ request }) => {
|
|
250
|
+
* return verifyServiceAuth(request)
|
|
251
|
+
* }
|
|
252
|
+
* }
|
|
253
|
+
* ```
|
|
254
|
+
*/
|
|
43
255
|
export type LexRouterSubscriptionConfig<Method extends Subscription = Subscription, Credentials = unknown> = {
|
|
256
|
+
/** The handler function that yields subscription messages. */
|
|
44
257
|
handler: LexRouterSubscriptionHandler<Method, Credentials>;
|
|
258
|
+
/** Authentication function that validates credentials before the handler runs. */
|
|
45
259
|
auth: LexRouterAuth<Credentials, Method>;
|
|
46
260
|
};
|
|
261
|
+
/**
|
|
262
|
+
* Context object passed to authentication handlers.
|
|
263
|
+
*
|
|
264
|
+
* Contains the information needed to authenticate a request before
|
|
265
|
+
* the main handler is invoked.
|
|
266
|
+
*
|
|
267
|
+
* @typeParam Method - The Lexicon method type
|
|
268
|
+
*
|
|
269
|
+
* @example
|
|
270
|
+
* ```typescript
|
|
271
|
+
* const authHandler: LexRouterAuth<UserCredentials> = async (ctx) => {
|
|
272
|
+
* const token = ctx.request.headers.get('authorization')
|
|
273
|
+
* if (!token) throw new LexError('AuthenticationRequired', 'Missing token')
|
|
274
|
+
* return { userId: await verifyToken(token) }
|
|
275
|
+
* }
|
|
276
|
+
* ```
|
|
277
|
+
*/
|
|
47
278
|
export type LexRouterAuthContext<Method extends LexMethod = LexMethod> = {
|
|
279
|
+
/** The Lexicon method definition being called. */
|
|
48
280
|
method: Method;
|
|
281
|
+
/** Parsed and validated URL query parameters. */
|
|
49
282
|
params: InferMethodParams<Method>;
|
|
283
|
+
/** The original HTTP request object. */
|
|
50
284
|
request: Request;
|
|
285
|
+
/** Connection metadata including remote address. */
|
|
51
286
|
connection?: ConnectionInfo;
|
|
52
287
|
};
|
|
288
|
+
/**
|
|
289
|
+
* Authentication handler function for XRPC methods.
|
|
290
|
+
*
|
|
291
|
+
* Called before the main handler to validate authentication credentials.
|
|
292
|
+
* Should return the validated credentials or throw an error if authentication fails.
|
|
293
|
+
*
|
|
294
|
+
* @typeParam Credentials - The type of credentials to return on success
|
|
295
|
+
* @typeParam Method - The Lexicon method type
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* ```typescript
|
|
299
|
+
* // Simple token-based auth
|
|
300
|
+
* const tokenAuth: LexRouterAuth<{ userId: string }> = async ({ request }) => {
|
|
301
|
+
* const token = request.headers.get('authorization')?.replace('Bearer ', '')
|
|
302
|
+
* if (!token) throw new LexError('AuthenticationRequired', 'Token required')
|
|
303
|
+
* const userId = await verifyToken(token)
|
|
304
|
+
* return { userId }
|
|
305
|
+
* }
|
|
306
|
+
*
|
|
307
|
+
* // Using with serviceAuth for AT Protocol service authentication
|
|
308
|
+
* import { serviceAuth } from '@atproto/lex-server'
|
|
309
|
+
* const auth = serviceAuth({ audience: 'did:web:example.com', unique: checkNonce })
|
|
310
|
+
* ```
|
|
311
|
+
*/
|
|
53
312
|
export type LexRouterAuth<Credentials = unknown, Method extends LexMethod = LexMethod> = (ctx: LexRouterAuthContext<Method>) => Credentials | Promise<Credentials>;
|
|
313
|
+
/**
|
|
314
|
+
* Context object passed to error handler callbacks.
|
|
315
|
+
*
|
|
316
|
+
* Used for logging and monitoring errors that occur during request handling.
|
|
317
|
+
*/
|
|
54
318
|
export type LexErrorHandlerContext = {
|
|
319
|
+
/** The error that was thrown during handling. */
|
|
55
320
|
error: unknown;
|
|
321
|
+
/** The original HTTP request that triggered the error. */
|
|
56
322
|
request: Request;
|
|
323
|
+
/** The Lexicon method that was being executed. */
|
|
57
324
|
method: LexMethod;
|
|
58
325
|
};
|
|
326
|
+
/**
|
|
327
|
+
* Function that upgrades an HTTP request to a WebSocket connection.
|
|
328
|
+
*
|
|
329
|
+
* This is platform-specific: Deno provides this natively, while Node.js
|
|
330
|
+
* requires the `upgradeWebSocket` function from this package.
|
|
331
|
+
*
|
|
332
|
+
* @param request - The HTTP request to upgrade
|
|
333
|
+
* @returns An object containing the WebSocket and the upgrade response
|
|
334
|
+
*
|
|
335
|
+
* @example
|
|
336
|
+
* ```typescript
|
|
337
|
+
* // In Node.js, use the provided upgradeWebSocket function
|
|
338
|
+
* import { upgradeWebSocket } from '@atproto/lex-server/nodejs'
|
|
339
|
+
*
|
|
340
|
+
* const router = new LexRouter({ upgradeWebSocket })
|
|
341
|
+
* ```
|
|
342
|
+
*/
|
|
59
343
|
export type UpgradeWebSocket = (request: Request) => {
|
|
344
|
+
/** The WebSocket instance for bidirectional communication. */
|
|
60
345
|
socket: WebSocket;
|
|
346
|
+
/** The HTTP response to return (101 Switching Protocols). */
|
|
61
347
|
response: Response;
|
|
62
348
|
};
|
|
349
|
+
/**
|
|
350
|
+
* Configuration options for the {@link LexRouter}.
|
|
351
|
+
*
|
|
352
|
+
* @example
|
|
353
|
+
* ```typescript
|
|
354
|
+
* const options: LexRouterOptions = {
|
|
355
|
+
* upgradeWebSocket,
|
|
356
|
+
* onHandlerError: async ({ error, request, method }) => {
|
|
357
|
+
* console.error(`Error in ${method.nsid}:`, error)
|
|
358
|
+
* await reportToSentry(error)
|
|
359
|
+
* },
|
|
360
|
+
* highWaterMark: 64 * 1024, // 64KB
|
|
361
|
+
* lowWaterMark: 16 * 1024 // 16KB
|
|
362
|
+
* }
|
|
363
|
+
* ```
|
|
364
|
+
*/
|
|
63
365
|
export type LexRouterOptions = {
|
|
366
|
+
/**
|
|
367
|
+
* Function to upgrade HTTP requests to WebSocket connections.
|
|
368
|
+
* Required for subscription methods. Defaults to Deno's built-in
|
|
369
|
+
* upgradeWebSocket if available.
|
|
370
|
+
*/
|
|
64
371
|
upgradeWebSocket?: UpgradeWebSocket;
|
|
372
|
+
/**
|
|
373
|
+
* Callback invoked when an error occurs during request handling.
|
|
374
|
+
* Useful for logging and error reporting. Not called for client-induced
|
|
375
|
+
* errors (e.g., request abortion).
|
|
376
|
+
*/
|
|
65
377
|
onHandlerError?: (ctx: LexErrorHandlerContext) => void | Promise<void>;
|
|
378
|
+
/**
|
|
379
|
+
* High water mark for WebSocket backpressure (in bytes).
|
|
380
|
+
* When buffered data exceeds this, the handler will wait before sending more.
|
|
381
|
+
*/
|
|
66
382
|
highWaterMark?: number;
|
|
383
|
+
/**
|
|
384
|
+
* Low water mark for WebSocket backpressure (in bytes).
|
|
385
|
+
* The handler resumes sending when buffered data drops below this.
|
|
386
|
+
*/
|
|
67
387
|
lowWaterMark?: number;
|
|
68
388
|
};
|
|
389
|
+
/**
|
|
390
|
+
* XRPC router for handling AT Protocol Lexicon methods.
|
|
391
|
+
*
|
|
392
|
+
* The router handles HTTP routing, parameter parsing, input validation,
|
|
393
|
+
* authentication, and response serialization for XRPC methods. It supports
|
|
394
|
+
* queries (GET), procedures (POST), and subscriptions (WebSocket).
|
|
395
|
+
*
|
|
396
|
+
* @example Setting up a basic XRPC server
|
|
397
|
+
* ```typescript
|
|
398
|
+
* import { LexRouter } from '@atproto/lex-server'
|
|
399
|
+
* import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'
|
|
400
|
+
* import { getProfile, createPost, subscribeRepos } from './lexicons'
|
|
401
|
+
*
|
|
402
|
+
* const router = new LexRouter({ upgradeWebSocket })
|
|
403
|
+
*
|
|
404
|
+
* // Register a query handler (GET request)
|
|
405
|
+
* router.add(getProfile, async (ctx) => {
|
|
406
|
+
* const profile = await db.getProfile(ctx.params.actor)
|
|
407
|
+
* return { body: profile }
|
|
408
|
+
* })
|
|
409
|
+
*
|
|
410
|
+
* // Register a procedure handler with authentication (POST request)
|
|
411
|
+
* router.add(createPost, {
|
|
412
|
+
* handler: async (ctx) => {
|
|
413
|
+
* const post = await db.createPost(ctx.credentials.did, ctx.input.body)
|
|
414
|
+
* return { body: { uri: post.uri, cid: post.cid } }
|
|
415
|
+
* },
|
|
416
|
+
* auth: async ({ request }) => {
|
|
417
|
+
* return verifyAccessToken(request)
|
|
418
|
+
* }
|
|
419
|
+
* })
|
|
420
|
+
*
|
|
421
|
+
* // Register a subscription handler (WebSocket)
|
|
422
|
+
* router.add(subscribeRepos, async function* (ctx) {
|
|
423
|
+
* for await (const event of eventStream.since(ctx.params.cursor)) {
|
|
424
|
+
* if (ctx.signal.aborted) break
|
|
425
|
+
* yield event
|
|
426
|
+
* }
|
|
427
|
+
* })
|
|
428
|
+
*
|
|
429
|
+
* // Start the server
|
|
430
|
+
* const server = await serve(router, { port: 3000 })
|
|
431
|
+
* console.log('XRPC server listening on port 3000')
|
|
432
|
+
* ```
|
|
433
|
+
*
|
|
434
|
+
* @example Using with service authentication
|
|
435
|
+
* ```typescript
|
|
436
|
+
* import { LexRouter, serviceAuth } from '@atproto/lex-server'
|
|
437
|
+
*
|
|
438
|
+
* const router = new LexRouter()
|
|
439
|
+
*
|
|
440
|
+
* const auth = serviceAuth({
|
|
441
|
+
* audience: 'did:web:api.example.com',
|
|
442
|
+
* unique: async (nonce) => {
|
|
443
|
+
* // Check and record nonce uniqueness
|
|
444
|
+
* return await nonceStore.checkAndAdd(nonce)
|
|
445
|
+
* }
|
|
446
|
+
* })
|
|
447
|
+
*
|
|
448
|
+
* router.add(protectedMethod, {
|
|
449
|
+
* handler: async (ctx) => {
|
|
450
|
+
* // ctx.credentials contains { did, didDocument, jwt }
|
|
451
|
+
* return { body: { callerDid: ctx.credentials.did } }
|
|
452
|
+
* },
|
|
453
|
+
* auth
|
|
454
|
+
* })
|
|
455
|
+
* ```
|
|
456
|
+
*/
|
|
69
457
|
export declare class LexRouter {
|
|
70
458
|
readonly options: LexRouterOptions;
|
|
459
|
+
/** Map of NSID strings to their fetch handlers. */
|
|
71
460
|
readonly handlers: Map<NsidString, FetchHandler>;
|
|
461
|
+
/**
|
|
462
|
+
* Creates a new XRPC router.
|
|
463
|
+
*
|
|
464
|
+
* @param options - Router configuration options
|
|
465
|
+
*/
|
|
72
466
|
constructor(options?: LexRouterOptions);
|
|
467
|
+
/**
|
|
468
|
+
* Registers a subscription handler without authentication.
|
|
469
|
+
*
|
|
470
|
+
* @param ns - The Lexicon namespace definition for the subscription
|
|
471
|
+
* @param handler - Async generator function that yields subscription messages
|
|
472
|
+
* @returns This router instance for chaining
|
|
473
|
+
*/
|
|
73
474
|
add<M extends Subscription>(ns: Main<M>, handler: LexRouterSubscriptionHandler<M, void>): this;
|
|
475
|
+
/**
|
|
476
|
+
* Registers a subscription handler with authentication.
|
|
477
|
+
*
|
|
478
|
+
* @param ns - The Lexicon namespace definition for the subscription
|
|
479
|
+
* @param config - Configuration object with handler and auth function
|
|
480
|
+
* @returns This router instance for chaining
|
|
481
|
+
*/
|
|
74
482
|
add<M extends Subscription, Credentials>(ns: Main<M>, config: LexRouterSubscriptionConfig<M, Credentials>): this;
|
|
483
|
+
/**
|
|
484
|
+
* Registers a query or procedure handler without authentication.
|
|
485
|
+
*
|
|
486
|
+
* @param ns - The Lexicon namespace definition for the method
|
|
487
|
+
* @param handler - Handler function that processes requests
|
|
488
|
+
* @returns This router instance for chaining
|
|
489
|
+
*/
|
|
75
490
|
add<M extends Query | Procedure>(ns: Main<M>, handler: LexRouterMethodHandler<M, void>): this;
|
|
491
|
+
/**
|
|
492
|
+
* Registers a query or procedure handler with authentication.
|
|
493
|
+
*
|
|
494
|
+
* @param ns - The Lexicon namespace definition for the method
|
|
495
|
+
* @param config - Configuration object with handler and auth function
|
|
496
|
+
* @returns This router instance for chaining
|
|
497
|
+
*/
|
|
76
498
|
add<M extends Query | Procedure, Credentials>(ns: Main<M>, config: LexRouterMethodConfig<M, Credentials>): this;
|
|
499
|
+
/**
|
|
500
|
+
* Registers a Lexicon method handler.
|
|
501
|
+
*
|
|
502
|
+
* This is the unified overload that accepts any method type with optional authentication.
|
|
503
|
+
*
|
|
504
|
+
* @param ns - The Lexicon namespace definition
|
|
505
|
+
* @param config - Handler function or configuration object
|
|
506
|
+
* @returns This router instance for chaining
|
|
507
|
+
*
|
|
508
|
+
* @throws {TypeError} If a method with the same NSID is already registered
|
|
509
|
+
*
|
|
510
|
+
* @example
|
|
511
|
+
* ```typescript
|
|
512
|
+
* // Register without auth (credentials will be void)
|
|
513
|
+
* router.add(myQuery, async (ctx) => {
|
|
514
|
+
* return { body: { data: 'value' } }
|
|
515
|
+
* })
|
|
516
|
+
*
|
|
517
|
+
* // Register with auth
|
|
518
|
+
* router.add(myProcedure, {
|
|
519
|
+
* handler: async (ctx) => {
|
|
520
|
+
* console.log('Caller:', ctx.credentials.userId)
|
|
521
|
+
* return { body: { success: true } }
|
|
522
|
+
* },
|
|
523
|
+
* auth: async ({ request }) => ({ userId: await verifyToken(request) })
|
|
524
|
+
* })
|
|
525
|
+
* ```
|
|
526
|
+
*/
|
|
77
527
|
add<M extends LexMethod, Credentials = unknown>(ns: Main<M>, config: M extends Subscription ? LexRouterSubscriptionHandler<M, Credentials> | LexRouterSubscriptionConfig<M, Credentials> : M extends Query | Procedure ? LexRouterMethodHandler<M, Credentials> | LexRouterMethodConfig<M, Credentials> : never): this;
|
|
78
528
|
private buildMethodHandler;
|
|
79
529
|
private buildSubscriptionHandler;
|
|
80
530
|
private handleError;
|
|
531
|
+
/**
|
|
532
|
+
* The main fetch handler for processing XRPC requests.
|
|
533
|
+
*
|
|
534
|
+
* Routes incoming requests to the appropriate method handler based on the
|
|
535
|
+
* NSID in the URL path. Returns appropriate error responses for invalid
|
|
536
|
+
* paths or unimplemented methods.
|
|
537
|
+
*
|
|
538
|
+
* This handler can be used directly with HTTP servers that support the
|
|
539
|
+
* fetch API pattern, or converted to a Node.js request listener using
|
|
540
|
+
* `toRequestListener()`.
|
|
541
|
+
*
|
|
542
|
+
* @param request - The incoming HTTP request
|
|
543
|
+
* @param connection - Optional connection metadata
|
|
544
|
+
* @returns A promise resolving to the HTTP response
|
|
545
|
+
*
|
|
546
|
+
* @example
|
|
547
|
+
* ```typescript
|
|
548
|
+
* // Use with Deno
|
|
549
|
+
* Deno.serve(router.fetch)
|
|
550
|
+
*
|
|
551
|
+
* // Use with Bun
|
|
552
|
+
* Bun.serve({ fetch: router.fetch })
|
|
553
|
+
*
|
|
554
|
+
* // Use with Node.js
|
|
555
|
+
* import { toRequestListener } from '@atproto/lex-server/nodejs'
|
|
556
|
+
* const listener = toRequestListener(router.fetch)
|
|
557
|
+
* http.createServer(listener).listen(3000)
|
|
558
|
+
* ```
|
|
559
|
+
*/
|
|
81
560
|
fetch: FetchHandler;
|
|
82
561
|
}
|
|
83
562
|
export {};
|
package/dist/lex-server.d.ts.map
CHANGED
|
@@ -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;
|
|
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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