@atproto/lex-client 0.0.17 → 0.0.19

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.
@@ -1 +1 @@
1
- {"version":3,"file":"response.js","sourceRoot":"","sources":["../src/response.ts"],"names":[],"mappings":";;;AAAA,gDAA6D;AAW7D,2CAMoB;AACpB,yCAImB;AAEnB,MAAM,mBAAmB,GAAG,0BAA0B,CAAA;AACtD,MAAM,iBAAiB,GAAG,kBAAkB,CAAA;AA4F5C;;;;GAIG;AACH,MAAa,YAAY;IAYZ;IACA;IACA;IACA;IAZX,yCAAyC;IAChC,OAAO,GAAG,IAAa,CAAA;IAEhC,uCAAuC;IACvC,IAAI,KAAK;QACP,OAAO,IAAI,CAAA;IACb,CAAC;IAED,YACW,MAAS,EACT,MAAc,EACd,OAAgB,EAChB,OAA+B;QAH/B,WAAM,GAAN,MAAM,CAAG;QACT,WAAM,GAAN,MAAM,CAAQ;QACd,YAAO,GAAP,OAAO,CAAS;QAChB,YAAO,GAAP,OAAO,CAAwB;IACvC,CAAC;IAEJ;;;OAGG;IACH,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,KAAK,iBAAiB,CAAA;IAC1D,CAAC;IAED;;;OAGG;IACH,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,OAAO,EAAE,QAAwC,CAAA;IAC/D,CAAC;IAED;;;;;;OAMG;IACH,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,OAAO,EAAE,IAA2B,CAAA;IAClD,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,KAAK,CAAC,iBAAiB,CAC5B,MAAS,EACT,QAAkB,EAClB,OAA6B;QAE7B,0EAA0E;QAC1E,kEAAkE;QAClE,oDAAoD;QAEpD,4EAA4E;QAC5E,IAAI,QAAQ,CAAC,MAAM,GAAG,GAAG,IAAI,QAAQ,CAAC,MAAM,IAAI,GAAG,EAAE,CAAC;YACpD,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AAE,IAAI,EAAE,IAAI,UAAU,CAAC,WAAW,CAAC,EAAE,CAAA;IACxD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,OAAO,GAAG,kCAAkC,CAAA;QAClD,MAAM,aAAa,GAAG,KAAK,YAAY,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAA;QAC5E,MAAM,IAAI,6BAAiB,CACzB,MAAM,EACN,QAAQ,EACR,IAAI,EACJ,aAAa,CAAC,CAAC,CAAC,GAAG,OAAO,KAAK,aAAa,EAAE,CAAC,CAAC,CAAC,OAAO,EACxD,EAAE,KAAK,EAAE,CACV,CAAA;IACH,CAAC;AACH,CAAC","sourcesContent":["import { LexParseOptions, lexParse } from '@atproto/lex-json'\nimport {\n InferMethodOutputEncoding,\n InferOutput,\n LexValue,\n Payload,\n Procedure,\n Query,\n ResultSuccess,\n Validator,\n} from '@atproto/lex-schema'\nimport {\n XrpcAuthenticationError,\n XrpcInvalidResponseError,\n XrpcResponseError,\n XrpcUpstreamError,\n isXrpcErrorPayload,\n} from './errors.js'\nimport {\n EncodingString,\n XrpcUnknownResponsePayload,\n isEncodingString,\n} from './types.js'\n\nconst CONTENT_TYPE_BINARY = 'application/octet-stream'\nconst CONTENT_TYPE_JSON = 'application/json'\n\n// @NOTE the output schema is used in \"parse\" mode (safeParse), which means that\n// defaults will be applied and coercions will be performed, so we need to use\n// InferOutput here to get the final parsed type, not Infer/InferInput. For this\n// reason, we cannot use InferMethodOutputBody and InferMethodOutput from\n// lex-schema here.\n\ntype InferEncodingType<TEncoding extends string> = TEncoding extends '*/*'\n ? EncodingString\n : TEncoding extends `${infer T extends string}/*`\n ? `${T}/${string}`\n : TEncoding\n\ntype InferBodyType<\n TEncoding extends string,\n TSchema,\n> = TSchema extends Validator\n ? InferOutput<TSchema>\n : TEncoding extends `application/json`\n ? LexValue\n : Uint8Array\n\n/**\n * The body type of an XRPC response, inferred from the method's output schema.\n *\n * For JSON responses, this is the parsed LexValue. For binary responses,\n * this is a Uint8Array.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponseBody<M extends Procedure | Query> =\n M['output'] extends Payload<infer TEncoding, infer TSchema>\n ? TEncoding extends string\n ? InferBodyType<TEncoding, TSchema>\n : undefined\n : never\n\n/**\n * The full payload type of an XRPC response, including body and encoding.\n *\n * Returns `null` for methods that have no output.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponsePayload<M extends Procedure | Query> =\n M['output'] extends Payload<infer TEncoding, infer TSchema>\n ? TEncoding extends string\n ? {\n encoding: InferEncodingType<TEncoding>\n body: InferBodyType<TEncoding, TSchema>\n }\n : undefined\n : never\n\nexport type XrpcResponseOptions = {\n /**\n * Whether to validate the response against the method's output schema.\n * Disabling this can improve performance but may lead to runtime errors if\n * the response does not conform to the expected schema. Only set this to\n * `false` if you are certain that the upstream service will always return\n * valid responses.\n *\n * @default true\n */\n validateResponse?: boolean\n\n /**\n * Whether to strictly process response payloads according to Lex encoding\n * rules. By default, the client will reject responses with invalid Lex data\n * (floats and invalid $bytes / $link objects).\n *\n * Setting this option to `false` will allow the client to accept such\n * responses in a non-strict mode, where invalid Lex data will be returned\n * as-is (e.g., floats will not be rejected, and invalid $bytes / $link\n * objects will not be converted to Uint8Array / Cid). When in non-strict\n * mode, the validation will also be relaxed when validating the response\n * against the method's output schema, allowing values that do not strictly\n * conform to the schema (e.g. datetime strings that are not valid RFC3339\n * format, blobs that are not of the right size/mime-type, etc.) to be\n * accepted as long as their basic structure is correct.\n *\n * When validation is enabled (the default), the values defined through the\n * method schema will be enforced, ensuring that the client can still process\n * the response even if the server returns invalid Lex data.\n *\n * @default true\n * @see {@link LexParseOptions.strict}\n */\n strictResponseProcessing?: boolean\n}\n\n/**\n * Small container for XRPC response data.\n *\n * @implements {ResultSuccess<XrpcResponse<M>>} for convenience in result handling contexts.\n */\nexport class XrpcResponse<M extends Procedure | Query>\n implements ResultSuccess<XrpcResponse<M>>\n{\n /** @see {@link ResultSuccess.success} */\n readonly success = true as const\n\n /** @see {@link ResultSuccess.value} */\n get value(): this {\n return this\n }\n\n constructor(\n readonly method: M,\n readonly status: number,\n readonly headers: Headers,\n readonly payload: XrpcResponsePayload<M>,\n ) {}\n\n /**\n * Whether the response payload was parsed as {@link LexValue} (`true`) or is\n * in binary form {@link Uint8Array} (`false`).\n */\n get isParsed() {\n return this.method.output.encoding === CONTENT_TYPE_JSON\n }\n\n /**\n * The Content-Type encoding of the response (e.g., 'application/json').\n * Returns `undefined` if the response has no body.\n */\n get encoding() {\n return this.payload?.encoding as InferMethodOutputEncoding<M>\n }\n\n /**\n * The parsed response body.\n *\n * For 'application/json' responses, this is the parsed and validated LexValue.\n * For binary responses, this is a Uint8Array.\n * Returns `undefined` if the response has no body.\n */\n get body() {\n return this.payload?.body as XrpcResponseBody<M>\n }\n\n /**\n * @throws {XrpcResponseError} in case of (valid) XRPC error responses. Use\n * {@link XrpcResponseError.matchesSchemaErrors} to narrow the error type based on\n * the method's declared error schema. This can be narrowed further as a\n * {@link XrpcAuthenticationError} if the error is an authentication error.\n * @throws {XrpcUpstreamError} when the response is not a valid XRPC\n * response, or if the response does not conform to the method's schema.\n */\n static async fromFetchResponse<const M extends Procedure | Query>(\n method: M,\n response: Response,\n options?: XrpcResponseOptions,\n ): Promise<XrpcResponse<M>> {\n // @NOTE The body MUST either be read or canceled to avoid resource leaks.\n // Since nothing should cause an exception before \"readPayload\" is\n // called, we can safely not use a try/finally here.\n\n // @NOTE redirect is set to 'follow', so we shouldn't get 3xx responses here\n if (response.status < 200 || response.status >= 300) {\n // Always parse json for error responses\n const payload = await readPayload(method, response, {\n parse: { strict: options?.strictResponseProcessing ?? true },\n })\n\n // Properly formatted XRPC error response ?\n if (response.status >= 400 && isXrpcErrorPayload(payload)) {\n throw response.status === 401\n ? new XrpcAuthenticationError<M>(method, response, payload)\n : new XrpcResponseError<M>(method, response, payload)\n }\n\n // Invalid XRPC response (we probably did not hit an XRPC implementation)\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n response.status >= 500\n ? 'Upstream server encountered an error'\n : response.status >= 400\n ? 'Invalid response payload'\n : 'Invalid response status code',\n )\n }\n\n const payload = await readPayload(method, response, {\n // Only parse json if the schema expects it\n parse: method.output.encoding === CONTENT_TYPE_JSON && {\n strict: options?.strictResponseProcessing ?? true,\n },\n })\n\n // Response is successful (2xx). Validate payload (data and encoding) against schema.\n if (method.output.encoding == null) {\n // Schema expects no payload\n if (payload) {\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n `Expected response with no body, got ${payload.encoding}`,\n )\n }\n } else {\n // Schema expects a payload\n if (!payload || !method.output.matchesEncoding(payload.encoding)) {\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n payload\n ? `Expected ${method.output.encoding} response, got ${payload.encoding}`\n : `Expected non-empty response with content-type ${method.output.encoding}`,\n )\n }\n\n // Assert valid response body.\n if (method.output.schema && options?.validateResponse !== false) {\n const result = method.output.schema.safeParse(payload.body, {\n strict: options?.strictResponseProcessing ?? true,\n })\n\n if (!result.success) {\n throw new XrpcInvalidResponseError(\n method,\n response,\n payload,\n result.reason,\n )\n }\n\n const parsedPayload = {\n body: result.value,\n encoding: payload.encoding,\n } as XrpcResponsePayload<M>\n\n return new XrpcResponse<M>(\n method,\n response.status,\n response.headers,\n parsedPayload,\n )\n }\n }\n\n return new XrpcResponse<M>(\n method,\n response.status,\n response.headers,\n payload as XrpcResponsePayload<M>,\n )\n }\n}\n\ntype ReadPayloadOptions = {\n /**\n * Whether to parse the response body as JSON and convert it to LexValue.\n *\n * @default false\n */\n parse?: false | LexParseOptions\n}\n\n/**\n * @note this function always consumes the response body\n */\nasync function readPayload(\n method: Query | Procedure,\n response: Response,\n options?: ReadPayloadOptions,\n): Promise<undefined | XrpcUnknownResponsePayload> {\n try {\n // @TODO Should we limit the maximum response size here (this could also be\n // done by the FetchHandler)?\n\n const encoding = response.headers\n .get('content-type')\n ?.split(';')[0]\n .trim()\n .toLowerCase()\n\n // Response content-type is undefined\n if (!encoding) {\n // If the body is empty, return undefined (= no payload)\n const arrayBuffer = await response.arrayBuffer()\n if (arrayBuffer.byteLength === 0) return undefined\n\n // If we got data despite no content-type, treat it as binary\n return {\n encoding: CONTENT_TYPE_BINARY,\n body: new Uint8Array(arrayBuffer),\n }\n }\n\n if (!isEncodingString(encoding)) {\n throw new TypeError(`Invalid content-type \"${encoding}\" in response`)\n }\n\n if (options?.parse && encoding === CONTENT_TYPE_JSON) {\n // @NOTE It might be worth returning the raw bytes here (Uint8Array) and\n // perform the lex parsing using cborg/json, allowing to do\n // bytes->LexValue in one step instead of bytes->text->JSON->LexValue.\n // This would require adding encode/decode utilities to lex-json (similar\n // to @ipld/dag-json)\n const text = await response.text()\n\n // @NOTE Using `lexParse(text)` (instead of `jsonToLex(json)`) here as\n // using a reviver function during JSON.parse should be faster than\n // parsing to JSON then converting to Lex (?)\n\n // @TODO verify statement above\n return { encoding, body: lexParse(text, options.parse) }\n }\n\n const arrayBuffer = await response.arrayBuffer()\n return { encoding, body: new Uint8Array(arrayBuffer) }\n } catch (cause) {\n const message = 'Unable to parse response payload'\n const messageDetail = cause instanceof TypeError ? cause.message : undefined\n throw new XrpcUpstreamError(\n method,\n response,\n null,\n messageDetail ? `${message}: ${messageDetail}` : message,\n { cause },\n )\n }\n}\n"]}
1
+ {"version":3,"file":"response.js","sourceRoot":"","sources":["../src/response.ts"],"names":[],"mappings":";;;AAAA,gDAAsE;AAWtE,2CAKoB;AACpB,yCAImB;AAEnB,MAAM,mBAAmB,GAAG,0BAA0B,CAAA;AACtD,MAAM,iBAAiB,GAAG,kBAAkB,CAAA;AA8F5C;;;;GAIG;AACH,MAAa,YAAY;IAYZ;IACA;IACA;IACA;IAZX,yCAAyC;IAChC,OAAO,GAAG,IAAa,CAAA;IAEhC,uCAAuC;IACvC,IAAI,KAAK;QACP,OAAO,IAAI,CAAA;IACb,CAAC;IAED,YACW,MAAS,EAC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, lexParseJsonBytes } from '@atproto/lex-json'\nimport {\n InferMethodOutputEncoding,\n InferOutput,\n LexValue,\n Payload,\n Procedure,\n Query,\n ResultSuccess,\n Validator,\n} from '@atproto/lex-schema'\nimport {\n XrpcAuthenticationError,\n XrpcInvalidResponseError,\n XrpcResponseError,\n XrpcResponseValidationError,\n} from './errors.js'\nimport {\n EncodingString,\n XrpcUnknownResponsePayload,\n isEncodingString,\n} from './types.js'\n\nconst CONTENT_TYPE_BINARY = 'application/octet-stream'\nconst CONTENT_TYPE_JSON = 'application/json'\n\n// @NOTE the output schema is used in \"parse\" mode (safeParse), which means that\n// defaults will be applied and coercions will be performed, so we need to use\n// InferOutput here to get the final parsed type, not Infer/InferInput. For this\n// reason, we cannot use InferMethodOutputBody and InferMethodOutput from\n// lex-schema here.\n\ntype InferEncodingType<TEncoding extends string> = TEncoding extends '*/*'\n ? EncodingString\n : TEncoding extends `${infer T extends string}/*`\n ? `${T}/${string}`\n : TEncoding\n\ntype InferBodyType<\n TEncoding extends string,\n TSchema,\n> = TSchema extends Validator\n ? InferOutput<TSchema>\n : TEncoding extends `application/json`\n ? LexValue\n : Uint8Array\n\n/**\n * The body type of an XRPC response, inferred from the method's output schema.\n *\n * For JSON responses, this is the parsed LexValue. For binary responses,\n * this is a Uint8Array.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponseBody<M extends Procedure | Query> =\n M['output'] extends Payload<infer TEncoding, infer TSchema>\n ? TEncoding extends string\n ? InferBodyType<TEncoding, TSchema>\n : undefined | LexValue | Uint8Array\n : never\n\n/**\n * The full payload type of an XRPC response, including body and encoding.\n *\n * Returns `null` for methods that have no output.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponsePayload<M extends Procedure | Query> =\n M['output'] extends Payload<infer TEncoding, infer TSchema>\n ? TEncoding extends string\n ? {\n encoding: InferEncodingType<TEncoding>\n body: InferBodyType<TEncoding, TSchema>\n }\n : // If the schema does not specify an output encoding, anything could be\n // returned, including no payload at all (undefined).\n undefined | { body: LexValue | Uint8Array; encoding: string }\n : never\n\nexport type XrpcResponseOptions = {\n /**\n * Whether to validate the response against the method's output schema.\n * Disabling this can improve performance but may lead to runtime errors if\n * the response does not conform to the expected schema. Only set this to\n * `false` if you are certain that the upstream service will always return\n * valid responses.\n *\n * @default true\n */\n validateResponse?: boolean\n\n /**\n * Whether to strictly process response payloads according to Lex encoding\n * rules. By default, the client will reject responses with invalid Lex data\n * (floats and invalid $bytes / $link objects).\n *\n * Setting this option to `false` will allow the client to accept such\n * responses in a non-strict mode, where invalid Lex data will be returned\n * as-is (e.g., floats will not be rejected, and invalid $bytes / $link\n * objects will not be converted to Uint8Array / Cid). When in non-strict\n * mode, the validation will also be relaxed when validating the response\n * against the method's output schema, allowing values that do not strictly\n * conform to the schema (e.g. datetime strings that are not valid RFC3339\n * format, blobs that are not of the right size/mime-type, etc.) to be\n * accepted as long as their basic structure is correct.\n *\n * When validation is enabled (the default), the values defined through the\n * method schema will be enforced, ensuring that the client can still process\n * the response even if the server returns invalid Lex data.\n *\n * @default true\n * @see {@link LexParseOptions.strict}\n */\n strictResponseProcessing?: boolean\n}\n\n/**\n * Small container for XRPC response data.\n *\n * @implements {ResultSuccess<XrpcResponse<M>>} for convenience in result handling contexts.\n */\nexport class XrpcResponse<M extends Procedure | Query>\n implements ResultSuccess<XrpcResponse<M>>\n{\n /** @see {@link ResultSuccess.success} */\n readonly success = true as const\n\n /** @see {@link ResultSuccess.value} */\n get value(): this {\n return this\n }\n\n constructor(\n readonly method: M,\n readonly status: number,\n readonly headers: Headers,\n readonly payload: XrpcResponsePayload<M>,\n ) {}\n\n /**\n * Whether the response payload was parsed as {@link LexValue} (`true`) or is\n * in binary form {@link Uint8Array} (`false`).\n */\n get isParsed() {\n return this.method.output.encoding === CONTENT_TYPE_JSON\n }\n\n /**\n * The Content-Type encoding of the response (e.g., 'application/json').\n * Returns `undefined` if the response has no body.\n */\n get encoding() {\n return this.payload?.encoding as InferMethodOutputEncoding<M>\n }\n\n /**\n * The parsed response body.\n *\n * For 'application/json' responses, this is the parsed and validated LexValue.\n * For binary responses, this is a Uint8Array.\n * Returns `undefined` if the response has no body.\n */\n get body() {\n return this.payload?.body as XrpcResponseBody<M>\n }\n\n /**\n * @throws {XrpcResponseError} in case of (valid) XRPC error responses. Use\n * {@link XrpcResponseError.matchesSchemaErrors} to narrow the error type based on\n * the method's declared error schema. This can be narrowed further as a\n * {@link XrpcAuthenticationError} if the error is an authentication error.\n * @throws {XrpcInvalidResponseError} when the response is not a valid XRPC\n * response, or if the response does not conform to the method's schema.\n */\n static async fromFetchResponse<const M extends Procedure | Query>(\n method: M,\n response: Response,\n options?: XrpcResponseOptions,\n ): Promise<XrpcResponse<M>> {\n // @NOTE The body MUST either be read or canceled to avoid resource leaks.\n // Since nothing should cause an exception before \"readPayload\" is\n // called, we can safely not use a try/finally here.\n\n // Always turn 4xx/5xx responses into XrpcResponseError\n if (response.status >= 400) {\n const payload = await readPayload(method, response, {\n // Always parse errors in non-strict mode\n parse: { strict: false },\n })\n\n if (response.status === 401) {\n throw new XrpcAuthenticationError<M>(method, response, payload)\n }\n\n throw new XrpcResponseError<M>(method, response, payload)\n }\n\n // @NOTE redirect is set to 'follow', so we shouldn't get 3xx responses here\n if (response.status < 200 || response.status >= 300) {\n await response.body?.cancel()\n\n throw new XrpcInvalidResponseError(\n method,\n response,\n undefined,\n `Unexpected status code ${response.status}`,\n )\n }\n\n const payload = await readPayload(method, response, {\n // Parse response if there is a schema, or if the encoding is\n // \"application/json\"\n parse:\n method.output.schema || method.output.encoding === CONTENT_TYPE_JSON\n ? { strict: options?.strictResponseProcessing ?? true }\n : // If there is no declared output encoding, we'll parse the output (in loose mode)\n method.output.encoding == null\n ? { strict: false }\n : false,\n })\n\n if (!method.output.matchesEncoding(payload?.encoding)) {\n throw new XrpcInvalidResponseError(\n method,\n response,\n payload,\n `Expected ${stringifyEncoding(method.output.encoding)} response (got ${stringifyEncoding(payload?.encoding)})`,\n )\n }\n\n // Response is successful (2xx). Validate payload (data and encoding) against schema.\n if (method.output.encoding != null) {\n // If the schema specifies an output, verify that the response properly\n // matches the expected format (encoding and schema, if present). If no\n // output is specified, any payload could be returned.\n\n // Needed for type safety. Should never happen since matchesEncoding()\n // should return not succeed if there is a schema encoding but no payload.\n if (!payload) throw new Error('Expected payload')\n\n // Assert valid response body.\n if (method.output.schema && options?.validateResponse !== false) {\n const result = method.output.schema.safeParse(payload.body, {\n strict: options?.strictResponseProcessing ?? true,\n })\n\n if (!result.success) {\n throw new XrpcResponseValidationError(\n method,\n response,\n payload,\n result.reason,\n )\n }\n\n const parsedPayload = {\n body: result.value,\n encoding: payload.encoding,\n } as XrpcResponsePayload<M>\n\n return new XrpcResponse<M>(\n method,\n response.status,\n response.headers,\n parsedPayload,\n )\n }\n }\n\n return new XrpcResponse<M>(\n method,\n response.status,\n response.headers,\n payload as XrpcResponsePayload<M>,\n )\n }\n}\n\ntype ReadPayloadOptions = {\n /**\n * Whether to parse the response body as JSON and convert it to LexValue.\n *\n * @default false\n */\n parse?: false | LexParseOptions\n}\n\n/**\n * @note this function always consumes the response body\n */\nasync function readPayload(\n method: Query | Procedure,\n response: Response,\n options?: ReadPayloadOptions,\n): Promise<undefined | XrpcUnknownResponsePayload> {\n try {\n // @TODO Should we limit the maximum response size here (this could also be\n // done by the FetchHandler)?\n\n const encoding = response.headers\n .get('content-type')\n ?.split(';')[0]\n .trim()\n .toLowerCase()\n\n // Response content-type is undefined\n if (!encoding) {\n // If the body is empty, return undefined (= no payload)\n const arrayBuffer = await response.arrayBuffer()\n if (arrayBuffer.byteLength === 0) return undefined\n\n // If we got data despite no content-type, treat it as binary\n return {\n encoding: CONTENT_TYPE_BINARY,\n body: new Uint8Array(arrayBuffer),\n }\n }\n\n if (!isEncodingString(encoding)) {\n throw new TypeError(`Invalid content-type \"${encoding}\" in response`)\n }\n\n if (options?.parse && encoding === CONTENT_TYPE_JSON) {\n const arrayBuffer = await response.arrayBuffer()\n const bytes = new Uint8Array(arrayBuffer)\n const body = lexParseJsonBytes(bytes, options.parse)\n return { encoding, body }\n }\n\n const arrayBuffer = await response.arrayBuffer()\n return { encoding, body: new Uint8Array(arrayBuffer) }\n } catch (cause) {\n const message = 'Unable to parse response payload'\n const messageDetail = cause instanceof TypeError ? cause.message : undefined\n throw new XrpcInvalidResponseError(\n method,\n response,\n undefined,\n messageDetail ? `${message}: ${messageDetail}` : message,\n { cause },\n )\n }\n}\n\nfunction stringifyEncoding(encoding: string | undefined) {\n return encoding ? `\"${encoding}\"` : 'no payload'\n}\n"]}
package/dist/xrpc.js CHANGED
@@ -125,7 +125,7 @@ function xrpcProcedureInput(method, options, encodingHint) {
125
125
  function buildPayload(schema, body, encodingHint) {
126
126
  if (schema.encoding === undefined) {
127
127
  if (body !== undefined) {
128
- throw new TypeError(`Cannot send a ${typeof body} body with undefined encoding`);
128
+ throw new TypeError(`Endpoint expects no payload`);
129
129
  }
130
130
  return null;
131
131
  }
package/dist/xrpc.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"xrpc.js","sourceRoot":"","sources":["../src/xrpc.ts"],"names":[],"mappings":";;AAsJA,oBAQC;AAmDD,4BAkBC;AAnOD,gDAAwE;AACxE,gDAAgD;AAChD,oDAY4B;AAC5B,yCAA4D;AAC5D,2CAAwE;AACxE,+CAAiE;AAEjE,uCAMkB;AA6HX,KAAK,UAAU,IAAI,CACxB,SAA+B,EAC/B,EAAW,EACX,UAA0B,EAAoB;IAE9C,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAI,SAAS,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;IAC1D,IAAI,QAAQ,CAAC,OAAO;QAAE,OAAO,QAAQ,CAAA;;QAChC,MAAM,QAAQ,CAAA;AACrB,CAAC;AAmDM,KAAK,UAAU,QAAQ,CAC5B,SAA+B,EAC/B,EAAW,EACX,UAA0B,EAAoB;IAE9C,OAAO,CAAC,MAAM,EAAE,cAAc,EAAE,CA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,CACjB,yCAAyC,YAAY,UAAU,MAAM,CAAC,QAAQ,YAAY,CAC3F,CAAA;QACH,CAAC;QACD,OAAO,YAAY,CAAA;IACrB,CAAC;IAED,WAAW;IAEX,IAAI,MAAM,CAAC,QAAQ,KAAK,KAAK,EAAE,CAAC;QAC9B,OAAO,0BAA0B,CAAA;IACnC,CAAC;IAED,IAAI,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;QACxC,OAAO,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC;YAClC,CAAC,CAAC,2BAA2B;YAC7B,CAAC,CAAC,GAAG,MAAM,CAAC,QAAQ,iBAAiB,CAAA;IACzC,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnC,OAAO,MAAM,CAAC,QAAQ,CAAA;IACxB,CAAC;IAED,MAAM,IAAI,SAAS,CACjB,yFAAyF,MAAM,CAAC,QAAQ,GAAG,CAC5G,CAAA;AACH,CAAC","sourcesContent":["import { LexValue, isLexScalar, isPlainObject } from '@atproto/lex-data'\nimport { lexStringify } from '@atproto/lex-json'\nimport {\n InferInput,\n InferPayload,\n Main,\n NsidString,\n Params,\n Payload,\n Procedure,\n Query,\n Restricted,\n Subscription,\n getMain,\n} from '@atproto/lex-schema'\nimport { Agent, AgentOptions, buildAgent } from './agent.js'\nimport { XrpcFailure, XrpcFetchError, asXrpcFailure } from './errors.js'\nimport { XrpcResponse, XrpcResponseOptions } from './response.js'\nimport { BinaryBodyInit } from './types.js'\nimport {\n XrpcRequestHeadersOptions,\n buildXrpcRequestHeaders,\n isAsyncIterable,\n isBlobLike,\n toReadableStream,\n} from './util.js'\n\n/**\n * The query/path parameters type for an XRPC method, inferred from its schema.\n *\n * @typeParam M - The XRPC method type (Procedure, Query, or Subscription)\n */\nexport type XrpcRequestParams<M extends Procedure | Query | Subscription> =\n InferInput<M['parameters']>\n\n// If all params are optional, allow omitting the params object\ntype XrpcRequestParamsOptions<P extends Params> =\n NonNullable<unknown> extends P ? { params?: P } : { params: P }\n\ntype XrpcRequestPayload<M extends Procedure | Query> = M extends Procedure\n ? InferPayload<M['input'], BinaryBodyInit>\n : undefined\n\ntype XrpcRequestPayloadOptions<TPayload> = TPayload extends {\n body: infer B\n encoding: infer E\n}\n ? {\n body: B\n\n /**\n * mime type hint for binary bodies\n *\n * Only needed for endpoints that accept binary input (e.g. file uploads)\n * when the body is a Blob-like object without a type (e.g. fetch-blob's\n * Blob). If the body is a Blob-like object with a type, that type will be\n * used as the content-type header instead of this option.\n *\n * @default \"application/octet-stream\"\n */\n encoding?: E\n }\n : { body?: undefined; encoding?: undefined }\n\n/**\n * Options for making an XRPC request, based on the method schema.\n *\n * Combines {@link XrpcRequestOptions} and {@link XrpcResponseOptions} with\n * method-specific params and body requirements. The type system ensures\n * required params/body are provided based on the method schema.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n *\n * @example Query with params\n * ```typescript\n * const options: XrpcOptions<typeof app.bsky.feed.getTimeline.main> = {\n * params: { limit: 50 }\n * }\n * ```\n *\n * @example Procedure with body\n * ```typescript\n * const options: XrpcOptions<typeof com.atproto.repo.createRecord.main> = {\n * body: { repo: did, collection: 'app.bsky.feed.post', record: { ... } }\n * }\n * ```\n */\nexport type XrpcOptions<M extends Procedure | Query = Procedure | Query> =\n XrpcRequestOptions<M> & XrpcResponseOptions\n\nexport type XrpcRequestOptions<\n M extends Procedure | Query = Procedure | Query,\n> = XrpcRequestProcessingOptions &\n XrpcRequestHeadersOptions &\n XrpcRequestPayloadOptions<XrpcRequestPayload<M>> &\n XrpcRequestParamsOptions<XrpcRequestParams<M>>\n\nexport type XrpcRequestProcessingOptions = {\n /**\n * AbortSignal to cancel the request.\n */\n signal?: AbortSignal\n\n /**\n * Whether to validate the request against the method's input schema. Enabling\n * this can help catch errors early but may have a performance cost. This\n * would typically only be set to `true` in development or debugging\n * scenarios.\n *\n * @default false\n */\n validateRequest?: boolean\n}\n\n/**\n * Makes an XRPC request and throws on failure.\n *\n * This is the low-level function for making XRPC calls.\n *\n * @param agent - The {@link Agent} to use for making the request\n * @param ns - The lexicon method definition\n * @param options - Request {@link XrpcOptions options} (params, body, headers, etc.)\n * @returns The successful {@link XrpcResponse}\n * @throws {XrpcFailure} When the request fails\n *\n * @example\n * ```typescript\n * const response = await xrpc('https://bsky.network', com.atproto.identity.resolveHandle, {\n * params: { handle: \"atproto.com\" }\n * })\n * ```\n *\n * @example\n * ```typescript\n * const response = await xrpc(agent, app.bsky.feed.getTimeline.main, {\n * params: { limit: 50 }\n * })\n * ```\n */\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n): Promise<XrpcResponse<M>>\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResponse<M>>\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n): Promise<XrpcResponse<M>> {\n const response = await xrpcSafe<M>(agentOpts, ns, options)\n if (response.success) return response\n else throw response\n}\n\n/**\n * Union type representing either a successful response or a failure.\n *\n * Both {@link XrpcResponse} and {@link XrpcFailure} have a `success` property\n * that can be used to discriminate between them.\n *\n * @typeParam M - The XRPC method type\n */\nexport type XrpcResult<M extends Procedure | Query> =\n | XrpcResponse<M>\n | XrpcFailure<M>\n\n/**\n * Makes an XRPC request without throwing on failure.\n *\n * Returns a discriminated union that can be checked via the `success` property.\n * This is useful for handling errors without try/catch blocks. This also allow\n * failure results to be typed with the method schema, which can provide better\n * type safety when handling errors (e.g. checking for specific error codes).\n *\n * @param agent - The {@link Agent} to use for making the request\n * @param ns - The lexicon method definition\n * @param options - Request {@link XrpcOptions options} (params, body, headers, etc.)\n * @returns Either a successful {@link XrpcResponse} or an {@link XrpcFailure}\n *\n * @example\n * ```typescript\n * const result = await xrpcSafe('https://example.com', app.bsky.actor.getProfile, {\n * params: { actor: 'alice.bsky.social' }\n * })\n *\n * if (result.success) {\n * console.log(result.body.displayName)\n * } else {\n * console.error('Request failed:', result.error)\n * }\n * ```\n */\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n): Promise<XrpcResult<M>>\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResult<M>>\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n): Promise<XrpcResult<M>> {\n options.signal?.throwIfAborted()\n const method: M = getMain(ns)\n try {\n const agent = buildAgent(agentOpts)\n const url = xrpcRequestUrl(method, options)\n const request = xrpcRequestInit(method, options)\n const response = await agent.fetchHandler(url, request).catch((cause) => {\n throw new XrpcFetchError(method, cause)\n })\n return await XrpcResponse.fromFetchResponse<M>(method, response, options)\n } catch (cause) {\n return asXrpcFailure(method, cause)\n }\n}\n\nfunction xrpcRequestUrl<M extends Procedure | Query | Subscription>(\n method: M,\n options: { params?: Params },\n): `/xrpc/${NsidString}${'' | `?${string}`}` {\n const path = `/xrpc/${method.nsid}` as const\n\n // @NOTE param.toURLSearchParams() will always validate the params in order to\n // apply default values, so we can't disable it with options.validateRequest\n\n const queryString = method.parameters\n ?.toURLSearchParams(options.params ?? {})\n .toString()\n\n return queryString ? (`${path}?${queryString}` as const) : path\n}\n\nfunction xrpcRequestInit<T extends Procedure | Query>(\n schema: T,\n options: XrpcRequestProcessingOptions &\n XrpcRequestHeadersOptions &\n XrpcProcedureInputOptions & {\n encoding?: string\n },\n): RequestInit & { duplex?: 'half' } {\n const headers = buildXrpcRequestHeaders(options)\n\n // Tell the server what type of response we're expecting\n if (schema.output.encoding) {\n headers.set('accept', schema.output.encoding)\n }\n\n // Caller should not set content-type header\n if (headers.has('content-type')) {\n const contentType = headers.get('content-type')\n throw new TypeError(`Unexpected content-type header (${contentType})`)\n }\n\n // Requests with body\n if ('input' in schema) {\n const encodingHint = options.encoding\n const input = xrpcProcedureInput(schema, options, encodingHint)\n\n if (input) {\n headers.set('content-type', input.encoding)\n } else if (encodingHint != null) {\n throw new TypeError(`Unexpected encoding hint (${encodingHint})`)\n }\n\n return {\n duplex: 'half',\n redirect: 'follow',\n referrerPolicy: 'strict-origin-when-cross-origin', // (default)\n mode: 'cors', // (default)\n signal: options.signal,\n method: 'POST',\n headers,\n body: input?.body,\n }\n }\n\n // Requests without body\n return {\n duplex: 'half',\n redirect: 'follow',\n referrerPolicy: 'strict-origin-when-cross-origin', // (default)\n mode: 'cors', // (default)\n signal: options.signal,\n method: 'GET',\n headers,\n }\n}\n\ntype XrpcProcedureInputOptions = {\n body?: LexValue | BinaryBodyInit\n validateRequest?: boolean\n}\n\nfunction xrpcProcedureInput(\n method: Procedure,\n options: XrpcProcedureInputOptions,\n encodingHint?: string,\n): null | { body: BodyInit; encoding: string } {\n const { input } = method\n const { body } = options\n\n if (options.validateRequest) {\n input.schema?.check(body)\n }\n\n // Special handling for endpoints expecting application/json input\n if (input.encoding === 'application/json') {\n // @NOTE **NOT** using isLexValue here to avoid deep checks in order to\n // distinguish between LexValue and BinaryBodyInit.\n if (!isLexScalar(body) && !isPlainObject(body) && !Array.isArray(body)) {\n throw new TypeError(`Expected LexValue body, got ${typeof body}`)\n }\n\n return buildPayload(input, lexStringify(body), encodingHint)\n }\n\n // Other encodings will be sent unaltered (ie. as binary data)\n switch (typeof body) {\n case 'undefined':\n case 'string':\n return buildPayload(input, body, encodingHint)\n case 'object': {\n if (body === null) break\n if (\n ArrayBuffer.isView(body) ||\n body instanceof ArrayBuffer ||\n body instanceof ReadableStream\n ) {\n return buildPayload(input, body, encodingHint)\n } else if (isAsyncIterable(body)) {\n return buildPayload(input, toReadableStream(body), encodingHint)\n } else if (isBlobLike(body)) {\n return buildPayload(input, body, encodingHint || body.type)\n }\n }\n }\n\n throw new TypeError(\n `Invalid ${typeof body} body for ${input.encoding} encoding`,\n )\n}\n\nfunction buildPayload(\n schema: Payload,\n body: undefined | BodyInit,\n encodingHint?: string,\n): null | { body: BodyInit; encoding: string } {\n if (schema.encoding === undefined) {\n if (body !== undefined) {\n throw new TypeError(\n `Cannot send a ${typeof body} body with undefined encoding`,\n )\n }\n\n return null\n }\n\n if (body === undefined) {\n // This error would be returned by the server, but we can catch it earlier\n // to avoid un-necessary requests. Note that a content-length of 0 does not\n // necessary mean that the body is \"empty\" (e.g. an empty txt file).\n throw new TypeError(`A request body is expected but none was provided`)\n }\n\n const encoding = buildEncoding(schema, encodingHint)\n return { encoding, body }\n}\n\nfunction buildEncoding(schema: Payload, encodingHint?: string): string {\n // Should never happen (required for type safety)\n if (!schema.encoding) {\n throw new TypeError('Unexpected payload')\n }\n\n if (encodingHint?.length) {\n if (!schema.matchesEncoding(encodingHint)) {\n throw new TypeError(\n `Cannot send a body with content-type \"${encodingHint}\" for \"${schema.encoding}\" encoding`,\n )\n }\n return encodingHint\n }\n\n // Fallback\n\n if (schema.encoding === '*/*') {\n return 'application/octet-stream'\n }\n\n if (schema.encoding.startsWith('text/')) {\n return schema.encoding.includes('*')\n ? 'text/plain; charset=utf-8'\n : `${schema.encoding}; charset=utf-8`\n }\n\n if (!schema.encoding.includes('*')) {\n return schema.encoding\n }\n\n throw new TypeError(\n `Unable to determine payload encoding. Please provide a 'content-type' header matching ${schema.encoding}.`,\n )\n}\n"]}
1
+ {"version":3,"file":"xrpc.js","sourceRoot":"","sources":["../src/xrpc.ts"],"names":[],"mappings":";;AAsJA,oBAQC;AAmDD,4BAkBC;AAnOD,gDAAwE;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;IACzE,CAAC;IAED,MAAM,QAAQ,GAAG,aAAa,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IACpD,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAA;AAC3B,CAAC;AAED,SAAS,aAAa,CAAC,MAAe,EAAE,YAAqB;IAC3D,iDAAiD;IACjD,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;QACrB,MAAM,IAAI,SAAS,CAAC,oBAAoB,CAAC,CAAA;IAC3C,CAAC;IAED,IAAI,YAAY,EAAE,MAAM,EAAE,CAAC;QACzB,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,YAAY,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,SAAS,CACjB,yCAAyC,YAAY,UAAU,MAAM,CAAC,QAAQ,YAAY,CAC3F,CAAA;QACH,CAAC;QACD,OAAO,YAAY,CAAA;IACrB,CAAC;IAED,WAAW;IAEX,IAAI,MAAM,CAAC,QAAQ,KAAK,KAAK,EAAE,CAAC;QAC9B,OAAO,0BAA0B,CAAA;IACnC,CAAC;IAED,IAAI,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;QACxC,OAAO,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC;YAClC,CAAC,CAAC,2BAA2B;YAC7B,CAAC,CAAC,GAAG,MAAM,CAAC,QAAQ,iBAAiB,CAAA;IACzC,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnC,OAAO,MAAM,CAAC,QAAQ,CAAA;IACxB,CAAC;IAED,MAAM,IAAI,SAAS,CACjB,yFAAyF,MAAM,CAAC,QAAQ,GAAG,CAC5G,CAAA;AACH,CAAC","sourcesContent":["import { LexValue, isLexScalar, isPlainObject } from '@atproto/lex-data'\nimport { lexStringify } from '@atproto/lex-json'\nimport {\n InferInput,\n InferPayload,\n Main,\n NsidString,\n Params,\n Payload,\n Procedure,\n Query,\n Restricted,\n Subscription,\n getMain,\n} from '@atproto/lex-schema'\nimport { Agent, AgentOptions, buildAgent } from './agent.js'\nimport { XrpcFailure, XrpcFetchError, asXrpcFailure } from './errors.js'\nimport { XrpcResponse, XrpcResponseOptions } from './response.js'\nimport { BinaryBodyInit } from './types.js'\nimport {\n XrpcRequestHeadersOptions,\n buildXrpcRequestHeaders,\n isAsyncIterable,\n isBlobLike,\n toReadableStream,\n} from './util.js'\n\n/**\n * The query/path parameters type for an XRPC method, inferred from its schema.\n *\n * @typeParam M - The XRPC method type (Procedure, Query, or Subscription)\n */\nexport type XrpcRequestParams<M extends Procedure | Query | Subscription> =\n InferInput<M['parameters']>\n\n// If all params are optional, allow omitting the params object\ntype XrpcRequestParamsOptions<P extends Params> =\n NonNullable<unknown> extends P ? { params?: P } : { params: P }\n\ntype XrpcRequestPayload<M extends Procedure | Query> = M extends Procedure\n ? InferPayload<M['input'], BinaryBodyInit>\n : undefined\n\ntype XrpcRequestPayloadOptions<TPayload> = TPayload extends {\n body: infer B\n encoding: infer E\n}\n ? {\n body: B\n\n /**\n * mime type hint for binary bodies\n *\n * Only needed for endpoints that accept binary input (e.g. file uploads)\n * when the body is a Blob-like object without a type (e.g. fetch-blob's\n * Blob). If the body is a Blob-like object with a type, that type will be\n * used as the content-type header instead of this option.\n *\n * @default \"application/octet-stream\"\n */\n encoding?: E\n }\n : { body?: undefined; encoding?: undefined }\n\n/**\n * Options for making an XRPC request, based on the method schema.\n *\n * Combines {@link XrpcRequestOptions} and {@link XrpcResponseOptions} with\n * method-specific params and body requirements. The type system ensures\n * required params/body are provided based on the method schema.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n *\n * @example Query with params\n * ```typescript\n * const options: XrpcOptions<typeof app.bsky.feed.getTimeline.main> = {\n * params: { limit: 50 }\n * }\n * ```\n *\n * @example Procedure with body\n * ```typescript\n * const options: XrpcOptions<typeof com.atproto.repo.createRecord.main> = {\n * body: { repo: did, collection: 'app.bsky.feed.post', record: { ... } }\n * }\n * ```\n */\nexport type XrpcOptions<M extends Procedure | Query = Procedure | Query> =\n XrpcRequestOptions<M> & XrpcResponseOptions\n\nexport type XrpcRequestOptions<\n M extends Procedure | Query = Procedure | Query,\n> = XrpcRequestProcessingOptions &\n XrpcRequestHeadersOptions &\n XrpcRequestPayloadOptions<XrpcRequestPayload<M>> &\n XrpcRequestParamsOptions<XrpcRequestParams<M>>\n\nexport type XrpcRequestProcessingOptions = {\n /**\n * AbortSignal to cancel the request.\n */\n signal?: AbortSignal\n\n /**\n * Whether to validate the request against the method's input schema. Enabling\n * this can help catch errors early but may have a performance cost. This\n * would typically only be set to `true` in development or debugging\n * scenarios.\n *\n * @default false\n */\n validateRequest?: boolean\n}\n\n/**\n * Makes an XRPC request and throws on failure.\n *\n * This is the low-level function for making XRPC calls.\n *\n * @param agent - The {@link Agent} to use for making the request\n * @param ns - The lexicon method definition\n * @param options - Request {@link XrpcOptions options} (params, body, headers, etc.)\n * @returns The successful {@link XrpcResponse}\n * @throws {XrpcFailure} When the request fails\n *\n * @example\n * ```typescript\n * const response = await xrpc('https://bsky.network', com.atproto.identity.resolveHandle, {\n * params: { handle: \"atproto.com\" }\n * })\n * ```\n *\n * @example\n * ```typescript\n * const response = await xrpc(agent, app.bsky.feed.getTimeline.main, {\n * params: { limit: 50 }\n * })\n * ```\n */\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n): Promise<XrpcResponse<M>>\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResponse<M>>\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n): Promise<XrpcResponse<M>> {\n const response = await xrpcSafe<M>(agentOpts, ns, options)\n if (response.success) return response\n else throw response\n}\n\n/**\n * Union type representing either a successful response or a failure.\n *\n * Both {@link XrpcResponse} and {@link XrpcFailure} have a `success` property\n * that can be used to discriminate between them.\n *\n * @typeParam M - The XRPC method type\n */\nexport type XrpcResult<M extends Procedure | Query> =\n | XrpcResponse<M>\n | XrpcFailure<M>\n\n/**\n * Makes an XRPC request without throwing on failure.\n *\n * Returns a discriminated union that can be checked via the `success` property.\n * This is useful for handling errors without try/catch blocks. This also allow\n * failure results to be typed with the method schema, which can provide better\n * type safety when handling errors (e.g. checking for specific error codes).\n *\n * @param agent - The {@link Agent} to use for making the request\n * @param ns - The lexicon method definition\n * @param options - Request {@link XrpcOptions options} (params, body, headers, etc.)\n * @returns Either a successful {@link XrpcResponse} or an {@link XrpcFailure}\n *\n * @example\n * ```typescript\n * const result = await xrpcSafe('https://example.com', app.bsky.actor.getProfile, {\n * params: { actor: 'alice.bsky.social' }\n * })\n *\n * if (result.success) {\n * console.log(result.body.displayName)\n * } else {\n * console.error('Request failed:', result.error)\n * }\n * ```\n */\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n): Promise<XrpcResult<M>>\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResult<M>>\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n): Promise<XrpcResult<M>> {\n options.signal?.throwIfAborted()\n const method: M = getMain(ns)\n try {\n const agent = buildAgent(agentOpts)\n const url = xrpcRequestUrl(method, options)\n const request = xrpcRequestInit(method, options)\n const response = await agent.fetchHandler(url, request).catch((cause) => {\n throw new XrpcFetchError(method, cause)\n })\n return await XrpcResponse.fromFetchResponse<M>(method, response, options)\n } catch (cause) {\n return asXrpcFailure(method, cause)\n }\n}\n\nfunction xrpcRequestUrl<M extends Procedure | Query | Subscription>(\n method: M,\n options: { params?: Params },\n): `/xrpc/${NsidString}${'' | `?${string}`}` {\n const path = `/xrpc/${method.nsid}` as const\n\n // @NOTE param.toURLSearchParams() will always validate the params in order to\n // apply default values, so we can't disable it with options.validateRequest\n\n const queryString = method.parameters\n ?.toURLSearchParams(options.params ?? {})\n .toString()\n\n return queryString ? (`${path}?${queryString}` as const) : path\n}\n\nfunction xrpcRequestInit<T extends Procedure | Query>(\n schema: T,\n options: XrpcRequestProcessingOptions &\n XrpcRequestHeadersOptions &\n XrpcProcedureInputOptions & {\n encoding?: string\n },\n): RequestInit & { duplex?: 'half' } {\n const headers = buildXrpcRequestHeaders(options)\n\n // Tell the server what type of response we're expecting\n if (schema.output.encoding) {\n headers.set('accept', schema.output.encoding)\n }\n\n // Caller should not set content-type header\n if (headers.has('content-type')) {\n const contentType = headers.get('content-type')\n throw new TypeError(`Unexpected content-type header (${contentType})`)\n }\n\n // Requests with body\n if ('input' in schema) {\n const encodingHint = options.encoding\n const input = xrpcProcedureInput(schema, options, encodingHint)\n\n if (input) {\n headers.set('content-type', input.encoding)\n } else if (encodingHint != null) {\n throw new TypeError(`Unexpected encoding hint (${encodingHint})`)\n }\n\n return {\n duplex: 'half',\n redirect: 'follow',\n referrerPolicy: 'strict-origin-when-cross-origin', // (default)\n mode: 'cors', // (default)\n signal: options.signal,\n method: 'POST',\n headers,\n body: input?.body,\n }\n }\n\n // Requests without body\n return {\n duplex: 'half',\n redirect: 'follow',\n referrerPolicy: 'strict-origin-when-cross-origin', // (default)\n mode: 'cors', // (default)\n signal: options.signal,\n method: 'GET',\n headers,\n }\n}\n\ntype XrpcProcedureInputOptions = {\n body?: LexValue | BinaryBodyInit\n validateRequest?: boolean\n}\n\nfunction xrpcProcedureInput(\n method: Procedure,\n options: XrpcProcedureInputOptions,\n encodingHint?: string,\n): null | { body: BodyInit; encoding: string } {\n const { input } = method\n const { body } = options\n\n if (options.validateRequest) {\n input.schema?.check(body)\n }\n\n // Special handling for endpoints expecting application/json input\n if (input.encoding === 'application/json') {\n // @NOTE **NOT** using isLexValue here to avoid deep checks in order to\n // distinguish between LexValue and BinaryBodyInit.\n if (!isLexScalar(body) && !isPlainObject(body) && !Array.isArray(body)) {\n throw new TypeError(`Expected LexValue body, got ${typeof body}`)\n }\n\n return buildPayload(input, lexStringify(body), encodingHint)\n }\n\n // Other encodings will be sent unaltered (ie. as binary data)\n switch (typeof body) {\n case 'undefined':\n case 'string':\n return buildPayload(input, body, encodingHint)\n case 'object': {\n if (body === null) break\n if (\n ArrayBuffer.isView(body) ||\n body instanceof ArrayBuffer ||\n body instanceof ReadableStream\n ) {\n return buildPayload(input, body, encodingHint)\n } else if (isAsyncIterable(body)) {\n return buildPayload(input, toReadableStream(body), encodingHint)\n } else if (isBlobLike(body)) {\n return buildPayload(input, body, encodingHint || body.type)\n }\n }\n }\n\n throw new TypeError(\n `Invalid ${typeof body} body for ${input.encoding} encoding`,\n )\n}\n\nfunction buildPayload(\n schema: Payload,\n body: undefined | BodyInit,\n encodingHint?: string,\n): null | { body: BodyInit; encoding: string } {\n if (schema.encoding === undefined) {\n if (body !== undefined) {\n throw new TypeError(`Endpoint expects no payload`)\n }\n\n return null\n }\n\n if (body === undefined) {\n // This error would be returned by the server, but we can catch it earlier\n // to avoid un-necessary requests. Note that a content-length of 0 does not\n // necessary mean that the body is \"empty\" (e.g. an empty txt file).\n throw new TypeError(`A request body is expected but none was provided`)\n }\n\n const encoding = buildEncoding(schema, encodingHint)\n return { encoding, body }\n}\n\nfunction buildEncoding(schema: Payload, encodingHint?: string): string {\n // Should never happen (required for type safety)\n if (!schema.encoding) {\n throw new TypeError('Unexpected payload')\n }\n\n if (encodingHint?.length) {\n if (!schema.matchesEncoding(encodingHint)) {\n throw new TypeError(\n `Cannot send a body with content-type \"${encodingHint}\" for \"${schema.encoding}\" encoding`,\n )\n }\n return encodingHint\n }\n\n // Fallback\n\n if (schema.encoding === '*/*') {\n return 'application/octet-stream'\n }\n\n if (schema.encoding.startsWith('text/')) {\n return schema.encoding.includes('*')\n ? 'text/plain; charset=utf-8'\n : `${schema.encoding}; charset=utf-8`\n }\n\n if (!schema.encoding.includes('*')) {\n return schema.encoding\n }\n\n throw new TypeError(\n `Unable to determine payload encoding. Please provide a 'content-type' header matching ${schema.encoding}.`,\n )\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/lex-client",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
4
4
  "license": "MIT",
5
5
  "description": "HTTP client for interacting with Lexicon based APIs",
6
6
  "keywords": [
@@ -37,14 +37,14 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "tslib": "^2.8.1",
40
- "@atproto/lex-data": "^0.0.14",
41
- "@atproto/lex-json": "^0.0.14",
42
- "@atproto/lex-schema": "^0.0.16"
40
+ "@atproto/lex-data": "^0.0.15",
41
+ "@atproto/lex-json": "^0.0.15",
42
+ "@atproto/lex-schema": "^0.0.18"
43
43
  },
44
44
  "devDependencies": {
45
45
  "vitest": "^4.0.16",
46
- "@atproto/lex-cbor": "^0.0.15",
47
- "@atproto/lex-builder": "^0.0.19"
46
+ "@atproto/lex-cbor": "^0.0.16",
47
+ "@atproto/lex-builder": "^0.0.21"
48
48
  },
49
49
  "scripts": {
50
50
  "prebuild": "node ./scripts/lex-build.mjs",
package/src/client.ts CHANGED
@@ -142,7 +142,7 @@ export type CreateRecordOptions = Omit<
142
142
  */
143
143
  export type DeleteRecordOptions = Omit<
144
144
  XrpcOptions<typeof com.atproto.repo.deleteRecord.main>,
145
- 'params'
145
+ 'body'
146
146
  > & {
147
147
  /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */
148
148
  repo?: AtIdentifierString
@@ -847,6 +847,7 @@ export class Client implements Agent {
847
847
  ): Promise<CreateOutput> {
848
848
  const schema: T = getMain(ns)
849
849
  const record = schema.build(input) as TypedLexMap<NsidString>
850
+ if (options?.validateRequest) schema.validate(record)
850
851
  const rkey = options.rkey ?? getDefaultRecordKey(schema)
851
852
  if (rkey !== undefined) schema.keySchema.assert(rkey)
852
853
  const response = await this.createRecord(record, rkey, options)
@@ -943,6 +944,7 @@ export class Client implements Agent {
943
944
  ): Promise<PutOutput> {
944
945
  const schema: T = getMain(ns)
945
946
  const record = schema.build(input) as TypedLexMap<NsidString>
947
+ if (options?.validateRequest) schema.validate(record)
946
948
  const rkey = options.rkey ?? getLiteralRecordKey(schema)
947
949
  const response = await this.putRecord(record, rkey, options)
948
950
  return response.body
@@ -6,7 +6,7 @@ import {
6
6
  XrpcInternalError,
7
7
  XrpcInvalidResponseError,
8
8
  XrpcResponseError,
9
- XrpcUpstreamError,
9
+ XrpcResponseValidationError,
10
10
  asXrpcFailure,
11
11
  } from './errors.js'
12
12
 
@@ -41,13 +41,141 @@ describe(XrpcResponseError, () => {
41
41
  })
42
42
  }
43
43
 
44
- it('exposes status from the response', () => {
45
- const err = createResponseError(404, 'NotFound')
46
- expect(err.reason).toBe(err)
47
- expect(err.status).toBe(404)
44
+ describe('StatusErrorCodes mapping for non-XRPC responses', () => {
45
+ it('maps 400 to InvalidRequest', () => {
46
+ const err = new XrpcResponseError(
47
+ testQuery,
48
+ new Response(null, { status: 400 }),
49
+ )
50
+ expect(err.error).toBe('InvalidRequest')
51
+ })
52
+
53
+ it('maps 401 to AuthenticationRequired', () => {
54
+ const err = new XrpcResponseError(
55
+ testQuery,
56
+ new Response(null, { status: 401 }),
57
+ )
58
+ expect(err.error).toBe('AuthenticationRequired')
59
+ })
60
+
61
+ it('maps 403 to Forbidden', () => {
62
+ const err = new XrpcResponseError(
63
+ testQuery,
64
+ new Response(null, { status: 403 }),
65
+ )
66
+ expect(err.error).toBe('Forbidden')
67
+ })
68
+
69
+ it('maps 404 to XRPCNotSupported', () => {
70
+ const err = new XrpcResponseError(
71
+ testQuery,
72
+ new Response(null, { status: 404 }),
73
+ )
74
+ expect(err.error).toBe('XRPCNotSupported')
75
+ })
76
+
77
+ it('maps 406 to NotAcceptable', () => {
78
+ const err = new XrpcResponseError(
79
+ testQuery,
80
+ new Response(null, { status: 406 }),
81
+ )
82
+ expect(err.error).toBe('NotAcceptable')
83
+ })
84
+
85
+ it('maps 413 to PayloadTooLarge', () => {
86
+ const err = new XrpcResponseError(
87
+ testQuery,
88
+ new Response(null, { status: 413 }),
89
+ )
90
+ expect(err.error).toBe('PayloadTooLarge')
91
+ })
92
+
93
+ it('maps 415 to UnsupportedMediaType', () => {
94
+ const err = new XrpcResponseError(
95
+ testQuery,
96
+ new Response(null, { status: 415 }),
97
+ )
98
+ expect(err.error).toBe('UnsupportedMediaType')
99
+ })
100
+
101
+ it('maps 429 to RateLimitExceeded', () => {
102
+ const err = new XrpcResponseError(
103
+ testQuery,
104
+ new Response(null, { status: 429 }),
105
+ )
106
+ expect(err.error).toBe('RateLimitExceeded')
107
+ })
108
+
109
+ it('maps 500 to InternalServerError', () => {
110
+ const err = new XrpcResponseError(
111
+ testQuery,
112
+ new Response(null, { status: 500 }),
113
+ )
114
+ expect(err.error).toBe('InternalServerError')
115
+ })
116
+
117
+ it('maps 501 to MethodNotImplemented', () => {
118
+ const err = new XrpcResponseError(
119
+ testQuery,
120
+ new Response(null, { status: 501 }),
121
+ )
122
+ expect(err.error).toBe('MethodNotImplemented')
123
+ })
124
+
125
+ it('maps 502 to UpstreamFailure', () => {
126
+ const err = new XrpcResponseError(
127
+ testQuery,
128
+ new Response(null, { status: 502 }),
129
+ )
130
+ expect(err.error).toBe('UpstreamFailure')
131
+ })
132
+
133
+ it('maps 503 to NotEnoughResources', () => {
134
+ const err = new XrpcResponseError(
135
+ testQuery,
136
+ new Response(null, { status: 503 }),
137
+ )
138
+ expect(err.error).toBe('NotEnoughResources')
139
+ })
140
+
141
+ it('maps 504 to UpstreamTimeout', () => {
142
+ const err = new XrpcResponseError(
143
+ testQuery,
144
+ new Response(null, { status: 504 }),
145
+ )
146
+ expect(err.error).toBe('UpstreamTimeout')
147
+ })
148
+
149
+ it('defaults to InvalidRequest for unmapped 4xx status codes', () => {
150
+ const err = new XrpcResponseError(
151
+ testQuery,
152
+ new Response(null, { status: 418 }),
153
+ )
154
+ expect(err.error).toBe('InvalidRequest')
155
+ })
156
+
157
+ it('defaults to UpstreamFailure for unmapped 5xx status codes', () => {
158
+ const err = new XrpcResponseError(
159
+ testQuery,
160
+ new Response(null, { status: 599 }),
161
+ )
162
+ expect(err.error).toBe('UpstreamFailure')
163
+ })
164
+
165
+ it('uses error from valid XRPC payload instead of status code mapping', () => {
166
+ const err = new XrpcResponseError(
167
+ testQuery,
168
+ new Response(null, { status: 400 }),
169
+ {
170
+ encoding: 'application/json',
171
+ body: { error: 'CustomError', message: 'Custom message' },
172
+ },
173
+ )
174
+ expect(err.error).toBe('CustomError')
175
+ })
48
176
  })
49
177
 
50
- it('exposes headers from the response', () => {
178
+ it('exposes the response object', () => {
51
179
  const response = new Response(null, {
52
180
  status: 400,
53
181
  headers: { 'X-Test': 'value' },
@@ -57,12 +185,13 @@ describe(XrpcResponseError, () => {
57
185
  body: { error: 'TestError' },
58
186
  })
59
187
  expect(err.reason).toBe(err)
60
- expect(err.headers.get('X-Test')).toBe('value')
188
+ expect(err.response.status).toBe(400)
189
+ expect(err.response.headers.get('X-Test')).toBe('value')
61
190
  })
62
191
 
63
192
  it('exposes body from the payload', () => {
64
193
  const err = createResponseError(400, 'TestError', 'details')
65
- expect(err.body).toEqual({ error: 'TestError', message: 'details' })
194
+ expect(err.toJSON()).toEqual({ error: 'TestError', message: 'details' })
66
195
  })
67
196
 
68
197
  describe('toDownstreamError', () => {
@@ -102,13 +231,89 @@ describe(XrpcResponseError, () => {
102
231
  message: 'Record not found',
103
232
  })
104
233
  })
234
+
235
+ it('preserves 429 status for rate limiting', () => {
236
+ const err = new XrpcResponseError(
237
+ testQuery,
238
+ new Response(null, { status: 429 }),
239
+ )
240
+ expect(err.toDownstreamError().status).toBe(429)
241
+ })
242
+
243
+ it('converts 500 to 502', () => {
244
+ const err = new XrpcResponseError(
245
+ testQuery,
246
+ new Response(null, { status: 500 }),
247
+ )
248
+ expect(err.toDownstreamError().status).toBe(502)
249
+ })
250
+
251
+ it('strips hop-by-hop headers', () => {
252
+ const response = new Response(null, {
253
+ status: 400,
254
+ headers: {
255
+ 'Content-Type': 'application/json',
256
+ Connection: 'keep-alive',
257
+ 'Keep-Alive': 'timeout=5',
258
+ 'Transfer-Encoding': 'chunked',
259
+ },
260
+ })
261
+ const err = new XrpcResponseError(testQuery, response, {
262
+ encoding: 'application/json',
263
+ body: { error: 'TestError' },
264
+ })
265
+ const downstream = err.toDownstreamError()
266
+
267
+ expect(downstream.headers?.has('Content-Type')).toBe(true)
268
+ expect(downstream.headers?.has('Connection')).toBe(false)
269
+ expect(downstream.headers?.has('Keep-Alive')).toBe(false)
270
+ expect(downstream.headers?.has('Transfer-Encoding')).toBe(false)
271
+ })
105
272
  })
106
273
 
107
274
  describe('toJSON', () => {
108
- it('returns the payload body', () => {
275
+ it('returns the payload body for valid XRPC errors', () => {
109
276
  const err = createResponseError(400, 'TestError', 'message')
110
277
  expect(err.toJSON()).toEqual({ error: 'TestError', message: 'message' })
111
278
  })
279
+
280
+ it('constructs XRPC error from status code when payload is not valid XRPC', () => {
281
+ const err = new XrpcResponseError(
282
+ testQuery,
283
+ new Response(null, { status: 429 }),
284
+ { encoding: 'text/plain', body: 'Rate limit exceeded' },
285
+ )
286
+ expect(err.toJSON()).toEqual({
287
+ error: 'RateLimitExceeded',
288
+ message: 'Upstream server responded with a 429 error',
289
+ })
290
+ })
291
+
292
+ it('constructs XRPC error from status code when payload is missing', () => {
293
+ const err = new XrpcResponseError(
294
+ testQuery,
295
+ new Response(null, { status: 503 }),
296
+ )
297
+ expect(err.toJSON()).toEqual({
298
+ error: 'NotEnoughResources',
299
+ message: 'Upstream server responded with a 503 error',
300
+ })
301
+ })
302
+
303
+ it('returns valid XRPC payload unchanged', () => {
304
+ const err = new XrpcResponseError(
305
+ testQuery,
306
+ new Response(null, { status: 400 }),
307
+ {
308
+ encoding: 'application/json',
309
+ body: { error: 'CustomError', message: 'Custom message' },
310
+ },
311
+ )
312
+ expect(err.toJSON()).toEqual({
313
+ error: 'CustomError',
314
+ message: 'Custom message',
315
+ })
316
+ })
112
317
  })
113
318
 
114
319
  describe('matchesSchemaErrors', () => {
@@ -203,57 +408,63 @@ describe(XrpcAuthenticationError, () => {
203
408
  })
204
409
 
205
410
  // ============================================================================
206
- // XrpcUpstreamError
411
+ // XrpcInvalidResponseError
207
412
  // ============================================================================
208
413
 
209
- describe(XrpcUpstreamError, () => {
210
- it('has error code UpstreamFailure', () => {
211
- const response = new Response(null, { status: 200 })
212
- const err = new XrpcUpstreamError(testQuery, response)
414
+ describe(XrpcInvalidResponseError, () => {
415
+ it('has error code InvalidResponse', () => {
416
+ const response = new Response(null, { status: 399 })
417
+ const err = new XrpcInvalidResponseError(testQuery, response)
213
418
  expect(err.reason).toBe(err)
214
- expect(err.error).toBe('UpstreamFailure')
419
+ expect(err.error).toBe('InvalidResponse')
420
+ expect(err.toDownstreamError()).toMatchObject({
421
+ status: 502,
422
+ body: {
423
+ error: 'InvalidResponse',
424
+ message: 'Upstream server responded with an invalid status code (399)',
425
+ },
426
+ })
215
427
  })
216
428
 
217
- it('toDownstreamError returns 502', () => {
218
- const response = new Response(null, { status: 200 })
219
- const err = new XrpcUpstreamError(testQuery, response)
220
- const downstream = err.toDownstreamError()
221
- expect(downstream.status).toBe(502)
429
+ it('toDownstreamError returns 502 for 500 upstream errors', () => {
430
+ const response = new Response(null, { status: 500 })
431
+ const err = new XrpcInvalidResponseError(testQuery, response)
432
+ expect(err.toDownstreamError().status).toBe(502)
222
433
  })
223
434
 
224
435
  it('shouldRetry is true for retryable status codes', () => {
225
436
  const response = new Response(null, { status: 502 })
226
- const err = new XrpcUpstreamError(testQuery, response)
437
+ const err = new XrpcInvalidResponseError(testQuery, response)
227
438
  expect(err.shouldRetry()).toBe(true)
228
439
  })
229
440
 
230
441
  it('shouldRetry is false for non-retryable status codes', () => {
231
- const response = new Response(null, { status: 200 })
232
- const err = new XrpcUpstreamError(testQuery, response)
442
+ const response = new Response(null, { status: 400 })
443
+ const err = new XrpcInvalidResponseError(testQuery, response)
233
444
  expect(err.shouldRetry()).toBe(false)
234
445
  })
235
446
  })
236
447
 
237
448
  // ============================================================================
238
- // XrpcInvalidResponseError
449
+ // XrpcResponseValidationError
239
450
  // ============================================================================
240
451
 
241
- describe(XrpcInvalidResponseError, () => {
242
- it('extends XrpcUpstreamError', () => {
452
+ describe(XrpcResponseValidationError, () => {
453
+ it('extends XrpcInvalidResponseError', () => {
243
454
  const response = new Response(null, { status: 200 })
244
455
  const validationError = new LexValidationError([
245
456
  new IssueInvalidType([], 42, ['string']),
246
457
  ])
247
- const err = new XrpcInvalidResponseError(
458
+ const err = new XrpcResponseValidationError(
248
459
  testQuery,
249
460
  response,
250
461
  { encoding: 'application/json', body: { value: 42 } },
251
462
  validationError,
252
463
  )
253
464
 
254
- expect(err).toBeInstanceOf(XrpcUpstreamError)
465
+ expect(err).toBeInstanceOf(XrpcInvalidResponseError)
255
466
  expect(err.reason).toBe(err)
256
- expect(err.error).toBe('UpstreamFailure')
467
+ expect(err.error).toBe('InvalidResponse')
257
468
  expect(err.cause).toBe(validationError)
258
469
  })
259
470
 
@@ -261,14 +472,14 @@ describe(XrpcInvalidResponseError, () => {
261
472
  const validationError = new LexValidationError([
262
473
  new IssueInvalidType([], 42, ['string']),
263
474
  ])
264
- const err = new XrpcInvalidResponseError(
475
+ const err = new XrpcResponseValidationError(
265
476
  testQuery,
266
477
  new Response(null, { status: 200 }),
267
478
  { encoding: 'application/json', body: { value: 42 } },
268
479
  validationError,
269
480
  )
270
481
 
271
- expect(err.message).toContain('Invalid response:')
482
+ expect(err.message).toContain('Invalid response payload:')
272
483
  expect(err.message).toContain(validationError.message)
273
484
  })
274
485
 
@@ -276,7 +487,7 @@ describe(XrpcInvalidResponseError, () => {
276
487
  const validationError = new LexValidationError([
277
488
  new IssueInvalidType([], 42, ['string']),
278
489
  ])
279
- const err = new XrpcInvalidResponseError(
490
+ const err = new XrpcResponseValidationError(
280
491
  testQuery,
281
492
  new Response(null, { status: 200 }),
282
493
  { encoding: 'application/json', body: { value: 42 } },