@distilled.cloud/core 0.30.2 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/lib/api.d.ts +165 -0
  2. package/lib/api.d.ts.map +1 -0
  3. package/lib/api.js +178 -0
  4. package/lib/api.js.map +1 -0
  5. package/lib/codegen/cli.d.ts +29 -0
  6. package/lib/codegen/cli.d.ts.map +1 -0
  7. package/lib/codegen/cli.js +165 -0
  8. package/lib/codegen/cli.js.map +1 -0
  9. package/lib/codegen/emit.d.ts +129 -0
  10. package/lib/codegen/emit.d.ts.map +1 -0
  11. package/lib/codegen/emit.js +105 -0
  12. package/lib/codegen/emit.js.map +1 -0
  13. package/lib/codegen/format.d.ts +23 -0
  14. package/lib/codegen/format.d.ts.map +1 -0
  15. package/lib/codegen/format.js +28 -0
  16. package/lib/codegen/format.js.map +1 -0
  17. package/lib/codegen/generator.d.ts +334 -0
  18. package/lib/codegen/generator.d.ts.map +1 -0
  19. package/lib/codegen/generator.js +691 -0
  20. package/lib/codegen/generator.js.map +1 -0
  21. package/lib/codegen/graph.d.ts +36 -0
  22. package/lib/codegen/graph.d.ts.map +1 -0
  23. package/lib/codegen/graph.js +136 -0
  24. package/lib/codegen/graph.js.map +1 -0
  25. package/lib/codegen/members.d.ts +25 -0
  26. package/lib/codegen/members.d.ts.map +1 -0
  27. package/lib/codegen/members.js +55 -0
  28. package/lib/codegen/members.js.map +1 -0
  29. package/lib/codegen/naming.d.ts +29 -0
  30. package/lib/codegen/naming.d.ts.map +1 -0
  31. package/lib/codegen/naming.js +74 -0
  32. package/lib/codegen/naming.js.map +1 -0
  33. package/lib/codegen/openapi-cli.d.ts +38 -0
  34. package/lib/codegen/openapi-cli.d.ts.map +1 -0
  35. package/lib/codegen/openapi-cli.js +107 -0
  36. package/lib/codegen/openapi-cli.js.map +1 -0
  37. package/lib/codegen/openapi.d.ts +115 -0
  38. package/lib/codegen/openapi.d.ts.map +1 -0
  39. package/lib/codegen/openapi.js +1220 -0
  40. package/lib/codegen/openapi.js.map +1 -0
  41. package/lib/codegen/operations.d.ts +24 -0
  42. package/lib/codegen/operations.d.ts.map +1 -0
  43. package/lib/codegen/operations.js +56 -0
  44. package/lib/codegen/operations.js.map +1 -0
  45. package/lib/codegen/pagination.d.ts +39 -0
  46. package/lib/codegen/pagination.d.ts.map +1 -0
  47. package/lib/codegen/pagination.js +33 -0
  48. package/lib/codegen/pagination.js.map +1 -0
  49. package/lib/codegen/prelude.d.ts +15 -0
  50. package/lib/codegen/prelude.d.ts.map +1 -0
  51. package/lib/codegen/prelude.js +60 -0
  52. package/lib/codegen/prelude.js.map +1 -0
  53. package/lib/error-category.d.ts +28 -0
  54. package/lib/error-category.d.ts.map +1 -0
  55. package/lib/error-category.js +46 -0
  56. package/lib/error-category.js.map +1 -0
  57. package/lib/errors.d.ts +1 -0
  58. package/lib/errors.d.ts.map +1 -1
  59. package/lib/errors.js +1 -0
  60. package/lib/errors.js.map +1 -1
  61. package/lib/json-patch.d.ts +25 -32
  62. package/lib/json-patch.d.ts.map +1 -1
  63. package/lib/json-patch.js +23 -95
  64. package/lib/json-patch.js.map +1 -1
  65. package/lib/pagination.d.ts +37 -51
  66. package/lib/pagination.d.ts.map +1 -1
  67. package/lib/pagination.js +72 -90
  68. package/lib/pagination.js.map +1 -1
  69. package/lib/protocol-http.d.ts +74 -0
  70. package/lib/protocol-http.d.ts.map +1 -0
  71. package/lib/protocol-http.js +554 -0
  72. package/lib/protocol-http.js.map +1 -0
  73. package/lib/protocol-rest.d.ts +124 -0
  74. package/lib/protocol-rest.d.ts.map +1 -0
  75. package/lib/protocol-rest.js +242 -0
  76. package/lib/protocol-rest.js.map +1 -0
  77. package/lib/retry.d.ts +8 -2
  78. package/lib/retry.d.ts.map +1 -1
  79. package/lib/retry.js +21 -15
  80. package/lib/retry.js.map +1 -1
  81. package/lib/schema.d.ts +7 -8
  82. package/lib/schema.d.ts.map +1 -1
  83. package/lib/schema.js +7 -8
  84. package/lib/schema.js.map +1 -1
  85. package/lib/trait.d.ts +150 -0
  86. package/lib/trait.d.ts.map +1 -0
  87. package/lib/trait.js +107 -0
  88. package/lib/trait.js.map +1 -0
  89. package/package.json +18 -75
  90. package/src/api.ts +446 -0
  91. package/src/codegen/cli.ts +268 -0
  92. package/src/codegen/emit.ts +207 -0
  93. package/src/codegen/format.ts +47 -0
  94. package/src/codegen/generator.ts +1153 -0
  95. package/src/codegen/graph.ts +151 -0
  96. package/src/codegen/members.ts +71 -0
  97. package/src/codegen/naming.ts +86 -0
  98. package/src/codegen/openapi-cli.ts +166 -0
  99. package/src/codegen/openapi.ts +1450 -0
  100. package/src/codegen/operations.ts +76 -0
  101. package/src/codegen/pagination.ts +71 -0
  102. package/src/codegen/prelude.ts +70 -0
  103. package/src/error-category.ts +84 -0
  104. package/src/errors.ts +2 -0
  105. package/src/json-patch.ts +26 -110
  106. package/src/pagination.ts +86 -142
  107. package/src/protocol-http.ts +699 -0
  108. package/src/protocol-rest.ts +367 -0
  109. package/src/retry.ts +20 -21
  110. package/src/schema.ts +7 -8
  111. package/src/trait.ts +238 -0
  112. package/README.md +0 -30
  113. package/lib/client.d.ts +0 -167
  114. package/lib/client.d.ts.map +0 -1
  115. package/lib/client.js +0 -659
  116. package/lib/client.js.map +0 -1
  117. package/lib/schemas.d.ts +0 -60
  118. package/lib/schemas.d.ts.map +0 -1
  119. package/lib/schemas.js +0 -79
  120. package/lib/schemas.js.map +0 -1
  121. package/lib/sensitive.d.ts +0 -71
  122. package/lib/sensitive.d.ts.map +0 -1
  123. package/lib/sensitive.js +0 -96
  124. package/lib/sensitive.js.map +0 -1
  125. package/lib/traits.d.ts +0 -421
  126. package/lib/traits.d.ts.map +0 -1
  127. package/lib/traits.js +0 -737
  128. package/lib/traits.js.map +0 -1
  129. package/src/client.ts +0 -1177
  130. package/src/schemas.ts +0 -128
  131. package/src/sensitive.ts +0 -119
  132. package/src/traits.ts +0 -996
@@ -0,0 +1,691 @@
1
+ /**
2
+ * The generic smithy→SDK service generator (dev-time only).
3
+ *
4
+ * One driver compiles a Smithy JSON model into an Effect SDK service module.
5
+ * Everything provider-specific arrives through {@link SdkSpec}: import
6
+ * header, trait vocabulary (which trait ids mean payload/file/nullable/…),
7
+ * the `T.*` pipe expressions to emit for each binding, how operations are
8
+ * declared (protocol/retry/error names), and naming policies. The driver
9
+ * owns the pipeline: operation discovery, reachability, topological order,
10
+ * schema/interface emission, error classes, pagination validation, and
11
+ * operation consts.
12
+ *
13
+ * A provider's `scripts/generate.ts` reduces to: load models (its own
14
+ * pipeline — docs-derived specs, patches, …), define its {@link SdkSpec},
15
+ * call {@link generateService} per model, write files.
16
+ */
17
+ import { camel as _camel, local, lowerFirst, oneLine, q, tsKey, upperFirst, } from "./naming.js";
18
+ import { orderIndex, reachableFrom, shapeDeps, topoOrder, } from "./graph.js";
19
+ import { enumDecl, errorClass, errorUnionAlias, interfaceDecl, interfaceField, operationConst, PURE, suspendConst, } from "./emit.js";
20
+ import { JSON_PRELUDE, makeSchemaRef, makeTsRef, TS_JSON_PRELUDE, } from "./prelude.js";
21
+ import { collectOperations, collectOpErrorIds, ensureNamedIo, modelNamespace, } from "./operations.js";
22
+ import { memberBases, smithyWireName } from "./members.js";
23
+ import { validatePaginated } from "./pagination.js";
24
+ const PAGINATED_TRAIT = "smithy.api#paginated";
25
+ /**
26
+ * Error categories, derived from the STANDARD Smithy error traits.
27
+ *
28
+ * `smithy.api#httpError` and `smithy.api#retryable` are how every Smithy
29
+ * model — AWS's included — says what kind of failure an error is. The
30
+ * categories the runtime acts on (`core/category.ts`, and `isTransientError`
31
+ * in `core/retry.ts`) are a reading of those two traits, so the reading
32
+ * belongs here, once, for every provider.
33
+ *
34
+ * A model that wants its errors classified states the status the API
35
+ * actually returns:
36
+ *
37
+ * "traits": { "smithy.api#error": "client", "smithy.api#httpError": 404 }
38
+ *
39
+ * and the error class is emitted with `.pipe(C.withNotFoundError)`. A model
40
+ * with no `httpError` gets no categories — the same as today.
41
+ */
42
+ export const errorCategories = (traits,
43
+ /** Categories a provider knows that the traits don't say (AWS's spec file). */
44
+ extra = []) => {
45
+ const categories = [];
46
+ const add = (name) => {
47
+ if (!categories.includes(name))
48
+ categories.push(name);
49
+ };
50
+ const status = traits?.["smithy.api#httpError"];
51
+ if (typeof status === "number") {
52
+ if (status === 401 || status === 403)
53
+ add("AuthError");
54
+ else if (status === 402)
55
+ add("QuotaError");
56
+ else if (status === 400 ||
57
+ status === 404 ||
58
+ status === 405 ||
59
+ status === 406 ||
60
+ status === 410 ||
61
+ status === 413 ||
62
+ status === 415 ||
63
+ status === 422) {
64
+ add("BadRequestError");
65
+ }
66
+ else if (status === 408 || status === 504)
67
+ add("TimeoutError");
68
+ else if (status === 409)
69
+ add("ConflictError");
70
+ else if (status === 429)
71
+ add("ThrottlingError");
72
+ else if (status >= 500 && status < 600)
73
+ add("ServerError");
74
+ }
75
+ const retryable = traits?.["smithy.api#retryable"];
76
+ if (retryable !== undefined) {
77
+ add("RetryableError");
78
+ if (retryable?.throttling)
79
+ add("ThrottlingError");
80
+ }
81
+ for (const name of extra)
82
+ add(name);
83
+ return categories;
84
+ };
85
+ /** `["NotFoundError"]` → `C.withNotFoundError`. */
86
+ const categoryPipes = (traits) => errorCategories(traits).map((name) => `C.with${name}`);
87
+ /** Compile one Smithy model into a service module. */
88
+ export const generateService = (model, spec) => {
89
+ const shapes = model.shapes;
90
+ const pure = spec.pure ?? PURE;
91
+ const prelude = spec.prelude ?? JSON_PRELUDE;
92
+ const tsPrelude = spec.tsPrelude ?? TS_JSON_PRELUDE;
93
+ const memberName = spec.memberName ?? ((n) => n);
94
+ const opExportName = spec.opExportName ?? lowerFirst;
95
+ // 1. Operations — synthesize named Request/Response for Unit I/O so every
96
+ // operation has an input shape that can carry operation-level traits.
97
+ const operations = collectOperations(shapes);
98
+ const httpFor = {}; // input shape id → http trait
99
+ const ns = modelNamespace(operations, shapes, spec.namespaceFallback ?? "smithy.unknown");
100
+ const selected = [];
101
+ for (const op of operations) {
102
+ selected.push(op);
103
+ const { input, output } = ensureNamedIo(shapes, op, ns);
104
+ op.def.__input = input;
105
+ op.def.__output = output;
106
+ const http = op.def.traits?.["smithy.api#http"];
107
+ if (http)
108
+ httpFor[input] = http;
109
+ }
110
+ if (selected.length === 0)
111
+ return { code: "", operations: 0 };
112
+ // 2. Reachability + dependencies-first order (cycles suspend at refs).
113
+ const roots = [
114
+ ...selected.flatMap((op) => [op.def.__input, op.def.__output]),
115
+ ...(spec.extraRoots?.(selected, shapes) ?? []),
116
+ ];
117
+ const reachable = reachableFrom(shapes, roots, shapeDeps);
118
+ const order = topoOrder(shapes, reachable, shapeDeps);
119
+ const indexOf = orderIndex(order);
120
+ const ref = makeSchemaRef(prelude, indexOf);
121
+ const tsRef = makeTsRef(tsPrelude);
122
+ // Direction classification for enum openness. Enum ALIASES are emitted
123
+ // CLOSED (exhaustively matchable on reads); request-reachable shapes
124
+ // re-open enum references inline (`X | (string & {})`) so consumers can
125
+ // send tomorrow's values without an SDK update.
126
+ const requestReachable = reachableFrom(shapes, selected.map((op) => op.def.__input), shapeDeps);
127
+ // Discriminant enums: single-value enums required by a union-arm
128
+ // structure (e.g. the worker binding `type: "ai"` literals). These stay
129
+ // CLOSED even on the request side — consumers and the union's TS
130
+ // narrowing rely on the exact literal (v0 parity).
131
+ const discriminantEnums = new Set();
132
+ for (const d of Object.values(shapes)) {
133
+ if (d?.type !== "union")
134
+ continue;
135
+ for (const um of Object.values(d.members ?? {})) {
136
+ const arm = shapes[um.target];
137
+ if (arm?.type !== "structure")
138
+ continue;
139
+ for (const am of Object.values(arm.members ?? {})) {
140
+ const t = shapes[am.target];
141
+ if ((t?.type === "enum" || t?.type === "intEnum") &&
142
+ Object.keys(t.members ?? {}).length === 1 &&
143
+ am.traits?.["smithy.api#required"] !== undefined) {
144
+ discriminantEnums.add(am.target);
145
+ }
146
+ }
147
+ }
148
+ }
149
+ /**
150
+ * TS reference with direction-aware enum openness. Any reference inside a
151
+ * request-reachable shape re-opens the enum inline — including shapes
152
+ * shared with responses (a value you can SEND must accept undocumented
153
+ * members, and response runtime is open regardless). References inside
154
+ * pure response/error shapes stay the plain closed alias, and so do
155
+ * union-arm discriminant literals.
156
+ */
157
+ const tsRefAt = (target, ownerId) => {
158
+ const base = tsRef(target);
159
+ if (!requestReachable.has(ownerId))
160
+ return base;
161
+ if (discriminantEnums.has(target))
162
+ return base;
163
+ const d = shapes[target];
164
+ if (d?.type === "enum")
165
+ return `${base} | (string & {})`;
166
+ if (d?.type === "intEnum")
167
+ return `${base} | (number & {})`;
168
+ return base;
169
+ };
170
+ const wireKind = spec.wireKind ??
171
+ ((b) => b === "label"
172
+ ? "label"
173
+ : b === "query"
174
+ ? "query"
175
+ : b === "header"
176
+ ? "header"
177
+ : "other");
178
+ // The generic binding cascade; provider bindings slot in after headers.
179
+ const extraBindingOf = (traits) => {
180
+ for (const b of spec.extraBindings ?? []) {
181
+ if (b.trait in traits)
182
+ return b.binding;
183
+ }
184
+ return undefined;
185
+ };
186
+ const bindingOf = (traits) => "smithy.api#httpLabel" in traits
187
+ ? "label"
188
+ : "smithy.api#httpQuery" in traits
189
+ ? "query"
190
+ : "smithy.api#httpHeader" in traits
191
+ ? "header"
192
+ : (extraBindingOf(traits) ??
193
+ ("smithy.api#httpPayload" in traits ? "rawBody" : "body"));
194
+ // Shapes reachable from any response/error root — used to scope the
195
+ // blanket-nullable-optionals rule to reads (the wire returns explicit
196
+ // nulls; requests only accept null where a nullable trait says so).
197
+ const responseReachable = spec.optionalsNullable === true
198
+ ? reachableFrom(shapes, [
199
+ ...selected.map((op) => op.def.__output),
200
+ ...collectOpErrorIds(selected, shapes),
201
+ ], shapeDeps)
202
+ : undefined;
203
+ const memberInfos = (d, ownerId) => memberBases(d, memberName).map((base) => {
204
+ const traits = base.traits;
205
+ const binding = bindingOf(traits);
206
+ return {
207
+ ...base,
208
+ binding,
209
+ wire: smithyWireName(traits, base.name, wireKind(binding)),
210
+ nullable: (spec.nullableTrait ? spec.nullableTrait in traits : false) ||
211
+ // Blanket-nullable optionals (v0 surface): every optional BODY
212
+ // member of a response-reachable shape accepts/announces null
213
+ // in addition to being omittable.
214
+ (responseReachable !== undefined &&
215
+ ownerId !== undefined &&
216
+ responseReachable.has(ownerId) &&
217
+ !base.required &&
218
+ binding === "body"),
219
+ };
220
+ });
221
+ // Generic pipes for the smithy bindings (the SDK's traits module exports
222
+ // core's Label/Query/Header/HttpBody/Body builders under these names);
223
+ // provider bindings and member traits append theirs via memberExtraPipes.
224
+ const genericPipes = (info) => {
225
+ switch (info.binding) {
226
+ case "label":
227
+ return [
228
+ info.wire === info.tsName ? "T.Label()" : `T.Label(${q(info.wire)})`,
229
+ ];
230
+ case "query":
231
+ return [
232
+ info.wire === info.tsName ? "T.Query()" : `T.Query(${q(info.wire)})`,
233
+ ];
234
+ case "header":
235
+ return [
236
+ info.wire === info.tsName
237
+ ? "T.Header()"
238
+ : `T.Header(${q(info.wire)})`,
239
+ ];
240
+ case "rawBody":
241
+ return ["T.HttpBody()"];
242
+ case "body":
243
+ return info.wire !== info.tsName ? [`T.Body(${q(info.wire)})`] : [];
244
+ default:
245
+ return [];
246
+ }
247
+ };
248
+ const memberPipes = spec.memberPipes ??
249
+ ((info) => [
250
+ ...genericPipes(info),
251
+ // The binding table's pipe (envelope payloads, file uploads, …).
252
+ ...(spec.extraBindings ?? [])
253
+ .filter((b) => b.binding === info.binding && b.trait in info.traits)
254
+ .map((b) => b.pipe),
255
+ // Trait-table pipes: trait value JSON-inlined as the argument.
256
+ ...Object.entries(spec.memberTraitPipes ?? {})
257
+ .filter(([trait]) => info.traits[trait] !== undefined)
258
+ .map(([trait, builder]) => `${builder}(${JSON.stringify(info.traits[trait])})`),
259
+ ...(spec.memberExtraPipes?.(info) ?? []),
260
+ ]);
261
+ const memberTsTypeOf = (info, tsRefFn) => spec.memberTsType?.(info, tsRefFn) ??
262
+ (spec.extraBindings ?? []).find((b) => b.binding === info.binding && b.tsType !== undefined)?.tsType;
263
+ const emitMember = (info, selfIdx) => {
264
+ let expr = ref(info.target, selfIdx);
265
+ if (info.nullable)
266
+ expr = `S.NullOr(${expr})`;
267
+ const pipes = memberPipes(info);
268
+ if (pipes.length)
269
+ expr = `${expr}.pipe(${pipes.join(", ")})`;
270
+ if (!info.required)
271
+ expr = `S.optional(${expr})`;
272
+ return ` ${q(info.tsName)}: ${expr},`;
273
+ };
274
+ const opIoShapes = new Set();
275
+ for (const op of selected) {
276
+ opIoShapes.add(op.def.__input);
277
+ opIoShapes.add(op.def.__output);
278
+ }
279
+ // 3. Validate pagination traits: a paginated op must actually carry its
280
+ // token on the input and its items member on the output, else it
281
+ // degrades to a plain operation.
282
+ const paginatedOutputs = new Set();
283
+ const paginatedItemsRoot = new Map();
284
+ /** Op id → its full (possibly dotted) items path, `""` when it has none. */
285
+ const paginatedItemsPath = new Map();
286
+ /** Output shape id → the pagination profile that decodes it. */
287
+ const outputProfile = new Map();
288
+ /** Op id → its pagination profile (drives protocol/strategy emission). */
289
+ const opProfile = new Map();
290
+ const usedProfiles = new Set();
291
+ const profileNames = Object.keys(spec.paginationProfiles ?? {});
292
+ if (profileNames.length > 0) {
293
+ for (const op of selected) {
294
+ const pg = op.def.traits?.[PAGINATED_TRAIT];
295
+ if (!pg)
296
+ continue;
297
+ // Which profile decodes this op's pages: the selector's answer, or
298
+ // the sole declared profile.
299
+ const profileName = spec.paginationProfileFor?.(pg, op) ??
300
+ (profileNames.length === 1 ? profileNames[0] : undefined);
301
+ const profile = profileName
302
+ ? spec.paginationProfiles[profileName]
303
+ : undefined;
304
+ if (!profile)
305
+ continue;
306
+ const inNames = new Set(memberInfos(shapes[op.def.__input] ?? {}).map((m) => m.tsName));
307
+ const outNames = new Set(memberInfos(shapes[op.def.__output] ?? {}).map((m) => m.tsName));
308
+ const { ok, itemsRoot } = validatePaginated({
309
+ trait: pg,
310
+ inputNames: inNames,
311
+ outputNames: outNames,
312
+ itemsFallback: profile.itemsFallback,
313
+ syntheticOutputs: new Set(profile.syntheticOutputs ?? []),
314
+ });
315
+ if (ok) {
316
+ op.def.__pagination = pg;
317
+ paginatedOutputs.add(op.def.__output);
318
+ paginatedItemsRoot.set(op.def.__output, itemsRoot);
319
+ paginatedItemsPath.set(op.id, String(pg.items ?? profile.itemsFallback ?? ""));
320
+ outputProfile.set(op.def.__output, profile);
321
+ opProfile.set(op.id, profile);
322
+ usedProfiles.add(profile);
323
+ }
324
+ }
325
+ }
326
+ // 4. Error classes from the operations' errors lists.
327
+ const out = [];
328
+ // Set when any error carries CATEGORY_TRAIT, so the header only imports
329
+ // the category module when something actually uses it.
330
+ let usesCategories = false;
331
+ const errorIds = collectOpErrorIds(selected, shapes);
332
+ const errorIdSet = new Set(errorIds);
333
+ const errorNames = new Set(errorIds.map(local));
334
+ const shapeDocs = spec.shapeDocs ?? true;
335
+ for (const id of errorIds) {
336
+ const d = shapes[id];
337
+ const name = local(id);
338
+ const doc = oneLine(d.traits?.["smithy.api#documentation"]);
339
+ if (doc && shapeDocs)
340
+ out.push(`/** ${doc} */`);
341
+ const overridden = spec.errors?.override?.({ id, def: d, name });
342
+ if (overridden) {
343
+ out.push(...overridden);
344
+ continue;
345
+ }
346
+ const errorField = spec.errors?.field ??
347
+ ((mn, target) => ` ${tsKey(mn)}: ${prelude[local(target)] ?? "S.Unknown"},`);
348
+ const fields = d.members && Object.keys(d.members).length
349
+ ? Object.entries(d.members).map(([mn, m]) => errorField(mn, m.target))
350
+ : (spec.errors?.defaultFields?.(prelude) ?? [
351
+ errorField("code", "smithy.api#Integer"),
352
+ errorField("message", "smithy.api#String"),
353
+ ]);
354
+ const matchers = spec.errorMatchersTrait
355
+ ? d.traits?.[spec.errorMatchersTrait]
356
+ : undefined;
357
+ const categories = categoryPipes(d.traits);
358
+ if (categories.length)
359
+ usesCategories = true;
360
+ out.push(errorClass({
361
+ name,
362
+ fields,
363
+ pipes: categories.length
364
+ ? `.pipe(${categories.join(", ")})`
365
+ : undefined,
366
+ wrap: spec.errors?.wrap?.(d.traits ?? {}) ??
367
+ (matchers
368
+ ? (cls) => `T.applyErrorMatchers(\n${cls},\n${JSON.stringify(matchers)},\n)`
369
+ : undefined),
370
+ }));
371
+ }
372
+ // 5. Every reachable shape in dependency order: explicit TS type next to
373
+ // a schema const cast to `S.Schema<T>` (the compile-perf pattern).
374
+ order.forEach((id, i) => {
375
+ if (errorIdSet.has(id))
376
+ return; // emitted as an error class above
377
+ const d = shapes[id];
378
+ const name = local(id);
379
+ const doc = oneLine(d.traits?.["smithy.api#documentation"]);
380
+ if (doc && shapeDocs)
381
+ out.push(`/** ${doc} */`);
382
+ const override = spec.shapeOverride?.({
383
+ id,
384
+ def: d,
385
+ name,
386
+ selfIdx: i,
387
+ ref,
388
+ tsRef,
389
+ members: memberInfos,
390
+ });
391
+ if (override) {
392
+ out.push(...override);
393
+ return;
394
+ }
395
+ if (d.type === "structure") {
396
+ // Bare-payload response: single trait-marked member — the response IS
397
+ // that member's value; emit its type + a root marker for the protocol.
398
+ const memberEntriesAll = Object.entries(d.members ?? {});
399
+ const soleMemberRoot = !paginatedOutputs.has(id) && memberEntriesAll.length === 1
400
+ ? (spec.extraBindings ?? []).find((b) => b.rootPipe !== undefined &&
401
+ b.trait in (memberEntriesAll[0][1].traits ?? {}))
402
+ : undefined;
403
+ if (soleMemberRoot) {
404
+ const [, m] = memberEntriesAll[0];
405
+ // Alias responses are op roots too — they must carry the service
406
+ // key dictionary so opaque content (union cases, freeform maps)
407
+ // nested in the payload decodes with the same wire mapping as
408
+ // struct-form roots.
409
+ const rootPipes = [
410
+ soleMemberRoot.rootPipe,
411
+ ...(spec.rootKeyDictionary && opIoShapes.has(id)
412
+ ? [`T.KeyDictionary(KEY_DICTIONARY)`]
413
+ : []),
414
+ ];
415
+ out.push(`export type ${name} = ${tsRef(m.target)};`);
416
+ out.push(suspendConst({
417
+ name,
418
+ pure,
419
+ multiline: true,
420
+ annotateIdentifier: true,
421
+ expr: `${ref(m.target, i)}.pipe(${rootPipes.join(", ")})`,
422
+ }));
423
+ return;
424
+ }
425
+ // Paginated outputs always deliver their items member — required.
426
+ const itemsRoot = paginatedItemsRoot.get(id);
427
+ const infos = memberInfos(d, id).map((info) => info.tsName === itemsRoot ? { ...info, required: true } : info);
428
+ const fields = infos.flatMap((info) => interfaceField({
429
+ name: info.tsName,
430
+ optional: !info.required,
431
+ doc: info.doc,
432
+ type: memberTsTypeOf(info, tsRef) ??
433
+ `${tsRefAt(info.target, id)}${info.nullable ? " | null" : ""}`,
434
+ }));
435
+ const members = infos.map((info) => emitMember(info, i));
436
+ const inject = outputProfile.get(id)?.injectOutputMember;
437
+ if (inject && !infos.some((m) => m.tsName === inject.tsName)) {
438
+ fields.push(...inject.interfaceLines);
439
+ members.push(inject.structLine);
440
+ }
441
+ out.push(interfaceDecl(name, fields));
442
+ const struct = members.length
443
+ ? `S.Struct({\n${members.join("\n")}\n})`
444
+ : `S.Struct({})`;
445
+ const structCtx = {
446
+ id,
447
+ isOpIo: opIoShapes.has(id),
448
+ httpTrait: httpFor[id],
449
+ };
450
+ const pipes = spec.structPipes?.(structCtx) ?? [
451
+ ...(structCtx.httpTrait
452
+ ? [`T.Http(${JSON.stringify(structCtx.httpTrait)})`]
453
+ : []),
454
+ ...(spec.rootKeyDictionary && structCtx.isOpIo
455
+ ? [`T.KeyDictionary(KEY_DICTIONARY)`]
456
+ : []),
457
+ ];
458
+ const tail = pipes.map((p) => `.pipe(${p})`).join("");
459
+ out.push(suspendConst({
460
+ name,
461
+ pure,
462
+ multiline: true,
463
+ annotateIdentifier: true,
464
+ expr: `${struct}${tail}`,
465
+ }));
466
+ }
467
+ else if (d.type === "list") {
468
+ out.push(`export type ${name} = Array<${tsRefAt(d.member.target, id)}>;`);
469
+ out.push(`export const ${name} = ${pure}S.Array(${ref(d.member.target, i)}) as any as S.Schema<${name}>;\n`);
470
+ }
471
+ else if (d.type === "map") {
472
+ out.push(`export type ${name} = { [key: string]: ${tsRefAt(d.value.target, id)} | undefined };`);
473
+ out.push(`export const ${name} = ${pure}S.Record(S.String, ${ref(d.value.target, i)}) as any as S.Schema<${name}>;\n`);
474
+ }
475
+ else if (d.type === "union") {
476
+ // A union arm targeting the union itself carries no information
477
+ // (`type X = X | A | B` ≡ `A | B`) and is an illegal circular type
478
+ // alias. Specs produce them: atlas's OnlineArchiveSchedule is a
479
+ // discriminated oneOf whose DEFAULT arm is `allOf: [$ref <the union
480
+ // itself>]`, so the arm resolves back to its own parent.
481
+ const caseTargets = Object.values(d.members ?? {})
482
+ .map((m) => m.target)
483
+ .filter((t) => t !== id);
484
+ const caseKeys = caseTargets.map((t) => {
485
+ const cd = shapes[t];
486
+ return cd?.type === "structure"
487
+ ? memberInfos(cd).map((mi) => mi.tsName)
488
+ : [];
489
+ });
490
+ if (spec.union) {
491
+ out.push(...spec.union({ name, caseTargets, caseKeys, tsRef }));
492
+ }
493
+ else if (spec.unionStyle === "opaque-cases") {
494
+ 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)}));\n`);
495
+ }
496
+ else {
497
+ throw new Error(`no union emission configured for shape ${id} — set unionStyle or union`);
498
+ }
499
+ }
500
+ else if (d.type === "enum") {
501
+ const values = Object.values(d.members ?? {})
502
+ .map((m) => m.traits?.["smithy.api#enumValue"])
503
+ .filter((v) => typeof v === "string");
504
+ out.push(...enumDecl({ name, values, pure }));
505
+ }
506
+ else if (d.type === "intEnum") {
507
+ // CLOSED numeric literal union alias (`type Y = 1 | 30`); INPUT
508
+ // references re-open it inline (`Y | (number & {})`). Schema stays
509
+ // S.Number (protocols never validate enum membership).
510
+ const values = Object.values(d.members ?? {})
511
+ .map((m) => m.traits?.["smithy.api#enumValue"])
512
+ .filter((v) => typeof v === "number");
513
+ const union = values.length ? values.join(" | ") : "number";
514
+ out.push(`export type ${name} = ${union};`, `export const ${name} = ${pure}S.Number;\n`);
515
+ }
516
+ });
517
+ // 6. Operations — declarative emission from the names in operationDecl,
518
+ // unless the provider overrides the whole shape.
519
+ /**
520
+ * The element type `.items()` yields, resolved from the pagination
521
+ * trait's items PATH against the response shape.
522
+ *
523
+ * `makePaginated` can't infer this — the path is a runtime string — and
524
+ * the structural `API.PaginatedItem` fallback only recognizes bare arrays
525
+ * and `{ result: […] }` envelopes, so every other envelope degrades to
526
+ * `unknown` (distilled #302). Resolving it here and passing it as an
527
+ * explicit type argument is what makes `.items()` typed.
528
+ *
529
+ * Returns undefined when the path doesn't lead to a list, which leaves
530
+ * the annotation on the structural fallback rather than asserting a type
531
+ * the shape doesn't support.
532
+ */
533
+ const paginatedItemTsType = (outputId, itemsPath) => {
534
+ // No items path: `.items()` is a page passthrough at runtime, so an
535
+ // item IS a whole response.
536
+ if (!itemsPath)
537
+ return tsRef(outputId);
538
+ let def = shapes[outputId];
539
+ for (const segment of itemsPath.split(".")) {
540
+ if (def?.type !== "structure")
541
+ return undefined;
542
+ const info = memberInfos(def).find((m) => m.tsName === segment);
543
+ if (!info)
544
+ return undefined;
545
+ def = shapes[info.target];
546
+ }
547
+ return def?.type === "list" ? tsRef(def.member.target) : undefined;
548
+ };
549
+ const emitOperation = spec.operation ??
550
+ ((ctx) => {
551
+ const decl = spec.operationDecl;
552
+ if (!decl) {
553
+ throw new Error("SdkSpec needs either operationDecl or operation");
554
+ }
555
+ const errList = [...ctx.errorNames, ...decl.commonErrorClasses];
556
+ const paginated = ctx.pagination !== undefined;
557
+ const itemTsType = paginated
558
+ ? paginatedItemTsType(ctx.op.def.__output, paginatedItemsPath.get(ctx.op.id) ?? "")
559
+ : undefined;
560
+ const typeAnnotation = `API.${paginated ? "PaginatedOperationMethod" : "OperationMethod"}<\n` +
561
+ ` ${ctx.inputName},\n` +
562
+ ` ${ctx.outputTsType},\n` +
563
+ ` ${ctx.opName}Error,\n` +
564
+ ` ${decl.contextType}` +
565
+ (itemTsType ? `,\n ${itemTsType}\n` : `\n`) +
566
+ `>`;
567
+ const config = `{\n` +
568
+ ` input: ${ctx.inputName},\n` +
569
+ ` output: ${ctx.outputSchema},\n` +
570
+ ` errors: [${errList.join(", ")}],\n` +
571
+ ` protocol: ${(paginated && opProfile.get(ctx.op.id)?.protocol) || decl.protocol},\n` +
572
+ ` retry: ${decl.retry},\n` +
573
+ (decl.extraConfig?.(ctx) ?? []).map((l) => ` ${l},\n`).join("") +
574
+ (paginated
575
+ ? ` pagination: ${JSON.stringify(ctx.pagination)} as const,\n`
576
+ : "") +
577
+ `}`;
578
+ return [
579
+ errorUnionAlias(ctx.opName, ctx.errorNames, decl.commonErrorType),
580
+ ...(ctx.doc ? [`/** ${ctx.doc} */`] : []),
581
+ operationConst({
582
+ exportName: ctx.exportName,
583
+ typeAnnotation,
584
+ factory: paginated ? "API.makePaginated" : "API.make",
585
+ pure,
586
+ extraArg: paginated ? opProfile.get(ctx.op.id)?.strategy : undefined,
587
+ config,
588
+ // `makePaginated` infers the items element from the structural
589
+ // fallback; an explicit item type needs the same `as any as`
590
+ // idiom the schema consts use.
591
+ castToAnnotation: itemTsType !== undefined,
592
+ }),
593
+ ].join("\n");
594
+ });
595
+ for (const op of selected) {
596
+ const opName = local(op.id);
597
+ const errNames = (op.def.errors ?? [])
598
+ .map((e) => local(e.target))
599
+ .filter((n) => errorNames.has(n));
600
+ out.push(emitOperation({
601
+ op,
602
+ opName,
603
+ exportName: opExportName(opName),
604
+ inputName: local(op.def.__input),
605
+ outputName: local(op.def.__output),
606
+ outputTsType: tsRef(op.def.__output),
607
+ outputSchema: ref(op.def.__output, indexOf.size),
608
+ errorNames: errNames,
609
+ doc: oneLine(op.def.traits?.["smithy.api#documentation"]),
610
+ pagination: op.def.__pagination,
611
+ }));
612
+ }
613
+ // 7. Alias re-exports, then provider trailing sections.
614
+ const emittedOps = new Set(selected.map((op) => opExportName(local(op.id))));
615
+ for (const { alias, target } of spec.opAliases ?? []) {
616
+ if (!emittedOps.has(target) || emittedOps.has(alias))
617
+ continue;
618
+ emittedOps.add(alias);
619
+ const A = upperFirst(alias);
620
+ const T2 = upperFirst(target);
621
+ out.push(`// Alias of ${target} (same route, alternate export name upstream).\n` +
622
+ `export const ${alias} = ${target};\n` +
623
+ `export type ${A}Request = ${T2}Request;\n` +
624
+ `export type ${A}Response = ${T2}Response;\n` +
625
+ `export type ${A}Error = ${T2}Error;\n`);
626
+ }
627
+ if (spec.footer) {
628
+ out.push(...spec.footer({ emittedOps }));
629
+ }
630
+ // Default header: banner + imports derived from operationDecl names and
631
+ // the conventional SDK module layout, op error/context type re-exports,
632
+ // and the KEY_DICTIONARY const when configured.
633
+ const defaultHeader = (ctx) => {
634
+ const decl = spec.operationDecl;
635
+ if (!decl) {
636
+ throw new Error("the default header needs operationDecl — or pass header");
637
+ }
638
+ const retryNs = decl.retry.split(".")[0];
639
+ // Imports the used pagination profiles pull in: their protocol consts
640
+ // (from the protocol module) and strategy/injected-member names (from
641
+ // the pagination module).
642
+ const profileProtocols = [
643
+ ...new Set([...usedProfiles]
644
+ .map((p) => p.protocol)
645
+ .filter((p) => p !== undefined && p !== decl.protocol)),
646
+ ];
647
+ const pagImports = [
648
+ ...new Set([...usedProfiles].flatMap((p) => [
649
+ ...(p.strategy ? [p.strategy] : []),
650
+ ...(p.injectOutputMember?.imports ?? []),
651
+ ])),
652
+ ];
653
+ return (`// AUTO-GENERATED by scripts/generate.ts${spec.sourceNote ? ` from ${spec.sourceNote}` : ""}. Do not edit.\n` +
654
+ `import * as S from "@distilled.cloud/core/schema";\n` +
655
+ `import * as API from "@distilled.cloud/core/api";\n` +
656
+ (usesCategories
657
+ ? `import * as C from "@distilled.cloud/core/category";\n`
658
+ : "") +
659
+ `import * as T from "../traits.ts";\n` +
660
+ `import {\n` +
661
+ ` ${decl.protocol},\n` +
662
+ profileProtocols.map((p) => ` ${p},\n`).join("") +
663
+ ` type ${decl.commonErrorType},\n` +
664
+ ` type ${decl.contextType},\n` +
665
+ `} from "../protocol.ts";\n` +
666
+ (ctx.hasPaginated && pagImports.length
667
+ ? `import { ${pagImports.join(", ")} } from "../pagination.ts";\n`
668
+ : "") +
669
+ `import { ${[...decl.commonErrorClasses].sort().join(", ")} } from "../errors.ts";\n` +
670
+ `import * as ${retryNs} from "../retry.ts";\n\n` +
671
+ // Re-exported so inferred provider types downstream can always name them.
672
+ `export type { ${decl.commonErrorType}, ${decl.contextType} };\n\n` +
673
+ (spec.rootKeyDictionary
674
+ ? `/** ${spec.rootKeyDictionary.doc} */\n` +
675
+ `const KEY_DICTIONARY: Record<string, string | ReadonlyArray<string>> = ${JSON.stringify(spec.rootKeyDictionary.dict)};\n\n`
676
+ : ""));
677
+ };
678
+ const header = (spec.header ?? defaultHeader)({
679
+ hasPaginated: paginatedOutputs.size > 0,
680
+ model,
681
+ });
682
+ const code = header + out.join("\n") + "\n";
683
+ return {
684
+ code: spec.postProcess?.(code) ?? code,
685
+ operations: selected.length,
686
+ };
687
+ };
688
+ // Re-exported so provider specs can be written against the same helpers the
689
+ // driver uses, without importing every codegen module individually.
690
+ export { errorUnionAlias, operationConst, upperFirst, tsKey, q, local };
691
+ //# sourceMappingURL=generator.js.map