@distilled.cloud/core 1.0.0-rc.16 → 1.0.0-rc.18

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 (306) 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/annotations.d.ts +15 -0
  12. package/lib/annotations.d.ts.map +1 -0
  13. package/lib/annotations.js +2 -0
  14. package/lib/annotations.js.map +1 -0
  15. package/lib/api.d.ts +15 -0
  16. package/lib/api.d.ts.map +1 -1
  17. package/lib/api.js +1 -796
  18. package/lib/category.d.ts.map +1 -1
  19. package/lib/category.js +1 -278
  20. package/lib/chunks.js +1 -11
  21. package/lib/config.d.ts +54 -13
  22. package/lib/config.d.ts.map +1 -1
  23. package/lib/config.js +1 -161
  24. package/lib/crypto.js +1 -130
  25. package/lib/debug.d.ts.map +1 -1
  26. package/lib/debug.js +1 -8
  27. package/lib/error-category.d.ts.map +1 -1
  28. package/lib/error-category.js +1 -47
  29. package/lib/errors.d.ts +2 -13
  30. package/lib/errors.d.ts.map +1 -1
  31. package/lib/errors.js +1 -198
  32. package/lib/graphql.d.ts +14 -0
  33. package/lib/graphql.d.ts.map +1 -1
  34. package/lib/graphql.js +1 -1058
  35. package/lib/graphql.types.js +1 -6
  36. package/lib/index.d.ts +3 -2
  37. package/lib/index.d.ts.map +1 -1
  38. package/lib/index.js +1 -15
  39. package/lib/pagination.d.ts +34 -2
  40. package/lib/pagination.d.ts.map +1 -1
  41. package/lib/pagination.js +1 -271
  42. package/lib/plain-values.js +1 -39
  43. package/lib/plain-values.js.map +1 -1
  44. package/lib/protocol-http.d.ts +30 -6
  45. package/lib/protocol-http.d.ts.map +1 -1
  46. package/lib/protocol-http.js +1 -812
  47. package/lib/protocol-rest.d.ts +53 -39
  48. package/lib/protocol-rest.d.ts.map +1 -1
  49. package/lib/protocol-rest.js +1 -375
  50. package/lib/query.js +1 -27
  51. package/lib/response-validation-strict.js +1 -284
  52. package/lib/response-validation.d.ts +4 -3
  53. package/lib/response-validation.d.ts.map +1 -1
  54. package/lib/response-validation.js +1 -118
  55. package/lib/retry-after.js +1 -112
  56. package/lib/retry.js +1 -197
  57. package/lib/schema-lite-impl.js +1 -341
  58. package/lib/schema-lite-typed.js +1 -27
  59. package/lib/schema-lite.js +1 -31
  60. package/lib/schema.js +1 -220
  61. package/lib/telemetry-debug.d.ts +14 -0
  62. package/lib/telemetry-debug.d.ts.map +1 -0
  63. package/lib/telemetry-debug.js +2 -0
  64. package/lib/telemetry-debug.js.map +1 -0
  65. package/lib/telemetry-hooks.d.ts +32 -0
  66. package/lib/telemetry-hooks.d.ts.map +1 -0
  67. package/lib/telemetry-hooks.js +2 -0
  68. package/lib/telemetry-hooks.js.map +1 -0
  69. package/lib/telemetry-host-rules.d.ts +23 -0
  70. package/lib/telemetry-host-rules.d.ts.map +1 -0
  71. package/lib/telemetry-host-rules.js +2 -0
  72. package/lib/telemetry-host-rules.js.map +1 -0
  73. package/lib/telemetry-lambda-context.d.ts +17 -0
  74. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  75. package/lib/telemetry-lambda-context.js +2 -0
  76. package/lib/telemetry-lambda-context.js.map +1 -0
  77. package/lib/telemetry-message-context.d.ts +52 -0
  78. package/lib/telemetry-message-context.d.ts.map +1 -0
  79. package/lib/telemetry-message-context.js +2 -0
  80. package/lib/telemetry-message-context.js.map +1 -0
  81. package/lib/telemetry-metrics.d.ts +6 -0
  82. package/lib/telemetry-metrics.d.ts.map +1 -0
  83. package/lib/telemetry-metrics.js +2 -0
  84. package/lib/telemetry-metrics.js.map +1 -0
  85. package/lib/telemetry-name-template.d.ts +13 -0
  86. package/lib/telemetry-name-template.d.ts.map +1 -0
  87. package/lib/telemetry-name-template.js +2 -0
  88. package/lib/telemetry-name-template.js.map +1 -0
  89. package/lib/telemetry-stream.d.ts +9 -0
  90. package/lib/telemetry-stream.d.ts.map +1 -0
  91. package/lib/telemetry-stream.js +2 -0
  92. package/lib/telemetry-stream.js.map +1 -0
  93. package/lib/telemetry-xray.d.ts +28 -0
  94. package/lib/telemetry-xray.d.ts.map +1 -0
  95. package/lib/telemetry-xray.js +2 -0
  96. package/lib/telemetry-xray.js.map +1 -0
  97. package/lib/telemetry.d.ts +269 -0
  98. package/lib/telemetry.d.ts.map +1 -0
  99. package/lib/telemetry.js +3 -0
  100. package/lib/telemetry.js.map +1 -0
  101. package/lib/trait.js +1 -131
  102. package/lib/xml.js +1 -323
  103. package/package.json +1 -3
  104. package/src/annotations.ts +37 -0
  105. package/src/api.ts +130 -30
  106. package/src/category.ts +21 -22
  107. package/src/config.ts +58 -29
  108. package/src/debug.ts +9 -6
  109. package/src/error-category.ts +12 -14
  110. package/src/errors.ts +7 -7
  111. package/src/graphql.ts +123 -18
  112. package/src/index.ts +3 -2
  113. package/src/pagination.ts +119 -6
  114. package/src/protocol-http.ts +63 -43
  115. package/src/protocol-rest.ts +201 -140
  116. package/src/response-validation.ts +4 -3
  117. package/src/telemetry-debug.ts +135 -0
  118. package/src/telemetry-hooks.ts +33 -0
  119. package/src/telemetry-host-rules.ts +39 -0
  120. package/src/telemetry-lambda-context.ts +46 -0
  121. package/src/telemetry-message-context.ts +170 -0
  122. package/src/telemetry-metrics.ts +69 -0
  123. package/src/telemetry-name-template.ts +26 -0
  124. package/src/telemetry-stream.ts +91 -0
  125. package/src/telemetry-xray.ts +66 -0
  126. package/src/telemetry.ts +768 -0
  127. package/lib/api.js.map +0 -1
  128. package/lib/category.js.map +0 -1
  129. package/lib/chunks.js.map +0 -1
  130. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  131. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  132. package/lib/codegen/boolean-string-enums.js +0 -147
  133. package/lib/codegen/boolean-string-enums.js.map +0 -1
  134. package/lib/codegen/chunk.d.ts +0 -7
  135. package/lib/codegen/chunk.d.ts.map +0 -1
  136. package/lib/codegen/chunk.js +0 -139
  137. package/lib/codegen/chunk.js.map +0 -1
  138. package/lib/codegen/cli.d.ts +0 -80
  139. package/lib/codegen/cli.d.ts.map +0 -1
  140. package/lib/codegen/cli.js +0 -166
  141. package/lib/codegen/cli.js.map +0 -1
  142. package/lib/codegen/datafy.d.ts +0 -14
  143. package/lib/codegen/datafy.d.ts.map +0 -1
  144. package/lib/codegen/datafy.js +0 -853
  145. package/lib/codegen/datafy.js.map +0 -1
  146. package/lib/codegen/dedupe.d.ts +0 -5
  147. package/lib/codegen/dedupe.d.ts.map +0 -1
  148. package/lib/codegen/dedupe.js +0 -153
  149. package/lib/codegen/dedupe.js.map +0 -1
  150. package/lib/codegen/emit.d.ts +0 -125
  151. package/lib/codegen/emit.d.ts.map +0 -1
  152. package/lib/codegen/emit.js +0 -99
  153. package/lib/codegen/emit.js.map +0 -1
  154. package/lib/codegen/format.d.ts +0 -11
  155. package/lib/codegen/format.d.ts.map +0 -1
  156. package/lib/codegen/format.js +0 -32
  157. package/lib/codegen/format.js.map +0 -1
  158. package/lib/codegen/generated-at.d.ts +0 -29
  159. package/lib/codegen/generated-at.d.ts.map +0 -1
  160. package/lib/codegen/generated-at.js +0 -78
  161. package/lib/codegen/generated-at.js.map +0 -1
  162. package/lib/codegen/generator.d.ts +0 -353
  163. package/lib/codegen/generator.d.ts.map +0 -1
  164. package/lib/codegen/generator.js +0 -810
  165. package/lib/codegen/generator.js.map +0 -1
  166. package/lib/codegen/graph.d.ts +0 -36
  167. package/lib/codegen/graph.d.ts.map +0 -1
  168. package/lib/codegen/graph.js +0 -136
  169. package/lib/codegen/graph.js.map +0 -1
  170. package/lib/codegen/graphql-client.d.ts +0 -70
  171. package/lib/codegen/graphql-client.d.ts.map +0 -1
  172. package/lib/codegen/graphql-client.js +0 -439
  173. package/lib/codegen/graphql-client.js.map +0 -1
  174. package/lib/codegen/graphql.d.ts +0 -207
  175. package/lib/codegen/graphql.d.ts.map +0 -1
  176. package/lib/codegen/graphql.js +0 -786
  177. package/lib/codegen/graphql.js.map +0 -1
  178. package/lib/codegen/latin1.d.ts +0 -3
  179. package/lib/codegen/latin1.d.ts.map +0 -1
  180. package/lib/codegen/latin1.js +0 -126
  181. package/lib/codegen/latin1.js.map +0 -1
  182. package/lib/codegen/members.d.ts +0 -32
  183. package/lib/codegen/members.d.ts.map +0 -1
  184. package/lib/codegen/members.js +0 -62
  185. package/lib/codegen/members.js.map +0 -1
  186. package/lib/codegen/model-diff.d.ts +0 -10
  187. package/lib/codegen/model-diff.d.ts.map +0 -1
  188. package/lib/codegen/model-diff.js +0 -67
  189. package/lib/codegen/model-diff.js.map +0 -1
  190. package/lib/codegen/naming.d.ts +0 -29
  191. package/lib/codegen/naming.d.ts.map +0 -1
  192. package/lib/codegen/naming.js +0 -74
  193. package/lib/codegen/naming.js.map +0 -1
  194. package/lib/codegen/openapi-cli.d.ts +0 -52
  195. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  196. package/lib/codegen/openapi-cli.js +0 -84
  197. package/lib/codegen/openapi-cli.js.map +0 -1
  198. package/lib/codegen/openapi.d.ts +0 -209
  199. package/lib/codegen/openapi.d.ts.map +0 -1
  200. package/lib/codegen/openapi.js +0 -1548
  201. package/lib/codegen/openapi.js.map +0 -1
  202. package/lib/codegen/operations.d.ts +0 -24
  203. package/lib/codegen/operations.d.ts.map +0 -1
  204. package/lib/codegen/operations.js +0 -56
  205. package/lib/codegen/operations.js.map +0 -1
  206. package/lib/codegen/pagination.d.ts +0 -39
  207. package/lib/codegen/pagination.d.ts.map +0 -1
  208. package/lib/codegen/pagination.js +0 -31
  209. package/lib/codegen/pagination.js.map +0 -1
  210. package/lib/codegen/patch-audit.d.ts +0 -84
  211. package/lib/codegen/patch-audit.d.ts.map +0 -1
  212. package/lib/codegen/patch-audit.js +0 -366
  213. package/lib/codegen/patch-audit.js.map +0 -1
  214. package/lib/codegen/patches.d.ts +0 -129
  215. package/lib/codegen/patches.d.ts.map +0 -1
  216. package/lib/codegen/patches.js +0 -472
  217. package/lib/codegen/patches.js.map +0 -1
  218. package/lib/codegen/prelude.d.ts +0 -15
  219. package/lib/codegen/prelude.d.ts.map +0 -1
  220. package/lib/codegen/prelude.js +0 -60
  221. package/lib/codegen/prelude.js.map +0 -1
  222. package/lib/codegen/privatize.d.ts +0 -21
  223. package/lib/codegen/privatize.d.ts.map +0 -1
  224. package/lib/codegen/privatize.js +0 -176
  225. package/lib/codegen/privatize.js.map +0 -1
  226. package/lib/codegen/proto.d.ts +0 -121
  227. package/lib/codegen/proto.d.ts.map +0 -1
  228. package/lib/codegen/proto.js +0 -960
  229. package/lib/codegen/proto.js.map +0 -1
  230. package/lib/codegen/pure.d.ts +0 -6
  231. package/lib/codegen/pure.d.ts.map +0 -1
  232. package/lib/codegen/pure.js +0 -91
  233. package/lib/codegen/pure.js.map +0 -1
  234. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  235. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  236. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  237. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  238. package/lib/codegen/spec-path.d.ts +0 -16
  239. package/lib/codegen/spec-path.d.ts.map +0 -1
  240. package/lib/codegen/spec-path.js +0 -101
  241. package/lib/codegen/spec-path.js.map +0 -1
  242. package/lib/codegen/table.d.ts +0 -5
  243. package/lib/codegen/table.d.ts.map +0 -1
  244. package/lib/codegen/table.js +0 -249
  245. package/lib/codegen/table.js.map +0 -1
  246. package/lib/config.js.map +0 -1
  247. package/lib/crypto.js.map +0 -1
  248. package/lib/debug.js.map +0 -1
  249. package/lib/error-category.js.map +0 -1
  250. package/lib/errors.js.map +0 -1
  251. package/lib/graphql.js.map +0 -1
  252. package/lib/graphql.types.js.map +0 -1
  253. package/lib/index.js.map +0 -1
  254. package/lib/json-patch.d.ts +0 -58
  255. package/lib/json-patch.d.ts.map +0 -1
  256. package/lib/json-patch.js +0 -227
  257. package/lib/json-patch.js.map +0 -1
  258. package/lib/pagination.js.map +0 -1
  259. package/lib/protocol-http.js.map +0 -1
  260. package/lib/protocol-rest.js.map +0 -1
  261. package/lib/query.js.map +0 -1
  262. package/lib/response-validation-strict.js.map +0 -1
  263. package/lib/response-validation.js.map +0 -1
  264. package/lib/retry-after.js.map +0 -1
  265. package/lib/retry.js.map +0 -1
  266. package/lib/schema-lite-impl.js.map +0 -1
  267. package/lib/schema-lite-typed.js.map +0 -1
  268. package/lib/schema-lite.js.map +0 -1
  269. package/lib/schema.js.map +0 -1
  270. package/lib/testing.d.ts +0 -40
  271. package/lib/testing.d.ts.map +0 -1
  272. package/lib/testing.js +0 -42
  273. package/lib/testing.js.map +0 -1
  274. package/lib/trait.js.map +0 -1
  275. package/lib/xml.js.map +0 -1
  276. package/src/codegen/boolean-string-enums.ts +0 -155
  277. package/src/codegen/chunk.ts +0 -147
  278. package/src/codegen/cli.ts +0 -293
  279. package/src/codegen/datafy.ts +0 -874
  280. package/src/codegen/dedupe.ts +0 -173
  281. package/src/codegen/emit.ts +0 -200
  282. package/src/codegen/format.ts +0 -49
  283. package/src/codegen/generated-at.ts +0 -88
  284. package/src/codegen/generator.ts +0 -1229
  285. package/src/codegen/graph.ts +0 -151
  286. package/src/codegen/graphql-client.ts +0 -545
  287. package/src/codegen/graphql.ts +0 -1145
  288. package/src/codegen/latin1.ts +0 -131
  289. package/src/codegen/members.ts +0 -79
  290. package/src/codegen/model-diff.ts +0 -67
  291. package/src/codegen/naming.ts +0 -85
  292. package/src/codegen/openapi-cli.ts +0 -141
  293. package/src/codegen/openapi.ts +0 -1845
  294. package/src/codegen/operations.ts +0 -73
  295. package/src/codegen/pagination.ts +0 -64
  296. package/src/codegen/patch-audit.ts +0 -480
  297. package/src/codegen/patches.ts +0 -581
  298. package/src/codegen/prelude.ts +0 -70
  299. package/src/codegen/privatize.ts +0 -200
  300. package/src/codegen/proto.ts +0 -1092
  301. package/src/codegen/pure.ts +0 -94
  302. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  303. package/src/codegen/spec-path.ts +0 -112
  304. package/src/codegen/table.ts +0 -254
  305. package/src/json-patch.ts +0 -273
  306. package/src/testing.ts +0 -74
@@ -1,810 +0,0 @@
1
- import { booleanStringEnums, STRING_ENCODED_TRAIT } from "./boolean-string-enums.js";
2
- import { enumDecl, errorClass, errorUnionAlias, interfaceDecl, interfaceField, operationConst, PURE, suspendConst, } from "./emit.js";
3
- import { orderIndex, reachableFrom, shapeDeps, topoOrder } from "./graph.js";
4
- import { ADDITIONAL_PROPERTIES_TRAIT, memberBases, smithyWireName } from "./members.js";
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
- import { camel as _camel, local, lowerFirst, oneLine, q, tsKey, upperFirst } from "./naming.js";
22
- import { collectOperations, collectOpErrorIds, ensureNamedIo, modelNamespace, } from "./operations.js";
23
- import { validatePaginated } from "./pagination.js";
24
- import { JSON_PRELUDE, makeSchemaRef, makeTsRef, TS_JSON_PRELUDE } from "./prelude.js";
25
- const PAGINATED_TRAIT = "smithy.api#paginated";
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
- export const errorCategories = (traits,
44
-
45
- extra = []) => {
46
- const categories = [];
47
- const add = (name) => {
48
- if (!categories.includes(name))
49
- categories.push(name);
50
- };
51
- const status = traits?.["smithy.api#httpError"];
52
- if (typeof status === "number") {
53
- if (status === 401 || status === 403)
54
- add("AuthError");
55
- else if (status === 402)
56
- add("QuotaError");
57
- else if (status === 400 ||
58
- status === 404 ||
59
- status === 405 ||
60
- status === 406 ||
61
- status === 410 ||
62
- status === 413 ||
63
- status === 415 ||
64
- status === 422) {
65
- add("BadRequestError");
66
- }
67
- else if (status === 408 || status === 504)
68
- add("TimeoutError");
69
- else if (status === 409)
70
- add("ConflictError");
71
- else if (status === 429)
72
- add("ThrottlingError");
73
- else if (status >= 500 && status < 600)
74
- add("ServerError");
75
- }
76
- const retryable = traits?.["smithy.api#retryable"];
77
- if (retryable !== undefined) {
78
- add("RetryableError");
79
- if (retryable?.throttling)
80
- add("ThrottlingError");
81
- }
82
- for (const name of extra)
83
- add(name);
84
- return categories;
85
- };
86
-
87
- const categoryPipes = (traits) => errorCategories(traits).map((name) => `C.with${name}`);
88
-
89
- export const generateService = (model, spec) => {
90
- // `"true" | "false"` request members become real booleans that travel as
91
- // their string spelling (see boolean-string-enums.ts).
92
- booleanStringEnums(model);
93
- const shapes = model.shapes;
94
- const pure = spec.pure ?? PURE;
95
- const prelude = spec.prelude ?? JSON_PRELUDE;
96
- const tsPrelude = spec.tsPrelude ?? TS_JSON_PRELUDE;
97
- const memberName = spec.memberName ?? ((n) => n);
98
- const opExportName = spec.opExportName ?? lowerFirst;
99
- // 1. Operations — synthesize named Request/Response for Unit I/O so every
100
- // operation has an input shape that can carry operation-level traits.
101
- const operations = collectOperations(shapes);
102
- const httpFor = {}; // input shape id → http trait
103
- const opTraitsFor = {}; // input shape id → op traits
104
- const ns = modelNamespace(operations, shapes, spec.namespaceFallback ?? "smithy.unknown");
105
- const selected = [];
106
- for (const op of operations) {
107
- selected.push(op);
108
- const { input, output } = ensureNamedIo(shapes, op, ns);
109
- op.def.__input = input;
110
- op.def.__output = output;
111
- const http = op.def.traits?.["smithy.api#http"];
112
- if (http)
113
- httpFor[input] = http;
114
- if (op.def.traits)
115
- opTraitsFor[input] = op.def.traits;
116
- }
117
- if (selected.length === 0)
118
- return { code: "", operations: 0 };
119
- // 2. Reachability + dependencies-first order (cycles suspend at refs).
120
- const roots = [
121
- ...selected.flatMap((op) => [op.def.__input, op.def.__output]),
122
- ...(spec.extraRoots?.(selected, shapes) ?? []),
123
- ];
124
- const reachable = reachableFrom(shapes, roots, shapeDeps);
125
- const order = topoOrder(shapes, reachable, shapeDeps);
126
- const indexOf = orderIndex(order);
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
- const canonicalId = new Map();
141
- const canon = (target) => canonicalId.get(target) ?? target;
142
- const rawRef = makeSchemaRef(prelude, indexOf);
143
- const rawTsRef = makeTsRef(tsPrelude);
144
- const ref = (target, selfIdx) => rawRef(canon(target), selfIdx);
145
- const tsRef = (target) => rawTsRef(canon(target));
146
- // Direction classification for enum openness. Enum ALIASES are emitted
147
- // CLOSED (exhaustively matchable on reads); request-reachable shapes
148
- // re-open enum references inline (`X | (string & {})`) so consumers can
149
- // send tomorrow's values without an SDK update.
150
- const requestReachable = reachableFrom(shapes, selected.map((op) => op.def.__input), shapeDeps);
151
- // Discriminant enums: single-value enums required by a union-arm
152
- // structure (e.g. the worker binding `type: "ai"` literals). These stay
153
- // CLOSED even on the request side — consumers and the union's TS
154
- // narrowing rely on the exact literal (v0 parity).
155
- const discriminantEnums = new Set();
156
- for (const d of Object.values(shapes)) {
157
- if (d?.type !== "union")
158
- continue;
159
- for (const um of Object.values(d.members ?? {})) {
160
- const arm = shapes[um.target];
161
- if (arm?.type !== "structure")
162
- continue;
163
- for (const am of Object.values(arm.members ?? {})) {
164
- const t = shapes[am.target];
165
- if ((t?.type === "enum" || t?.type === "intEnum") &&
166
- Object.keys(t.members ?? {}).length === 1 &&
167
- am.traits?.["smithy.api#required"] !== undefined) {
168
- discriminantEnums.add(am.target);
169
- }
170
- }
171
- }
172
- }
173
-
174
-
175
-
176
-
177
-
178
-
179
-
180
-
181
- const tsRefAt = (rawTarget, ownerId) => {
182
- const target = canon(rawTarget);
183
- const base = tsRef(target);
184
- if (!requestReachable.has(ownerId))
185
- return base;
186
- if (discriminantEnums.has(target))
187
- return base;
188
- const d = shapes[target];
189
- if (d?.type === "enum")
190
- return `${base} | (string & {})`;
191
- if (d?.type === "intEnum")
192
- return `${base} | (number & {})`;
193
- return base;
194
- };
195
- const wireKind = spec.wireKind ??
196
- ((b) => b === "label" ? "label" : b === "query" ? "query" : b === "header" ? "header" : "other");
197
- // The generic binding cascade; provider bindings slot in after headers.
198
- const extraBindingOf = (traits) => {
199
- for (const b of spec.extraBindings ?? []) {
200
- if (b.trait in traits)
201
- return b.binding;
202
- }
203
- return undefined;
204
- };
205
- const bindingOf = (traits) => "smithy.api#httpLabel" in traits
206
- ? "label"
207
- : "smithy.api#httpQuery" in traits
208
- ? "query"
209
- : "smithy.api#httpHeader" in traits
210
- ? "header"
211
- : (extraBindingOf(traits) ?? ("smithy.api#httpPayload" in traits ? "rawBody" : "body"));
212
- // Shapes reachable from any response/error root — used to scope the
213
- // blanket-nullable-optionals rule to reads (the wire returns explicit
214
- // nulls; requests only accept null where a nullable trait says so).
215
- const responseReachable = spec.optionalsNullable === true
216
- ? reachableFrom(shapes, [...selected.map((op) => op.def.__output), ...collectOpErrorIds(selected, shapes)], shapeDeps)
217
- : undefined;
218
- const memberInfos = (d, ownerId) => memberBases(d, memberName).map((base) => {
219
- const traits = base.traits;
220
- const binding = bindingOf(traits);
221
- return {
222
- ...base,
223
- binding,
224
- wire: smithyWireName(traits, base.name, wireKind(binding)),
225
- nullable: (spec.nullableTrait ? spec.nullableTrait in traits : false) ||
226
- // Blanket-nullable optionals (v0 surface): every optional BODY
227
- // member of a response-reachable shape accepts/announces null
228
- // in addition to being omittable.
229
- (responseReachable !== undefined &&
230
- ownerId !== undefined &&
231
- responseReachable.has(ownerId) &&
232
- !base.required &&
233
- binding === "body"),
234
- };
235
- });
236
-
237
- const soleEnumValue = (target) => {
238
- const d = shapes[target];
239
- if (d?.type !== "enum")
240
- return undefined;
241
- const values = Object.values(d.members ?? {}).map((m) => m.traits?.["smithy.api#enumValue"]);
242
- return values.length === 1 && typeof values[0] === "string" ? values[0] : undefined;
243
- };
244
-
245
-
246
-
247
-
248
-
249
-
250
- const unionDiscriminator = (caseTargets) => {
251
- if (caseTargets.length < 2)
252
- return undefined;
253
- const perCase = caseTargets.map((t) => {
254
- const cd = shapes[t];
255
- if (cd?.type !== "structure")
256
- return undefined;
257
- const tags = new Map();
258
- for (const mi of memberInfos(cd)) {
259
- const value = soleEnumValue(mi.target);
260
- if (value !== undefined)
261
- tags.set(mi.tsName, value);
262
- }
263
- return tags;
264
- });
265
- if (perCase.some((tags) => tags === undefined || tags.size === 0)) {
266
- return undefined;
267
- }
268
- for (const key of perCase[0].keys()) {
269
- const values = perCase.map((tags) => tags.get(key));
270
- if (values.some((v) => v === undefined))
271
- continue;
272
- if (new Set(values).size !== values.length)
273
- continue;
274
- return { key, values: values };
275
- }
276
- return undefined;
277
- };
278
- // Generic pipes for the smithy bindings (the SDK's traits module exports
279
- // core's Label/Query/Header/HttpBody/Body builders under these names);
280
- // provider bindings and member traits append theirs via memberExtraPipes.
281
- const genericPipes = (info) => {
282
- switch (info.binding) {
283
- case "label":
284
- return [info.wire === info.tsName ? "T.Label()" : `T.Label(${q(info.wire)})`];
285
- case "query":
286
- return [info.wire === info.tsName ? "T.Query()" : `T.Query(${q(info.wire)})`];
287
- case "header":
288
- return [info.wire === info.tsName ? "T.Header()" : `T.Header(${q(info.wire)})`];
289
- case "rawBody":
290
- return ["T.HttpBody()"];
291
- case "body":
292
- return info.wire !== info.tsName ? [`T.Body(${q(info.wire)})`] : [];
293
- default:
294
- return [];
295
- }
296
- };
297
- const memberPipes = spec.memberPipes ??
298
- ((info) => [
299
- ...genericPipes(info),
300
- // The binding table's pipe (envelope payloads, file uploads, …).
301
- ...(spec.extraBindings ?? [])
302
- .filter((b) => b.binding === info.binding && b.trait in info.traits)
303
- .map((b) => b.pipe),
304
- // Trait-table pipes: trait value JSON-inlined as the argument.
305
- ...Object.entries(spec.memberTraitPipes ?? {})
306
- .filter(([trait]) => info.traits[trait] !== undefined)
307
- .map(([trait, builder]) => `${builder}(${JSON.stringify(info.traits[trait])})`),
308
- ...(STRING_ENCODED_TRAIT in info.traits ? ["T.StringEncoded()"] : []),
309
- ...(spec.memberExtraPipes?.(info) ?? []),
310
- ]);
311
- const memberTsTypeOf = (info, tsRefFn) => spec.memberTsType?.(info, tsRefFn) ??
312
- (spec.extraBindings ?? []).find((b) => b.binding === info.binding && b.tsType !== undefined)
313
- ?.tsType;
314
- const emitMember = (info, selfIdx) => {
315
- let expr = spec.memberSchema?.(info, (target) => ref(target, selfIdx)) ?? ref(info.target, selfIdx);
316
- if (info.nullable)
317
- expr = `S.NullOr(${expr})`;
318
- const pipes = memberPipes(info);
319
- if (pipes.length)
320
- expr = `${expr}.pipe(${pipes.join(", ")})`;
321
- if (!info.required)
322
- expr = `S.optional(${expr})`;
323
- return ` ${q(info.tsName)}: ${expr},`;
324
- };
325
- const opIoShapes = new Set();
326
- for (const op of selected) {
327
- opIoShapes.add(op.def.__input);
328
- opIoShapes.add(op.def.__output);
329
- }
330
- // 3. Validate pagination traits: a paginated op must actually carry its
331
- // token on the input and its items member on the output, else it
332
- // degrades to a plain operation.
333
- const paginatedOutputs = new Set();
334
- const paginatedItemsRoot = new Map();
335
-
336
- const paginatedItemsPath = new Map();
337
-
338
- const outputProfile = new Map();
339
-
340
- const opProfile = new Map();
341
- const usedProfiles = new Set();
342
- const profileNames = Object.keys(spec.paginationProfiles ?? {});
343
- if (profileNames.length > 0) {
344
- for (const op of selected) {
345
- const pg = op.def.traits?.[PAGINATED_TRAIT];
346
- if (!pg)
347
- continue;
348
- // Which profile decodes this op's pages: the selector's answer, or
349
- // the sole declared profile.
350
- const profileName = spec.paginationProfileFor?.(pg, op) ??
351
- (profileNames.length === 1 ? profileNames[0] : undefined);
352
- const profile = profileName ? spec.paginationProfiles[profileName] : undefined;
353
- if (!profile)
354
- continue;
355
- const inNames = new Set(memberInfos(shapes[op.def.__input] ?? {}).map((m) => m.tsName));
356
- const outNames = new Set(memberInfos(shapes[op.def.__output] ?? {}).map((m) => m.tsName));
357
- const { ok, itemsRoot } = validatePaginated({
358
- trait: pg,
359
- inputNames: inNames,
360
- outputNames: outNames,
361
- itemsFallback: profile.itemsFallback,
362
- syntheticOutputs: new Set(profile.syntheticOutputs ?? []),
363
- });
364
- if (ok) {
365
- op.def.__pagination = pg;
366
- paginatedOutputs.add(op.def.__output);
367
- paginatedItemsRoot.set(op.def.__output, itemsRoot);
368
- paginatedItemsPath.set(op.id, String(pg.items ?? profile.itemsFallback ?? ""));
369
- outputProfile.set(op.def.__output, profile);
370
- opProfile.set(op.id, profile);
371
- usedProfiles.add(profile);
372
- }
373
- }
374
- }
375
- // 4. Error classes from the operations' errors lists.
376
- const out = [];
377
- // Emitted struct body → the name that owns it, for structural aliasing.
378
- // Keyed on the emitted TEXT, so two shapes collapse only when what they
379
- // would emit is byte-identical — including member names, targets, docs and
380
- // pipes. References are already resolved to names at this point, so a
381
- // difference anywhere in the tree shows up as different text.
382
- const structBodies = new Map();
383
- // Set when any error carries CATEGORY_TRAIT, so the header only imports
384
- // the category module when something actually uses it.
385
- let usesCategories = false;
386
- const errorIds = collectOpErrorIds(selected, shapes);
387
- const errorIdSet = new Set(errorIds);
388
- const errorNames = new Set(errorIds.map(local));
389
- const shapeDocs = spec.shapeDocs ?? true;
390
- for (const id of errorIds) {
391
- const d = shapes[id];
392
- const name = local(id);
393
- const doc = oneLine(d.traits?.["smithy.api#documentation"]);
394
- if (doc && shapeDocs)
395
- out.push(`/** ${doc} */`);
396
- const overridden = spec.errors?.override?.({ id, def: d, name });
397
- if (overridden) {
398
- out.push(...overridden);
399
- continue;
400
- }
401
- const errorField = spec.errors?.field ??
402
- ((mn, target) => ` ${tsKey(mn)}: ${prelude[local(target)] ?? "S.Unknown"},`);
403
- const fields = d.members && Object.keys(d.members).length
404
- ? Object.entries(d.members).map(([mn, m]) => errorField(mn, m.target))
405
- : (spec.errors?.defaultFields?.(prelude) ?? [
406
- errorField("code", "smithy.api#Integer"),
407
- errorField("message", "smithy.api#String"),
408
- ]);
409
- const matchers = spec.errorMatchersTrait ? d.traits?.[spec.errorMatchersTrait] : undefined;
410
- const categories = categoryPipes(d.traits);
411
- if (categories.length)
412
- usesCategories = true;
413
- out.push(errorClass({
414
- name,
415
- fields,
416
- pipes: categories.length ? `.pipe(${categories.join(", ")})` : undefined,
417
- wrap: spec.errors?.wrap?.(d.traits ?? {}) ??
418
- (matchers
419
- ? (cls) => `T.applyErrorMatchers(\n${cls},\n${JSON.stringify(matchers)},\n)`
420
- : undefined),
421
- }));
422
- }
423
- // 5. Every reachable shape in dependency order: explicit TS type next to
424
- // a schema const cast to `S.Schema<T>` (the compile-perf pattern).
425
- order.forEach((id, i) => {
426
- if (errorIdSet.has(id))
427
- return; // emitted as an error class above
428
- const d = shapes[id];
429
- const name = local(id);
430
- const doc = oneLine(d.traits?.["smithy.api#documentation"]);
431
- if (doc && shapeDocs)
432
- out.push(`/** ${doc} */`);
433
- const override = spec.shapeOverride?.({
434
- id,
435
- def: d,
436
- name,
437
- selfIdx: i,
438
- ref,
439
- tsRef,
440
- members: memberInfos,
441
- });
442
- if (override) {
443
- out.push(...override);
444
- return;
445
- }
446
- if (d.type === "structure") {
447
- // Bare-payload response: single trait-marked member — the response IS
448
- // that member's value; emit its type + a root marker for the protocol.
449
- const memberEntriesAll = Object.entries(d.members ?? {});
450
- const soleMemberRoot = !paginatedOutputs.has(id) && memberEntriesAll.length === 1
451
- ? (spec.extraBindings ?? []).find((b) => b.rootPipe !== undefined &&
452
- b.trait in (memberEntriesAll[0][1].traits ?? {}))
453
- : undefined;
454
- if (soleMemberRoot) {
455
- const [, m] = memberEntriesAll[0];
456
- // Alias responses are op roots too — they must carry the service
457
- // key dictionary so opaque content (union cases, freeform maps)
458
- // nested in the payload decodes with the same wire mapping as
459
- // struct-form roots.
460
- const rootPipes = [
461
- soleMemberRoot.rootPipe,
462
- ...(spec.rootKeyDictionary && opIoShapes.has(id)
463
- ? [`T.KeyDictionary(KEY_DICTIONARY)`]
464
- : []),
465
- ];
466
- out.push(`export type ${name} = ${tsRef(m.target)};`);
467
- out.push(suspendConst({
468
- name,
469
- pure,
470
- multiline: true,
471
- annotateIdentifier: true,
472
- castTo: `S.${spec.schemaType ?? "Schema"}<${name}>`,
473
- expr: `${ref(m.target, i)}.pipe(${rootPipes.join(", ")})`,
474
- }));
475
- return;
476
- }
477
- // Paginated outputs always deliver their items member — required.
478
- const itemsRoot = paginatedItemsRoot.get(id);
479
- const infos = memberInfos(d, id).map((info) => info.tsName === itemsRoot ? { ...info, required: true } : info);
480
- const fields = infos.flatMap((info) => interfaceField({
481
- name: info.tsName,
482
- optional: !info.required,
483
- doc: info.doc,
484
- type: memberTsTypeOf(info, tsRef) ??
485
- `${tsRefAt(info.target, id)}${info.nullable ? " | null" : ""}`,
486
- }));
487
- const members = infos.map((info) => emitMember(info, i));
488
- const inject = outputProfile.get(id)?.injectOutputMember;
489
- if (inject && !infos.some((m) => m.tsName === inject.tsName)) {
490
- fields.push(...inject.interfaceLines);
491
- members.push(inject.structLine);
492
- }
493
- const closed = members.length ? `S.Struct({\n${members.join("\n")}\n})` : `S.Struct({})`;
494
- // Open object: keys beyond the declared members are typed `unknown`.
495
- // A typed value (OpenAPI `additionalProperties: {schema}`) would have
496
- // to accept every declared member's type too, so it stays `unknown`.
497
- const open = ADDITIONAL_PROPERTIES_TRAIT in (d.traits ?? {});
498
- if (open)
499
- fields.push(` [key: string]: unknown;`);
500
- const struct = open ? `S.StructWithRest(${closed}, [S.Record(S.String, S.Unknown)])` : closed;
501
- const structCtx = {
502
- id,
503
- isOpIo: opIoShapes.has(id),
504
- httpTrait: httpFor[id],
505
- opTraits: opTraitsFor[id],
506
- };
507
- const pipes = spec.structPipes?.(structCtx) ?? [
508
- ...(structCtx.httpTrait ? [`T.Http(${JSON.stringify(structCtx.httpTrait)})`] : []),
509
- ...(spec.rootKeyDictionary && structCtx.isOpIo ? [`T.KeyDictionary(KEY_DICTIONARY)`] : []),
510
- ];
511
- const tail = pipes.map((p) => `.pipe(${p})`).join("");
512
- // Shapes whose emitted body is byte-identical are one shape wearing
513
- // many names. The docs pipelines generate a fresh copy of every nested
514
- // shape per operation, so cloudflare's zero_trust carries 374 copies of
515
- // `{ group?: unknown }` — one per operation x application type x
516
- // include/exclude/require — and 72% of its 16,800 structures are
517
- // redundant that way.
518
- //
519
- // Emit the body once and alias the rest to it. The public name is kept,
520
- // so nothing about the surface changes; only the duplicate bodies go.
521
- // Operation I/O is excluded: those carry the operation's Http trait and
522
- // must never be merged onto one another.
523
- const bodyKey = `${JSON.stringify(fields)}|${struct}${tail}`;
524
- const canonical = structCtx.isOpIo ? undefined : structBodies.get(bodyKey);
525
- if (canonical !== undefined) {
526
- out.push(`export type ${name} = ${canonical.name};`);
527
- out.push(`export const ${name} = ${canonical.name};\n`);
528
- // Later shapes referencing this one now render the canonical name,
529
- // which is what lets their bodies collapse too.
530
- canonicalId.set(id, canonical.id);
531
- }
532
- else {
533
- if (!structCtx.isOpIo) {
534
- structBodies.set(bodyKey, { id, name });
535
- }
536
- out.push(interfaceDecl(name, fields));
537
- out.push(suspendConst({
538
- name,
539
- pure,
540
- multiline: true,
541
- annotateIdentifier: true,
542
- castTo: `S.${spec.schemaType ?? "Schema"}<${name}>`,
543
- expr: `${struct}${tail}`,
544
- }));
545
- }
546
- }
547
- else if (d.type === "list") {
548
- const nullable = spec.nullableTrait !== undefined && spec.nullableTrait in (d.member.traits ?? {});
549
- const item = ref(d.member.target, i);
550
- out.push(`export type ${name} = Array<${tsRefAt(d.member.target, id)}${nullable ? " | null" : ""}>;`);
551
- out.push(`export const ${name} = ${pure}S.Array(${nullable ? `S.NullOr(${item})` : item}) as any as S.${spec.schemaType ?? "Schema"}<${name}>;\n`);
552
- }
553
- else if (d.type === "map") {
554
- const nullable = spec.nullableTrait !== undefined && spec.nullableTrait in (d.value.traits ?? {});
555
- const value = ref(d.value.target, i);
556
- out.push(`export type ${name} = { [key: string]: ${tsRefAt(d.value.target, id)}${nullable ? " | null" : ""} | undefined };`);
557
- out.push(`export const ${name} = ${pure}S.Record(S.String, ${nullable ? `S.NullOr(${value})` : value}) as any as S.${spec.schemaType ?? "Schema"}<${name}>;\n`);
558
- }
559
- else if (d.type === "union") {
560
- // A union arm targeting the union itself carries no information
561
- // (`type X = X | A | B` ≡ `A | B`) and is an illegal circular type
562
- // alias. Specs produce them: atlas's OnlineArchiveSchedule is a
563
- // discriminated oneOf whose DEFAULT arm is `allOf: [$ref <the union
564
- // itself>]`, so the arm resolves back to its own parent.
565
- const caseTargets = Object.values(d.members ?? {})
566
- .map((m) => m.target)
567
- .filter((t) => t !== id);
568
- const caseKeys = caseTargets.map((t) => {
569
- const cd = shapes[t];
570
- return cd?.type === "structure" ? memberInfos(cd).map((mi) => mi.tsName) : [];
571
- });
572
- if (spec.union) {
573
- out.push(...spec.union({ name, caseTargets, caseKeys, tsRef }));
574
- }
575
- else if (spec.unionStyle === "untagged") {
576
- out.push(`export type ${name} = ${caseTargets.map((t) => tsRefAt(t, id)).join(" | ") || "never"};`, `export const ${name} = ${pure}S.Union([${caseTargets.map((t) => ref(t, i)).join(", ")}]) as any as S.${spec.schemaType ?? "Schema"}<${name}>;\n`);
577
- }
578
- else if (spec.unionStyle === "primitive" &&
579
- caseTargets.length > 0 &&
580
- caseTargets.every((target) => ["string", "number", "boolean"].includes(tsRef(target)) ||
581
- shapes[target]?.type === "enum" ||
582
- shapes[target]?.type === "intEnum")) {
583
- // Primitive unions keep response enums open to match S.String/S.Number.
584
- const primitiveType = (target) => {
585
- const type = tsRef(target);
586
- if (shapes[target]?.type === "enum")
587
- return `${type} | (string & {})`;
588
- if (shapes[target]?.type === "intEnum")
589
- return `${type} | (number & {})`;
590
- return type;
591
- };
592
- out.push(`export type ${name} = ${caseTargets.map(primitiveType).join(" | ")};`, `export const ${name}: S.Codec<${name}> = ${pure}S.Union([${caseTargets.map((t) => ref(t, i)).join(", ")}]);\n`);
593
- }
594
- else if (spec.unionStyle === "opaque-cases") {
595
- const disc = unionDiscriminator(caseTargets);
596
- out.push(`export type ${name} = ${caseTargets.map((t) => tsRefAt(t, id)).join(" | ") || "unknown"};`, `export const ${name} = ${pure}S.Unknown.pipe(T.UnionCases(${JSON.stringify(caseKeys)}${disc ? `, ${JSON.stringify(disc)}` : ""}));\n`);
597
- }
598
- else {
599
- throw new Error(`no union emission configured for shape ${id} — set unionStyle or union`);
600
- }
601
- }
602
- else if (d.type === "enum") {
603
- const values = Object.values(d.members ?? {})
604
- .map((m) => m.traits?.["smithy.api#enumValue"])
605
- .filter((v) => typeof v === "string");
606
- out.push(...enumDecl({ name, values, pure }));
607
- }
608
- else if (d.type === "intEnum") {
609
- // CLOSED numeric literal union alias (`type Y = 1 | 30`); INPUT
610
- // references re-open it inline (`Y | (number & {})`). Schema stays
611
- // S.Number (protocols never validate enum membership).
612
- const values = Object.values(d.members ?? {})
613
- .map((m) => m.traits?.["smithy.api#enumValue"])
614
- .filter((v) => typeof v === "number");
615
- const union = values.length ? values.join(" | ") : "number";
616
- out.push(`export type ${name} = ${union};`, `export const ${name} = S.Number;\n`);
617
- }
618
- });
619
- // 6. Operations — declarative emission from the names in operationDecl,
620
- // unless the provider overrides the whole shape.
621
-
622
-
623
-
624
-
625
-
626
-
627
-
628
-
629
-
630
-
631
-
632
-
633
-
634
-
635
- const paginatedItemTsType = (outputId, itemsPath) => {
636
- // No items path: `.items()` is a page passthrough at runtime, so an
637
- // item IS a whole response.
638
- if (!itemsPath)
639
- return tsRef(outputId);
640
- let id = outputId;
641
- // Whether the path crossed a list on the way down (`"edges.node"` on a
642
- // Relay connection). When it did, the path itself is what fans out, so
643
- // the value it lands on IS one item — it needn't be a list again.
644
- let fannedOut = false;
645
- for (const segment of itemsPath.split(".")) {
646
- let def = shapes[id];
647
- if (def?.type === "list") {
648
- id = def.member.target;
649
- def = shapes[id];
650
- fannedOut = true;
651
- }
652
- if (def?.type !== "structure")
653
- return undefined;
654
- const info = memberInfos(def).find((m) => m.tsName === segment);
655
- if (!info)
656
- return undefined;
657
- id = info.target;
658
- }
659
- const last = shapes[id];
660
- if (last?.type === "list")
661
- return tsRef(last.member.target);
662
- return fannedOut ? tsRef(id) : undefined;
663
- };
664
- const usedProtocols = new Set();
665
- const emitOperation = spec.operation ??
666
- ((ctx) => {
667
- const decl = spec.operationDecl;
668
- if (!decl) {
669
- throw new Error("SdkSpec needs either operationDecl or operation");
670
- }
671
- const errList = [...ctx.errorNames, ...decl.commonErrorClasses];
672
- const overrides = decl.overrides?.(ctx);
673
- const contextType = overrides?.contextType ?? decl.contextType;
674
- const paginated = ctx.pagination !== undefined;
675
- const itemTsType = paginated
676
- ? paginatedItemTsType(ctx.op.def.__output, paginatedItemsPath.get(ctx.op.id) ?? "")
677
- : undefined;
678
- const typeAnnotation = `API.${paginated ? "PaginatedOperationMethod" : "OperationMethod"}<\n` +
679
- ` ${ctx.inputName},\n` +
680
- ` ${ctx.outputTsType},\n` +
681
- ` ${ctx.opName}Error,\n` +
682
- ` ${contextType}` +
683
- (itemTsType ? `,\n ${itemTsType}\n` : `\n`) +
684
- `>`;
685
- const protocol = (paginated && opProfile.get(ctx.op.id)?.protocol) || overrides?.protocol || decl.protocol;
686
- usedProtocols.add(protocol);
687
- const config = `{\n` +
688
- ` input: ${ctx.inputName},\n` +
689
- ` output: ${ctx.outputSchema},\n` +
690
- ` errors: [${errList.join(", ")}],\n` +
691
- ` protocol: ${protocol},\n` +
692
- (decl.retry ? ` retry: ${decl.retry},\n` : "") +
693
- (decl.extraConfig?.(ctx) ?? []).map((l) => ` ${l},\n`).join("") +
694
- (paginated ? ` pagination: ${JSON.stringify(ctx.pagination)} as const,\n` : "") +
695
- `}`;
696
- return [
697
- errorUnionAlias(ctx.opName, ctx.errorNames, decl.commonErrorType),
698
- ...(ctx.doc ? [`/** ${ctx.doc} */`] : []),
699
- operationConst({
700
- exportName: ctx.exportName,
701
- typeAnnotation,
702
- factory: paginated ? "API.makePaginated" : "API.make",
703
- pure,
704
- extraArg: paginated ? opProfile.get(ctx.op.id)?.strategy : undefined,
705
- config,
706
- // `makePaginated` infers the items element from the structural
707
- // fallback; an explicit item type needs the same `as any as`
708
- // idiom the schema consts use.
709
- castToAnnotation: itemTsType !== undefined,
710
- }),
711
- ].join("\n");
712
- });
713
- for (const op of selected) {
714
- const opName = local(op.id);
715
- const errNames = (op.def.errors ?? [])
716
- .map((e) => local(e.target))
717
- .filter((n) => errorNames.has(n));
718
- out.push(emitOperation({
719
- op,
720
- opName,
721
- exportName: opExportName(opName),
722
- inputName: local(op.def.__input),
723
- outputName: local(op.def.__output),
724
- outputTsType: tsRef(op.def.__output),
725
- outputSchema: ref(op.def.__output, indexOf.size),
726
- errorNames: errNames,
727
- doc: oneLine(op.def.traits?.["smithy.api#documentation"]),
728
- pagination: op.def.__pagination,
729
- }));
730
- }
731
- // 7. Alias re-exports, then provider trailing sections.
732
- const emittedOps = new Set(selected.map((op) => opExportName(local(op.id))));
733
- for (const { alias, target } of spec.opAliases ?? []) {
734
- if (!emittedOps.has(target) || emittedOps.has(alias))
735
- continue;
736
- emittedOps.add(alias);
737
- const A = upperFirst(alias);
738
- const T2 = upperFirst(target);
739
- out.push(`// Alias of ${target} (same route, alternate export name upstream).\n` +
740
- `export const ${alias} = ${target};\n` +
741
- `export type ${A}Request = ${T2}Request;\n` +
742
- `export type ${A}Response = ${T2}Response;\n` +
743
- `export type ${A}Error = ${T2}Error;\n`);
744
- }
745
- if (spec.footer) {
746
- out.push(...spec.footer({ emittedOps }));
747
- }
748
- // Default header: banner + imports derived from operationDecl names and
749
- // the conventional SDK module layout, op error/context type re-exports,
750
- // and the KEY_DICTIONARY const when configured.
751
- const defaultHeader = (ctx) => {
752
- const decl = spec.operationDecl;
753
- if (!decl) {
754
- throw new Error("the default header needs operationDecl — or pass header");
755
- }
756
- const retryNs = decl.retry?.split(".")[0];
757
- // Imports the used pagination profiles pull in: their protocol consts
758
- // (from the protocol module) and strategy/injected-member names (from
759
- // the pagination module).
760
- const profileProtocols = [
761
- ...new Set([...usedProfiles]
762
- .map((p) => p.protocol)
763
- .filter((p) => p !== undefined && p !== decl.protocol)),
764
- ];
765
- const pagImports = [
766
- ...new Set([...usedProfiles].flatMap((p) => [
767
- ...(p.strategy ? [p.strategy] : []),
768
- ...(p.injectOutputMember?.imports ?? []),
769
- ])),
770
- ];
771
- return (`// AUTO-GENERATED by scripts/generate.ts${spec.sourceNote ? ` from ${spec.sourceNote}` : ""}. Do not edit.\n` +
772
- // Lite schemas: Effect Schema is bundled only with ResponseValidation.strict.
773
- `import * as S from "@distilled.cloud/core/schema-lite";\n` +
774
- `import * as API from "@distilled.cloud/core/api";\n` +
775
- (usesCategories ? `import * as C from "@distilled.cloud/core/category";\n` : "") +
776
- `import * as T from "../traits.ts";\n` +
777
- `import {\n` +
778
- (spec.operation || usedProtocols.has(decl.protocol) ? ` ${decl.protocol},\n` : "") +
779
- profileProtocols.map((p) => ` ${p},\n`).join("") +
780
- ` type ${decl.commonErrorType},\n` +
781
- ` type ${decl.contextType},\n` +
782
- `} from "../protocol.ts";\n` +
783
- (ctx.hasPaginated && pagImports.length
784
- ? `import { ${pagImports.join(", ")} } from "../pagination.ts";\n`
785
- : "") +
786
- (decl.commonErrorClasses.length
787
- ? `import { ${[...decl.commonErrorClasses].sort().join(", ")} } from "../errors.ts";\n`
788
- : "") +
789
- (retryNs ? `import * as ${retryNs} from "../retry.ts";\n\n` : "\n") +
790
- // Re-exported so inferred provider types downstream can always name them.
791
- `export type { ${decl.commonErrorType}, ${decl.contextType} };\n\n` +
792
- (spec.rootKeyDictionary
793
- ? `/** ${spec.rootKeyDictionary.doc} */\n` +
794
- `const KEY_DICTIONARY: Record<string, string | ReadonlyArray<string>> = ${JSON.stringify(spec.rootKeyDictionary.dict)};\n\n`
795
- : ""));
796
- };
797
- const header = (spec.header ?? defaultHeader)({
798
- hasPaginated: paginatedOutputs.size > 0,
799
- model,
800
- });
801
- const code = header + out.join("\n") + "\n";
802
- return {
803
- code: spec.postProcess?.(code) ?? code,
804
- operations: selected.length,
805
- };
806
- };
807
- // Re-exported so provider specs can be written against the same helpers the
808
- // driver uses, without importing every codegen module individually.
809
- export { errorUnionAlias, operationConst, upperFirst, tsKey, q, local };
810
- //# sourceMappingURL=generator.js.map