@atproto/lex-client 0.1.5 → 0.2.1

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.
Files changed (74) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/agent.d.ts +1 -1
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js.map +1 -1
  5. package/dist/client.d.ts +42 -21
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +97 -16
  8. package/dist/client.js.map +1 -1
  9. package/dist/errors.d.ts +6 -4
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/errors.js +3 -3
  12. package/dist/errors.js.map +1 -1
  13. package/dist/response.d.ts +3 -2
  14. package/dist/response.d.ts.map +1 -1
  15. package/dist/response.js +2 -1
  16. package/dist/response.js.map +1 -1
  17. package/dist/types.d.ts +1 -1
  18. package/dist/types.d.ts.map +1 -1
  19. package/dist/types.js.map +1 -1
  20. package/dist/util.d.ts +6 -2
  21. package/dist/util.d.ts.map +1 -1
  22. package/dist/util.js +25 -0
  23. package/dist/util.js.map +1 -1
  24. package/dist/write-operation-builder.d.ts +3 -2
  25. package/dist/write-operation-builder.d.ts.map +1 -1
  26. package/dist/write-operation-builder.js +2 -2
  27. package/dist/write-operation-builder.js.map +1 -1
  28. package/dist/xrpc.d.ts +8 -6
  29. package/dist/xrpc.d.ts.map +1 -1
  30. package/dist/xrpc.js +1 -1
  31. package/dist/xrpc.js.map +1 -1
  32. package/package.json +11 -14
  33. package/src/agent.test.ts +0 -216
  34. package/src/agent.ts +0 -186
  35. package/src/client.ts +0 -1086
  36. package/src/errors.test.ts +0 -626
  37. package/src/errors.ts +0 -570
  38. package/src/index.ts +0 -6
  39. package/src/lexicons/com/atproto/repo/applyWrites.defs.ts +0 -201
  40. package/src/lexicons/com/atproto/repo/applyWrites.ts +0 -6
  41. package/src/lexicons/com/atproto/repo/createRecord.defs.ts +0 -58
  42. package/src/lexicons/com/atproto/repo/createRecord.ts +0 -6
  43. package/src/lexicons/com/atproto/repo/defs.defs.ts +0 -28
  44. package/src/lexicons/com/atproto/repo/defs.ts +0 -5
  45. package/src/lexicons/com/atproto/repo/deleteRecord.defs.ts +0 -52
  46. package/src/lexicons/com/atproto/repo/deleteRecord.ts +0 -6
  47. package/src/lexicons/com/atproto/repo/getRecord.defs.ts +0 -37
  48. package/src/lexicons/com/atproto/repo/getRecord.ts +0 -6
  49. package/src/lexicons/com/atproto/repo/listRecords.defs.ts +0 -65
  50. package/src/lexicons/com/atproto/repo/listRecords.ts +0 -6
  51. package/src/lexicons/com/atproto/repo/putRecord.defs.ts +0 -59
  52. package/src/lexicons/com/atproto/repo/putRecord.ts +0 -6
  53. package/src/lexicons/com/atproto/repo/uploadBlob.defs.ts +0 -35
  54. package/src/lexicons/com/atproto/repo/uploadBlob.ts +0 -6
  55. package/src/lexicons/com/atproto/repo.ts +0 -12
  56. package/src/lexicons/com/atproto/sync/getBlob.defs.ts +0 -37
  57. package/src/lexicons/com/atproto/sync/getBlob.ts +0 -6
  58. package/src/lexicons/com/atproto/sync.ts +0 -5
  59. package/src/lexicons/com/atproto.ts +0 -6
  60. package/src/lexicons/com.ts +0 -5
  61. package/src/lexicons/index.ts +0 -5
  62. package/src/response.bench.ts +0 -113
  63. package/src/response.ts +0 -366
  64. package/src/types.ts +0 -71
  65. package/src/util.test.ts +0 -333
  66. package/src/util.ts +0 -182
  67. package/src/write-operation-builder.ts +0 -110
  68. package/src/www-authenticate.test.ts +0 -227
  69. package/src/www-authenticate.ts +0 -101
  70. package/src/xrpc.test.ts +0 -1450
  71. package/src/xrpc.ts +0 -446
  72. package/tsconfig.build.json +0 -12
  73. package/tsconfig.json +0 -7
  74. package/tsconfig.tests.json +0 -8
package/src/client.ts DELETED
@@ -1,1086 +0,0 @@
1
- import { LexMap, LexValue, TypedLexMap } from '@atproto/lex-data'
2
- import {
3
- AtIdentifierString,
4
- AtUriString,
5
- CidString,
6
- DidString,
7
- Infer,
8
- InferMethodInputBody,
9
- InferMethodOutputBody,
10
- InferRecordKey,
11
- LexiconRecordKey,
12
- Main,
13
- NsidString,
14
- Params,
15
- Procedure,
16
- Query,
17
- RecordSchema,
18
- Restricted,
19
- getMain,
20
- } from '@atproto/lex-schema'
21
- import { Agent, AgentOptions, buildAgent } from './agent.js'
22
- import { XrpcFailure } from './errors.js'
23
- // @NOTE We could use import { com } from "./lexicons/index.js" here, but some
24
- // consumers might not know how to properly tree-shake that, so we import only
25
- // the needed lexicon schemas directly.
26
- import applyWrites from './lexicons/com/atproto/repo/applyWrites.js'
27
- import createRecord from './lexicons/com/atproto/repo/createRecord.js'
28
- import deleteRecord from './lexicons/com/atproto/repo/deleteRecord.js'
29
- import getRecord from './lexicons/com/atproto/repo/getRecord.js'
30
- import listRecords from './lexicons/com/atproto/repo/listRecords.js'
31
- import putRecord from './lexicons/com/atproto/repo/putRecord.js'
32
- import uploadBlob from './lexicons/com/atproto/repo/uploadBlob.js'
33
- import getBlob from './lexicons/com/atproto/sync/getBlob.js'
34
- import {
35
- XrpcResponse,
36
- XrpcResponseBody,
37
- XrpcResponseOptions,
38
- } from './response.js'
39
- import { BinaryBodyInit, Service } from './types.js'
40
- import {
41
- RecordKeyOptions,
42
- XrpcRequestHeadersOptions,
43
- applyDefaults,
44
- buildXrpcRequestHeaders,
45
- getDefaultRecordKey,
46
- getLiteralRecordKey,
47
- } from './util.js'
48
- import {
49
- WriteOperation,
50
- WriteOperationCreateOptions,
51
- WriteOperationDeleteOptions,
52
- WriteOperationHelper,
53
- WriteOperationUpdateOptions,
54
- WriteOperationsFactory,
55
- } from './write-operation-builder.js'
56
- import {
57
- XrpcOptions,
58
- XrpcRequestParams,
59
- XrpcRequestProcessingOptions,
60
- xrpc,
61
- xrpcSafe,
62
- } from './xrpc.js'
63
-
64
- export {
65
- type AtIdentifierString,
66
- type CidString,
67
- type DidString,
68
- type Infer,
69
- type InferMethodInputBody,
70
- type InferMethodOutputBody,
71
- type InferRecordKey,
72
- type LexMap,
73
- type LexValue,
74
- type LexiconRecordKey,
75
- type Main,
76
- type NsidString,
77
- type Params,
78
- Procedure,
79
- Query,
80
- RecordSchema,
81
- type Restricted,
82
- type TypedLexMap,
83
- type WriteOperation,
84
- type WriteOperationCreateOptions,
85
- type WriteOperationDeleteOptions,
86
- WriteOperationHelper,
87
- type WriteOperationUpdateOptions,
88
- type WriteOperationsFactory,
89
- }
90
-
91
- /**
92
- * Configuration options for creating a {@link Client}.
93
- *
94
- * @property {@link ClientOptions.labelers} - An iterable of labeler DIDs to include in requests. These will be combined with any global app labelers configured via {@link Client.configure}.
95
- * @property {@link ClientOptions.service} - An optional service identifier (DID or URL) for routing requests with service proxying.
96
- * @property {@link ClientOptions.headers} - Custom headers to include in all requests made by this client instance.
97
- * @property {@link ClientOptions.validateRequest} - If true, validates request bodies against their lexicon schemas before sending. Defaults to false for performance.
98
- * @property {@link ClientOptions.validateResponse} - If false, skips validation of response bodies against their lexicon schemas. Defaults to true to catch errors, but can be disabled for performance if you trust the server responses. Note that defaults will not be applied if validation is disabled, which can cause typing inconsistencies, so use with caution.
99
- * @property {@link ClientOptions.strictResponseProcessing} - If false, relaxes certain validation rules during response processing (e.g., allowing floats, deeper nesting, etc.). Defaults to true for strict compliance with {@link https://atproto.com/specs/data-model lexicon data model}, but can be disabled to handle non-compliant responses.
100
- *
101
- * @see {@link XrpcRequestHeadersOptions}
102
- * @see {@link XrpcRequestProcessingOptions}
103
- * @see {@link XrpcResponseOptions}
104
- *
105
- * @example
106
- * ```typescript
107
- * const options: ClientOptions = {
108
- * labelers: ['did:plc:labeler1'],
109
- * service: 'did:web:api.bsky.app#bsky_appview',
110
- * headers: { 'X-Custom-Header': 'value' },
111
- * validateRequest: false,
112
- * validateResponse: true,
113
- * strictResponseProcessing: false,
114
- * }
115
- * ```
116
- */
117
- export type ClientOptions = XrpcRequestHeadersOptions &
118
- Pick<XrpcRequestProcessingOptions, 'validateRequest'> &
119
- XrpcResponseOptions
120
-
121
- export type ActionOptions = {
122
- /** AbortSignal to cancel the request. */
123
- signal?: AbortSignal
124
- }
125
-
126
- /**
127
- * A composable action that can be invoked via {@link Client.call}.
128
- *
129
- * Actions provide a way to define custom operations that integrate with the
130
- * Client's call interface, enabling type-safe, reusable business logic.
131
- *
132
- * @typeParam I - The input type for the action
133
- * @typeParam O - The output type for the action
134
- *
135
- * @example
136
- * ```typescript
137
- * const myAction: Action<{ userId: string }, { profile: Profile }> = async (client, input, options) => {
138
- * const response = await client.xrpc(someMethod, { params: { actor: input.userId }, ...options })
139
- * return { profile: response.body }
140
- * }
141
- * ```
142
- */
143
- export type Action<I = any, O = any> = (
144
- client: Client,
145
- input: I,
146
- options: ActionOptions,
147
- ) => O | Promise<O>
148
-
149
- /**
150
- * Extracts the input type from an {@link Action}.
151
- * @typeParam A - The Action type to extract from
152
- */
153
- export type InferActionInput<A extends Action> =
154
- A extends Action<infer I, any> ? I : never
155
-
156
- /**
157
- * Extracts the output type from an {@link Action}.
158
- * @typeParam A - The Action type to extract from
159
- */
160
- export type InferActionOutput<A extends Action> =
161
- A extends Action<any, infer O> ? O : never
162
-
163
- /**
164
- * Options for creating a record in an AT Protocol repository.
165
- *
166
- * @see {@link Client.createRecord}
167
- */
168
- export type CreateRecordOptions = Omit<
169
- XrpcOptions<typeof createRecord>,
170
- 'body'
171
- > & {
172
- /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */
173
- repo?: AtIdentifierString
174
- /** Compare-and-swap on the repo commit. If specified, must match current commit. */
175
- swapCommit?: string
176
- /**
177
- * Whether the PDS should validate the record against its lexicon schema.
178
- * When `true`, the PDS is asked to explicitly validate the record. When
179
- * `false`, the PDS is asked to explicitly skip validation. When `undefined`
180
- * (default), the PDS decides -- typically validating only collections whose
181
- * schemas it knows. This is server-side validation; for client-side
182
- * validation before sending, use {@link XrpcRequestProcessingOptions.validateRequest}.
183
- */
184
- validate?: boolean
185
- }
186
-
187
- /**
188
- * Options for deleting a record from an AT Protocol repository.
189
- *
190
- * @see {@link Client.deleteRecord}
191
- */
192
- export type DeleteRecordOptions = Omit<
193
- XrpcOptions<typeof deleteRecord>,
194
- 'body'
195
- > & {
196
- /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */
197
- repo?: AtIdentifierString
198
- /** Compare-and-swap on the repo commit. If specified, must match current commit. */
199
- swapCommit?: string
200
- /** Compare-and-swap on the record CID. If specified, must match current record. */
201
- swapRecord?: string
202
- }
203
-
204
- /**
205
- * Options for retrieving a record from an AT Protocol repository.
206
- *
207
- * @see {@link Client.getRecord}
208
- */
209
- export type GetRecordOptions = Omit<XrpcOptions<typeof getRecord>, 'params'> & {
210
- /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */
211
- repo?: AtIdentifierString
212
- }
213
-
214
- /**
215
- * Options for creating or updating a record in an AT Protocol repository.
216
- *
217
- * @see {@link Client.putRecord}
218
- */
219
- export type PutRecordOptions = Omit<XrpcOptions<typeof putRecord>, 'body'> & {
220
- /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */
221
- repo?: AtIdentifierString
222
- /** Compare-and-swap on the repo commit. If specified, must match current commit. */
223
- swapCommit?: string
224
- /** Compare-and-swap on the record CID. If specified, must match current record. */
225
- swapRecord?: string
226
- /**
227
- * Whether the PDS should validate the record against its lexicon schema.
228
- * When `true`, the PDS is asked to explicitly validate the record. When
229
- * `false`, the PDS is asked to explicitly skip validation. When `undefined`
230
- * (default), the PDS decides — typically validating only collections whose
231
- * schemas it knows. This is server-side validation; for client-side
232
- * validation before sending, use {@link XrpcRequestProcessingOptions.validateRequest}.
233
- */
234
- validate?: boolean
235
- }
236
-
237
- /**
238
- * Options for listing records in an AT Protocol repository collection.
239
- *
240
- * @see {@link Client.listRecords}
241
- */
242
- export type ListRecordsOptions = Omit<
243
- XrpcOptions<typeof listRecords>,
244
- 'params'
245
- > & {
246
- /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */
247
- repo?: AtIdentifierString
248
- /** Maximum number of records to return. */
249
- limit?: number
250
- /** Pagination cursor from a previous response. */
251
- cursor?: string
252
- /** If true, returns records in reverse chronological order. */
253
- reverse?: boolean
254
- }
255
-
256
- /**
257
- * Options for applying a batch of writes (create/update/delete) to an AT Protocol repository.
258
- *
259
- * @see {@link Client.applyWrites}
260
- */
261
- export type ApplyWritesOptions = Omit<
262
- XrpcOptions<typeof applyWrites>,
263
- 'body'
264
- > & {
265
- /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */
266
- repo?: AtIdentifierString
267
- /**
268
- * Whether the PDS should validate the records against their lexicon schemas.
269
- * When `true`, the PDS is asked to explicitly validate every record. When
270
- * `false`, the PDS is asked to explicitly skip validation. When `undefined`
271
- * (default), the PDS decides — typically validating only collections whose
272
- * schemas it knows.
273
- */
274
- validate?: boolean
275
- /** Compare-and-swap on the repo commit. If specified, must match current commit. */
276
- swapCommit?: CidString
277
- }
278
-
279
- export type UploadBlobOptions = Omit<XrpcOptions<typeof uploadBlob>, 'body'>
280
-
281
- export type GetBlobOptions = Omit<XrpcOptions<typeof getBlob>, 'params'>
282
-
283
- /**
284
- * Type-safe options for {@link Client.create}, combining record options with key requirements.
285
- * @typeParam T - The record schema type
286
- * @see {@link CreateRecordOptions}
287
- */
288
- export type CreateOptions<T extends RecordSchema> = CreateRecordOptions &
289
- RecordKeyOptions<T, 'tid' | 'any'>
290
-
291
- /**
292
- * Output type for record creation operations.
293
- * Contains the URI and CID of the newly created record.
294
- */
295
- export type CreateOutput = InferMethodOutputBody<
296
- typeof createRecord,
297
- Uint8Array
298
- >
299
-
300
- /**
301
- * Type-safe options for {@link Client.delete}, combining delete options with key requirements.
302
- * @typeParam T - The record schema type
303
- */
304
- export type DeleteOptions<T extends RecordSchema> = DeleteRecordOptions &
305
- RecordKeyOptions<T>
306
-
307
- /**
308
- * Output type for record deletion operations.
309
- */
310
- export type DeleteOutput = InferMethodOutputBody<
311
- typeof deleteRecord,
312
- Uint8Array
313
- >
314
-
315
- /**
316
- * Type-safe options for {@link Client.get}, combining get options with key requirements.
317
- * @typeParam T - The record schema type
318
- */
319
- export type GetOptions<T extends RecordSchema> = GetRecordOptions &
320
- RecordKeyOptions<T>
321
-
322
- /**
323
- * Output type for record retrieval operations.
324
- * Contains the record value validated against the schema type.
325
- * @typeParam T - The record schema type
326
- */
327
- export type GetOutput<T extends RecordSchema> = Omit<
328
- InferMethodOutputBody<typeof getRecord, Uint8Array>,
329
- 'value'
330
- > & { value: Infer<T> }
331
-
332
- /**
333
- * Type-safe options for {@link Client.put}, combining put options with key requirements.
334
- * @typeParam T - The record schema type
335
- */
336
- export type PutOptions<T extends RecordSchema> = PutRecordOptions &
337
- RecordKeyOptions<T>
338
-
339
- /**
340
- * Output type for record put (create/update) operations.
341
- * Contains the URI and CID of the record.
342
- */
343
- export type PutOutput = InferMethodOutputBody<typeof putRecord, Uint8Array>
344
-
345
- /**
346
- * Options for {@link Client.list} operations.
347
- */
348
- export type ListOptions = ListRecordsOptions
349
-
350
- /**
351
- * Output type for record listing operations.
352
- * Contains validated records and any invalid records that failed schema validation.
353
- * @typeParam T - The record schema type
354
- */
355
- export type ListOutput<T extends RecordSchema> = InferMethodOutputBody<
356
- typeof listRecords,
357
- Uint8Array
358
- > & {
359
- /** Records that successfully validated against the schema. */
360
- records: ListRecord<Infer<T>>[]
361
- // @NOTE Because the schema uses "type": "unknown" instead of an open union,
362
- // we have to use LexMap instead of Unknown$TypedObject here, which is
363
- // unfortunate.
364
- /** Records that failed schema validation. */
365
- invalid: LexMap[]
366
- }
367
-
368
- /**
369
- * A record from a list operation with its value typed to the schema.
370
- * @typeParam Value - The validated record value type
371
- */
372
- export type ListRecord<Value extends LexMap> = {
373
- uri: AtUriString
374
- cid: CidString
375
- value: Value
376
- }
377
-
378
- /**
379
- * The Client class is the primary interface for interacting with AT Protocol
380
- * services. It provides type-safe methods for XRPC calls, record operations,
381
- * and blob handling.
382
- *
383
- * @example
384
- * ```typescript
385
- * import { Client } from '@atproto/lex'
386
- * import { app } from '#/lexicons
387
- *
388
- * const client = new Client(oauthSession)
389
- *
390
- * const response = await client.xrpc(app.bsky.feed.getTimeline.main, {
391
- * params: { limit: 50 }
392
- * })
393
- * ```
394
- */
395
- export class Client implements Agent {
396
- static appLabelers: readonly DidString[] = []
397
-
398
- /**
399
- * Configures the Client (or its sub classes) globally.
400
- */
401
- static configure(opts: { appLabelers?: Iterable<DidString> }) {
402
- if (opts.appLabelers) this.appLabelers = [...opts.appLabelers]
403
- }
404
-
405
- /** The underlying agent used for making requests. */
406
- public readonly agent: Agent
407
-
408
- /** Custom headers included in all requests. */
409
- public readonly headers: Headers
410
-
411
- /** Optional service identifier for routing requests. */
412
- public readonly service?: Service
413
-
414
- /** Set of labeler DIDs specific to this client instance. */
415
- public readonly labelers: Set<DidString>
416
-
417
- public readonly xrpcDefaults: {
418
- readonly validateRequest: boolean
419
- readonly validateResponse: boolean
420
- readonly strictResponseProcessing: boolean
421
- }
422
-
423
- constructor(agent: Agent | AgentOptions, options: ClientOptions = {}) {
424
- this.agent = buildAgent(agent)
425
- this.service = options.service
426
- this.labelers = new Set(options.labelers)
427
- this.headers = new Headers(options.headers)
428
- this.xrpcDefaults = Object.freeze({
429
- validateRequest: options.validateRequest ?? false,
430
- validateResponse: options.validateResponse ?? true,
431
- strictResponseProcessing: options.strictResponseProcessing ?? true,
432
- })
433
- }
434
-
435
- /**
436
- * The DID of the authenticated user, or `undefined` if not authenticated.
437
- */
438
- get did(): DidString | undefined {
439
- return this.agent.did
440
- }
441
-
442
- /**
443
- * The DID of the authenticated user.
444
- * @throws {Error} if not authenticated
445
- */
446
- get assertDid(): DidString {
447
- this.assertAuthenticated()
448
- return this.did
449
- }
450
-
451
- /**
452
- * Asserts that the client is authenticated.
453
- * Use as a type guard when you need to ensure authentication.
454
- *
455
- * @throws {Error} if not authenticated
456
- *
457
- * @example
458
- * ```typescript
459
- * client.assertAuthenticated()
460
- * // TypeScript now knows client.did is defined
461
- * console.log(client.did)
462
- * ```
463
- */
464
- public assertAuthenticated(): asserts this is { did: DidString } {
465
- if (!this.did) throw new Error('Client is not authenticated')
466
- }
467
-
468
- /**
469
- * Replaces all labelers with the given set.
470
- * @param labelers - Iterable of labeler DIDs
471
- */
472
- public setLabelers(labelers: Iterable<DidString> = []) {
473
- this.clearLabelers()
474
- this.addLabelers(labelers)
475
- }
476
-
477
- /**
478
- * Adds labelers to the current set.
479
- * @param labelers - Iterable of labeler DIDs to add
480
- */
481
- public addLabelers(labelers: Iterable<DidString>) {
482
- for (const labeler of labelers) this.labelers.add(labeler)
483
- }
484
-
485
- /**
486
- * Removes all labelers from this client instance.
487
- */
488
- public clearLabelers() {
489
- this.labelers.clear()
490
- }
491
-
492
- /**
493
- * {@link Agent}'s {@link Agent.fetchHandler} implementation, which adds
494
- * labelers and service proxying headers. This method allow a {@link Client}
495
- * instance to be used directly as an {@link Agent} for another
496
- * {@link Client}, enabling composition of headers (labelers, proxying, etc.).
497
- *
498
- * @param path - The request path
499
- * @param init - Request initialization options
500
- */
501
- public fetchHandler(
502
- path: `/${string}`,
503
- init: RequestInit,
504
- ): Promise<Response> {
505
- const headers = buildXrpcRequestHeaders({
506
- headers: init.headers,
507
- service: this.service,
508
- labelers: [
509
- ...(this.constructor as typeof Client).appLabelers.map(
510
- (l) => `${l};redact` as const,
511
- ),
512
- ...this.labelers,
513
- ],
514
- })
515
-
516
- // Incoming headers take precedence
517
- for (const [key, value] of this.headers) {
518
- if (!headers.has(key)) headers.set(key, value)
519
- }
520
-
521
- // @NOTE The agent here could be another Client instance.
522
- return this.agent.fetchHandler(path, { ...init, headers })
523
- }
524
-
525
- /**
526
- * Makes an XRPC request. Throws on failure.
527
- *
528
- * @param ns - The lexicon method definition (e.g., `app.bsky.feed.getTimeline`)
529
- * @param options - Request options including params and body
530
- * @returns The successful XRPC response
531
- * @throws {XrpcFailure} when the request fails or returns an error
532
- *
533
- * @example Query with parameters
534
- * ```typescript
535
- * const response = await client.xrpc(app.bsky.feed.getTimeline, {
536
- * params: { limit: 50, cursor: 'abc123' }
537
- * })
538
- * console.log(response.body.feed)
539
- * ```
540
- *
541
- * @example Procedure with body
542
- * ```typescript
543
- * const response = await client.xrpc(com.atproto.repo.createRecord, {
544
- * body: {
545
- * repo: client.assertDid,
546
- * collection: 'app.bsky.feed.post',
547
- * record: { text: 'Hello!', createdAt: new Date().toISOString() }
548
- * }
549
- * })
550
- * ```
551
- *
552
- * @see {@link xrpcSafe} for a non-throwing variant
553
- */
554
- async xrpc<const M extends Query | Procedure>(
555
- ns: NonNullable<unknown> extends XrpcOptions<M>
556
- ? Main<M>
557
- : Restricted<'This XRPC method requires an "options" argument'>,
558
- ): Promise<XrpcResponse<M>>
559
- async xrpc<const M extends Query | Procedure>(
560
- ns: Main<M>,
561
- options: XrpcOptions<M>,
562
- ): Promise<XrpcResponse<M>>
563
- async xrpc<const M extends Query | Procedure>(
564
- ns: Main<M>,
565
- options: XrpcOptions<M> = {} as XrpcOptions<M>,
566
- ): Promise<XrpcResponse<M>> {
567
- return xrpc(this, ns, applyDefaults(options, this.xrpcDefaults))
568
- }
569
-
570
- /**
571
- * Makes an XRPC request without throwing on failure.
572
- * Returns either a successful response or a failure object.
573
- *
574
- * @param ns - The lexicon method definition
575
- * @param options - Request options
576
- * @returns Either an XrpcResponse on success or XrpcFailure on failure
577
- *
578
- * @example
579
- * ```typescript
580
- * const result = await client.xrpcSafe(app.bsky.actor.getProfile.main, {
581
- * params: { actor: 'alice.bsky.social' }
582
- * })
583
- *
584
- * if (result.success) {
585
- * console.log(result.body.displayName)
586
- * } else {
587
- * console.error('Failed:', result.error)
588
- * }
589
- * ```
590
- *
591
- * @see {@link xrpc} for a throwing variant
592
- */
593
- async xrpcSafe<const M extends Query | Procedure>(
594
- ns: NonNullable<unknown> extends XrpcOptions<M>
595
- ? Main<M>
596
- : Restricted<'This XRPC method requires an "options" argument'>,
597
- ): Promise<XrpcResponse<M> | XrpcFailure<M>>
598
- async xrpcSafe<const M extends Query | Procedure>(
599
- ns: Main<M>,
600
- options: XrpcOptions<M>,
601
- ): Promise<XrpcResponse<M> | XrpcFailure<M>>
602
- async xrpcSafe<const M extends Query | Procedure>(
603
- ns: Main<M>,
604
- options: XrpcOptions<M> = {} as XrpcOptions<M>,
605
- ): Promise<XrpcResponse<M> | XrpcFailure<M>> {
606
- return xrpcSafe(this, ns, applyDefaults(options, this.xrpcDefaults))
607
- }
608
-
609
- /**
610
- * Creates a new record in an AT Protocol repository.
611
- *
612
- * @param record - The record to create, must include an {@link NsidString} `$type`
613
- * @param rkey - Optional record key; if omitted, server generates a TID
614
- * @param options - Create options including repo, swapCommit, validate
615
- * @returns The XRPC response containing the created record's URI and CID
616
- *
617
- * @example
618
- * ```typescript
619
- * const response = await client.createRecord(
620
- * { $type: 'app.bsky.feed.post', text: 'Hello!', createdAt: new Date().toISOString() },
621
- * undefined, // Let server generate rkey
622
- * { validate: true }
623
- * )
624
- * console.log(response.body.uri)
625
- * ```
626
- *
627
- * @see {@link create} for a higher-level typed alternative
628
- */
629
- public async createRecord(
630
- record: TypedLexMap<NsidString>,
631
- rkey?: string,
632
- options?: CreateRecordOptions,
633
- ) {
634
- return this.xrpc(createRecord, {
635
- ...options,
636
- body: {
637
- repo: options?.repo ?? this.assertDid,
638
- collection: record.$type,
639
- record,
640
- rkey,
641
- validate: options?.validate,
642
- swapCommit: options?.swapCommit,
643
- },
644
- })
645
- }
646
-
647
- /**
648
- * Deletes a record from an AT Protocol repository.
649
- *
650
- * @param collection - The collection NSID
651
- * @param rkey - The record key
652
- * @param options - Delete options including repo, swapCommit, swapRecord
653
- *
654
- * @see {@link delete} for a higher-level typed alternative
655
- */
656
- async deleteRecord(
657
- collection: NsidString,
658
- rkey: string,
659
- options?: DeleteRecordOptions,
660
- ) {
661
- return this.xrpc(deleteRecord, {
662
- ...options,
663
- body: {
664
- repo: options?.repo ?? this.assertDid,
665
- collection,
666
- rkey,
667
- swapCommit: options?.swapCommit,
668
- swapRecord: options?.swapRecord,
669
- },
670
- })
671
- }
672
-
673
- /**
674
- * Retrieves a record from an AT Protocol repository.
675
- *
676
- * @param collection - The collection NSID
677
- * @param rkey - The record key
678
- * @param options - Get options including repo
679
- *
680
- * @see {@link get} for a higher-level typed alternative
681
- */
682
- public async getRecord(
683
- collection: NsidString,
684
- rkey: string,
685
- options?: GetRecordOptions,
686
- ) {
687
- return this.xrpc(getRecord, {
688
- ...options,
689
- params: {
690
- repo: options?.repo ?? this.assertDid,
691
- collection,
692
- rkey,
693
- },
694
- })
695
- }
696
-
697
- /**
698
- * Creates or updates a record in a repository.
699
- *
700
- * @param record - The record to put, must include an {@link NsidString} `$type`
701
- * @param rkey - The record key
702
- * @param options - Put options including repo, swapCommit, swapRecord, validate
703
- *
704
- * @see {@link put} for a higher-level typed alternative
705
- */
706
- async putRecord(
707
- record: TypedLexMap<NsidString>,
708
- rkey: string,
709
- options?: PutRecordOptions,
710
- ) {
711
- return this.xrpc(putRecord, {
712
- ...options,
713
- body: {
714
- repo: options?.repo ?? this.assertDid,
715
- collection: record.$type,
716
- rkey,
717
- record,
718
- validate: options?.validate,
719
- swapCommit: options?.swapCommit,
720
- swapRecord: options?.swapRecord,
721
- },
722
- })
723
- }
724
-
725
- /**
726
- * Lists records in a collection.
727
- *
728
- * @param nsid - The collection NSID
729
- * @param options - List options including repo, limit, cursor, reverse
730
- *
731
- * @see {@link list} for a higher-level typed alternative
732
- */
733
- async listRecords(nsid: NsidString, options?: ListRecordsOptions) {
734
- return this.xrpc(listRecords, {
735
- ...options,
736
- params: {
737
- repo: options?.repo ?? this.assertDid,
738
- collection: nsid,
739
- cursor: options?.cursor,
740
- limit: options?.limit,
741
- reverse: options?.reverse,
742
- },
743
- })
744
- }
745
-
746
- /**
747
- * Performs an atomic batch of create, update, and delete operations on records in a repository.
748
- *
749
- * @param builder - A function that receives an {@link ApplyWritesOperations} instance to build the operations
750
- * @param options - ApplyWrites options including repo, validate, swapCommit
751
- * @returns The XRPC response from the applyWrites call
752
- *
753
- * @example
754
- * ```typescript
755
- * const response = await client.applyWrites((op) => [
756
- * op.create(app.bsky.feed.post, { text: 'Hello!' }),
757
- * op.update(app.bsky.feed.post, { text: 'Updated text' }, { rkey: 'post123' }),
758
- * op.delete(app.bsky.feed.post, 'post456'),
759
- * op.update(app.bsky.actor.profile, { displayName: 'Alice' }),
760
- * ], {
761
- * validate: true,
762
- * })
763
- *
764
- * for (const result of response.body.results) {
765
- * console.log(result.uri)
766
- * }
767
- * ```
768
- */
769
- async applyWrites(
770
- factory: WriteOperationsFactory,
771
- options?: ApplyWritesOptions,
772
- ) {
773
- return this.xrpc(applyWrites, {
774
- ...options,
775
- body: {
776
- repo: options?.repo ?? this.assertDid,
777
- writes: WriteOperationHelper.build(factory),
778
- validate: options?.validate,
779
- swapCommit: options?.swapCommit,
780
- },
781
- })
782
- }
783
-
784
- /**
785
- * Uploads a blob to an AT Protocol repository.
786
- *
787
- * @param body - The blob data (Uint8Array, ReadableStream, Blob, etc.)
788
- * @param options - Upload options including encoding hint
789
- * @returns Response containing the blob reference
790
- *
791
- * @example
792
- * ```typescript
793
- * const imageData = await fetch('image.png').then(r => r.arrayBuffer())
794
- * const response = await client.uploadBlob(new Uint8Array(imageData), {
795
- * encoding: 'image/png'
796
- * })
797
- * console.log(response.body.blob) // Use this ref in records
798
- * ```
799
- */
800
- async uploadBlob(body: BinaryBodyInit, options?: UploadBlobOptions) {
801
- return this.xrpc(uploadBlob, { ...options, body })
802
- }
803
-
804
- /**
805
- * Retrieves a blob by DID and CID.
806
- *
807
- * @param did - The DID of the repository containing the blob
808
- * @param cid - The CID of the blob
809
- * @param options - Call options
810
- */
811
- async getBlob(did: DidString, cid: CidString, options?: GetBlobOptions) {
812
- return this.xrpc(getBlob, {
813
- ...options,
814
- params: { did, cid },
815
- })
816
- }
817
-
818
- /**
819
- * Universal call method for queries, procedures, and custom actions.
820
- * Automatically determines the call type based on the lexicon definition.
821
- *
822
- * @param ns - The lexicon method or action definition
823
- * @param arg - The input argument (params for queries, body for procedures, input for actions)
824
- * @param options - Call options
825
- * @returns The method response body or action output
826
- * @see {@link xrpc} if you need access to the full response object
827
- *
828
- * @example Query
829
- * ```typescript
830
- * const profile = await client.call(app.bsky.actor.getProfile.main, {
831
- * actor: 'alice.bsky.social'
832
- * })
833
- * ```
834
- *
835
- * @example Procedure
836
- * ```typescript
837
- * const result = await client.call(com.atproto.repo.createRecord.main, {
838
- * repo: did,
839
- * collection: 'app.bsky.feed.post',
840
- * record: { text: 'Hello!' }
841
- * })
842
- * ```
843
- */
844
- public async call<const T extends Query>(
845
- ns: NonNullable<unknown> extends XrpcRequestParams<T>
846
- ? Main<T>
847
- : Restricted<'This query type requires a "params" argument'>,
848
- ): Promise<XrpcResponseBody<T>>
849
- public async call<const T extends Procedure>(
850
- ns: undefined extends InferMethodInputBody<T, Uint8Array>
851
- ? Main<T>
852
- : Restricted<'This procedure type requires an "input" argument'>,
853
- ): Promise<XrpcResponseBody<T>>
854
- public async call<const T extends Action>(
855
- ns: void extends InferActionInput<T>
856
- ? Main<T>
857
- : Restricted<'This action type requires an "input" argument'>,
858
- ): Promise<InferActionOutput<T>>
859
- public async call<const T extends Action | Procedure | Query>(
860
- ns: Main<T>,
861
- arg: T extends Action
862
- ? InferActionInput<T>
863
- : T extends Procedure
864
- ? InferMethodInputBody<T, Uint8Array>
865
- : T extends Query
866
- ? XrpcRequestParams<T>
867
- : never,
868
- options?: T extends Action
869
- ? ActionOptions
870
- : T extends Procedure
871
- ? Omit<XrpcOptions<T>, 'body'>
872
- : T extends Query
873
- ? Omit<XrpcOptions<T>, 'params'>
874
- : never,
875
- ): Promise<
876
- T extends Action
877
- ? InferActionOutput<T>
878
- : T extends Procedure
879
- ? XrpcResponseBody<T>
880
- : T extends Query
881
- ? XrpcResponseBody<T>
882
- : never
883
- >
884
- public async call(
885
- ns: Main<Action> | Main<Procedure> | Main<Query>,
886
- arg?: LexValue | Params,
887
- options: ActionOptions = {},
888
- ): Promise<unknown> {
889
- const method = getMain(ns)
890
-
891
- if (typeof method === 'function') {
892
- return method(this, arg, options)
893
- }
894
-
895
- if (method instanceof Procedure) {
896
- const result = await this.xrpc(method, { ...options, body: arg as any })
897
- return result.body
898
- } else if (method instanceof Query) {
899
- const result = await this.xrpc(method, { ...options, params: arg as any })
900
- return result.body
901
- } else {
902
- throw new TypeError('Invalid lexicon')
903
- }
904
- }
905
-
906
- /**
907
- * Creates a new record with full type safety based on the schema.
908
- *
909
- * @param ns - The record schema definition
910
- * @param input - The record data (without `$type`, which is added automatically)
911
- * @param options - Create options including rkey (required for some record types)
912
- * @returns The create output including URI and CID
913
- *
914
- * @example Creating a post
915
- * ```typescript
916
- * const result = await client.create(app.bsky.feed.post.main, {
917
- * text: 'Hello, world!',
918
- * createdAt: new Date().toISOString()
919
- * })
920
- * console.log(result.uri)
921
- * ```
922
- *
923
- * @example Creating a record with explicit rkey
924
- * ```typescript
925
- * const result = await client.create(app.bsky.actor.profile.main, {
926
- * displayName: 'Alice'
927
- * }, { rkey: 'self' })
928
- * ```
929
- */
930
- public async create<const T extends RecordSchema>(
931
- ns: NonNullable<unknown> extends CreateOptions<T>
932
- ? Main<T>
933
- : Restricted<'This record type requires an "options" argument'>,
934
- input: Omit<Infer<T>, '$type'>,
935
- ): Promise<CreateOutput>
936
- public async create<const T extends RecordSchema>(
937
- ns: Main<T>,
938
- input: Omit<Infer<T>, '$type'>,
939
- options: CreateOptions<T>,
940
- ): Promise<CreateOutput>
941
- public async create<const T extends RecordSchema>(
942
- ns: Main<T>,
943
- input: Omit<Infer<T>, '$type'>,
944
- options: CreateOptions<T> = {} as CreateOptions<T>,
945
- ): Promise<CreateOutput> {
946
- const schema: T = getMain(ns)
947
- const record = schema.build(input) as TypedLexMap<NsidString>
948
- if (options?.validateRequest) schema.validate(record)
949
- const rkey = options.rkey ?? getDefaultRecordKey(schema)
950
- if (rkey !== undefined) schema.keySchema.assert(rkey)
951
- const response = await this.createRecord(record, rkey, options)
952
- return response.body
953
- }
954
-
955
- /**
956
- * Deletes a record with type-safe options.
957
- *
958
- * @param ns - The record schema definition
959
- * @param options - Delete options (rkey required for non-literal keys)
960
- * @returns The delete output
961
- */
962
- public async delete<const T extends RecordSchema>(
963
- ns: NonNullable<unknown> extends DeleteOptions<T>
964
- ? Main<T>
965
- : Restricted<'This record type requires an "options" argument'>,
966
- ): Promise<DeleteOutput>
967
- public async delete<const T extends RecordSchema>(
968
- ns: Main<T>,
969
- options?: DeleteOptions<T>,
970
- ): Promise<DeleteOutput>
971
- public async delete<const T extends RecordSchema>(
972
- ns: Main<T>,
973
- options: DeleteOptions<T> = {} as DeleteOptions<T>,
974
- ): Promise<DeleteOutput> {
975
- const schema = getMain(ns)
976
- const rkey = schema.keySchema.parse(
977
- options.rkey ?? getLiteralRecordKey(schema),
978
- )
979
- const response = await this.deleteRecord(schema.$type, rkey, options)
980
- return response.body
981
- }
982
-
983
- /**
984
- * Retrieves a record with type-safe validation.
985
- *
986
- * @param ns - The record schema definition
987
- * @param options - Get options (rkey required for non-literal keys)
988
- * @returns The record data validated against the schema
989
- *
990
- * @example
991
- * ```typescript
992
- * const profile = await client.get(app.bsky.actor.profile.main)
993
- * // profile.value is typed as app.bsky.actor.profile.Record
994
- * console.log(profile.value.displayName)
995
- * ```
996
- */
997
- public async get<const T extends RecordSchema>(
998
- ns: T['key'] extends `literal:${string}`
999
- ? Main<T>
1000
- : Restricted<'This record type requires an "options" argument'>,
1001
- ): Promise<GetOutput<T>>
1002
- public async get<const T extends RecordSchema>(
1003
- ns: Main<T>,
1004
- options: GetOptions<T>,
1005
- ): Promise<GetOutput<T>>
1006
- public async get<const T extends RecordSchema>(
1007
- ns: Main<T>,
1008
- options: GetOptions<T> = {} as GetOptions<T>,
1009
- ): Promise<GetOutput<T>> {
1010
- const schema = getMain(ns)
1011
- const rkey = schema.keySchema.parse(
1012
- options.rkey ?? getLiteralRecordKey(schema),
1013
- )
1014
- const response = await this.getRecord(schema.$type, rkey, options)
1015
- const value = schema.validate(response.body.value)
1016
- return { ...response.body, value }
1017
- }
1018
-
1019
- /**
1020
- * Creates or updates a record with full type safety.
1021
- *
1022
- * @param ns - The record schema definition
1023
- * @param input - The record data
1024
- * @param options - Put options (rkey required for non-literal keys)
1025
- * @returns The put output including URI and CID
1026
- */
1027
- public async put<const T extends RecordSchema>(
1028
- ns: NonNullable<unknown> extends PutOptions<T>
1029
- ? Main<T>
1030
- : Restricted<'This record type requires an "options" argument'>,
1031
- input: Omit<Infer<T>, '$type'>,
1032
- ): Promise<PutOutput>
1033
- public async put<const T extends RecordSchema>(
1034
- ns: Main<T>,
1035
- input: Omit<Infer<T>, '$type'>,
1036
- options: PutOptions<T>,
1037
- ): Promise<PutOutput>
1038
- public async put<const T extends RecordSchema>(
1039
- ns: Main<T>,
1040
- input: Omit<Infer<T>, '$type'>,
1041
- options: PutOptions<T> = {} as PutOptions<T>,
1042
- ): Promise<PutOutput> {
1043
- const schema: T = getMain(ns)
1044
- const record = schema.build(input) as TypedLexMap<NsidString>
1045
- if (options?.validateRequest) schema.validate(record)
1046
- const rkey = options.rkey ?? getLiteralRecordKey(schema)
1047
- const response = await this.putRecord(record, rkey, options)
1048
- return response.body
1049
- }
1050
-
1051
- /**
1052
- * Lists records with type-safe validation and separation of valid/invalid records.
1053
- *
1054
- * @param ns - The record schema definition
1055
- * @param options - List options
1056
- * @returns Records split into valid (matching schema) and invalid arrays
1057
- *
1058
- * @example
1059
- * ```typescript
1060
- * const result = await client.list(app.bsky.feed.post.main, { limit: 100 })
1061
- * console.log(`Found ${result.records.length} valid posts`)
1062
- * console.log(`Found ${result.invalid.length} invalid records`)
1063
- * ```
1064
- */
1065
- async list<const T extends RecordSchema>(
1066
- ns: Main<T>,
1067
- options?: ListOptions,
1068
- ): Promise<ListOutput<T>> {
1069
- const schema = getMain(ns)
1070
- const { body } = await this.listRecords(schema.$type, options)
1071
-
1072
- const records: ListRecord<Infer<T>>[] = []
1073
- const invalid: LexMap[] = []
1074
-
1075
- for (const record of body.records) {
1076
- const parsed = schema.safeValidate(record.value)
1077
- if (parsed.success) {
1078
- records.push({ ...record, value: parsed.value })
1079
- } else {
1080
- invalid.push(record.value)
1081
- }
1082
- }
1083
-
1084
- return { ...body, records, invalid }
1085
- }
1086
- }