@distilled.cloud/core 1.0.0-rc.15 → 1.0.0-rc.17

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 (318) hide show
  1. package/lib/_bundle/aws.js +2 -0
  2. package/lib/_bundle/aws.js.map +1 -0
  3. package/lib/_bundle/base.js +5 -0
  4. package/lib/_bundle/base.js.map +1 -0
  5. package/lib/_bundle/graphql.js +3 -0
  6. package/lib/_bundle/graphql.js.map +1 -0
  7. package/lib/_bundle/rest.js +2 -0
  8. package/lib/_bundle/rest.js.map +1 -0
  9. package/lib/_bundle/xml.js +4 -0
  10. package/lib/_bundle/xml.js.map +1 -0
  11. package/lib/api.d.ts +118 -13
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -188
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/category.js +1 -278
  16. package/lib/chunks.d.ts +3 -0
  17. package/lib/chunks.d.ts.map +1 -0
  18. package/lib/chunks.js +1 -0
  19. package/lib/codegen/boolean-string-enums.js +36 -36
  20. package/lib/codegen/chunk.d.ts +7 -0
  21. package/lib/codegen/chunk.d.ts.map +1 -0
  22. package/lib/codegen/chunk.js +139 -0
  23. package/lib/codegen/chunk.js.map +1 -0
  24. package/lib/codegen/cli.d.ts.map +1 -1
  25. package/lib/codegen/cli.js +28 -14
  26. package/lib/codegen/cli.js.map +1 -1
  27. package/lib/codegen/datafy.d.ts +14 -0
  28. package/lib/codegen/datafy.d.ts.map +1 -0
  29. package/lib/codegen/datafy.js +853 -0
  30. package/lib/codegen/datafy.js.map +1 -0
  31. package/lib/codegen/dedupe.d.ts +5 -0
  32. package/lib/codegen/dedupe.d.ts.map +1 -0
  33. package/lib/codegen/dedupe.js +153 -0
  34. package/lib/codegen/dedupe.js.map +1 -0
  35. package/lib/codegen/emit.js +56 -56
  36. package/lib/codegen/format.js +18 -18
  37. package/lib/codegen/generated-at.js +29 -29
  38. package/lib/codegen/generator.d.ts.map +1 -1
  39. package/lib/codegen/generator.js +92 -84
  40. package/lib/codegen/generator.js.map +1 -1
  41. package/lib/codegen/graph.js +36 -36
  42. package/lib/codegen/graphql-client.d.ts +2 -0
  43. package/lib/codegen/graphql-client.d.ts.map +1 -1
  44. package/lib/codegen/graphql-client.js +55 -26
  45. package/lib/codegen/graphql-client.js.map +1 -1
  46. package/lib/codegen/graphql.js +113 -113
  47. package/lib/codegen/latin1.d.ts +3 -0
  48. package/lib/codegen/latin1.d.ts.map +1 -0
  49. package/lib/codegen/latin1.js +126 -0
  50. package/lib/codegen/latin1.js.map +1 -0
  51. package/lib/codegen/members.d.ts +7 -0
  52. package/lib/codegen/members.d.ts.map +1 -1
  53. package/lib/codegen/members.js +26 -19
  54. package/lib/codegen/members.js.map +1 -1
  55. package/lib/codegen/model-diff.js +6 -6
  56. package/lib/codegen/naming.js +19 -19
  57. package/lib/codegen/openapi-cli.js +15 -15
  58. package/lib/codegen/openapi.d.ts +17 -0
  59. package/lib/codegen/openapi.d.ts.map +1 -1
  60. package/lib/codegen/openapi.js +323 -169
  61. package/lib/codegen/openapi.js.map +1 -1
  62. package/lib/codegen/operations.js +14 -14
  63. package/lib/codegen/pagination.js +11 -11
  64. package/lib/codegen/patch-audit.js +57 -57
  65. package/lib/codegen/patches.js +79 -79
  66. package/lib/codegen/prelude.js +19 -19
  67. package/lib/codegen/privatize.d.ts +21 -0
  68. package/lib/codegen/privatize.d.ts.map +1 -0
  69. package/lib/codegen/privatize.js +176 -0
  70. package/lib/codegen/privatize.js.map +1 -0
  71. package/lib/codegen/proto.js +25 -25
  72. package/lib/codegen/pure.d.ts +6 -0
  73. package/lib/codegen/pure.d.ts.map +1 -0
  74. package/lib/codegen/pure.js +91 -0
  75. package/lib/codegen/pure.js.map +1 -0
  76. package/lib/codegen/rewrite-operation-ids.js +108 -108
  77. package/lib/codegen/spec-path.js +57 -57
  78. package/lib/codegen/table.d.ts +5 -0
  79. package/lib/codegen/table.d.ts.map +1 -0
  80. package/lib/codegen/table.js +249 -0
  81. package/lib/codegen/table.js.map +1 -0
  82. package/lib/config.d.ts +27 -0
  83. package/lib/config.d.ts.map +1 -0
  84. package/lib/config.js +1 -0
  85. package/lib/crypto.d.ts +76 -0
  86. package/lib/crypto.d.ts.map +1 -0
  87. package/lib/crypto.js +1 -0
  88. package/lib/debug.d.ts +2 -0
  89. package/lib/debug.d.ts.map +1 -0
  90. package/lib/debug.js +1 -0
  91. package/lib/error-category.d.ts +1 -1
  92. package/lib/error-category.d.ts.map +1 -1
  93. package/lib/error-category.js +1 -46
  94. package/lib/errors.d.ts +62 -62
  95. package/lib/errors.d.ts.map +1 -1
  96. package/lib/errors.js +1 -195
  97. package/lib/graphql.d.ts +31 -20
  98. package/lib/graphql.d.ts.map +1 -1
  99. package/lib/graphql.js +1 -1027
  100. package/lib/graphql.types.js +1 -5
  101. package/lib/index.d.ts +3 -2
  102. package/lib/index.d.ts.map +1 -1
  103. package/lib/index.js +1 -15
  104. package/lib/json-patch.d.ts +2 -2
  105. package/lib/json-patch.js +1 -226
  106. package/lib/json-patch.js.map +1 -1
  107. package/lib/pagination.d.ts +9 -25
  108. package/lib/pagination.d.ts.map +1 -1
  109. package/lib/pagination.js +1 -266
  110. package/lib/plain-values.d.ts +10 -0
  111. package/lib/plain-values.d.ts.map +1 -0
  112. package/lib/plain-values.js +2 -0
  113. package/lib/plain-values.js.map +1 -0
  114. package/lib/protocol-http.d.ts +50 -14
  115. package/lib/protocol-http.d.ts.map +1 -1
  116. package/lib/protocol-http.js +1 -639
  117. package/lib/protocol-rest.d.ts +38 -25
  118. package/lib/protocol-rest.d.ts.map +1 -1
  119. package/lib/protocol-rest.js +1 -267
  120. package/lib/query.js +1 -27
  121. package/lib/response-validation-strict.d.ts +48 -0
  122. package/lib/response-validation-strict.d.ts.map +1 -0
  123. package/lib/response-validation-strict.js +1 -0
  124. package/lib/response-validation.d.ts +43 -25
  125. package/lib/response-validation.d.ts.map +1 -1
  126. package/lib/response-validation.js +1 -76
  127. package/lib/retry-after.d.ts +3 -3
  128. package/lib/retry-after.js +1 -112
  129. package/lib/retry.d.ts +48 -29
  130. package/lib/retry.d.ts.map +1 -1
  131. package/lib/retry.js +1 -209
  132. package/lib/schema-lite-impl.d.ts +158 -0
  133. package/lib/schema-lite-impl.d.ts.map +1 -0
  134. package/lib/schema-lite-impl.js +1 -0
  135. package/lib/schema-lite-typed.d.ts +41 -0
  136. package/lib/schema-lite-typed.d.ts.map +1 -0
  137. package/lib/schema-lite-typed.js +2 -0
  138. package/lib/schema-lite-typed.js.map +1 -0
  139. package/lib/schema-lite.d.ts +40 -0
  140. package/lib/schema-lite.d.ts.map +1 -0
  141. package/lib/schema-lite.js +1 -0
  142. package/lib/schema.d.ts +20 -6
  143. package/lib/schema.d.ts.map +1 -1
  144. package/lib/schema.js +1 -48
  145. package/lib/testing.d.ts +3 -2
  146. package/lib/testing.d.ts.map +1 -1
  147. package/lib/testing.js +1 -40
  148. package/lib/testing.js.map +1 -1
  149. package/lib/trait.d.ts +13 -13
  150. package/lib/trait.d.ts.map +1 -1
  151. package/lib/trait.js +1 -131
  152. package/lib/xml.d.ts +1 -1
  153. package/lib/xml.d.ts.map +1 -1
  154. package/lib/xml.js +1 -311
  155. package/package.json +9 -7
  156. package/src/api.ts +1080 -180
  157. package/src/category.ts +33 -33
  158. package/src/chunks.ts +30 -0
  159. package/src/codegen/chunk.ts +147 -0
  160. package/src/codegen/cli.ts +27 -1
  161. package/src/codegen/datafy.ts +874 -0
  162. package/src/codegen/dedupe.ts +173 -0
  163. package/src/codegen/generator.ts +10 -3
  164. package/src/codegen/graphql-client.ts +49 -15
  165. package/src/codegen/latin1.ts +131 -0
  166. package/src/codegen/members.ts +8 -0
  167. package/src/codegen/openapi.ts +194 -3
  168. package/src/codegen/privatize.ts +200 -0
  169. package/src/codegen/pure.ts +94 -0
  170. package/src/codegen/table.ts +254 -0
  171. package/src/config.ts +216 -0
  172. package/src/crypto.ts +202 -0
  173. package/src/debug.ts +8 -0
  174. package/src/error-category.ts +2 -1
  175. package/src/errors.ts +65 -56
  176. package/src/graphql.ts +109 -62
  177. package/src/graphql.types.ts +9 -7
  178. package/src/index.ts +3 -2
  179. package/src/json-patch.ts +2 -2
  180. package/src/pagination.ts +37 -18
  181. package/src/plain-values.ts +41 -0
  182. package/src/protocol-http.ts +378 -145
  183. package/src/protocol-rest.ts +337 -169
  184. package/src/response-validation-strict.ts +327 -0
  185. package/src/response-validation.ts +101 -50
  186. package/src/retry-after.ts +3 -3
  187. package/src/retry.ts +94 -93
  188. package/src/schema-lite-impl.ts +550 -0
  189. package/src/schema-lite-typed.ts +44 -0
  190. package/src/schema-lite.ts +44 -0
  191. package/src/schema.ts +258 -14
  192. package/src/testing.ts +4 -2
  193. package/src/trait.ts +36 -28
  194. package/src/xml.ts +31 -17
  195. package/lib/api.js.map +0 -1
  196. package/lib/category.js.map +0 -1
  197. package/lib/codegen/boolean-string-enums.test.d.ts +0 -2
  198. package/lib/codegen/boolean-string-enums.test.d.ts.map +0 -1
  199. package/lib/codegen/boolean-string-enums.test.js +0 -275
  200. package/lib/codegen/boolean-string-enums.test.js.map +0 -1
  201. package/lib/codegen/defer-naming.test.d.ts +0 -2
  202. package/lib/codegen/defer-naming.test.d.ts.map +0 -1
  203. package/lib/codegen/defer-naming.test.js +0 -105
  204. package/lib/codegen/defer-naming.test.js.map +0 -1
  205. package/lib/codegen/generated-at.test.d.ts +0 -2
  206. package/lib/codegen/generated-at.test.d.ts.map +0 -1
  207. package/lib/codegen/generated-at.test.js +0 -81
  208. package/lib/codegen/generated-at.test.js.map +0 -1
  209. package/lib/codegen/generator.test.d.ts +0 -2
  210. package/lib/codegen/generator.test.d.ts.map +0 -1
  211. package/lib/codegen/generator.test.js +0 -121
  212. package/lib/codegen/generator.test.js.map +0 -1
  213. package/lib/codegen/graphql-client.test.d.ts +0 -2
  214. package/lib/codegen/graphql-client.test.d.ts.map +0 -1
  215. package/lib/codegen/graphql-client.test.js +0 -171
  216. package/lib/codegen/graphql-client.test.js.map +0 -1
  217. package/lib/codegen/openapi-binary.test.d.ts +0 -2
  218. package/lib/codegen/openapi-binary.test.d.ts.map +0 -1
  219. package/lib/codegen/openapi-binary.test.js +0 -67
  220. package/lib/codegen/openapi-binary.test.js.map +0 -1
  221. package/lib/codegen/patch-audit.test.d.ts +0 -2
  222. package/lib/codegen/patch-audit.test.d.ts.map +0 -1
  223. package/lib/codegen/patch-audit.test.js +0 -141
  224. package/lib/codegen/patch-audit.test.js.map +0 -1
  225. package/lib/codegen/patches.test.d.ts +0 -2
  226. package/lib/codegen/patches.test.d.ts.map +0 -1
  227. package/lib/codegen/patches.test.js +0 -155
  228. package/lib/codegen/patches.test.js.map +0 -1
  229. package/lib/codegen/protocol-imports.test.d.ts +0 -2
  230. package/lib/codegen/protocol-imports.test.d.ts.map +0 -1
  231. package/lib/codegen/protocol-imports.test.js +0 -36
  232. package/lib/codegen/protocol-imports.test.js.map +0 -1
  233. package/lib/codegen/rewrite-operation-ids.test.d.ts +0 -2
  234. package/lib/codegen/rewrite-operation-ids.test.d.ts.map +0 -1
  235. package/lib/codegen/rewrite-operation-ids.test.js +0 -451
  236. package/lib/codegen/rewrite-operation-ids.test.js.map +0 -1
  237. package/lib/codegen/untagged-unions.test.d.ts +0 -2
  238. package/lib/codegen/untagged-unions.test.d.ts.map +0 -1
  239. package/lib/codegen/untagged-unions.test.js +0 -80
  240. package/lib/codegen/untagged-unions.test.js.map +0 -1
  241. package/lib/error-category.js.map +0 -1
  242. package/lib/errors.js.map +0 -1
  243. package/lib/fixtures/xml/upstream-validator.json +0 -397
  244. package/lib/graphql.js.map +0 -1
  245. package/lib/graphql.test.d.ts +0 -2
  246. package/lib/graphql.test.d.ts.map +0 -1
  247. package/lib/graphql.test.js +0 -151
  248. package/lib/graphql.test.js.map +0 -1
  249. package/lib/graphql.types.js.map +0 -1
  250. package/lib/index.js.map +0 -1
  251. package/lib/json-patch.test.d.ts +0 -2
  252. package/lib/json-patch.test.d.ts.map +0 -1
  253. package/lib/json-patch.test.js +0 -65
  254. package/lib/json-patch.test.js.map +0 -1
  255. package/lib/pagination.js.map +0 -1
  256. package/lib/pagination.test.d.ts +0 -2
  257. package/lib/pagination.test.d.ts.map +0 -1
  258. package/lib/pagination.test.js +0 -131
  259. package/lib/pagination.test.js.map +0 -1
  260. package/lib/protocol-http.js.map +0 -1
  261. package/lib/protocol-http.test.d.ts +0 -2
  262. package/lib/protocol-http.test.d.ts.map +0 -1
  263. package/lib/protocol-http.test.js +0 -228
  264. package/lib/protocol-http.test.js.map +0 -1
  265. package/lib/protocol-rest.js.map +0 -1
  266. package/lib/protocol-rest.test.d.ts +0 -2
  267. package/lib/protocol-rest.test.d.ts.map +0 -1
  268. package/lib/protocol-rest.test.js +0 -498
  269. package/lib/protocol-rest.test.js.map +0 -1
  270. package/lib/query.js.map +0 -1
  271. package/lib/response-validation.js.map +0 -1
  272. package/lib/response-validation.test.d.ts +0 -2
  273. package/lib/response-validation.test.d.ts.map +0 -1
  274. package/lib/response-validation.test.js +0 -72
  275. package/lib/response-validation.test.js.map +0 -1
  276. package/lib/retry-after.js.map +0 -1
  277. package/lib/retry-after.test.d.ts +0 -2
  278. package/lib/retry-after.test.d.ts.map +0 -1
  279. package/lib/retry-after.test.js +0 -204
  280. package/lib/retry-after.test.js.map +0 -1
  281. package/lib/retry.js.map +0 -1
  282. package/lib/retry.test.d.ts +0 -2
  283. package/lib/retry.test.d.ts.map +0 -1
  284. package/lib/retry.test.js +0 -407
  285. package/lib/retry.test.js.map +0 -1
  286. package/lib/schema.js.map +0 -1
  287. package/lib/sdks.test.d.ts +0 -2
  288. package/lib/sdks.test.d.ts.map +0 -1
  289. package/lib/sdks.test.js +0 -76
  290. package/lib/sdks.test.js.map +0 -1
  291. package/lib/trait.js.map +0 -1
  292. package/lib/xml.js.map +0 -1
  293. package/lib/xml.test.d.ts +0 -2
  294. package/lib/xml.test.d.ts.map +0 -1
  295. package/lib/xml.test.js +0 -210
  296. package/lib/xml.test.js.map +0 -1
  297. package/src/codegen/boolean-string-enums.test.ts +0 -299
  298. package/src/codegen/defer-naming.test.ts +0 -113
  299. package/src/codegen/generated-at.test.ts +0 -89
  300. package/src/codegen/generator.test.ts +0 -137
  301. package/src/codegen/graphql-client.test.ts +0 -189
  302. package/src/codegen/openapi-binary.test.ts +0 -91
  303. package/src/codegen/patch-audit.test.ts +0 -160
  304. package/src/codegen/patches.test.ts +0 -188
  305. package/src/codegen/protocol-imports.test.ts +0 -39
  306. package/src/codegen/rewrite-operation-ids.test.ts +0 -472
  307. package/src/codegen/untagged-unions.test.ts +0 -85
  308. package/src/fixtures/xml/upstream-validator.json +0 -397
  309. package/src/graphql.test.ts +0 -198
  310. package/src/json-patch.test.ts +0 -77
  311. package/src/pagination.test.ts +0 -169
  312. package/src/protocol-http.test.ts +0 -276
  313. package/src/protocol-rest.test.ts +0 -703
  314. package/src/response-validation.test.ts +0 -89
  315. package/src/retry-after.test.ts +0 -267
  316. package/src/retry.test.ts +0 -566
  317. package/src/sdks.test.ts +0 -87
  318. package/src/xml.test.ts +0 -251
@@ -1,639 +1 @@
1
- import * as HttpBody from "effect/http/HttpBody";
2
- import * as HttpClientRequest from "effect/http/HttpClientRequest";
3
- import { bodySymbol, deepQuerySymbol, formDataFileSymbol, getErrorMatchers, headerSymbol, httpBodySymbol, httpSymbol, keyDictionarySymbol, labelSymbol, labelEncodingSymbol, querySymbol, stringEncodedSymbol, unionCasesSymbol, } from "./trait.js";
4
- //#region AST helpers (survive S.optional / Suspend / transforms)
5
- export const getProps = (ast) => {
6
- if (ast._tag === "Objects")
7
- return ast.propertySignatures;
8
- if (ast._tag === "Suspend")
9
- return getProps(ast.thunk());
10
- if (ast.encoding && ast.encoding.length > 0)
11
- return getProps(ast.encoding[0].to);
12
- return [];
13
- };
14
- export const getAnn = (ast, symbol) => {
15
- const direct = ast.annotations?.[symbol];
16
- if (direct !== undefined)
17
- return direct;
18
- if (ast._tag === "Suspend")
19
- return getAnn(ast.thunk(), symbol);
20
- if (ast.encoding && ast.encoding.length > 0)
21
- return getAnn(ast.encoding[0].to, symbol);
22
- // S.optional → Union[self, Undefined]; descend into the single real member.
23
- if (ast._tag === "Union") {
24
- const real = ast.types.filter((t) => t._tag !== "Undefined" && !(t._tag === "Literal" && t.literal === null));
25
- if (real.length === 1)
26
- return getAnn(real[0], symbol);
27
- }
28
- return undefined;
29
- };
30
- export const getPropAnn = (prop, symbol) => getAnn(prop.type, symbol);
31
- export const hasPropAnn = (prop, symbol) => getPropAnn(prop, symbol) !== undefined;
32
- export const nameOf = (prop, symbol) => {
33
- const v = getPropAnn(prop, symbol);
34
- return typeof v === "string" ? v : String(prop.name);
35
- };
36
- /** Resolve wrappers to the real node: Suspend, encoding, optional/null unions. */
37
- export const resolveNode = (ast) => {
38
- if (ast._tag === "Suspend")
39
- return resolveNode(ast.thunk());
40
- if (ast.encoding && ast.encoding.length > 0)
41
- return resolveNode(ast.encoding[0].to);
42
- if (ast._tag === "Union") {
43
- const real = ast.types.filter((t) => t._tag !== "Undefined" &&
44
- t._tag !== "Null" &&
45
- !(t._tag === "Literal" && t.literal === null));
46
- if (real.length === 1)
47
- return resolveNode(real[0]);
48
- }
49
- return ast;
50
- };
51
- //#endregion
52
- //#region Recursive wire-name mapping
53
- /** Binary/opaque values that must never be treated as key-value objects. */
54
- export const isOpaqueValue = (v) => v instanceof Blob ||
55
- v instanceof File ||
56
- v instanceof ArrayBuffer ||
57
- v instanceof Uint8Array ||
58
- v instanceof Date;
59
- /**
60
- * Deep-rename keys via a plain dictionary (see `T.KeyDictionary`). An entry
61
- * may list several wire spellings; encode uses the first (canonical) one and
62
- * decode maps every listed spelling back to the TS name.
63
- */
64
- export const mapKeysByDictionary = (dict, value, direction) => {
65
- if (value === null || typeof value !== "object" || isOpaqueValue(value)) {
66
- return value;
67
- }
68
- if (Array.isArray(value)) {
69
- return value.map((v) => mapKeysByDictionary(dict, v, direction));
70
- }
71
- const rename = direction === "decode"
72
- ? Object.fromEntries(Object.entries(dict).flatMap(([ts, wire]) => typeof wire === "string" ? [[wire, ts]] : wire.map((w) => [w, ts])))
73
- : Object.fromEntries(Object.entries(dict).map(([ts, wire]) => [
74
- ts,
75
- typeof wire === "string" ? wire : wire[0],
76
- ]));
77
- const out = {};
78
- for (const [k, v] of Object.entries(value)) {
79
- if (v === undefined)
80
- continue;
81
- out[rename[k] ?? k] = mapKeysByDictionary(dict, v, direction);
82
- }
83
- return out;
84
- };
85
- /**
86
- * Recursively rename keys between TS names and wire names, per the schema.
87
- *
88
- * `fallback` is the nearest ancestor `T.KeyDictionary` — schema-known members
89
- * always map via their own annotations, but opaque values (Document members,
90
- * keys the schema doesn't know) deep-rename via the dictionary so nested
91
- * TS-cased content still reaches the wire in wire case. Content with no
92
- * dictionary in scope passes through verbatim.
93
- */
94
- /**
95
- * Value form for a `StringEncoded()` member: the string spelling of the
96
- * value, element-wise for lists. `null` stays `null` — an API that models a
97
- * flag as `"true" | "false"` still means "unset" by null, not `"null"`.
98
- */
99
- const stringEncode = (value) => value === null ? null : Array.isArray(value) ? value.map(stringEncode) : String(value);
100
- export const mapKeys = (ast, value, direction, fallback) => {
101
- if (value === null || value === undefined || typeof value !== "object" || isOpaqueValue(value)) {
102
- return value;
103
- }
104
- const dict = getAnn(ast, keyDictionarySymbol) ?? fallback;
105
- // Discriminated union whose cases the API returns merged (every case's
106
- // keys present, `null` for the inactive ones). Map wire names, then keep
107
- // only the active case's keys. The case is read off the union's
108
- // discriminator when it has one — cases that share a key set (every
109
- // resource kind of `resource_tagging`, every page-rule action) are
110
- // indistinguishable by keys alone. Without one, a case does NOT need every
111
- // key present — arms carry optional members the wire may omit — so the
112
- // active case is the one that best EXPLAINS the value: most present,
113
- // non-null keys covered, minus present keys the case cannot explain (ties
114
- // break by coverage, then declaration order).
115
- const unionCases = getAnn(ast, unionCasesSymbol);
116
- if (unionCases && direction === "decode" && !Array.isArray(value)) {
117
- const obj = (dict ? mapKeysByDictionary(dict, value, "decode") : value);
118
- const present = Object.keys(obj).filter((k) => obj[k] !== undefined && obj[k] !== null);
119
- const disc = unionCases.discriminator;
120
- const tag = disc ? obj[disc.key] : undefined;
121
- const tagged = typeof tag === "string" ? disc.values.indexOf(tag) : -1;
122
- let best;
123
- if (tagged >= 0) {
124
- best = { keys: unionCases.cases[tagged], score: 0, matched: 0 };
125
- }
126
- else {
127
- for (const keys of unionCases.cases) {
128
- const set = new Set(keys);
129
- let matched = 0;
130
- let excess = 0;
131
- for (const k of present) {
132
- if (set.has(k))
133
- matched++;
134
- else
135
- excess++;
136
- }
137
- const score = matched - excess;
138
- if (matched > 0 &&
139
- (!best || score > best.score || (score === best.score && matched > best.matched))) {
140
- best = { keys, score, matched };
141
- }
142
- }
143
- }
144
- if (best) {
145
- const out = {};
146
- for (const k of best.keys)
147
- out[k] = obj[k];
148
- return out;
149
- }
150
- return obj;
151
- }
152
- const node = resolveNode(ast);
153
- // Schema-level union member (a merged response struct whose arms disagree
154
- // on a member's type — see the codegen's response-union merge): pick the
155
- // arm that explains the value best and map with it. Object values score
156
- // arms by how many of their declared keys are present; array values take
157
- // the first array arm. Anything unmatched deep-renames via the dictionary
158
- // fallback, like other opaque content. (Single-real-member unions —
159
- // optional/null wrappers — were already collapsed by resolveNode; the
160
- // opaque `T.UnionCases` mechanism never produces a Union node and is
161
- // handled above.)
162
- if (node._tag === "Union") {
163
- const arms = node.types.map(resolveNode);
164
- if (Array.isArray(value)) {
165
- const arr = arms.find((t) => t._tag === "Arrays");
166
- if (arr)
167
- return mapKeys(arr, value, direction, dict);
168
- }
169
- else {
170
- let best;
171
- let bestScore = 0;
172
- for (const t of arms) {
173
- if (t._tag !== "Objects")
174
- continue;
175
- let score = 0;
176
- for (const p of t.propertySignatures) {
177
- const from = direction === "encode" ? String(p.name) : nameOf(p, bodySymbol);
178
- if (value[from] !== undefined)
179
- score++;
180
- }
181
- if (score > bestScore) {
182
- best = t;
183
- bestScore = score;
184
- }
185
- }
186
- if (best)
187
- return mapKeys(best, value, direction, dict);
188
- }
189
- return dict ? mapKeysByDictionary(dict, value, direction) : value;
190
- }
191
- if (node._tag === "Arrays") {
192
- if (!Array.isArray(value))
193
- return value;
194
- const elem = node.rest?.[0];
195
- return elem
196
- ? value.map((v) => mapKeys(elem, v, direction, dict))
197
- : dict
198
- ? mapKeysByDictionary(dict, value, direction)
199
- : value;
200
- }
201
- if (node._tag === "Objects" && !Array.isArray(value)) {
202
- const props = node.propertySignatures;
203
- const isigs = node.indexSignatures;
204
- if (props.length === 0 && !(isigs && isigs.length)) {
205
- // opaque object — dictionary fallback or verbatim
206
- return dict ? mapKeysByDictionary(dict, value, direction) : value;
207
- }
208
- const out = {};
209
- const consumed = new Set();
210
- for (const p of props) {
211
- const tsName = String(p.name);
212
- const wire = nameOf(p, bodySymbol);
213
- const from = direction === "encode" ? tsName : wire;
214
- const to = direction === "encode" ? wire : tsName;
215
- consumed.add(from);
216
- const v = value[from];
217
- if (v === undefined)
218
- continue;
219
- // A `StringEncoded()` member nested in a body struct (e.g. Azure's
220
- // `hardwareProfile.dynamicMemoryEnabled`) stringifies here — the
221
- // top-level pass in `buildRequest` only sees the outermost member.
222
- out[to] =
223
- direction === "encode" && hasPropAnn(p, stringEncodedSymbol)
224
- ? stringEncode(v)
225
- : mapKeys(p.type, v, direction, dict);
226
- }
227
- for (const [k, v] of Object.entries(value)) {
228
- if (consumed.has(k) || v === undefined)
229
- continue;
230
- const renamed = dict
231
- ? direction === "encode"
232
- ? (dict[k] ?? k)
233
- : (Object.entries(dict).find(([, w]) => w === k)?.[0] ?? k)
234
- : k;
235
- out[typeof renamed === "string" ? renamed : renamed[0]] =
236
- isigs && isigs.length
237
- ? mapKeys(isigs[0].type, v, direction, dict)
238
- : dict
239
- ? mapKeysByDictionary(dict, v, direction)
240
- : v;
241
- }
242
- return out;
243
- }
244
- // Scalar-typed schema node holding object content (spec drift) —
245
- // dictionary fallback or verbatim.
246
- return dict ? mapKeysByDictionary(dict, value, direction) : value;
247
- };
248
- //#endregion
249
- //#region Request building
250
- const BODYLESS = new Set(["GET", "HEAD"]);
251
- /**
252
- * Serialize one query member. Scalars go as `k=v`, arrays as repeated `k=v`
253
- * pairs, and nested plain objects recurse as DOTTED params — several list
254
- * endpoints model their filters as structs (e.g. Cloudflare DNS listRecords
255
- * takes `name: { exact, contains, ... }`) that must go over the wire as
256
- * `name.exact=value`. Without this they fell through to `String(value)` and
257
- * were sent as `name=[object Object]`, which servers happily treat as a
258
- * filter matching nothing — the call "succeeds" with zero results and the
259
- * bug is invisible to the caller.
260
- */
261
- const appendQuery = (query, name, value) => {
262
- if (Array.isArray(value)) {
263
- for (const v of value)
264
- appendQuery(query, name, v);
265
- }
266
- else if (value !== null && typeof value === "object" && !(value instanceof Date)) {
267
- for (const [k, v] of Object.entries(value)) {
268
- if (v !== undefined)
269
- appendQuery(query, `${name}.${k}`, v);
270
- }
271
- }
272
- else {
273
- query.append(name, String(value));
274
- }
275
- };
276
- /**
277
- * Build an HTTP request from an operation input and its schema, driven by
278
- * the trait annotations: `Http()` supplies method + URI template, `Label()`
279
- * members fill URI placeholders, `Header()`/`Query()` members bind to
280
- * headers/query params, `DeepQuery()` struct members expand into dotted
281
- * query params, `HttpBody()` sends the member as the whole body,
282
- * `FormDataFile()` members become multipart file parts, and everything else
283
- * is a JSON body field (wire-named via `Body()` / `KeyDictionary`).
284
- *
285
- * Throws when the input schema is missing the `Http()` trait — a codegen
286
- * bug, surfaced as a defect by the calling protocol's Effect context.
287
- */
288
- /**
289
- * Encode a greedy `{name+}` label: the value may span several path
290
- * segments (e.g. an Azure scope `/subscriptions/{id}/resourceGroups/{rg}`),
291
- * so each segment is encoded on its own and the `/` separators are kept.
292
- * Leading slashes are dropped because the URI template already supplies one.
293
- */
294
- export const encodeGreedyLabel = (value) => value.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
295
- /**
296
- * Flatten a nested object into Stripe-style bracket notation pairs for
297
- * form-urlencoded bodies: nested objects become `a[b][c]`, arrays index as
298
- * `a[0]`; null/undefined dropped, booleans as "true"/"false".
299
- */
300
- const flattenToFormPairs = (obj, prefix = "") => {
301
- const pairs = [];
302
- for (const [key, value] of Object.entries(obj)) {
303
- if (value === undefined || value === null)
304
- continue;
305
- const fullKey = prefix ? `${prefix}[${key}]` : key;
306
- if (Array.isArray(value)) {
307
- for (let i = 0; i < value.length; i++) {
308
- const item = value[i];
309
- if (item === undefined || item === null)
310
- continue;
311
- if (typeof item === "object" && !Array.isArray(item)) {
312
- pairs.push(...flattenToFormPairs(item, `${fullKey}[${i}]`));
313
- }
314
- else {
315
- pairs.push([`${fullKey}[${i}]`, String(item)]);
316
- }
317
- }
318
- }
319
- else if (typeof value === "object") {
320
- pairs.push(...flattenToFormPairs(value, fullKey));
321
- }
322
- else {
323
- pairs.push([fullKey, String(value)]);
324
- }
325
- }
326
- return pairs;
327
- };
328
- export const buildRequest = ({ input, inputAst, baseUrl, headers: baseHeaders, mapMemberHeader, unknownKeyToWire, }) => {
329
- const inputObj = (input ?? {});
330
- const http = getAnn(inputAst, httpSymbol);
331
- if (!http) {
332
- throw new Error("operation input is missing the Http() trait");
333
- }
334
- // Root key dictionary: fallback wire mapping for opaque/unknown content
335
- // the schema doesn't model.
336
- const rootDict = getAnn(inputAst, keyDictionarySymbol);
337
- const headers = { ...baseHeaders };
338
- const body = {};
339
- let rawBody; // whole-body member (T.HttpBody) — sent as-is
340
- const files = [];
341
- const query = new URLSearchParams();
342
- let uri = http.uri;
343
- const consumed = new Set();
344
- let hasBodyMembers = false;
345
- // Value of a modeled `Content-Type` header member, e.g. R2 putObject's
346
- // `contentType`. A raw body is sent under it (see below).
347
- let memberContentType;
348
- for (const prop of getProps(inputAst)) {
349
- const key = String(prop.name);
350
- consumed.add(key);
351
- const value = inputObj[key];
352
- const isBodyMember = !hasPropAnn(prop, labelSymbol) &&
353
- !hasPropAnn(prop, headerSymbol) &&
354
- !hasPropAnn(prop, querySymbol) &&
355
- !hasPropAnn(prop, deepQuerySymbol);
356
- if (isBodyMember)
357
- hasBodyMembers = true;
358
- if (value === undefined)
359
- continue;
360
- if (hasPropAnn(prop, labelSymbol)) {
361
- const token = nameOf(prop, labelSymbol);
362
- const preserve = getPropAnn(prop, labelEncodingSymbol);
363
- const encoded = encodeURIComponent(String(value));
364
- const label = typeof preserve === "string"
365
- ? encoded.replace(/%[0-9A-F]{2}/g, (escape) => {
366
- const character = String.fromCharCode(Number.parseInt(escape.slice(1), 16));
367
- return preserve.includes(character) ? character : escape;
368
- })
369
- : encoded;
370
- uri = uri.includes(`{${token}+}`)
371
- ? uri.replace(`{${token}+}`, () => encodeGreedyLabel(String(value)))
372
- : uri.replace(`{${token}}`, () => label);
373
- }
374
- else if (hasPropAnn(prop, headerSymbol)) {
375
- const hName = nameOf(prop, headerSymbol).toLowerCase();
376
- const hVal = String(value);
377
- headers[hName] = mapMemberHeader ? mapMemberHeader(hName, hVal) : hVal;
378
- if (hName === "content-type")
379
- memberContentType = headers[hName];
380
- }
381
- else if (hasPropAnn(prop, querySymbol)) {
382
- appendQuery(query, nameOf(prop, querySymbol), value);
383
- }
384
- else if (hasPropAnn(prop, deepQuerySymbol)) {
385
- // Deep-object query member (T.DeepQuery): a nested struct expands into
386
- // dotted query keys (`account.id=…`) under the member's wire name.
387
- // Wire-name the nested content via the schema first, skip null/
388
- // undefined entries; deeper nesting recurses through appendQuery.
389
- const base = nameOf(prop, deepQuerySymbol);
390
- const mapped = mapKeys(prop.type, value, "encode", rootDict);
391
- if (mapped !== null && typeof mapped === "object") {
392
- for (const [k, v] of Object.entries(mapped)) {
393
- if (v !== undefined && v !== null) {
394
- appendQuery(query, `${base}.${k}`, v);
395
- }
396
- }
397
- }
398
- }
399
- else if (hasPropAnn(prop, formDataFileSymbol)) {
400
- for (const f of Array.isArray(value) ? value : [value]) {
401
- files.push(f);
402
- }
403
- }
404
- else if (hasPropAnn(prop, httpBodySymbol)) {
405
- rawBody = mapKeys(prop.type, value, "encode", rootDict);
406
- }
407
- else {
408
- // T.StringEncoded(): the API takes this member's value only as its
409
- // string spelling (`true` → `"true"`), while the TS surface keeps the
410
- // natural type. Explicit here so a JSON body carries the string too,
411
- // rather than relying on the multipart encoder's own `String()`.
412
- body[nameOf(prop, bodySymbol)] = hasPropAnn(prop, stringEncodedSymbol)
413
- ? stringEncode(value)
414
- : mapKeys(prop.type, value, "encode", rootDict);
415
- }
416
- }
417
- // Input keys the schema doesn't know pass through as body fields — the
418
- // generated schemas can lag the real API, and silently dropping them
419
- // would break working callers. The key dictionary maps them when it knows
420
- // the key, otherwise `unknownKeyToWire` decides the wire name.
421
- for (const [key, value] of Object.entries(inputObj)) {
422
- if (consumed.has(key) || value === undefined)
423
- continue;
424
- const wire = rootDict?.[key] ?? (unknownKeyToWire ? unknownKeyToWire(key) : key);
425
- body[typeof wire === "string" ? wire : wire[0]] = rootDict
426
- ? mapKeysByDictionary(rootDict, value, "encode")
427
- : value;
428
- hasBodyMembers = true;
429
- }
430
- const qs = query.toString();
431
- const url = `${baseUrl}${uri}${qs ? `?${qs}` : ""}`;
432
- if (process.env.DISTILLED_DEBUG_HTTP) {
433
- console.error(`[distilled] -> ${http.method} ${http.uri}`);
434
- }
435
- let request = HttpClientRequest.make(http.method)(url).pipe(HttpClientRequest.setHeaders(headers));
436
- if (http.contentType === "multipart") {
437
- // Multipart upload: each body member is a form part (objects
438
- // JSON-encoded under their wire name), each file appends under its own
439
- // filename. A whole-body member (T.HttpBody) that is a record of files
440
- // becomes one part per entry (e.g. asset upload: { <hash>: File }).
441
- // Files and byte buffers become binary parts; objects become JSON parts.
442
- const form = new FormData();
443
- const parts = rawBody !== undefined && typeof rawBody === "object"
444
- ? rawBody
445
- : body;
446
- const isFileOrBlob = (v) => v instanceof Blob || v instanceof File;
447
- for (const [key, value] of Object.entries(parts)) {
448
- if (value === undefined || value === null)
449
- continue;
450
- if (isFileOrBlob(value)) {
451
- form.append(key, value, value instanceof File ? value.name : key);
452
- }
453
- else if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
454
- const bytes = value instanceof Uint8Array ? new Uint8Array(value).buffer : value;
455
- form.append(key, new Blob([bytes]), key);
456
- }
457
- else if (Array.isArray(value) && value.length > 0 && isFileOrBlob(value[0])) {
458
- for (const file of value) {
459
- if (isFileOrBlob(file)) {
460
- form.append(file instanceof File ? file.name : key, file, file instanceof File ? file.name : undefined);
461
- }
462
- }
463
- }
464
- else if (typeof value === "object") {
465
- form.append(key, JSON.stringify(value));
466
- }
467
- else {
468
- form.append(key, String(value));
469
- }
470
- }
471
- for (const f of files) {
472
- const filename = f.name ?? "file";
473
- form.append(filename, f, filename);
474
- }
475
- request = request.pipe(HttpClientRequest.bodyFormData(form));
476
- }
477
- else if (http.contentType === "form-urlencoded" && !BODYLESS.has(http.method)) {
478
- // application/x-www-form-urlencoded with Stripe-style deepObject bracket
479
- // notation: { shipping: { address: { city } } } → shipping[address][city],
480
- // arrays indexed ({ expand: ["a"] } → expand[0]=a).
481
- const source = rawBody !== undefined && typeof rawBody === "object"
482
- ? rawBody
483
- : body;
484
- const params = new URLSearchParams();
485
- for (const [k, v] of flattenToFormPairs(source))
486
- params.append(k, v);
487
- request = request.pipe(HttpClientRequest.setBody(HttpBody.text(params.toString(), "application/x-www-form-urlencoded")));
488
- }
489
- else if (rawBody !== undefined && !BODYLESS.has(http.method)) {
490
- // Whole-body member (raw arrays/scalars) — sent as the body itself.
491
- // Binary payloads (Blob / ArrayBuffer / Uint8Array) send verbatim
492
- // (raw object uploads). With a bodyMediaType, the member is a
493
- // preserialized payload (string / bytes) sent verbatim; otherwise it's
494
- // JSON.
495
- //
496
- // `setBody` overwrites the Content-Type header with the body's media
497
- // type (and removes it when that is undefined), so the body carries the
498
- // modeled Content-Type member when the caller set one, else the declared
499
- // bodyMediaType (e.g. application/x-ndjson for Vectorize insert/upsert).
500
- const mediaType = memberContentType ?? http.bodyMediaType;
501
- if (rawBody instanceof Blob || rawBody instanceof ArrayBuffer) {
502
- // With no media type at all, fetch falls back to the Blob's own type.
503
- request = request.pipe(HttpClientRequest.setBody(HttpBody.raw(rawBody, { contentType: mediaType })));
504
- }
505
- else if (rawBody instanceof Uint8Array) {
506
- request = request.pipe(HttpClientRequest.setBody(HttpBody.uint8Array(rawBody, mediaType)));
507
- }
508
- else if (http.bodyMediaType) {
509
- request = request.pipe(HttpClientRequest.setBody(typeof rawBody === "string"
510
- ? HttpBody.text(rawBody, mediaType)
511
- : HttpBody.uint8Array(rawBody, mediaType)));
512
- }
513
- else {
514
- request = request.pipe(HttpClientRequest.bodyJsonUnsafe(rawBody));
515
- }
516
- }
517
- else if (
518
- // A GET/HEAD sends a body only when body members actually carry values.
519
- // Some APIs really do document GET-with-body: MongoDB Atlas's
520
- // `…/lineItems:search` declares a `requestBody` on `get`, and AWS EFS's
521
- // DescribeAccountPreferences takes `{ MaxResults, NextToken }` on a GET.
522
- // Suppressing it outright dropped those members silently — the request
523
- // succeeded, unfiltered, with nothing on the wire to show why.
524
- //
525
- // The `{}`-when-empty rule below stays limited to methods that expect a
526
- // body, so a bodyless method with nothing set still sends nothing.
527
- Object.keys(body).length > 0 ||
528
- (hasBodyMembers && !BODYLESS.has(http.method) && http.method !== "DELETE")) {
529
- // Send `{}` rather than no body when the schema declares body members —
530
- // some endpoints reject a missing JSON body outright.
531
- request = request.pipe(HttpClientRequest.bodyJsonUnsafe(body));
532
- }
533
- return request;
534
- };
535
- const matchesText = (matcher, value) => {
536
- if (typeof value !== "string")
537
- return false;
538
- if (typeof matcher === "string")
539
- return matcher === value;
540
- const { includes, matches } = matcher;
541
- return ((includes !== undefined || matches !== undefined) &&
542
- (includes === undefined || value.includes(includes)) &&
543
- (matches === undefined || new RegExp(matches).test(value)));
544
- };
545
- // Own properties only: inherited properties are not JSON response members.
546
- const atPointer = (body, pointer) => {
547
- if (pointer === "")
548
- return body;
549
- if (!pointer.startsWith("/") || /~(?![01])/u.test(pointer))
550
- return undefined;
551
- let value = body;
552
- for (const segment of pointer.slice(1).split("/")) {
553
- const key = segment.replace(/~1/g, "/").replace(/~0/g, "~");
554
- if (value === null ||
555
- typeof value !== "object" ||
556
- !Object.hasOwn(value, key) ||
557
- (Array.isArray(value) && !/^(0|[1-9][0-9]*)$/.test(key)))
558
- return undefined;
559
- value = value[key];
560
- }
561
- return value;
562
- };
563
- const matcherSpecificity = (m) => (m.code !== undefined ? 1 : 0) +
564
- (m.status !== undefined ? 1 : 0) +
565
- (m.message !== undefined ? 1 : 0) +
566
- (m.body === undefined ? 0 : Object.keys(m.body).length) +
567
- (m.headers === undefined ? 0 : Object.keys(m.headers).length);
568
- /** Every supplied constraint must match; an unconstrained matcher matches nothing. */
569
- export const matchesExpression = (m, code, status, message, response = {}) => {
570
- if (m.code === undefined &&
571
- m.status === undefined &&
572
- m.message === undefined &&
573
- matcherSpecificity(m) === 0)
574
- return false;
575
- if (m.code !== undefined && m.code !== code)
576
- return false;
577
- if (m.status !== undefined && m.status !== status)
578
- return false;
579
- if (m.message !== undefined && !matchesText(m.message, message))
580
- return false;
581
- if (m.body !== undefined) {
582
- for (const [pointer, expected] of Object.entries(m.body)) {
583
- const actual = atPointer(response.body, pointer);
584
- if (typeof expected === "string" || (expected !== null && typeof expected === "object")) {
585
- if (!matchesText(expected, actual))
586
- return false;
587
- }
588
- else if (actual !== expected)
589
- return false;
590
- }
591
- }
592
- if (m.headers !== undefined) {
593
- for (const [name, expected] of Object.entries(m.headers)) {
594
- if (response.headers === undefined)
595
- return false;
596
- const actual = Object.entries(response.headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
597
- if (!matchesText(expected, actual))
598
- return false;
599
- }
600
- }
601
- return true;
602
- };
603
- /**
604
- * Pick the operation's typed error class for a failed response: among all
605
- * declared classes whose matchers (see `applyErrorMatchers`) match the wire
606
- * failure, the most specific matcher wins (ties break by declaration order).
607
- * Empty error lists use an HTTP-status message so body/header-only failures can
608
- * still match. The constructor receives the raw body and headers as well as
609
- * code/message; error schemas can declare these fields to expose them to callers.
610
- */
611
- export const matchTypedError = (errorClasses, status, errors, response = {}) => {
612
- let best;
613
- const wireErrors = errors.length > 0 ? errors : [{ message: `HTTP ${status}` }];
614
- for (const cls of errorClasses) {
615
- const matchers = getErrorMatchers(cls);
616
- if (!matchers)
617
- continue;
618
- for (const m of matchers) {
619
- for (const e of wireErrors) {
620
- if (!matchesExpression(m, e.code, status, e.message, response))
621
- continue;
622
- const specificity = matcherSpecificity(m);
623
- if (!best || specificity > best.specificity) {
624
- best = { cls, specificity, code: e.code, message: e.message };
625
- }
626
- }
627
- }
628
- }
629
- if (!best)
630
- return undefined;
631
- return new best.cls({
632
- code: best.code ?? 0,
633
- message: best.message,
634
- body: response.body,
635
- headers: response.headers,
636
- });
637
- };
638
- //#endregion
639
- //# sourceMappingURL=protocol-http.js.map
1
+ export { protocol_http$buildRequest as buildRequest, protocol_http$encodeGreedyLabel as encodeGreedyLabel, protocol_http$getAnn as getAnn, protocol_http$getPropAnn as getPropAnn, protocol_http$getProps as getProps, protocol_http$hasPropAnn as hasPropAnn, protocol_http$isOpaqueValue as isOpaqueValue, protocol_http$makeRequest as makeRequest, protocol_http$mapKeys as mapKeys, protocol_http$mapKeysByDictionary as mapKeysByDictionary, protocol_http$mapsVerbatim as mapsVerbatim, protocol_http$matchTypedError as matchTypedError, protocol_http$matchesExpression as matchesExpression, protocol_http$nameOf as nameOf, protocol_http$resolveNode as resolveNode, protocol_http$responseHeaderMembers as responseHeaderMembers, protocol_http$withResponseHeaders as withResponseHeaders } from "./_bundle/rest.js";