@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.21

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 (321) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -0
  3. package/lib/_bundle/aws.js +2 -0
  4. package/lib/_bundle/aws.js.map +1 -0
  5. package/lib/_bundle/base.js +5 -0
  6. package/lib/_bundle/base.js.map +1 -0
  7. package/lib/_bundle/graphql.js +3 -0
  8. package/lib/_bundle/graphql.js.map +1 -0
  9. package/lib/_bundle/grpc.js +3 -0
  10. package/lib/_bundle/grpc.js.map +1 -0
  11. package/lib/_bundle/rest.js +2 -0
  12. package/lib/_bundle/rest.js.map +1 -0
  13. package/lib/_bundle/xml.js +4 -0
  14. package/lib/_bundle/xml.js.map +1 -0
  15. package/lib/annotations.d.ts +17 -0
  16. package/lib/annotations.d.ts.map +1 -0
  17. package/lib/annotations.js +2 -0
  18. package/lib/annotations.js.map +1 -0
  19. package/lib/api.d.ts +220 -51
  20. package/lib/api.d.ts.map +1 -1
  21. package/lib/api.js +1 -178
  22. package/lib/category.d.ts +19 -16
  23. package/lib/category.d.ts.map +1 -1
  24. package/lib/category.js +1 -280
  25. package/lib/chunks.d.ts +3 -0
  26. package/lib/chunks.d.ts.map +1 -0
  27. package/lib/chunks.js +1 -0
  28. package/lib/config.d.ts +81 -0
  29. package/lib/config.d.ts.map +1 -0
  30. package/lib/config.js +1 -0
  31. package/lib/crypto.d.ts +76 -0
  32. package/lib/crypto.d.ts.map +1 -0
  33. package/lib/crypto.js +1 -0
  34. package/lib/error-category.d.ts +1 -1
  35. package/lib/error-category.d.ts.map +1 -1
  36. package/lib/error-category.js +1 -46
  37. package/lib/errors.d.ts +99 -74
  38. package/lib/errors.d.ts.map +1 -1
  39. package/lib/errors.js +1 -186
  40. package/lib/graphql.d.ts +420 -0
  41. package/lib/graphql.d.ts.map +1 -0
  42. package/lib/graphql.js +1 -0
  43. package/lib/graphql.types.d.ts +11 -0
  44. package/lib/graphql.types.d.ts.map +1 -0
  45. package/lib/graphql.types.js +1 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  47. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  48. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  49. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  51. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  53. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  54. package/lib/grpc-transport-node-http2.d.ts +19 -0
  55. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  56. package/lib/grpc-transport-node-http2.js +2 -0
  57. package/lib/grpc-transport-node-http2.js.map +1 -0
  58. package/lib/grpc-transport.d.ts +111 -0
  59. package/lib/grpc-transport.d.ts.map +1 -0
  60. package/lib/grpc-transport.js +1 -0
  61. package/lib/hpack.d.ts +34 -0
  62. package/lib/hpack.d.ts.map +1 -0
  63. package/lib/hpack.js +2 -0
  64. package/lib/hpack.js.map +1 -0
  65. package/lib/index.d.ts +32 -0
  66. package/lib/index.d.ts.map +1 -0
  67. package/lib/index.js +17 -0
  68. package/lib/max-message-bytes.d.ts +42 -0
  69. package/lib/max-message-bytes.d.ts.map +1 -0
  70. package/lib/max-message-bytes.js +2 -0
  71. package/lib/max-message-bytes.js.map +1 -0
  72. package/lib/ndjson.d.ts +3 -0
  73. package/lib/ndjson.d.ts.map +1 -0
  74. package/lib/ndjson.js +2 -0
  75. package/lib/ndjson.js.map +1 -0
  76. package/lib/pagination.d.ts +105 -25
  77. package/lib/pagination.d.ts.map +1 -1
  78. package/lib/pagination.js +1 -182
  79. package/lib/plain-values.d.ts +21 -0
  80. package/lib/plain-values.d.ts.map +1 -0
  81. package/lib/plain-values.js +2 -0
  82. package/lib/plain-values.js.map +1 -0
  83. package/lib/protobuf.d.ts +85 -0
  84. package/lib/protobuf.d.ts.map +1 -0
  85. package/lib/protobuf.js +1 -0
  86. package/lib/protocol-grpc.d.ts +123 -0
  87. package/lib/protocol-grpc.d.ts.map +1 -0
  88. package/lib/protocol-grpc.js +1 -0
  89. package/lib/protocol-http.d.ts +206 -25
  90. package/lib/protocol-http.d.ts.map +1 -1
  91. package/lib/protocol-http.js +1 -554
  92. package/lib/protocol-rest.d.ts +258 -64
  93. package/lib/protocol-rest.d.ts.map +1 -1
  94. package/lib/protocol-rest.js +1 -242
  95. package/lib/protocol.d.ts +113 -0
  96. package/lib/protocol.d.ts.map +1 -0
  97. package/lib/protocol.js +0 -0
  98. package/lib/query.d.ts +29 -0
  99. package/lib/query.d.ts.map +1 -0
  100. package/lib/query.js +1 -0
  101. package/lib/response-validation-strict.d.ts +48 -0
  102. package/lib/response-validation-strict.d.ts.map +1 -0
  103. package/lib/response-validation-strict.js +1 -0
  104. package/lib/response-validation.d.ts +86 -0
  105. package/lib/response-validation.d.ts.map +1 -0
  106. package/lib/response-validation.js +1 -0
  107. package/lib/retry-after.d.ts +4 -4
  108. package/lib/retry-after.d.ts.map +1 -1
  109. package/lib/retry-after.js +1 -112
  110. package/lib/retry-state.d.ts +26 -0
  111. package/lib/retry-state.d.ts.map +1 -0
  112. package/lib/retry-state.js +2 -0
  113. package/lib/retry-state.js.map +1 -0
  114. package/lib/retry.d.ts +141 -42
  115. package/lib/retry.d.ts.map +1 -1
  116. package/lib/retry.js +1 -210
  117. package/lib/schema-lite-impl.d.ts +179 -0
  118. package/lib/schema-lite-impl.d.ts.map +1 -0
  119. package/lib/schema-lite-impl.js +1 -0
  120. package/lib/schema-lite-typed.d.ts +41 -0
  121. package/lib/schema-lite-typed.d.ts.map +1 -0
  122. package/lib/schema-lite-typed.js +1 -0
  123. package/lib/schema-lite.d.ts +41 -0
  124. package/lib/schema-lite.d.ts.map +1 -0
  125. package/lib/schema-lite.js +1 -0
  126. package/lib/schema.d.ts +21 -7
  127. package/lib/schema.d.ts.map +1 -1
  128. package/lib/schema.js +1 -48
  129. package/lib/sdk-error.d.ts +31 -0
  130. package/lib/sdk-error.d.ts.map +1 -0
  131. package/lib/sdk-error.js +1 -0
  132. package/lib/send.d.ts +37 -0
  133. package/lib/send.d.ts.map +1 -0
  134. package/lib/send.js +2 -0
  135. package/lib/send.js.map +1 -0
  136. package/lib/sensitive.d.ts +28 -0
  137. package/lib/sensitive.d.ts.map +1 -0
  138. package/lib/sensitive.js +2 -0
  139. package/lib/sensitive.js.map +1 -0
  140. package/lib/telemetry-debug.d.ts +6 -0
  141. package/lib/telemetry-debug.d.ts.map +1 -0
  142. package/lib/telemetry-debug.js +2 -0
  143. package/lib/telemetry-debug.js.map +1 -0
  144. package/lib/telemetry-hooks.d.ts +32 -0
  145. package/lib/telemetry-hooks.d.ts.map +1 -0
  146. package/lib/telemetry-hooks.js +2 -0
  147. package/lib/telemetry-hooks.js.map +1 -0
  148. package/lib/telemetry-host-rules.d.ts +23 -0
  149. package/lib/telemetry-host-rules.d.ts.map +1 -0
  150. package/lib/telemetry-host-rules.js +2 -0
  151. package/lib/telemetry-host-rules.js.map +1 -0
  152. package/lib/telemetry-lambda-context.d.ts +17 -0
  153. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  154. package/lib/telemetry-lambda-context.js +2 -0
  155. package/lib/telemetry-lambda-context.js.map +1 -0
  156. package/lib/telemetry-message-context.d.ts +52 -0
  157. package/lib/telemetry-message-context.d.ts.map +1 -0
  158. package/lib/telemetry-message-context.js +2 -0
  159. package/lib/telemetry-message-context.js.map +1 -0
  160. package/lib/telemetry-metrics.d.ts +6 -0
  161. package/lib/telemetry-metrics.d.ts.map +1 -0
  162. package/lib/telemetry-metrics.js +2 -0
  163. package/lib/telemetry-metrics.js.map +1 -0
  164. package/lib/telemetry-name-template.d.ts +13 -0
  165. package/lib/telemetry-name-template.d.ts.map +1 -0
  166. package/lib/telemetry-name-template.js +2 -0
  167. package/lib/telemetry-name-template.js.map +1 -0
  168. package/lib/telemetry-stream.d.ts +11 -0
  169. package/lib/telemetry-stream.d.ts.map +1 -0
  170. package/lib/telemetry-stream.js +2 -0
  171. package/lib/telemetry-stream.js.map +1 -0
  172. package/lib/telemetry-xray.d.ts +28 -0
  173. package/lib/telemetry-xray.d.ts.map +1 -0
  174. package/lib/telemetry-xray.js +2 -0
  175. package/lib/telemetry-xray.js.map +1 -0
  176. package/lib/telemetry.d.ts +317 -0
  177. package/lib/telemetry.d.ts.map +1 -0
  178. package/lib/telemetry.js +3 -0
  179. package/lib/telemetry.js.map +1 -0
  180. package/lib/token-cache.d.ts +31 -0
  181. package/lib/token-cache.d.ts.map +1 -0
  182. package/lib/token-cache.js +2 -0
  183. package/lib/token-cache.js.map +1 -0
  184. package/lib/trait.d.ts +94 -20
  185. package/lib/trait.d.ts.map +1 -1
  186. package/lib/trait.js +1 -107
  187. package/lib/unknown-error.d.ts +18 -0
  188. package/lib/unknown-error.d.ts.map +1 -0
  189. package/lib/unknown-error.js +1 -0
  190. package/lib/xml.d.ts +44 -0
  191. package/lib/xml.d.ts.map +1 -0
  192. package/lib/xml.js +1 -0
  193. package/package.json +13 -13
  194. package/src/annotations.ts +53 -0
  195. package/src/api.ts +1597 -234
  196. package/src/category.ts +97 -134
  197. package/src/chunks.ts +30 -0
  198. package/src/config.ts +261 -0
  199. package/src/crypto.ts +202 -0
  200. package/src/error-category.ts +16 -29
  201. package/src/errors.ts +99 -77
  202. package/src/graphql.ts +1817 -0
  203. package/src/graphql.types.ts +120 -0
  204. package/src/grpc-transport-cloudflare-http2.ts +569 -0
  205. package/src/grpc-transport-cloudflare-sockets.ts +368 -0
  206. package/src/grpc-transport-node-http2.ts +307 -0
  207. package/src/grpc-transport.ts +287 -0
  208. package/src/hpack.ts +331 -0
  209. package/src/index.ts +31 -0
  210. package/src/max-message-bytes.ts +58 -0
  211. package/src/ndjson.ts +55 -0
  212. package/src/pagination.ts +379 -94
  213. package/src/plain-values.ts +70 -0
  214. package/src/protobuf.ts +1367 -0
  215. package/src/protocol-grpc.ts +811 -0
  216. package/src/protocol-http.ts +1045 -371
  217. package/src/protocol-rest.ts +908 -255
  218. package/src/protocol.ts +150 -0
  219. package/src/query.ts +39 -0
  220. package/src/response-validation-strict.ts +333 -0
  221. package/src/response-validation.ts +161 -0
  222. package/src/retry-after.ts +8 -14
  223. package/src/retry-state.ts +105 -0
  224. package/src/retry.ts +260 -145
  225. package/src/schema-lite-impl.ts +621 -0
  226. package/src/schema-lite-typed.ts +44 -0
  227. package/src/schema-lite.ts +45 -0
  228. package/src/schema.ts +259 -15
  229. package/src/sdk-error.ts +37 -0
  230. package/src/send.ts +156 -0
  231. package/src/sensitive.ts +188 -0
  232. package/src/telemetry-debug.ts +179 -0
  233. package/src/telemetry-hooks.ts +33 -0
  234. package/src/telemetry-host-rules.ts +39 -0
  235. package/src/telemetry-lambda-context.ts +46 -0
  236. package/src/telemetry-message-context.ts +170 -0
  237. package/src/telemetry-metrics.ts +69 -0
  238. package/src/telemetry-name-template.ts +26 -0
  239. package/src/telemetry-stream.ts +100 -0
  240. package/src/telemetry-xray.ts +66 -0
  241. package/src/telemetry.ts +800 -0
  242. package/src/token-cache.ts +117 -0
  243. package/src/trait.ts +139 -67
  244. package/src/unknown-error.ts +38 -0
  245. package/src/xml.ts +346 -0
  246. package/lib/api.js.map +0 -1
  247. package/lib/category.js.map +0 -1
  248. package/lib/codegen/cli.d.ts +0 -29
  249. package/lib/codegen/cli.d.ts.map +0 -1
  250. package/lib/codegen/cli.js +0 -165
  251. package/lib/codegen/cli.js.map +0 -1
  252. package/lib/codegen/emit.d.ts +0 -129
  253. package/lib/codegen/emit.d.ts.map +0 -1
  254. package/lib/codegen/emit.js +0 -105
  255. package/lib/codegen/emit.js.map +0 -1
  256. package/lib/codegen/format.d.ts +0 -23
  257. package/lib/codegen/format.d.ts.map +0 -1
  258. package/lib/codegen/format.js +0 -28
  259. package/lib/codegen/format.js.map +0 -1
  260. package/lib/codegen/generator.d.ts +0 -334
  261. package/lib/codegen/generator.d.ts.map +0 -1
  262. package/lib/codegen/generator.js +0 -691
  263. package/lib/codegen/generator.js.map +0 -1
  264. package/lib/codegen/graph.d.ts +0 -36
  265. package/lib/codegen/graph.d.ts.map +0 -1
  266. package/lib/codegen/graph.js +0 -136
  267. package/lib/codegen/graph.js.map +0 -1
  268. package/lib/codegen/members.d.ts +0 -25
  269. package/lib/codegen/members.d.ts.map +0 -1
  270. package/lib/codegen/members.js +0 -55
  271. package/lib/codegen/members.js.map +0 -1
  272. package/lib/codegen/naming.d.ts +0 -29
  273. package/lib/codegen/naming.d.ts.map +0 -1
  274. package/lib/codegen/naming.js +0 -74
  275. package/lib/codegen/naming.js.map +0 -1
  276. package/lib/codegen/openapi-cli.d.ts +0 -38
  277. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  278. package/lib/codegen/openapi-cli.js +0 -107
  279. package/lib/codegen/openapi-cli.js.map +0 -1
  280. package/lib/codegen/openapi.d.ts +0 -115
  281. package/lib/codegen/openapi.d.ts.map +0 -1
  282. package/lib/codegen/openapi.js +0 -1220
  283. package/lib/codegen/openapi.js.map +0 -1
  284. package/lib/codegen/operations.d.ts +0 -24
  285. package/lib/codegen/operations.d.ts.map +0 -1
  286. package/lib/codegen/operations.js +0 -56
  287. package/lib/codegen/operations.js.map +0 -1
  288. package/lib/codegen/pagination.d.ts +0 -39
  289. package/lib/codegen/pagination.d.ts.map +0 -1
  290. package/lib/codegen/pagination.js +0 -33
  291. package/lib/codegen/pagination.js.map +0 -1
  292. package/lib/codegen/prelude.d.ts +0 -15
  293. package/lib/codegen/prelude.d.ts.map +0 -1
  294. package/lib/codegen/prelude.js +0 -60
  295. package/lib/codegen/prelude.js.map +0 -1
  296. package/lib/error-category.js.map +0 -1
  297. package/lib/errors.js.map +0 -1
  298. package/lib/json-patch.d.ts +0 -44
  299. package/lib/json-patch.d.ts.map +0 -1
  300. package/lib/json-patch.js +0 -174
  301. package/lib/json-patch.js.map +0 -1
  302. package/lib/pagination.js.map +0 -1
  303. package/lib/protocol-http.js.map +0 -1
  304. package/lib/protocol-rest.js.map +0 -1
  305. package/lib/retry-after.js.map +0 -1
  306. package/lib/retry.js.map +0 -1
  307. package/lib/schema.js.map +0 -1
  308. package/lib/trait.js.map +0 -1
  309. package/src/codegen/cli.ts +0 -268
  310. package/src/codegen/emit.ts +0 -207
  311. package/src/codegen/format.ts +0 -47
  312. package/src/codegen/generator.ts +0 -1153
  313. package/src/codegen/graph.ts +0 -151
  314. package/src/codegen/members.ts +0 -71
  315. package/src/codegen/naming.ts +0 -86
  316. package/src/codegen/openapi-cli.ts +0 -166
  317. package/src/codegen/openapi.ts +0 -1450
  318. package/src/codegen/operations.ts +0 -76
  319. package/src/codegen/pagination.ts +0 -71
  320. package/src/codegen/prelude.ts +0 -70
  321. package/src/json-patch.ts +0 -222
@@ -1,18 +1,30 @@
1
+ import * as Effect from "effect/Effect";
2
+ import * as Headers from "effect/http/Headers";
3
+ import * as HttpBody from "effect/http/HttpBody";
4
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
1
5
  /**
2
- * Generic REST protocol machinery, shared by SDK protocol layers.
6
+ * Generic REST protocol machinery, shared by SDK protocols.
3
7
  *
4
8
  * Everything here is driven purely by the trait annotations in
5
- * `core/trait.ts` — nothing is provider-specific. An SDK protocol (e.g.
9
+ * `core/trait.ts` -- nothing is provider-specific. An SDK protocol (e.g.
6
10
  * cloudflare's) supplies credentials/base-URL, calls {@link buildRequest} to
7
11
  * encode, and layers its own response-envelope handling on top of the
8
12
  * decode-side helpers ({@link getProps}/{@link mapKeys}/
9
13
  * {@link matchTypedError}).
10
14
  */
11
15
  import type * as AST from "effect/SchemaAST";
12
- import * as HttpBody from "effect/unstable/http/HttpBody";
13
- import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
16
+ import type * as Stream from "effect/Stream";
17
+ import { getAnn, getProps, resolveNode } from "./annotations.ts";
18
+ import * as Category from "./category.ts";
19
+ import { ConfigError } from "./config.ts";
20
+ import { isEffectStream, isOpaqueValue } from "./plain-values.ts";
21
+ import { parseServerRetryHint } from "./retry-after.ts";
22
+ import * as Schema from "./schema-lite-typed.ts";
23
+ import { SdkError } from "./sdk-error.ts";
24
+ import { restoreStack, suppressStack } from "./telemetry.ts";
14
25
  import {
15
26
  bodySymbol,
27
+ commaDelimitedSymbol,
16
28
  deepQuerySymbol,
17
29
  formDataFileSymbol,
18
30
  getErrorMatchers,
@@ -21,83 +33,134 @@ import {
21
33
  httpSymbol,
22
34
  keyDictionarySymbol,
23
35
  labelSymbol,
36
+ labelEncodingSymbol,
24
37
  querySymbol,
38
+ stringEncodedSymbol,
25
39
  unionCasesSymbol,
26
40
  type ErrorMatcher,
41
+ type ErrorTextMatcher,
27
42
  type HttpTrait,
28
43
  type KeyDictionaryEntries,
44
+ type UnionDiscriminator,
29
45
  } from "./trait.ts";
30
46
 
31
47
  //#region AST helpers (survive S.optional / Suspend / transforms)
32
48
 
33
- export const getProps = (ast: AST.AST): readonly AST.PropertySignature[] => {
34
- if (ast._tag === "Objects") return ast.propertySignatures;
35
- if (ast._tag === "Suspend") return getProps(ast.thunk());
36
- if (ast.encoding && ast.encoding.length > 0)
37
- return getProps(ast.encoding[0]!.to);
38
- return [];
39
- };
40
-
41
- export const getAnn = (ast: AST.AST, symbol: symbol): unknown => {
42
- const direct = (ast.annotations as Record<symbol, unknown> | undefined)?.[
43
- symbol
44
- ];
45
- if (direct !== undefined) return direct;
46
- if (ast._tag === "Suspend") return getAnn(ast.thunk(), symbol);
47
- if (ast.encoding && ast.encoding.length > 0)
48
- return getAnn(ast.encoding[0]!.to, symbol);
49
- // S.optional → Union[self, Undefined]; descend into the single real member.
50
- if (ast._tag === "Union") {
51
- const real = (ast as AST.Union).types.filter(
52
- (t) =>
53
- t._tag !== "Undefined" &&
54
- !(t._tag === "Literal" && (t as any).literal === null),
55
- );
56
- if (real.length === 1) return getAnn(real[0]!, symbol);
57
- }
58
- return undefined;
59
- };
49
+ export { getAnn, getProps, resolveNode } from "./annotations.ts";
60
50
 
61
- export const getPropAnn = (
62
- prop: AST.PropertySignature,
63
- symbol: symbol,
64
- ): unknown => getAnn(prop.type, symbol);
65
- export const hasPropAnn = (
66
- prop: AST.PropertySignature,
67
- symbol: symbol,
68
- ): boolean => getPropAnn(prop, symbol) !== undefined;
51
+ export const getPropAnn = (prop: AST.PropertySignature, symbol: symbol): unknown =>
52
+ getAnn(prop.type, symbol);
53
+ export const hasPropAnn = (prop: AST.PropertySignature, symbol: symbol): boolean =>
54
+ getPropAnn(prop, symbol) !== undefined;
69
55
  export const nameOf = (prop: AST.PropertySignature, symbol: symbol): string => {
70
56
  const v = getPropAnn(prop, symbol);
71
57
  return typeof v === "string" ? v : String(prop.name);
72
58
  };
73
59
 
74
- /** Resolve wrappers to the real node: Suspend, encoding, optional/null unions. */
75
- export const resolveNode = (ast: AST.AST): AST.AST => {
76
- if (ast._tag === "Suspend") return resolveNode(ast.thunk());
77
- if (ast.encoding && ast.encoding.length > 0)
78
- return resolveNode(ast.encoding[0]!.to);
79
- if (ast._tag === "Union") {
80
- const real = (ast as AST.Union).types.filter(
81
- (t) =>
82
- t._tag !== "Undefined" &&
83
- t._tag !== "Null" &&
84
- !(t._tag === "Literal" && (t as any).literal === null),
85
- );
86
- if (real.length === 1) return resolveNode(real[0]!);
60
+ //#endregion
61
+
62
+ //#region Response headers on outputs
63
+
64
+ /** An output member read from a response header (`T.Header`). */
65
+ export interface ResponseHeaderMember {
66
+ readonly key: string;
67
+ /** Lowercase header name. */
68
+ readonly wire: string;
69
+ /** The member is a number; the header's text is parsed. */
70
+ readonly number: boolean;
71
+ }
72
+
73
+ const noHeaderMembers: ReadonlyArray<ResponseHeaderMember> = [];
74
+ const headerMemberCache = /*@__PURE__*/ new WeakMap<AST.AST, ReadonlyArray<ResponseHeaderMember>>();
75
+
76
+ /** The output's header-bound members, read from the schema once. */
77
+ export const responseHeaderMembers = (outputAst: AST.AST): ReadonlyArray<ResponseHeaderMember> => {
78
+ let members = headerMemberCache.get(outputAst);
79
+ if (members !== undefined) return members;
80
+ const found: ResponseHeaderMember[] = [];
81
+ for (const prop of getProps(outputAst)) {
82
+ if (!hasPropAnn(prop, headerSymbol)) continue;
83
+ found.push({
84
+ key: String(prop.name),
85
+ wire: nameOf(prop, headerSymbol).toLowerCase(),
86
+ number: resolveNode(prop.type)._tag === "Number",
87
+ });
88
+ }
89
+ members = found.length === 0 ? noHeaderMembers : found;
90
+ headerMemberCache.set(outputAst, members);
91
+ return members;
92
+ };
93
+
94
+ /**
95
+ * Copy the response headers an output declares onto its decoded body. A
96
+ * number member gets the header parsed; text that is not a number is kept
97
+ * as sent, so strict validation reports it. A body that is not an object
98
+ * (a raw root) is returned as is -- generators bind no headers there.
99
+ */
100
+ export const withResponseHeaders = (
101
+ members: ReadonlyArray<ResponseHeaderMember>,
102
+ body: unknown,
103
+ headers: Record<string, string | undefined>,
104
+ ): unknown => {
105
+ if (members.length === 0 || body === null || typeof body !== "object" || Array.isArray(body)) {
106
+ return body;
87
107
  }
88
- return ast;
108
+ let result: Record<string, unknown> | undefined;
109
+ for (const m of members) {
110
+ const raw = headers[m.wire];
111
+ if (raw === undefined) continue;
112
+ result ??= { ...(body as Record<string, unknown>) };
113
+ const parsed = m.number && raw.trim() !== "" ? Number(raw) : Number.NaN;
114
+ result[m.key] = Number.isNaN(parsed) ? raw : parsed;
115
+ }
116
+ return result ?? body;
89
117
  };
90
118
  //#endregion
91
119
 
92
120
  //#region Recursive wire-name mapping
93
121
 
94
- /** Binary/opaque values that must never be treated as key-value objects. */
95
- export const isOpaqueValue = (v: unknown): boolean =>
96
- v instanceof Blob ||
97
- v instanceof File ||
98
- v instanceof ArrayBuffer ||
99
- v instanceof Uint8Array ||
100
- v instanceof Date;
122
+ export { isOpaqueValue };
123
+
124
+ /** A key dictionary's lookup tables, each built on first use. */
125
+ const dictionaryTables = /*@__PURE__*/ new WeakMap<
126
+ KeyDictionaryEntries,
127
+ { encode?: Record<string, string>; decode?: Record<string, string>; first?: Map<string, string> }
128
+ >();
129
+ const tablesOf = (dict: KeyDictionaryEntries) => {
130
+ let tables = dictionaryTables.get(dict);
131
+ if (tables === undefined) dictionaryTables.set(dict, (tables = {}));
132
+ return tables;
133
+ };
134
+
135
+ /** TS name -> wire name (encode) or every wire spelling -> TS name (decode). */
136
+ const renameTable = (
137
+ dict: KeyDictionaryEntries,
138
+ direction: "encode" | "decode",
139
+ ): Record<string, string> =>
140
+ (tablesOf(dict)[direction] ??=
141
+ direction === "decode"
142
+ ? Object.fromEntries(
143
+ Object.entries(dict).flatMap(([ts, wire]) =>
144
+ typeof wire === "string" ? [[wire, ts] as const] : wire.map((w) => [w, ts] as const),
145
+ ),
146
+ )
147
+ : Object.fromEntries(
148
+ Object.entries(dict).map(([ts, wire]) => [
149
+ ts,
150
+ typeof wire === "string" ? wire : wire[0]!,
151
+ ]),
152
+ ));
153
+
154
+ /** The TS name of the first entry whose wire name is `wire` (not a list of spellings). */
155
+ const tsNameOf = (dict: KeyDictionaryEntries, wire: string): string | undefined => {
156
+ const tables = tablesOf(dict);
157
+ if (tables.first === undefined) {
158
+ tables.first = new Map();
159
+ for (const [ts, w] of Object.entries(dict))
160
+ if (typeof w === "string" && !tables.first.has(w)) tables.first.set(w, ts);
161
+ }
162
+ return tables.first.get(wire);
163
+ };
101
164
 
102
165
  /**
103
166
  * Deep-rename keys via a plain dictionary (see `T.KeyDictionary`). An entry
@@ -115,21 +178,7 @@ export const mapKeysByDictionary = (
115
178
  if (Array.isArray(value)) {
116
179
  return value.map((v) => mapKeysByDictionary(dict, v, direction));
117
180
  }
118
- const rename: Record<string, string> =
119
- direction === "decode"
120
- ? Object.fromEntries(
121
- Object.entries(dict).flatMap(([ts, wire]) =>
122
- typeof wire === "string"
123
- ? [[wire, ts] as const]
124
- : wire.map((w) => [w, ts] as const),
125
- ),
126
- )
127
- : Object.fromEntries(
128
- Object.entries(dict).map(([ts, wire]) => [
129
- ts,
130
- typeof wire === "string" ? wire : wire[0]!,
131
- ]),
132
- );
181
+ const rename = renameTable(dict, direction);
133
182
  const out: Record<string, unknown> = {};
134
183
  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
135
184
  if (v === undefined) continue;
@@ -141,102 +190,248 @@ export const mapKeysByDictionary = (
141
190
  /**
142
191
  * Recursively rename keys between TS names and wire names, per the schema.
143
192
  *
144
- * `fallback` is the nearest ancestor `T.KeyDictionary` — schema-known members
193
+ * `fallback` is the nearest ancestor `T.KeyDictionary` -- schema-known members
145
194
  * always map via their own annotations, but opaque values (Document members,
146
195
  * keys the schema doesn't know) deep-rename via the dictionary so nested
147
196
  * TS-cased content still reaches the wire in wire case. Content with no
148
197
  * dictionary in scope passes through verbatim.
149
198
  */
199
+ /**
200
+ * Value form for a `StringEncoded()` member: the string spelling of the
201
+ * value, element-wise for lists. `null` stays `null` -- an API that models a
202
+ * flag as `"true" | "false"` still means "unset" by null, not `"null"`.
203
+ */
204
+ const stringEncode = (value: unknown): unknown =>
205
+ value === null ? null : Array.isArray(value) ? value.map(stringEncode) : String(value);
206
+
207
+ /**
208
+ * Whether {@link mapKeys} returns every value of `root` unchanged (as a deep
209
+ * copy) in `direction` with no fallback dictionary: no member is renamed,
210
+ * string-encoded (encode) or picked by `T.UnionCases` (decode, or encode for
211
+ * a union whose cases carry member dictionaries), and no
212
+ * `T.KeyDictionary` is in scope anywhere below `root`. Protocols use it to
213
+ * skip the walk. Computed once per schema node and direction.
214
+ */
215
+ export const mapsVerbatim = (root: AST.AST, direction: "encode" | "decode"): boolean => {
216
+ const cache = direction === "encode" ? verbatimEncode : verbatimDecode;
217
+ let result = cache.get(root);
218
+ if (result !== undefined) return result;
219
+ result = true;
220
+ const seen = new Set<AST.AST>();
221
+ const stack: AST.AST[] = [root];
222
+ walk: while (stack.length > 0) {
223
+ const ast = stack.pop()!;
224
+ if (seen.has(ast)) continue;
225
+ seen.add(ast);
226
+ if (getAnn(ast, keyDictionarySymbol) !== undefined) {
227
+ result = false;
228
+ break;
229
+ }
230
+ const unionCases = getAnn(ast, unionCasesSymbol) as UnionCasesValue | undefined;
231
+ if (
232
+ unionCases !== undefined &&
233
+ (direction === "decode" || unionCases.dictionaries !== undefined)
234
+ ) {
235
+ result = false;
236
+ break;
237
+ }
238
+ const node = resolveNode(ast);
239
+ if (node._tag === "Union") {
240
+ for (const t of (node as AST.Union).types) stack.push(resolveNode(t));
241
+ } else if (node._tag === "Arrays") {
242
+ const elem = (node as any).rest?.[0] as AST.AST | undefined;
243
+ if (elem) stack.push(elem);
244
+ } else if (node._tag === "Objects") {
245
+ for (const p of (node as any).propertySignatures as readonly AST.PropertySignature[]) {
246
+ if (
247
+ nameOf(p, bodySymbol) !== String(p.name) ||
248
+ (direction === "encode" && hasPropAnn(p, stringEncodedSymbol))
249
+ ) {
250
+ result = false;
251
+ break walk;
252
+ }
253
+ stack.push(p.type);
254
+ }
255
+ for (const s of ((node as any).indexSignatures ?? []) as readonly { type: AST.AST }[]) {
256
+ stack.push(s.type);
257
+ }
258
+ }
259
+ }
260
+ cache.set(root, result);
261
+ return result;
262
+ };
263
+
264
+ /** The value `T.UnionCases` annotates. */
265
+ interface UnionCasesValue {
266
+ readonly cases: ReadonlyArray<ReadonlyArray<string>>;
267
+ readonly discriminator?: UnionDiscriminator;
268
+ readonly dictionaries?: ReadonlyArray<Readonly<Record<string, KeyDictionaryEntries>>>;
269
+ }
270
+ const verbatimEncode = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
271
+ const verbatimDecode = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
272
+
273
+ /** What {@link mapKeys} reads from a schema node, once per node. */
274
+ interface NodeFacts {
275
+ readonly dict: KeyDictionaryEntries | undefined;
276
+ readonly unionCases: UnionCasesValue | undefined;
277
+ readonly node: AST.AST;
278
+ /** A struct's members: TS name, wire name, type, and whether it is `StringEncoded()`. */
279
+ readonly members: ReadonlyArray<readonly [string, string, AST.AST, boolean]>;
280
+ /** The keys the members take: TS names (encode) and wire names (decode). */
281
+ readonly tsNames: ReadonlySet<string>;
282
+ readonly wireNames: ReadonlySet<string>;
283
+ }
284
+ const nodeFacts = /*@__PURE__*/ new WeakMap<AST.AST, NodeFacts>();
285
+ const factsOf = (ast: AST.AST): NodeFacts => {
286
+ let facts = nodeFacts.get(ast);
287
+ if (facts === undefined) {
288
+ const node = resolveNode(ast);
289
+ const members =
290
+ node._tag === "Objects"
291
+ ? ((node as any).propertySignatures as readonly AST.PropertySignature[]).map(
292
+ (p) =>
293
+ [
294
+ String(p.name),
295
+ nameOf(p, bodySymbol),
296
+ p.type,
297
+ hasPropAnn(p, stringEncodedSymbol),
298
+ ] as const,
299
+ )
300
+ : [];
301
+ facts = {
302
+ dict: getAnn(ast, keyDictionarySymbol) as KeyDictionaryEntries | undefined,
303
+ unionCases: getAnn(ast, unionCasesSymbol) as UnionCasesValue | undefined,
304
+ node,
305
+ members,
306
+ tsNames: new Set(members.map((m) => m[0])),
307
+ wireNames: new Set(members.map((m) => m[1])),
308
+ };
309
+ nodeFacts.set(ast, facts);
310
+ }
311
+ return facts;
312
+ };
313
+
314
+ /**
315
+ * Rename keys between TS names and wire names, per the schema (see
316
+ * {@link walkKeys}). A decode with no fallback dictionary returns `value`
317
+ * itself when the schema renames nothing ({@link mapsVerbatim}): the walk
318
+ * would only copy it.
319
+ */
150
320
  export const mapKeys = (
151
321
  ast: AST.AST,
152
322
  value: unknown,
153
323
  direction: "encode" | "decode",
154
324
  fallback?: KeyDictionaryEntries,
325
+ ): unknown =>
326
+ fallback === undefined && direction === "decode" && mapsVerbatim(ast, "decode")
327
+ ? value
328
+ : walkKeys(ast, value, direction, fallback);
329
+
330
+ const walkKeys = (
331
+ ast: AST.AST,
332
+ value: unknown,
333
+ direction: "encode" | "decode",
334
+ fallback?: KeyDictionaryEntries,
155
335
  ): unknown => {
156
- if (
157
- value === null ||
158
- value === undefined ||
159
- typeof value !== "object" ||
160
- isOpaqueValue(value)
161
- ) {
336
+ if (value === null || value === undefined || typeof value !== "object" || isOpaqueValue(value)) {
162
337
  return value;
163
338
  }
164
- const dict =
165
- (getAnn(ast, keyDictionarySymbol) as KeyDictionaryEntries | undefined) ??
166
- fallback;
339
+ const facts = factsOf(ast);
340
+ const dict = facts.dict ?? fallback;
167
341
 
168
342
  // Discriminated union whose cases the API returns merged (every case's
169
343
  // keys present, `null` for the inactive ones). Map wire names, then keep
170
- // only the active case's keys. A case does NOT need every key present —
171
- // arms carry optional members the wire may omit — so the active case is
172
- // the one that best EXPLAINS the value: most present, non-null keys
173
- // covered, minus present keys the case cannot explain (ties break by
174
- // coverage, then declaration order).
175
- const unionCases = getAnn(ast, unionCasesSymbol) as
176
- | ReadonlyArray<ReadonlyArray<string>>
177
- | undefined;
178
- if (unionCases && direction === "decode" && !Array.isArray(value)) {
179
- const obj = (
180
- dict ? mapKeysByDictionary(dict, value, "decode") : value
181
- ) as Record<string, unknown>;
182
- const present = Object.keys(obj).filter(
183
- (k) => obj[k] !== undefined && obj[k] !== null,
184
- );
185
- let best:
186
- | { keys: ReadonlyArray<string>; score: number; matched: number }
187
- | undefined;
188
- for (const keys of unionCases) {
189
- const set = new Set(keys);
190
- let matched = 0;
191
- let excess = 0;
192
- for (const k of present) {
193
- if (set.has(k)) matched++;
194
- else excess++;
195
- }
196
- const score = matched - excess;
197
- if (
198
- matched > 0 &&
199
- (!best ||
200
- score > best.score ||
201
- (score === best.score && matched > best.matched))
202
- ) {
203
- best = { keys, score, matched };
344
+ // only the active case's keys. The case is read off the union's
345
+ // discriminator when it has one -- cases that share a key set (every
346
+ // resource kind of `resource_tagging`, every page-rule action) are
347
+ // indistinguishable by keys alone. Without one, a case does NOT need every
348
+ // key present -- arms carry optional members the wire may omit -- so the
349
+ // active case is the one that best EXPLAINS the value: most present,
350
+ // non-null keys covered, minus present keys the case cannot explain (ties
351
+ // break by coverage, then declaration order).
352
+ //
353
+ // A case member with its own dictionary (`{}` for caller content such as
354
+ // a Worker binding's `json`) maps its value by that one. Encode takes this
355
+ // path only for a union that has such members: it picks the case the same
356
+ // way, then renames the top-level keys.
357
+ const unionCases = facts.unionCases;
358
+ if (
359
+ unionCases &&
360
+ (direction === "decode" || unionCases.dictionaries !== undefined) &&
361
+ !Array.isArray(value)
362
+ ) {
363
+ // Top-level keys in TS names; values still as given.
364
+ const rename = dict ? renameTable(dict, direction) : undefined;
365
+ const obj: Record<string, unknown> = {};
366
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
367
+ if (v !== undefined) obj[direction === "decode" ? (rename?.[k] ?? k) : k] = v;
368
+ }
369
+ const present = Object.keys(obj).filter((k) => obj[k] !== undefined && obj[k] !== null);
370
+ const disc = unionCases.discriminator;
371
+ const tag = disc ? obj[disc.key] : undefined;
372
+ const tagged = typeof tag === "string" ? disc!.values.indexOf(tag) : -1;
373
+ let best: { index: number; score: number; matched: number } | undefined;
374
+ if (tagged >= 0) {
375
+ best = { index: tagged, score: 0, matched: 0 };
376
+ } else {
377
+ for (let index = 0; index < unionCases.cases.length; index++) {
378
+ const set = new Set(unionCases.cases[index]);
379
+ let matched = 0;
380
+ let excess = 0;
381
+ for (const k of present) {
382
+ if (set.has(k)) matched++;
383
+ else excess++;
384
+ }
385
+ const score = matched - excess;
386
+ if (
387
+ matched > 0 &&
388
+ (!best || score > best.score || (score === best.score && matched > best.matched))
389
+ ) {
390
+ best = { index, score, matched };
391
+ }
204
392
  }
205
393
  }
206
- if (best) {
207
- const out: Record<string, unknown> = {};
208
- for (const k of best.keys) out[k] = obj[k];
209
- return out;
394
+ const own = best ? unionCases.dictionaries?.[best.index] : undefined;
395
+ const mapValue = (k: string, v: unknown): unknown => {
396
+ const d = own?.[k] ?? dict;
397
+ return d ? mapKeysByDictionary(d, v, direction) : v;
398
+ };
399
+ const out: Record<string, unknown> = {};
400
+ if (direction === "encode") {
401
+ // Every given key goes out, like the plain dictionary walk.
402
+ for (const [k, v] of Object.entries(obj)) out[rename?.[k] ?? k] = mapValue(k, v);
403
+ } else {
404
+ for (const k of best ? unionCases.cases[best.index]! : Object.keys(obj)) {
405
+ out[k] = mapValue(k, obj[k]);
406
+ }
210
407
  }
211
- return obj;
408
+ return out;
212
409
  }
213
410
 
214
- const node = resolveNode(ast);
411
+ const node = facts.node;
215
412
 
216
413
  // Schema-level union member (a merged response struct whose arms disagree
217
- // on a member's type — see the codegen's response-union merge): pick the
414
+ // on a member's type -- see the codegen's response-union merge): pick the
218
415
  // arm that explains the value best and map with it. Object values score
219
416
  // arms by how many of their declared keys are present; array values take
220
417
  // the first array arm. Anything unmatched deep-renames via the dictionary
221
- // fallback, like other opaque content. (Single-real-member unions —
222
- // optional/null wrappers — were already collapsed by resolveNode; the
418
+ // fallback, like other opaque content. (Single-real-member unions --
419
+ // optional/null wrappers -- were already collapsed by resolveNode; the
223
420
  // opaque `T.UnionCases` mechanism never produces a Union node and is
224
421
  // handled above.)
225
422
  if (node._tag === "Union") {
226
423
  const arms = (node as AST.Union).types.map(resolveNode);
227
424
  if (Array.isArray(value)) {
228
425
  const arr = arms.find((t) => t._tag === "Arrays");
229
- if (arr) return mapKeys(arr, value, direction, dict);
426
+ if (arr) return walkKeys(arr, value, direction, dict);
230
427
  } else {
231
428
  let best: AST.AST | undefined;
232
429
  let bestScore = 0;
233
430
  for (const t of arms) {
234
431
  if (t._tag !== "Objects") continue;
235
432
  let score = 0;
236
- for (const p of (t as any)
237
- .propertySignatures as readonly AST.PropertySignature[]) {
238
- const from =
239
- direction === "encode" ? String(p.name) : nameOf(p, bodySymbol);
433
+ for (const p of (t as any).propertySignatures as readonly AST.PropertySignature[]) {
434
+ const from = direction === "encode" ? String(p.name) : nameOf(p, bodySymbol);
240
435
  if ((value as Record<string, unknown>)[from] !== undefined) score++;
241
436
  }
242
437
  if (score > bestScore) {
@@ -244,7 +439,7 @@ export const mapKeys = (
244
439
  bestScore = score;
245
440
  }
246
441
  }
247
- if (best) return mapKeys(best, value, direction, dict);
442
+ if (best) return walkKeys(best, value, direction, dict);
248
443
  }
249
444
  return dict ? mapKeysByDictionary(dict, value, direction) : value;
250
445
  }
@@ -253,45 +448,45 @@ export const mapKeys = (
253
448
  if (!Array.isArray(value)) return value;
254
449
  const elem = (node as any).rest?.[0] as AST.AST | undefined;
255
450
  return elem
256
- ? value.map((v) => mapKeys(elem, v, direction, dict))
451
+ ? value.map((v) => walkKeys(elem, v, direction, dict))
257
452
  : dict
258
453
  ? mapKeysByDictionary(dict, value, direction)
259
454
  : value;
260
455
  }
261
456
 
262
457
  if (node._tag === "Objects" && !Array.isArray(value)) {
263
- const props = (node as any)
264
- .propertySignatures as readonly AST.PropertySignature[];
265
- const isigs = (node as any).indexSignatures as
266
- | readonly { type: AST.AST }[]
267
- | undefined;
268
- if (props.length === 0 && !(isigs && isigs.length)) {
269
- // opaque object — dictionary fallback or verbatim
458
+ const members = facts.members;
459
+ const isigs = (node as any).indexSignatures as readonly { type: AST.AST }[] | undefined;
460
+ if (members.length === 0 && !(isigs && isigs.length)) {
461
+ // opaque object -- dictionary fallback or verbatim
270
462
  return dict ? mapKeysByDictionary(dict, value, direction) : value;
271
463
  }
272
464
  const out: Record<string, unknown> = {};
273
- const consumed = new Set<string>();
274
- for (const p of props) {
275
- const tsName = String(p.name);
276
- const wire = nameOf(p, bodySymbol);
465
+ const consumed = direction === "encode" ? facts.tsNames : facts.wireNames;
466
+ for (const [tsName, wire, type, stringEncoded] of members) {
277
467
  const from = direction === "encode" ? tsName : wire;
278
468
  const to = direction === "encode" ? wire : tsName;
279
- consumed.add(from);
280
469
  const v = (value as Record<string, unknown>)[from];
281
470
  if (v === undefined) continue;
282
- out[to] = mapKeys(p.type, v, direction, dict);
471
+ // A `StringEncoded()` member nested in a body struct (e.g. Azure's
472
+ // `hardwareProfile.dynamicMemoryEnabled`) stringifies here -- the
473
+ // top-level pass in `buildRequest` only sees the outermost member.
474
+ out[to] =
475
+ direction === "encode" && stringEncoded
476
+ ? stringEncode(v)
477
+ : walkKeys(type, v, direction, dict);
283
478
  }
284
479
  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
285
480
  if (consumed.has(k) || v === undefined) continue;
286
481
  const renamed = dict
287
482
  ? direction === "encode"
288
483
  ? (dict[k] ?? k)
289
- : (Object.entries(dict).find(([, w]) => w === k)?.[0] ?? k)
484
+ : (tsNameOf(dict, k) ?? k)
290
485
  : k;
291
486
 
292
487
  out[typeof renamed === "string" ? renamed : renamed[0]] =
293
488
  isigs && isigs.length
294
- ? mapKeys(isigs[0]!.type, v, direction, dict)
489
+ ? walkKeys(isigs[0]!.type, v, direction, dict)
295
490
  : dict
296
491
  ? mapKeysByDictionary(dict, v, direction)
297
492
  : v;
@@ -299,7 +494,7 @@ export const mapKeys = (
299
494
  return out;
300
495
  }
301
496
 
302
- // Scalar-typed schema node holding object content (spec drift) —
497
+ // Scalar-typed schema node holding object content (spec drift) --
303
498
  // dictionary fallback or verbatim.
304
499
  return dict ? mapKeysByDictionary(dict, value, direction) : value;
305
500
  };
@@ -307,30 +502,22 @@ export const mapKeys = (
307
502
 
308
503
  //#region Request building
309
504
 
310
- const BODYLESS = new Set(["GET", "HEAD"]);
505
+ const BODYLESS = /*@__PURE__*/ new Set(["GET", "HEAD"]);
311
506
 
312
507
  /**
313
508
  * Serialize one query member. Scalars go as `k=v`, arrays as repeated `k=v`
314
- * pairs, and nested plain objects recurse as DOTTED params — several list
509
+ * pairs, and nested plain objects recurse as DOTTED params -- several list
315
510
  * endpoints model their filters as structs (e.g. Cloudflare DNS listRecords
316
511
  * takes `name: { exact, contains, ... }`) that must go over the wire as
317
512
  * `name.exact=value`. Without this they fell through to `String(value)` and
318
513
  * were sent as `name=[object Object]`, which servers happily treat as a
319
- * filter matching nothing — the call "succeeds" with zero results and the
514
+ * filter matching nothing -- the call "succeeds" with zero results and the
320
515
  * bug is invisible to the caller.
321
516
  */
322
- const appendQuery = (
323
- query: URLSearchParams,
324
- name: string,
325
- value: unknown,
326
- ): void => {
517
+ const appendQuery = (query: URLSearchParams, name: string, value: unknown): void => {
327
518
  if (Array.isArray(value)) {
328
519
  for (const v of value) appendQuery(query, name, v);
329
- } else if (
330
- value !== null &&
331
- typeof value === "object" &&
332
- !(value instanceof Date)
333
- ) {
520
+ } else if (value !== null && typeof value === "object" && !(value instanceof Date)) {
334
521
  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
335
522
  if (v !== undefined) appendQuery(query, `${name}.${k}`, v);
336
523
  }
@@ -352,34 +539,46 @@ export interface BuildRequestOptions {
352
539
  */
353
540
  readonly mapMemberHeader?: (name: string, value: string) => string;
354
541
  /**
355
- * Wire name for input keys the schema doesn't declare (spec drift —
542
+ * Wire name for input keys the schema doesn't declare (spec drift --
356
543
  * unknown keys pass through as body fields rather than being dropped).
357
544
  * Defaults to the key verbatim.
358
545
  */
359
546
  readonly unknownKeyToWire?: (key: string) => string;
547
+ /**
548
+ * Send `{}` on a method that takes a body even when the input declares no
549
+ * body members. Connect unary RPCs (E2B's envd) POST JSON for every call,
550
+ * and refuse a bodyless one with 415.
551
+ */
552
+ readonly emptyJsonBody?: boolean;
553
+ /**
554
+ * How a query member spells a nested object or an array.
555
+ *
556
+ * - `"dotted"` (default): `created.gte=1`; an array repeats the key
557
+ * (`expand=a&expand=b`).
558
+ * - `"brackets"`: `created[gte]=1`; an array indexes the key
559
+ * (`expand[0]=a&expand[1]=b`), the same rule as form-urlencoded bodies.
560
+ * Stripe needs this: its v2 API refuses `key[]` and repeated keys.
561
+ *
562
+ * `T.CommaDelimited` and `T.DeepQuery` members keep their own spelling.
563
+ */
564
+ readonly queryStyle?: "dotted" | "brackets";
360
565
  }
361
566
 
362
567
  /**
363
- * Build an HTTP request from an operation input and its schema, driven by
364
- * the trait annotations: `Http()` supplies method + URI template, `Label()`
365
- * members fill URI placeholders, `Header()`/`Query()` members bind to
366
- * headers/query params, `DeepQuery()` struct members expand into dotted
367
- * query params, `HttpBody()` sends the member as the whole body,
368
- * `FormDataFile()` members become multipart file parts, and everything else
369
- * is a JSON body field (wire-named via `Body()` / `KeyDictionary`).
370
- *
371
- * Throws when the input schema is missing the `Http()` trait — a codegen
372
- * bug, surfaced as a defect by the calling protocol's Effect context.
568
+ * Encode a greedy `{name+}` label: the value may span several path
569
+ * segments (e.g. an Azure scope `/subscriptions/{id}/resourceGroups/{rg}`),
570
+ * so each segment is encoded on its own and the `/` separators are kept.
571
+ * Leading slashes are dropped because the URI template already supplies one.
373
572
  */
573
+ export const encodeGreedyLabel = (value: string): string =>
574
+ value.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
575
+
374
576
  /**
375
577
  * Flatten a nested object into Stripe-style bracket notation pairs for
376
578
  * form-urlencoded bodies: nested objects become `a[b][c]`, arrays index as
377
579
  * `a[0]`; null/undefined dropped, booleans as "true"/"false".
378
580
  */
379
- const flattenToFormPairs = (
380
- obj: Record<string, unknown>,
381
- prefix = "",
382
- ): Array<[string, string]> => {
581
+ const flattenToFormPairs = (obj: Record<string, unknown>, prefix = ""): Array<[string, string]> => {
383
582
  const pairs: Array<[string, string]> = [];
384
583
  for (const [key, value] of Object.entries(obj)) {
385
584
  if (value === undefined || value === null) continue;
@@ -389,20 +588,13 @@ const flattenToFormPairs = (
389
588
  const item = value[i];
390
589
  if (item === undefined || item === null) continue;
391
590
  if (typeof item === "object" && !Array.isArray(item)) {
392
- pairs.push(
393
- ...flattenToFormPairs(
394
- item as Record<string, unknown>,
395
- `${fullKey}[${i}]`,
396
- ),
397
- );
591
+ pairs.push(...flattenToFormPairs(item as Record<string, unknown>, `${fullKey}[${i}]`));
398
592
  } else {
399
593
  pairs.push([`${fullKey}[${i}]`, String(item)]);
400
594
  }
401
595
  }
402
596
  } else if (typeof value === "object") {
403
- pairs.push(
404
- ...flattenToFormPairs(value as Record<string, unknown>, fullKey),
405
- );
597
+ pairs.push(...flattenToFormPairs(value as Record<string, unknown>, fullKey));
406
598
  } else {
407
599
  pairs.push([fullKey, String(value)]);
408
600
  }
@@ -410,219 +602,581 @@ const flattenToFormPairs = (
410
602
  return pairs;
411
603
  };
412
604
 
413
- export const buildRequest = ({
605
+ /**
606
+ * Marks a raw body member as binary (core `RawBody`): a string is sent as
607
+ * its bytes, never JSON-encoded, even with no declared media type.
608
+ */
609
+ export const binaryBodySymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/binary-body");
610
+
611
+ /** How an input member binds to the request. */
612
+ type Bind = "label" | "header" | "query" | "deepQuery" | "file" | "httpBody" | "body";
613
+
614
+ /** One input member, with its binding read from the schema once. */
615
+ interface MemberPlan {
616
+ readonly key: string;
617
+ readonly bind: Bind;
618
+ /** Label token, lower-cased header name, query name or body wire name. */
619
+ readonly name: string;
620
+ readonly type: AST.AST;
621
+ /** `LabelEncoding` characters kept unescaped. */
622
+ readonly preserve: string | undefined;
623
+ /** `{name+}` placeholder. */
624
+ readonly greedy: boolean;
625
+ /** The schema marks the member optional (`S.optional`). */
626
+ readonly optional: boolean;
627
+ readonly stringEncoded: boolean;
628
+ /** A list query member sent as one comma-separated parameter. */
629
+ readonly commaDelimited: boolean;
630
+ /** `mapKeys(type, value, "encode", rootDict)` returns the value unchanged. */
631
+ readonly verbatim: boolean;
632
+ /** A binary raw body (see {@link binaryBodySymbol}). */
633
+ readonly binary: boolean;
634
+ }
635
+
636
+ /** What `buildRequest` reads from an input schema, computed once per schema. */
637
+ interface RequestPlan {
638
+ readonly http: HttpTrait;
639
+ readonly rootDict: KeyDictionaryEntries | undefined;
640
+ readonly members: ReadonlyArray<MemberPlan>;
641
+ readonly known: ReadonlySet<string>;
642
+ /** The schema declares a member that is sent in the body. */
643
+ readonly hasBodyMembers: boolean;
644
+ }
645
+
646
+ const plans = /*@__PURE__*/ new WeakMap<AST.AST, RequestPlan>();
647
+
648
+ const planFor = (inputAst: AST.AST): RequestPlan | SdkError => {
649
+ let plan = plans.get(inputAst);
650
+ if (plan !== undefined) return plan;
651
+ const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
652
+ if (!http) {
653
+ return new SdkError({ message: "operation input is missing the Http() trait" });
654
+ }
655
+ const rootDict = getAnn(inputAst, keyDictionarySymbol) as KeyDictionaryEntries | undefined;
656
+ const members: MemberPlan[] = [];
657
+ const known = new Set<string>();
658
+ let hasBodyMembers = false;
659
+ for (const prop of getProps(inputAst)) {
660
+ const key = String(prop.name);
661
+ known.add(key);
662
+ let bind: Bind;
663
+ let name: string;
664
+ let greedy = false;
665
+ if (hasPropAnn(prop, labelSymbol)) {
666
+ bind = "label";
667
+ name = nameOf(prop, labelSymbol);
668
+ greedy = http.uri.includes(`{${name}+}`);
669
+ } else if (hasPropAnn(prop, headerSymbol)) {
670
+ bind = "header";
671
+ name = nameOf(prop, headerSymbol).toLowerCase();
672
+ } else if (hasPropAnn(prop, querySymbol)) {
673
+ bind = "query";
674
+ name = nameOf(prop, querySymbol);
675
+ } else if (hasPropAnn(prop, deepQuerySymbol)) {
676
+ bind = "deepQuery";
677
+ name = nameOf(prop, deepQuerySymbol);
678
+ } else {
679
+ hasBodyMembers = true;
680
+ bind = hasPropAnn(prop, formDataFileSymbol)
681
+ ? "file"
682
+ : hasPropAnn(prop, httpBodySymbol)
683
+ ? "httpBody"
684
+ : "body";
685
+ name = nameOf(prop, bodySymbol);
686
+ }
687
+ const preserve = getPropAnn(prop, labelEncodingSymbol);
688
+ members.push({
689
+ key,
690
+ bind,
691
+ name,
692
+ type: prop.type,
693
+ preserve: typeof preserve === "string" ? preserve : undefined,
694
+ greedy,
695
+ optional: prop.type.context?.isOptional === true,
696
+ stringEncoded: hasPropAnn(prop, stringEncodedSymbol),
697
+ commaDelimited: hasPropAnn(prop, commaDelimitedSymbol),
698
+ verbatim: rootDict === undefined && mapsVerbatim(prop.type, "encode"),
699
+ binary: hasPropAnn(prop, binaryBodySymbol),
700
+ });
701
+ }
702
+ plan = { http, rootDict, members, known, hasBodyMembers };
703
+ plans.set(inputAst, plan);
704
+ return plan;
705
+ };
706
+
707
+ const emptyRequest = /*@__PURE__*/ HttpClientRequest.get("");
708
+
709
+ /**
710
+ * `HttpClientRequest.make(method)(url)` with `headers` set, in one object:
711
+ * the same request as `make(...).pipe(setHeaders(headers))` without the
712
+ * intermediate copies. `url` may carry a query string.
713
+ */
714
+ export const makeRequest = (
715
+ method: HttpTrait["method"],
716
+ url: string,
717
+ headers: Record<string, string>,
718
+ ): HttpClientRequest.HttpClientRequest =>
719
+ HttpClientRequest.makeWith(
720
+ method,
721
+ url,
722
+ emptyRequest.urlParams,
723
+ emptyRequest.hash,
724
+ Headers.fromInput(headers),
725
+ HttpBody.empty,
726
+ );
727
+
728
+ /**
729
+ * The input cannot be sent: a path label whose value would address another
730
+ * resource (`.` or `..`, which the URL parser resolves to the parent path,
731
+ * or `""`, which addresses the parent path), or a host label that would
732
+ * address another host. Raised before anything is sent.
733
+ */
734
+ export class InvalidInput
735
+ extends /*@__PURE__*/ Schema.TaggedError<InvalidInput>()("InvalidInput", {
736
+ member: Schema.String,
737
+ message: Schema.String,
738
+ }).pipe(Category.withBadRequestError) {}
739
+
740
+ /**
741
+ * The refusal for an input no request can carry. `cause` is what a step
742
+ * that only reads the caller's values threw: `JSON.stringify` on a `BigInt`,
743
+ * a walk of an object that contains itself.
744
+ */
745
+ export const unsendable = (cause: unknown): InvalidInput =>
746
+ new InvalidInput({ member: "input", message: `The input cannot be sent: ${String(cause)}` });
747
+
748
+ /** `value` as the JSON body of `request`, or the refusal for a value JSON cannot carry. */
749
+ const withJsonBody = (
750
+ request: HttpClientRequest.HttpClientRequest,
751
+ value: unknown,
752
+ contentType: string | undefined,
753
+ ): HttpClientRequest.HttpClientRequest | InvalidInput => {
754
+ try {
755
+ return HttpClientRequest.setBody(request, HttpBody.jsonUnsafe(value, contentType));
756
+ } catch (cause) {
757
+ return unsendable(cause);
758
+ }
759
+ };
760
+
761
+ /**
762
+ * The refusal for a path label value that would address another resource,
763
+ * or `undefined`. The URL parser resolves a `.` or `..` segment,
764
+ * percent-encoded or not, so no encoding can carry one
765
+ * (`/projects/p1/branches/..` -> `/projects/p1/`). A greedy label keeps its
766
+ * `/`, so each of its segments counts.
767
+ *
768
+ * Also refuses an empty value, unless the label is `optional`. It leaves the
769
+ * segment empty, and a server that ignores a trailing slash (Smithy routing
770
+ * does) reads `/things/` as the collection `/things`: Kubernetes runs a
771
+ * delete of the Secret `""` as a delete of every Secret in the namespace.
772
+ * A label the schema marks optional is one the API documents as possibly
773
+ * empty (Azure Key Vault's `{secret-version}`), so it may be `""`.
774
+ *
775
+ * Also refuses a value with a lone UTF-16 surrogate (`"\ud800"`):
776
+ * `encodeURIComponent` throws `URIError` on it, and no encoding keeps the
777
+ * name as written.
778
+ */
779
+ export const invalidLabel = (
780
+ member: string,
781
+ value: unknown,
782
+ greedy?: boolean,
783
+ optional?: boolean,
784
+ ): InvalidInput | undefined => {
785
+ const text = String(value);
786
+ if (!text.isWellFormed()) {
787
+ return new InvalidInput({
788
+ member,
789
+ message: `Input member ${member} cannot be ${JSON.stringify(text)}: it has a lone UTF-16 surrogate, which a URL cannot carry`,
790
+ });
791
+ }
792
+ return (text === "" && !optional) ||
793
+ (greedy ? text.split("/") : [text]).some((s) => s === "." || s === "..")
794
+ ? new InvalidInput({
795
+ member,
796
+ message: `Input member ${member} cannot be ${JSON.stringify(text)}: as a path label it would address another resource`,
797
+ })
798
+ : undefined;
799
+ };
800
+
801
+ /**
802
+ * A path label value, percent-encoded, or the {@link InvalidInput} that
803
+ * {@link invalidLabel} refuses it with. A greedy label keeps its `/` and
804
+ * encodes each segment ({@link encodeGreedyLabel}). Use it wherever a
805
+ * caller's value goes into a URL path, so the check can't be skipped.
806
+ */
807
+ export const encodeLabel = (
808
+ member: string,
809
+ value: unknown,
810
+ greedy?: boolean,
811
+ optional?: boolean,
812
+ ): string | InvalidInput =>
813
+ invalidLabel(member, value, greedy, optional) ??
814
+ (greedy ? encodeGreedyLabel(String(value)) : encodeURIComponent(String(value)));
815
+
816
+ /** One RFC 1123 DNS label: 1-63 letters, digits and `-`, no `-` at either end. */
817
+ const HOST_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
818
+
819
+ /**
820
+ * Whether `value` is one DNS host label (RFC 1123), or with
821
+ * `allowSubDomains` a dot-separated name made of them. A value that goes into
822
+ * a URL host must pass it: any other character (`/`, `@`, `#`, `?`, `:`)
823
+ * can move the request to another host, and no encoding fixes a host.
824
+ */
825
+ export const isHostLabel = (value: unknown, allowSubDomains?: boolean): boolean =>
826
+ typeof value === "string" &&
827
+ (allowSubDomains ? value.split(".") : [value]).every((label) => HOST_LABEL.test(label));
828
+
829
+ /**
830
+ * The refusal for a value that goes into a URL host but is not a host label
831
+ * ({@link isHostLabel}), or `undefined`. The host-side counterpart of
832
+ * {@link invalidLabel}. A value read from credentials config fails with
833
+ * {@link invalidHostLabelConfig} instead.
834
+ */
835
+ export const invalidHostLabel = (
836
+ member: string,
837
+ value: unknown,
838
+ allowSubDomains?: boolean,
839
+ ): InvalidInput | undefined =>
840
+ isHostLabel(value, allowSubDomains)
841
+ ? undefined
842
+ : new InvalidInput({
843
+ member,
844
+ message: `Input member ${member} cannot be ${JSON.stringify(String(value))}: as a host label it would address another host`,
845
+ });
846
+
847
+ /**
848
+ * {@link invalidHostLabel} for a value read from credentials config: the
849
+ * refusal is a `ConfigError` naming the setting (`"S2 basin"`,
850
+ * `"STACKIT region"`), or `undefined`.
851
+ */
852
+ export const invalidHostLabelConfig = (
853
+ name: string,
854
+ value: unknown,
855
+ allowSubDomains?: boolean,
856
+ ): ConfigError | undefined =>
857
+ isHostLabel(value, allowSubDomains)
858
+ ? undefined
859
+ : new ConfigError({
860
+ message: `${name} ${JSON.stringify(String(value))} cannot go into a host name: it must be ${allowSubDomains ? "DNS labels separated by dots, each" : "one DNS label:"} letters, digits and hyphens, at most 63 characters`,
861
+ });
862
+
863
+ /**
864
+ * The origin (`https://host[:port]`) that a host or origin read from
865
+ * credentials config names, or the `ConfigError` refusing it. The value is
866
+ * a host (`acme.zendesk.com`, `udm.lan:8443`, given `defaultScheme`) or an
867
+ * origin (`https://acme.zendesk.com/`). It picks the host and nothing else:
868
+ * a user, path, query or fragment, a scheme other than `http`/`https`, or a
869
+ * host name that is not DNS labels ({@link isHostLabel}) or an IPv6 literal
870
+ * is refused.
871
+ */
872
+ export const originFromConfig = (
873
+ name: string,
874
+ value: string,
875
+ defaultScheme: "https" | "http" = "https",
876
+ ): string | ConfigError => {
877
+ const refuse = (reason: string) =>
878
+ new ConfigError({ message: `${name} ${JSON.stringify(value)} ${reason}` });
879
+ const trimmed = value.replace(/\/+$/, "");
880
+ const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)
881
+ ? trimmed
882
+ : `${defaultScheme}://${trimmed}`;
883
+ if (!URL.canParse(candidate)) return refuse("is not a host name or origin");
884
+ const url = new URL(candidate);
885
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
886
+ return refuse("must use https:// or http://");
887
+ }
888
+ if (url.href !== `${url.origin}/`) {
889
+ return refuse("must be a host, such as example.com, with no user, path, query or fragment");
890
+ }
891
+ if (!url.hostname.startsWith("[") && !isHostLabel(url.hostname, true)) {
892
+ return refuse("cannot be a host name: each label must be letters, digits and hyphens");
893
+ }
894
+ return url.origin;
895
+ };
896
+
897
+ /**
898
+ * Build an HTTP request from an operation input and its schema, driven by
899
+ * the trait annotations: `Http()` supplies method + URI template, `Label()`
900
+ * members fill URI placeholders, `Header()`/`Query()` members bind to
901
+ * headers/query params, `DeepQuery()` struct members expand into dotted
902
+ * query params, `HttpBody()` sends the member as the whole body,
903
+ * `FormDataFile()` members become multipart file parts, and everything else
904
+ * is a JSON body field (wire-named via `Body()` / `KeyDictionary`).
905
+ *
906
+ * The schema is read once per input schema (see `planFor`); later calls only
907
+ * walk the input value.
908
+ *
909
+ * An optional label left out of the input is an empty segment, like `""`
910
+ * (Azure Key Vault's `/secrets/{name}/{version}` -> `/secrets/db/`).
911
+ *
912
+ * Fails with {@link InvalidInput}, before anything is sent, when a label is
913
+ * `.` or `..` (for a greedy `{name+}` label, when any of its segments is),
914
+ * is `""` and the schema marks it required, or has a lone UTF-16 surrogate,
915
+ * and when a JSON body holds a value JSON cannot carry (a `BigInt`, an
916
+ * object that contains itself).
917
+ * Fails with {@link SdkError} when the input schema is missing the `Http()`
918
+ * trait (a codegen bug the generator refuses).
919
+ */
920
+ export const buildRequest = (
921
+ options: BuildRequestOptions,
922
+ ): Effect.Effect<HttpClientRequest.HttpClientRequest, InvalidInput | SdkError> => {
923
+ const request = requestOrInvalid(options);
924
+ return request instanceof InvalidInput || request instanceof SdkError
925
+ ? Effect.fail(request)
926
+ : Effect.succeed(request);
927
+ };
928
+
929
+ const requestOrInvalid = ({
414
930
  input,
415
931
  inputAst,
416
932
  baseUrl,
417
933
  headers: baseHeaders,
418
934
  mapMemberHeader,
419
935
  unknownKeyToWire,
420
- }: BuildRequestOptions): HttpClientRequest.HttpClientRequest => {
936
+ emptyJsonBody,
937
+ queryStyle,
938
+ }: BuildRequestOptions): HttpClientRequest.HttpClientRequest | InvalidInput | SdkError => {
421
939
  const inputObj = (input ?? {}) as Record<string, unknown>;
422
- const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
423
- if (!http) {
424
- throw new Error("operation input is missing the Http() trait");
425
- }
426
- // Root key dictionary: fallback wire mapping for opaque/unknown content
427
- // the schema doesn't model.
428
- const rootDict = getAnn(inputAst, keyDictionarySymbol) as
429
- | KeyDictionaryEntries
430
- | undefined;
940
+ const plan = planFor(inputAst);
941
+ if (plan instanceof SdkError) return plan;
942
+ const { http, rootDict, members, known } = plan;
943
+ let hasBodyMembers = plan.hasBodyMembers;
431
944
 
432
945
  const headers: Record<string, string> = { ...baseHeaders };
433
946
  const body: Record<string, unknown> = {};
434
- let rawBody: unknown; // whole-body member (T.HttpBody) — sent as-is
435
- const files: Array<Blob | File> = [];
436
- const query = new URLSearchParams();
947
+ let bodyKeys = 0;
948
+ let rawBody: unknown; // whole-body member (T.HttpBody) -- sent as-is
949
+ let rawBinary = false; // that member is binary: a string goes out as its bytes
950
+ let files: Array<Blob | File> | undefined;
951
+ let query: URLSearchParams | undefined;
437
952
  let uri = http.uri;
438
- const consumed = new Set<string>();
439
- let hasBodyMembers = false;
440
-
441
- for (const prop of getProps(inputAst)) {
442
- const key = String(prop.name);
443
- consumed.add(key);
444
- const value = inputObj[key];
445
- const isBodyMember =
446
- !hasPropAnn(prop, labelSymbol) &&
447
- !hasPropAnn(prop, headerSymbol) &&
448
- !hasPropAnn(prop, querySymbol) &&
449
- !hasPropAnn(prop, deepQuerySymbol);
450
- if (isBodyMember) hasBodyMembers = true;
451
- if (value === undefined) continue;
953
+ // Value of a modeled `Content-Type` header member, e.g. R2 putObject's
954
+ // `contentType`. A raw body is sent under it (see below).
955
+ let memberContentType: string | undefined;
452
956
 
453
- if (hasPropAnn(prop, labelSymbol)) {
454
- const token = nameOf(prop, labelSymbol);
455
- uri = uri.replace(`{${token}}`, encodeURIComponent(String(value)));
456
- } else if (hasPropAnn(prop, headerSymbol)) {
457
- const hName = nameOf(prop, headerSymbol).toLowerCase();
458
- const hVal = String(value);
459
- headers[hName] = mapMemberHeader ? mapMemberHeader(hName, hVal) : hVal;
460
- } else if (hasPropAnn(prop, querySymbol)) {
461
- appendQuery(query, nameOf(prop, querySymbol), value);
462
- } else if (hasPropAnn(prop, deepQuerySymbol)) {
463
- // Deep-object query member (T.DeepQuery): a nested struct expands into
464
- // dotted query keys (`account.id=…`) under the member's wire name.
465
- // Wire-name the nested content via the schema first, skip null/
466
- // undefined entries; deeper nesting recurses through appendQuery.
467
- const base = nameOf(prop, deepQuerySymbol);
468
- const mapped = mapKeys(prop.type, value, "encode", rootDict);
469
- if (mapped !== null && typeof mapped === "object") {
470
- for (const [k, v] of Object.entries(
471
- mapped as Record<string, unknown>,
472
- )) {
473
- if (v !== undefined && v !== null) {
474
- appendQuery(query, `${base}.${k}`, v);
957
+ for (let i = 0; i < members.length; i++) {
958
+ const m = members[i]!;
959
+ const value = inputObj[m.key];
960
+ if (value === undefined) {
961
+ // An omitted optional label is an empty segment, the same as `""`.
962
+ if (m.bind === "label" && m.optional) {
963
+ uri = uri.replace(m.greedy ? `{${m.name}+}` : `{${m.name}}`, "");
964
+ }
965
+ continue;
966
+ }
967
+ switch (m.bind) {
968
+ case "label": {
969
+ const encoded = encodeLabel(m.key, value, m.greedy, m.optional);
970
+ if (encoded instanceof InvalidInput) return encoded;
971
+ const preserve = m.preserve;
972
+ const label =
973
+ preserve !== undefined && !m.greedy
974
+ ? encoded.replace(/%[0-9A-F]{2}/g, (escape) => {
975
+ const character = String.fromCharCode(Number.parseInt(escape.slice(1), 16));
976
+ return preserve.includes(character) ? character : escape;
977
+ })
978
+ : encoded;
979
+ uri = uri.replace(m.greedy ? `{${m.name}+}` : `{${m.name}}`, () => label);
980
+ break;
981
+ }
982
+ case "header": {
983
+ const hVal = String(value);
984
+ headers[m.name] = mapMemberHeader ? mapMemberHeader(m.name, hVal) : hVal;
985
+ if (m.name === "content-type") memberContentType = headers[m.name];
986
+ break;
987
+ }
988
+ case "query":
989
+ if (m.commaDelimited && Array.isArray(value)) {
990
+ (query ??= new URLSearchParams()).append(m.name, value.map(String).join(","));
991
+ } else if (queryStyle === "brackets") {
992
+ query ??= new URLSearchParams();
993
+ for (const [k, v] of flattenToFormPairs({ [m.name]: value })) query.append(k, v);
994
+ } else {
995
+ appendQuery((query ??= new URLSearchParams()), m.name, value);
996
+ }
997
+ break;
998
+ case "deepQuery": {
999
+ // Deep-object query member (T.DeepQuery): a nested struct expands into
1000
+ // dotted query keys (`account.id=...`) under the member's wire name.
1001
+ // Wire-name the nested content via the schema first, skip null/
1002
+ // undefined entries; deeper nesting recurses through appendQuery.
1003
+ const mapped = m.verbatim ? value : mapKeys(m.type, value, "encode", rootDict);
1004
+ if (mapped !== null && typeof mapped === "object") {
1005
+ for (const [k, v] of Object.entries(mapped as Record<string, unknown>)) {
1006
+ if (v !== undefined && v !== null) {
1007
+ appendQuery((query ??= new URLSearchParams()), `${m.name}.${k}`, v);
1008
+ }
475
1009
  }
476
1010
  }
1011
+ break;
477
1012
  }
478
- } else if (hasPropAnn(prop, formDataFileSymbol)) {
479
- for (const f of Array.isArray(value) ? value : [value]) {
480
- files.push(f as Blob | File);
481
- }
482
- } else if (hasPropAnn(prop, httpBodySymbol)) {
483
- rawBody = mapKeys(prop.type, value, "encode", rootDict);
484
- } else {
485
- body[nameOf(prop, bodySymbol)] = mapKeys(
486
- prop.type,
487
- value,
488
- "encode",
489
- rootDict,
490
- );
1013
+ case "file":
1014
+ files ??= [];
1015
+ for (const f of Array.isArray(value) ? value : [value]) {
1016
+ files.push(f as Blob | File);
1017
+ }
1018
+ break;
1019
+ case "httpBody":
1020
+ rawBody = m.verbatim ? value : mapKeys(m.type, value, "encode", rootDict);
1021
+ rawBinary = m.binary;
1022
+ break;
1023
+ default:
1024
+ // T.StringEncoded(): the API takes this member's value only as its
1025
+ // string spelling (`true` -> `"true"`), while the TS surface keeps the
1026
+ // natural type. Explicit here so a JSON body carries the string too,
1027
+ // rather than relying on the multipart encoder's own `String()`.
1028
+ body[m.name] = m.stringEncoded
1029
+ ? stringEncode(value)
1030
+ : m.verbatim
1031
+ ? value
1032
+ : mapKeys(m.type, value, "encode", rootDict);
1033
+ bodyKeys++;
491
1034
  }
492
1035
  }
493
1036
 
494
- // Input keys the schema doesn't know pass through as body fields — the
1037
+ // Input keys the schema doesn't know pass through as body fields -- the
495
1038
  // generated schemas can lag the real API, and silently dropping them
496
1039
  // would break working callers. The key dictionary maps them when it knows
497
1040
  // the key, otherwise `unknownKeyToWire` decides the wire name.
498
- for (const [key, value] of Object.entries(inputObj)) {
499
- if (consumed.has(key) || value === undefined) continue;
500
- const wire =
501
- rootDict?.[key] ?? (unknownKeyToWire ? unknownKeyToWire(key) : key);
1041
+ for (const key in inputObj) {
1042
+ if (known.has(key) || !Object.hasOwn(inputObj, key)) continue;
1043
+ const value = inputObj[key];
1044
+ if (value === undefined) continue;
1045
+ const wire = rootDict?.[key] ?? (unknownKeyToWire ? unknownKeyToWire(key) : key);
502
1046
  body[typeof wire === "string" ? wire : wire[0]] = rootDict
503
1047
  ? mapKeysByDictionary(rootDict, value, "encode")
504
1048
  : value;
1049
+ bodyKeys++;
505
1050
  hasBodyMembers = true;
506
1051
  }
507
1052
 
508
- const qs = query.toString();
509
- const url = `${baseUrl}${uri}${qs ? `?${qs}` : ""}`;
510
- if (process.env.DISTILLED_DEBUG_HTTP) {
511
- console.error(
512
- `[distilled] ${http.method} ${url}` +
513
- (Object.keys(body).length
514
- ? ` body=${JSON.stringify(body).slice(0, 400)}`
515
- : ""),
516
- );
517
- }
1053
+ const qs = query === undefined ? "" : query.toString();
1054
+ const url = qs ? `${baseUrl}${uri}?${qs}` : `${baseUrl}${uri}`;
518
1055
 
519
- let request = HttpClientRequest.make(http.method)(url).pipe(
520
- HttpClientRequest.setHeaders(headers),
521
- );
1056
+ const request = makeRequest(http.method, url, headers);
1057
+ const bodied = !BODYLESS.has(http.method);
522
1058
  if (http.contentType === "multipart") {
523
1059
  // Multipart upload: each body member is a form part (objects
524
- // JSON-encoded under their wire name), each file appends under its own
525
- // filename. A whole-body member (T.HttpBody) that is a record of files
526
- // becomes one part per entry (e.g. asset upload: { <hash>: File }).
527
- // File/Blob → binary part (filename = File.name), array of files → each
528
- // appended, object → JSON string, primitive → string.
1060
+ // JSON-encoded under their wire name). Files and byte buffers become
1061
+ // binary parts under the member's wire name, with a File's own filename
1062
+ // (the wire name for a nameless Blob or a byte buffer); a list of them is
1063
+ // one such part per element, the repeated-field form multipart APIs read
1064
+ // (`-F documents=@a.pdf -F documents=@b.txt`). `FormDataFile()` members
1065
+ // append under each file's own filename instead (below). A whole-body
1066
+ // member (T.HttpBody) that is a record of files becomes one part per
1067
+ // entry (e.g. asset upload: { <hash>: File }).
529
1068
  const form = new FormData();
530
1069
  const parts =
531
1070
  rawBody !== undefined && typeof rawBody === "object"
532
1071
  ? (rawBody as Record<string, unknown>)
533
1072
  : body;
534
- const isFileOrBlob = (v: unknown): v is Blob =>
535
- v instanceof Blob || v instanceof File;
1073
+ const isBinary = (v: unknown): v is Blob | Uint8Array | ArrayBuffer =>
1074
+ v instanceof Blob || v instanceof Uint8Array || v instanceof ArrayBuffer;
1075
+ const appendBinary = (key: string, value: Blob | Uint8Array | ArrayBuffer) => {
1076
+ if (value instanceof Blob) {
1077
+ form.append(key, value, value instanceof File ? value.name : key);
1078
+ } else {
1079
+ // Copy a Uint8Array view's own bytes (a subarray shares a larger buffer).
1080
+ const bytes = value instanceof Uint8Array ? new Uint8Array(value).buffer : value;
1081
+ form.append(key, new Blob([bytes]), key);
1082
+ }
1083
+ };
536
1084
  for (const [key, value] of Object.entries(parts)) {
537
1085
  if (value === undefined || value === null) continue;
538
- if (isFileOrBlob(value)) {
539
- form.append(key, value, value instanceof File ? value.name : key);
540
- } else if (
541
- Array.isArray(value) &&
542
- value.length > 0 &&
543
- isFileOrBlob(value[0])
544
- ) {
545
- for (const file of value as Blob[]) {
546
- if (isFileOrBlob(file)) {
547
- form.append(
548
- file instanceof File ? file.name : key,
549
- file,
550
- file instanceof File ? file.name : undefined,
551
- );
552
- }
553
- }
1086
+ if (isBinary(value)) {
1087
+ appendBinary(key, value);
1088
+ } else if (Array.isArray(value) && value.length > 0 && value.every(isBinary)) {
1089
+ for (const element of value) appendBinary(key, element);
554
1090
  } else if (typeof value === "object") {
555
1091
  form.append(key, JSON.stringify(value));
556
1092
  } else {
557
1093
  form.append(key, String(value));
558
1094
  }
559
1095
  }
560
- for (const f of files) {
1096
+ for (const f of files ?? []) {
561
1097
  const filename = (f as File).name ?? "file";
562
1098
  form.append(filename, f, filename);
563
1099
  }
564
- request = request.pipe(HttpClientRequest.bodyFormData(form));
565
- } else if (
566
- http.contentType === "form-urlencoded" &&
567
- !BODYLESS.has(http.method)
568
- ) {
1100
+ return HttpClientRequest.setBody(request, HttpBody.formData(form));
1101
+ }
1102
+ if (http.contentType === "form-urlencoded" && bodied) {
569
1103
  // application/x-www-form-urlencoded with Stripe-style deepObject bracket
570
- // notation: { shipping: { address: { city } } } → shipping[address][city],
571
- // arrays indexed ({ expand: ["a"] } → expand[0]=a).
1104
+ // notation: { shipping: { address: { city } } } -> shipping[address][city],
1105
+ // arrays indexed ({ expand: ["a"] } -> expand[0]=a).
572
1106
  const source =
573
1107
  rawBody !== undefined && typeof rawBody === "object"
574
1108
  ? (rawBody as Record<string, unknown>)
575
1109
  : body;
576
1110
  const params = new URLSearchParams();
577
1111
  for (const [k, v] of flattenToFormPairs(source)) params.append(k, v);
578
- request = request.pipe(
579
- HttpClientRequest.setBody(
580
- HttpBody.text(params.toString(), "application/x-www-form-urlencoded"),
581
- ),
1112
+ return HttpClientRequest.setBody(
1113
+ request,
1114
+ HttpBody.text(params.toString(), "application/x-www-form-urlencoded"),
582
1115
  );
583
- } else if (rawBody !== undefined && !BODYLESS.has(http.method)) {
584
- // Whole-body member (raw arrays/scalars) — sent as the body itself.
1116
+ }
1117
+ if (rawBody !== undefined && bodied) {
1118
+ // Whole-body member (raw arrays/scalars) -- sent as the body itself.
585
1119
  // Binary payloads (Blob / ArrayBuffer / Uint8Array) send verbatim
586
- // (raw object uploads — the Content-Type header member, when modeled,
587
- // rides alongside). With a bodyMediaType, the member is a
588
- // preserialized payload (string / bytes) sent verbatim under that
589
- // media type (e.g. application/x-ndjson for Vectorize
590
- // insert/upsert); otherwise it's JSON.
591
- if (rawBody instanceof Blob || rawBody instanceof ArrayBuffer) {
592
- // Honor the declared media type (e.g. application/x-ndjson for
593
- // Vectorize insert/upsert) — without it the server may fall back to
594
- // JSON parsing. When no bodyMediaType is modeled the header is left
595
- // untouched (a modeled Content-Type header member rides alongside).
596
- request = request.pipe(
597
- HttpClientRequest.setBody(
598
- HttpBody.raw(rawBody, { contentType: http.bodyMediaType }),
599
- ),
600
- );
601
- } else if (rawBody instanceof Uint8Array) {
602
- request = request.pipe(
603
- HttpClientRequest.setBody(
604
- HttpBody.uint8Array(rawBody, http.bodyMediaType),
1120
+ // (raw object uploads). With a bodyMediaType, the member is a
1121
+ // preserialized payload (string / bytes) sent verbatim; otherwise it's
1122
+ // JSON, under the Content-Type member when set (e.g. Kubernetes'
1123
+ // application/merge-patch+json).
1124
+ //
1125
+ // `setBody` overwrites the Content-Type header with the body's media
1126
+ // type (and removes it when that is undefined), so the body carries the
1127
+ // modeled Content-Type member when the caller set one, else the declared
1128
+ // bodyMediaType (e.g. application/x-ndjson for Vectorize insert/upsert).
1129
+ const mediaType = memberContentType ?? http.bodyMediaType;
1130
+ if (isEffectStream(rawBody)) {
1131
+ // Sent as it is pulled, chunked unless a modeled `Content-Length`
1132
+ // member gave its size. The REST protocol never retries it.
1133
+ const length = headers["content-length"];
1134
+ return HttpClientRequest.setBody(
1135
+ request,
1136
+ HttpBody.stream(
1137
+ rawBody as Stream.Stream<Uint8Array, unknown>,
1138
+ mediaType,
1139
+ length === undefined ? undefined : Number(length),
605
1140
  ),
606
1141
  );
607
- } else if (http.bodyMediaType) {
608
- request = request.pipe(
609
- HttpClientRequest.setBody(
610
- typeof rawBody === "string"
611
- ? HttpBody.text(rawBody, http.bodyMediaType)
612
- : HttpBody.uint8Array(rawBody as Uint8Array, http.bodyMediaType),
613
- ),
1142
+ }
1143
+ if (rawBody instanceof Blob || rawBody instanceof ArrayBuffer) {
1144
+ // With no media type at all, fetch falls back to the Blob's own type.
1145
+ return HttpClientRequest.setBody(request, HttpBody.raw(rawBody, { contentType: mediaType }));
1146
+ }
1147
+ if (rawBody instanceof Uint8Array) {
1148
+ return HttpClientRequest.setBody(request, HttpBody.uint8Array(rawBody, mediaType));
1149
+ }
1150
+ if (http.bodyMediaType || rawBinary) {
1151
+ // A binary member's text with no media type is still bytes.
1152
+ const contentType = mediaType ?? "application/octet-stream";
1153
+ return HttpClientRequest.setBody(
1154
+ request,
1155
+ typeof rawBody === "string"
1156
+ ? HttpBody.text(rawBody, contentType)
1157
+ : HttpBody.uint8Array(rawBody as Uint8Array, contentType),
614
1158
  );
615
- } else {
616
- request = request.pipe(HttpClientRequest.bodyJsonUnsafe(rawBody));
617
1159
  }
618
- } else if (
619
- !BODYLESS.has(http.method) &&
620
- (Object.keys(body).length > 0 ||
621
- (hasBodyMembers && http.method !== "DELETE"))
1160
+ return withJsonBody(request, rawBody, memberContentType);
1161
+ }
1162
+ if (
1163
+ // A GET/HEAD sends a body only when body members actually carry values.
1164
+ // Some APIs really do document GET-with-body: MongoDB Atlas's
1165
+ // `.../lineItems:search` declares a `requestBody` on `get`, and AWS EFS's
1166
+ // DescribeAccountPreferences takes `{ MaxResults, NextToken }` on a GET.
1167
+ // Suppressing it outright dropped those members silently -- the request
1168
+ // succeeded, unfiltered, with nothing on the wire to show why.
1169
+ //
1170
+ // The `{}`-when-empty rule below stays limited to methods that expect a
1171
+ // body, so a bodyless method with nothing set still sends nothing.
1172
+ bodyKeys > 0 ||
1173
+ ((hasBodyMembers || emptyJsonBody === true) && bodied && http.method !== "DELETE")
622
1174
  ) {
623
- // Send `{}` rather than no body when the schema declares body members —
624
- // some endpoints reject a missing JSON body outright.
625
- request = request.pipe(HttpClientRequest.bodyJsonUnsafe(body));
1175
+ // Send `{}` rather than no body when the schema declares body members --
1176
+ // some endpoints reject a missing JSON body outright. A Content-Type
1177
+ // member names the JSON media type, as for a whole body above (a
1178
+ // Kubernetes merge patch is `application/merge-patch+json`).
1179
+ return withJsonBody(request, body, memberContentType);
626
1180
  }
627
1181
  return request;
628
1182
  };
@@ -630,59 +1184,171 @@ export const buildRequest = ({
630
1184
 
631
1185
  //#region Typed error matching
632
1186
 
633
- /**
634
- * Whether one matcher matches one wire error: every present field must
635
- * match; a matcher (or a message object) with no constraints matches
636
- * nothing.
637
- */
1187
+ /** Parsed response metadata supplied by a protocol after it detects a failure. */
1188
+ export interface ErrorResponse {
1189
+ readonly body?: unknown;
1190
+ readonly headers?: Readonly<Record<string, string | undefined>>;
1191
+ /**
1192
+ * JSON pointer to the object that holds the error's fields when the
1193
+ * provider nests them, e.g. `"/error"` for `{ error: { status, details } }`.
1194
+ */
1195
+ readonly fieldsAt?: string;
1196
+ }
1197
+
1198
+ const matchesText = (matcher: ErrorTextMatcher, value: unknown): boolean => {
1199
+ if (typeof value !== "string") return false;
1200
+ if (typeof matcher === "string") return matcher === value;
1201
+ const { includes, matches } = matcher;
1202
+ return (
1203
+ (includes !== undefined || matches !== undefined) &&
1204
+ (includes === undefined || value.includes(includes)) &&
1205
+ (matches === undefined || new RegExp(matches).test(value))
1206
+ );
1207
+ };
1208
+
1209
+ // Own properties only: inherited properties are not JSON response members.
1210
+ const atPointer = (body: unknown, pointer: string): unknown => {
1211
+ if (pointer === "") return body;
1212
+ if (!pointer.startsWith("/") || /~(?![01])/u.test(pointer)) return undefined;
1213
+ let value = body;
1214
+ for (const segment of pointer.slice(1).split("/")) {
1215
+ const key = segment.replace(/~1/g, "/").replace(/~0/g, "~");
1216
+ if (
1217
+ value === null ||
1218
+ typeof value !== "object" ||
1219
+ !Object.hasOwn(value, key) ||
1220
+ (Array.isArray(value) && !/^(0|[1-9][0-9]*)$/.test(key))
1221
+ )
1222
+ return undefined;
1223
+ value = (value as Record<string, unknown>)[key];
1224
+ }
1225
+ return value;
1226
+ };
1227
+
1228
+ const matcherSpecificity = (m: ErrorMatcher): number =>
1229
+ (m.code !== undefined ? 1 : 0) +
1230
+ (m.status !== undefined ? 1 : 0) +
1231
+ (m.message !== undefined ? 1 : 0) +
1232
+ (m.body === undefined ? 0 : Object.keys(m.body).length) +
1233
+ (m.headers === undefined ? 0 : Object.keys(m.headers).length);
1234
+
1235
+ /** Every supplied constraint must match; an unconstrained matcher matches nothing. */
638
1236
  export const matchesExpression = (
639
1237
  m: ErrorMatcher,
640
1238
  code: number | undefined,
641
1239
  status: number,
642
1240
  message: string,
1241
+ response: ErrorResponse = {},
643
1242
  ): boolean => {
644
- if (m.code === undefined && m.status === undefined && m.message === undefined)
1243
+ if (
1244
+ m.code === undefined &&
1245
+ m.status === undefined &&
1246
+ m.message === undefined &&
1247
+ matcherSpecificity(m) === 0
1248
+ )
645
1249
  return false;
646
1250
  if (m.code !== undefined && m.code !== code) return false;
647
1251
  if (m.status !== undefined && m.status !== status) return false;
648
- if (m.message !== undefined) {
649
- if (typeof m.message === "string") {
650
- if (m.message !== message) return false;
651
- } else {
652
- const { includes, matches } = m.message;
653
- if (includes === undefined && matches === undefined) return false;
654
- if (includes !== undefined && !message.includes(includes)) return false;
655
- if (matches !== undefined && !new RegExp(matches).test(message))
656
- return false;
1252
+ if (m.message !== undefined && !matchesText(m.message, message)) return false;
1253
+ if (m.body !== undefined) {
1254
+ for (const [pointer, expected] of Object.entries(m.body)) {
1255
+ const actual = atPointer(response.body, pointer);
1256
+ if (typeof expected === "string" || (expected !== null && typeof expected === "object")) {
1257
+ if (!matchesText(expected, actual)) return false;
1258
+ } else if (actual !== expected) return false;
1259
+ }
1260
+ }
1261
+ if (m.headers !== undefined) {
1262
+ for (const [name, expected] of Object.entries(m.headers)) {
1263
+ if (response.headers === undefined) return false;
1264
+ const actual = Object.entries(response.headers).find(
1265
+ ([key]) => key.toLowerCase() === name.toLowerCase(),
1266
+ )?.[1];
1267
+ if (!matchesText(expected, actual)) return false;
657
1268
  }
658
1269
  }
659
1270
  return true;
660
1271
  };
661
1272
 
662
- const matcherSpecificity = (m: ErrorMatcher): number =>
663
- (m.code !== undefined ? 1 : 0) +
664
- (m.status !== undefined ? 1 : 0) +
665
- (m.message !== undefined ? 1 : 0);
1273
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
1274
+ typeof value === "object" && value !== null && !Array.isArray(value);
1275
+
1276
+ /**
1277
+ * The body values whose keys the error class declares as fields: from the
1278
+ * object at `fieldsAt` first, then from the top level.
1279
+ */
1280
+ const declaredBodyFields = (
1281
+ fields: Record<string, unknown> | undefined,
1282
+ body: unknown,
1283
+ fieldsAt: string | undefined,
1284
+ ): Record<string, unknown> => {
1285
+ if (fields === undefined) return {};
1286
+ const nested = fieldsAt === undefined ? undefined : atPointer(body, fieldsAt);
1287
+ const out: Record<string, unknown> = {};
1288
+ for (const key of Object.keys(fields)) {
1289
+ if (isRecord(nested) && Object.hasOwn(nested, key)) out[key] = nested[key];
1290
+ else if (isRecord(body) && Object.hasOwn(body, key)) out[key] = body[key];
1291
+ }
1292
+ return out;
1293
+ };
1294
+
1295
+ /**
1296
+ * The fields every error built from a response gets, when its class declares
1297
+ * them: the body (keys mapped to TS names when the class types it), the
1298
+ * headers, and the server's retry hint from `Retry-After` or `RateLimit`.
1299
+ */
1300
+ export const responseErrorFields = (
1301
+ fields: Record<string, unknown> | undefined,
1302
+ response: ErrorResponse,
1303
+ ): Record<string, unknown> => {
1304
+ // A typed body (the provider's documented error schema) gets the TS names
1305
+ // a success body gets; an untyped one stays as the wire sent it.
1306
+ const bodyAst = (fields?.body as { readonly ast?: AST.AST } | undefined)?.ast;
1307
+ const out: Record<string, unknown> = {
1308
+ body:
1309
+ bodyAst !== undefined &&
1310
+ typeof response.body === "object" &&
1311
+ response.body !== null &&
1312
+ !mapsVerbatim(bodyAst, "decode")
1313
+ ? mapKeys(bodyAst, response.body, "decode")
1314
+ : response.body,
1315
+ headers: response.headers,
1316
+ };
1317
+ if (fields !== undefined && Object.hasOwn(fields, "retryAfter") && response.headers) {
1318
+ out.retryAfter = parseServerRetryHint(response.headers);
1319
+ }
1320
+ return out;
1321
+ };
666
1322
 
667
1323
  /**
668
1324
  * Pick the operation's typed error class for a failed response: among all
669
1325
  * declared classes whose matchers (see `applyErrorMatchers`) match the wire
670
1326
  * failure, the most specific matcher wins (ties break by declaration order).
1327
+ * Empty error lists use an HTTP-status message so body/header-only failures can
1328
+ * still match. The constructor receives the raw body and headers as well as
1329
+ * code/message; error schemas can declare these fields to expose them to callers.
1330
+ * Any other field the class declares is read from the JSON body's key of the
1331
+ * same name -- at `response.fieldsAt` first, then at the top level -- so a
1332
+ * patch that adds `requestId` to an error gets the body's `requestId`. A
1333
+ * declared `retryAfter` gets the `Retry-After` / `RateLimit` header hint. The
1334
+ * matched `code` and `message` always win over the body's.
671
1335
  */
672
- export const matchTypedError = (
673
- errorClasses: ReadonlyArray<unknown>,
1336
+ export function matchTypedError<E>(
1337
+ errorClasses: ReadonlyArray<new (...args: any[]) => E>,
674
1338
  status: number,
675
1339
  errors: ReadonlyArray<{ code?: number; message: string }>,
676
- ): unknown | undefined => {
1340
+ response: ErrorResponse = {},
1341
+ ): E | undefined {
677
1342
  let best:
678
- | { cls: unknown; specificity: number; code?: number; message: string }
1343
+ | { cls: new (...args: any[]) => E; specificity: number; code?: number; message: string }
679
1344
  | undefined;
1345
+ const wireErrors = errors.length > 0 ? errors : [{ message: `HTTP ${status}` }];
680
1346
  for (const cls of errorClasses) {
681
1347
  const matchers = getErrorMatchers(cls);
682
1348
  if (!matchers) continue;
683
1349
  for (const m of matchers) {
684
- for (const e of errors) {
685
- if (!matchesExpression(m, e.code, status, e.message)) continue;
1350
+ for (const e of wireErrors) {
1351
+ if (!matchesExpression(m, e.code, status, e.message, response)) continue;
686
1352
  const specificity = matcherSpecificity(m);
687
1353
  if (!best || specificity > best.specificity) {
688
1354
  best = { cls, specificity, code: e.code, message: e.message };
@@ -691,9 +1357,17 @@ export const matchTypedError = (
691
1357
  }
692
1358
  }
693
1359
  if (!best) return undefined;
694
- return new (best.cls as new (args: any) => unknown)({
695
- code: best.code ?? 0,
696
- message: best.message,
697
- });
698
- };
1360
+ const fields = (best.cls as { fields?: Record<string, unknown> }).fields;
1361
+ const saved = suppressStack();
1362
+ try {
1363
+ return new best.cls({
1364
+ ...declaredBodyFields(fields, response.body, response.fieldsAt),
1365
+ code: best.code ?? 0,
1366
+ message: best.message,
1367
+ ...responseErrorFields(fields, response),
1368
+ });
1369
+ } finally {
1370
+ restoreStack(saved);
1371
+ }
1372
+ }
699
1373
  //#endregion