@distilled.cloud/core 0.30.3 → 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,1153 @@
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 {
18
+ camel as _camel,
19
+ local,
20
+ lowerFirst,
21
+ oneLine,
22
+ q,
23
+ tsKey,
24
+ upperFirst,
25
+ } from "./naming.ts";
26
+ import {
27
+ orderIndex,
28
+ reachableFrom,
29
+ shapeDeps,
30
+ topoOrder,
31
+ type ShapeMap,
32
+ } from "./graph.ts";
33
+ import {
34
+ enumDecl,
35
+ errorClass,
36
+ errorUnionAlias,
37
+ interfaceDecl,
38
+ interfaceField,
39
+ operationConst,
40
+ PURE,
41
+ suspendConst,
42
+ } from "./emit.ts";
43
+ import {
44
+ JSON_PRELUDE,
45
+ makeSchemaRef,
46
+ makeTsRef,
47
+ TS_JSON_PRELUDE,
48
+ } from "./prelude.ts";
49
+ import {
50
+ collectOperations,
51
+ collectOpErrorIds,
52
+ ensureNamedIo,
53
+ modelNamespace,
54
+ type OpEntry,
55
+ } from "./operations.ts";
56
+ import { memberBases, smithyWireName } from "./members.ts";
57
+ import { validatePaginated } from "./pagination.ts";
58
+
59
+ const PAGINATED_TRAIT = "smithy.api#paginated";
60
+
61
+ /**
62
+ * Error categories, derived from the STANDARD Smithy error traits.
63
+ *
64
+ * `smithy.api#httpError` and `smithy.api#retryable` are how every Smithy
65
+ * model — AWS's included — says what kind of failure an error is. The
66
+ * categories the runtime acts on (`core/category.ts`, and `isTransientError`
67
+ * in `core/retry.ts`) are a reading of those two traits, so the reading
68
+ * belongs here, once, for every provider.
69
+ *
70
+ * A model that wants its errors classified states the status the API
71
+ * actually returns:
72
+ *
73
+ * "traits": { "smithy.api#error": "client", "smithy.api#httpError": 404 }
74
+ *
75
+ * and the error class is emitted with `.pipe(C.withNotFoundError)`. A model
76
+ * with no `httpError` gets no categories — the same as today.
77
+ */
78
+ export const errorCategories = (
79
+ traits: Record<string, any> | undefined,
80
+ /** Categories a provider knows that the traits don't say (AWS's spec file). */
81
+ extra: readonly string[] = [],
82
+ ): string[] => {
83
+ const categories: string[] = [];
84
+ const add = (name: string) => {
85
+ if (!categories.includes(name)) categories.push(name);
86
+ };
87
+ const status = traits?.["smithy.api#httpError"] as number | undefined;
88
+ if (typeof status === "number") {
89
+ if (status === 401 || status === 403) add("AuthError");
90
+ else if (status === 402) add("QuotaError");
91
+ else if (
92
+ status === 400 ||
93
+ status === 404 ||
94
+ status === 405 ||
95
+ status === 406 ||
96
+ status === 410 ||
97
+ status === 413 ||
98
+ status === 415 ||
99
+ status === 422
100
+ ) {
101
+ add("BadRequestError");
102
+ } else if (status === 408 || status === 504) add("TimeoutError");
103
+ else if (status === 409) add("ConflictError");
104
+ else if (status === 429) add("ThrottlingError");
105
+ else if (status >= 500 && status < 600) add("ServerError");
106
+ }
107
+ const retryable = traits?.["smithy.api#retryable"];
108
+ if (retryable !== undefined) {
109
+ add("RetryableError");
110
+ if (retryable?.throttling) add("ThrottlingError");
111
+ }
112
+ for (const name of extra) add(name);
113
+ return categories;
114
+ };
115
+
116
+ /** `["NotFoundError"]` → `C.withNotFoundError`. */
117
+ const categoryPipes = (traits: Record<string, any> | undefined): string[] =>
118
+ errorCategories(traits).map((name) => `C.with${name}`);
119
+
120
+ /** A member's resolved binding. The four generic kinds plus provider extras. */
121
+ export type MemberBinding =
122
+ | "label"
123
+ | "query"
124
+ | "header"
125
+ | "body"
126
+ | (string & {});
127
+
128
+ export interface EmittedMember {
129
+ readonly name: string;
130
+ readonly tsName: string;
131
+ readonly wire: string;
132
+ readonly target: string;
133
+ readonly binding: MemberBinding;
134
+ readonly required: boolean;
135
+ readonly nullable: boolean;
136
+ readonly doc: string | undefined;
137
+ readonly traits: Record<string, any>;
138
+ }
139
+
140
+ export interface PaginationProfile {
141
+ /** Protocol const for paginated ops. Defaults to operationDecl.protocol. */
142
+ readonly protocol?: string;
143
+ /** Strategy expression passed as makePaginated's second argument. */
144
+ readonly strategy?: string;
145
+ /** Items path fallback when the trait omits `items`. */
146
+ readonly itemsFallback: string;
147
+ /** Output names accepted even when not modeled (delivered by the protocol). */
148
+ readonly syntheticOutputs?: readonly string[];
149
+ /**
150
+ * Extra interface field + struct member appended to paginated outputs
151
+ * that don't already model them (what the protocol delivers beyond the
152
+ * modeled shape — e.g. cloudflare's `resultInfo` from the envelope's
153
+ * `result_info`). `imports` are pulled from the pagination module in the
154
+ * header.
155
+ */
156
+ readonly injectOutputMember?: {
157
+ readonly tsName: string;
158
+ readonly interfaceLines: readonly string[];
159
+ readonly structLine: string;
160
+ readonly imports?: readonly string[];
161
+ };
162
+ }
163
+
164
+ export interface OperationEmit {
165
+ readonly op: OpEntry;
166
+ readonly opName: string;
167
+ readonly exportName: string;
168
+ readonly inputName: string;
169
+ readonly outputName: string;
170
+ /**
171
+ * The output as a TS type and as a schema expression. These differ from
172
+ * {@link outputName} when the operation's output IS a prelude shape
173
+ * (e.g. stripe's freeform `smithy.api#Document` responses): the bare
174
+ * local name isn't declared in the module, so it must resolve through
175
+ * the prelude maps (`unknown` / `S.Unknown`) instead.
176
+ */
177
+ readonly outputTsType: string;
178
+ readonly outputSchema: string;
179
+ /** Declared error class names present in the model. */
180
+ readonly errorNames: readonly string[];
181
+ readonly doc: string | undefined;
182
+ /** The validated pagination trait, when the op paginates. */
183
+ readonly pagination: unknown | undefined;
184
+ }
185
+
186
+ export interface SdkSpec {
187
+ /** Namespace fallback for models with no operations. Default `"smithy.unknown"`. */
188
+ readonly namespaceFallback?: string;
189
+ /** PURE marker before schema consts. Default: the shared single marker. */
190
+ readonly pure?: string;
191
+ /** Prelude scalar → schema expression map. Default {@link JSON_PRELUDE}. */
192
+ readonly prelude?: Record<string, string>;
193
+ /** Prelude scalar → TS type map. Default {@link TS_JSON_PRELUDE}. */
194
+ readonly tsPrelude?: Record<string, string>;
195
+ /** Wire member name → TS-facing name. Default: identity. */
196
+ readonly memberName?: (name: string) => string;
197
+ /** Operation shape name → exported const name. Default: lowerFirst. */
198
+ readonly opExportName?: (name: string) => string;
199
+ /**
200
+ * Emit the one-line smithy doc comment above shapes and error classes.
201
+ * Default true. AWS turns this off — its models carry multi-kilobyte HTML
202
+ * docs per shape and the SDK only surfaces operation-level docs.
203
+ */
204
+ readonly shapeDocs?: boolean;
205
+ /**
206
+ * Extra reachability roots beyond the operations' I/O shapes. AWS seeds
207
+ * the error shapes here so their member targets are emitted (error class
208
+ * fields reference schema consts); the error shapes themselves are still
209
+ * emitted as error classes, not schemas.
210
+ */
211
+ readonly extraRoots?: (
212
+ selected: readonly OpEntry[],
213
+ shapes: ShapeMap,
214
+ ) => Iterable<string>;
215
+
216
+ /**
217
+ * Provider member bindings as data, checked in order between the generic
218
+ * header binding and `smithy.api#httpPayload`. The driver's cascade:
219
+ * label → query → header → extraBindings → rawBody (httpPayload) → body.
220
+ *
221
+ * `pipe` is emitted for the member; `tsType` overrides its interface
222
+ * type (e.g. file uploads → `(File | Blob)[]`).
223
+ */
224
+ readonly extraBindings?: ReadonlyArray<{
225
+ readonly trait: string;
226
+ readonly binding: MemberBinding;
227
+ readonly pipe: string;
228
+ readonly tsType?: string;
229
+ /**
230
+ * Bare-payload form: when this binding is the sole member of a
231
+ * (non-paginated) output structure, the whole response IS that
232
+ * member's value — the driver emits the member's type directly and
233
+ * pipes the schema through this root marker for the protocol.
234
+ */
235
+ readonly rootPipe?: string;
236
+ }>;
237
+ /**
238
+ * Which wire-name rule a binding follows. Defaults: the three generic
239
+ * kinds map to themselves, everything else to `"other"` (jsonName).
240
+ */
241
+ readonly wireKind?: (
242
+ binding: MemberBinding,
243
+ ) => "label" | "query" | "header" | "other";
244
+ /** Trait id marking a member nullable (`S.NullOr` + `| null`). */
245
+ readonly nullableTrait?: string;
246
+ /**
247
+ * Blanket-nullable optionals: every optional body member types and
248
+ * decodes as `X | null` in addition to being omittable (`?: X | null`,
249
+ * `S.optional(S.NullOr(X))`). The cloudflare docs pipeline sets this —
250
+ * the v4 API freely returns explicit nulls for absent optional fields,
251
+ * and the v0 SDK surface modeled every optional that way.
252
+ */
253
+ readonly optionalsNullable?: boolean;
254
+ /**
255
+ * Member traits emitted as pipes when present: trait id → pipe builder
256
+ * name in the SDK's traits module. The trait's value is JSON-inlined as
257
+ * the argument (e.g. `"…#keyDictionary": "T.KeyDictionary"` →
258
+ * `T.KeyDictionary({…})`).
259
+ */
260
+ readonly memberTraitPipes?: Readonly<Record<string, string>>;
261
+ /**
262
+ * Extra schema pipes appended after the generic ones, for anything the
263
+ * data tables can't express. The driver emits `T.Label/T.Query/T.Header`
264
+ * (wire-aware), `T.HttpBody()` for rawBody, and `T.Body(wire)` renames —
265
+ * the SDK's traits module must export those core builders under these
266
+ * names.
267
+ */
268
+ readonly memberExtraPipes?: (m: EmittedMember) => string[];
269
+ /** Full override of member pipe emission (rarely needed). */
270
+ readonly memberPipes?: (m: EmittedMember) => string[];
271
+ /** Function override for member TS types beyond the binding table. */
272
+ readonly memberTsType?: (
273
+ m: EmittedMember,
274
+ tsRef: (target: string) => string,
275
+ ) => string | undefined;
276
+
277
+ /**
278
+ * Struct-level pipes for a shape (after the member struct): the http
279
+ * trait on op inputs, service-wide key-dictionary stamping, etc.
280
+ */
281
+ readonly structPipes?: (ctx: {
282
+ readonly id: string;
283
+ readonly isOpIo: boolean;
284
+ readonly httpTrait: unknown | undefined;
285
+ }) => string[];
286
+
287
+ /**
288
+ * Pagination profiles. A profile is the codegen-side description of one
289
+ * paginated wire variant: the Protocol const that decodes it, the
290
+ * strategy passed to makePaginated, the trait-validation rules, and any
291
+ * output member the protocol delivers beyond the modeled shape. SDKs
292
+ * with several pagination styles declare several profiles and select
293
+ * per-op via {@link SdkSpec.paginationProfileFor}.
294
+ */
295
+ readonly paginationProfiles?: Readonly<Record<string, PaginationProfile>>;
296
+ /**
297
+ * Select the profile for a paginated op (from its `smithy.api#paginated`
298
+ * trait / shape). Default: the sole declared profile; with several
299
+ * profiles this becomes required for ops to paginate.
300
+ */
301
+ readonly paginationProfileFor?: (
302
+ trait: any,
303
+ op: OpEntry,
304
+ ) => string | undefined;
305
+
306
+ /**
307
+ * Service-wide fallback key dictionary stamped on op I/O roots (emitted
308
+ * as a `KEY_DICTIONARY` header const + `T.KeyDictionary(KEY_DICTIONARY)`
309
+ * root pipe). `doc` is the const's doc comment. An entry may list several
310
+ * wire spellings (first = canonical encode name; decode accepts all).
311
+ */
312
+ readonly rootKeyDictionary?: {
313
+ readonly dict: Record<string, string | ReadonlyArray<string>>;
314
+ readonly doc: string;
315
+ };
316
+
317
+ /** Banner suffix: `AUTO-GENERATED by scripts/generate.ts from <note>`. */
318
+ readonly sourceNote?: string;
319
+
320
+ /**
321
+ * Operation aliases: re-export the canonical op (and its
322
+ * Request/Response/Error types) under each alias name. Skipped when the
323
+ * target wasn't emitted or the alias name is taken.
324
+ */
325
+ readonly opAliases?: ReadonlyArray<{
326
+ readonly alias: string;
327
+ readonly target: string;
328
+ }>;
329
+
330
+ /**
331
+ * Full shape-emission override, checked before the driver's own shape
332
+ * handling. Return the emitted lines to own a shape (e.g. AWS's
333
+ * newtypes, structural unions, event streams), or undefined to let the
334
+ * driver emit it. `selfIdx` is the shape's position in emission order
335
+ * for forward-ref decisions.
336
+ */
337
+ readonly shapeOverride?: (ctx: {
338
+ readonly id: string;
339
+ readonly def: any;
340
+ readonly name: string;
341
+ readonly selfIdx: number;
342
+ readonly ref: (target: string, selfIdx: number) => string;
343
+ readonly tsRef: (target: string) => string;
344
+ readonly members: (d: any) => EmittedMember[];
345
+ }) => string[] | undefined;
346
+
347
+ /**
348
+ * Union emission style. `"opaque-cases"`: the TS type is the case union
349
+ * and the schema is `S.Unknown.pipe(T.UnionCases([...case key sets]))` —
350
+ * the protocol discriminates by key-set at decode time (for APIs that
351
+ * return every case's keys with nulls, like Cloudflare's).
352
+ */
353
+ readonly unionStyle?: "opaque-cases";
354
+ /** Full override of union emission. */
355
+ readonly union?: (ctx: {
356
+ readonly name: string;
357
+ readonly caseTargets: readonly string[];
358
+ readonly caseKeys: readonly (readonly string[])[];
359
+ readonly tsRef: (target: string) => string;
360
+ }) => string[];
361
+
362
+ /**
363
+ * Trait id carrying error matchers: when present on an error shape, the
364
+ * class is wrapped in `T.applyErrorMatchers(<cls>, <trait value>)`.
365
+ */
366
+ readonly errorMatchersTrait?: string;
367
+ /** Error-class emission details. All optional. */
368
+ readonly errors?: {
369
+ /**
370
+ * Full override of one error class's emission (mirrors shapeOverride):
371
+ * return the emitted lines to own the error, or undefined to fall back
372
+ * to the driver's field/wrap-based emission.
373
+ */
374
+ readonly override?: (ctx: {
375
+ readonly id: string;
376
+ readonly def: any;
377
+ readonly name: string;
378
+ }) => string[] | undefined;
379
+ /**
380
+ * Field lines used when the error shape declares no members.
381
+ * Default: `code` (integer) + `message` (string) — the common REST
382
+ * error envelope.
383
+ */
384
+ readonly defaultFields?: (prelude: Record<string, string>) => string[];
385
+ /** Field line for a declared member. Default: prelude-mapped schema. */
386
+ readonly field?: (name: string, target: string) => string;
387
+ /** Optional wrapper (e.g. matcher application) from the shape's traits. */
388
+ readonly wrap?: (
389
+ traits: Record<string, any>,
390
+ ) => ((cls: string) => string) | undefined;
391
+ };
392
+
393
+ /**
394
+ * Declarative operation emission — the names the op consts are built
395
+ * from. `operation` overrides this entirely when a provider needs full
396
+ * control of the emitted shape.
397
+ */
398
+ readonly operationDecl?: {
399
+ /** Requirements type in the OperationMethod annotation. */
400
+ readonly contextType: string;
401
+ /** Base of the per-op error union alias (e.g. `CloudflareOpError`). */
402
+ readonly commonErrorType: string;
403
+ /** Error classes appended to every op's `errors: [...]` list. */
404
+ readonly commonErrorClasses: readonly string[];
405
+ readonly protocol: string;
406
+ /** The retry tag expression (e.g. `Retry.Retry`). */
407
+ readonly retry: string;
408
+ /**
409
+ * Extra config lines inserted before the pagination entry (e.g. AWS's
410
+ * `operationName` and `endpointHostPrefix`).
411
+ */
412
+ readonly extraConfig?: (ctx: OperationEmit) => string[];
413
+ };
414
+ /** Full override of operation const emission. */
415
+ readonly operation?: (ctx: OperationEmit) => string;
416
+
417
+ /**
418
+ * Module header override. The default builds the banner + imports from
419
+ * {@link SdkSpec.operationDecl} names and the conventional module layout
420
+ * (`../traits.ts`, `../protocol.ts`, `../pagination.ts`, `../errors.ts`,
421
+ * `../retry.ts`), re-exports the op error/context types, and emits the
422
+ * `KEY_DICTIONARY` const when {@link SdkSpec.rootKeyDictionary} is set.
423
+ */
424
+ readonly header?: (ctx: {
425
+ readonly hasPaginated: boolean;
426
+ readonly model: any;
427
+ }) => string;
428
+
429
+ /** Final pass over the assembled module (e.g. pruning unused imports). */
430
+ readonly postProcess?: (code: string) => string;
431
+
432
+ /**
433
+ * Trailing sections after operations (e.g. route-alias re-exports).
434
+ * Receives the set of emitted op export names (mutable — additions are
435
+ * visible to subsequent alias checks).
436
+ */
437
+ readonly footer?: (ctx: { readonly emittedOps: Set<string> }) => string[];
438
+ }
439
+
440
+ export interface GeneratedService {
441
+ code: string;
442
+ operations: number;
443
+ }
444
+
445
+ /** Compile one Smithy model into a service module. */
446
+ export const generateService = (
447
+ model: any,
448
+ spec: SdkSpec,
449
+ ): GeneratedService => {
450
+ const shapes: ShapeMap = model.shapes;
451
+ const pure = spec.pure ?? PURE;
452
+ const prelude = spec.prelude ?? JSON_PRELUDE;
453
+ const tsPrelude = spec.tsPrelude ?? TS_JSON_PRELUDE;
454
+ const memberName = spec.memberName ?? ((n: string) => n);
455
+ const opExportName = spec.opExportName ?? lowerFirst;
456
+
457
+ // 1. Operations — synthesize named Request/Response for Unit I/O so every
458
+ // operation has an input shape that can carry operation-level traits.
459
+ const operations = collectOperations(shapes);
460
+ const httpFor: Record<string, any> = {}; // input shape id → http trait
461
+ const ns = modelNamespace(
462
+ operations,
463
+ shapes,
464
+ spec.namespaceFallback ?? "smithy.unknown",
465
+ );
466
+
467
+ const selected: OpEntry[] = [];
468
+ for (const op of operations) {
469
+ selected.push(op);
470
+
471
+ const { input, output } = ensureNamedIo(shapes, op, ns);
472
+ op.def.__input = input;
473
+ op.def.__output = output;
474
+
475
+ const http = op.def.traits?.["smithy.api#http"];
476
+ if (http) httpFor[input] = http;
477
+ }
478
+
479
+ if (selected.length === 0) return { code: "", operations: 0 };
480
+
481
+ // 2. Reachability + dependencies-first order (cycles suspend at refs).
482
+ const roots = [
483
+ ...selected.flatMap((op) => [op.def.__input, op.def.__output]),
484
+ ...(spec.extraRoots?.(selected, shapes) ?? []),
485
+ ];
486
+ const reachable = reachableFrom(shapes, roots, shapeDeps);
487
+ const order = topoOrder(shapes, reachable, shapeDeps);
488
+ const indexOf = orderIndex(order);
489
+
490
+ const ref = makeSchemaRef(prelude, indexOf);
491
+ const tsRef = makeTsRef(tsPrelude);
492
+
493
+ // Direction classification for enum openness. Enum ALIASES are emitted
494
+ // CLOSED (exhaustively matchable on reads); request-reachable shapes
495
+ // re-open enum references inline (`X | (string & {})`) so consumers can
496
+ // send tomorrow's values without an SDK update.
497
+ const requestReachable = reachableFrom(
498
+ shapes,
499
+ selected.map((op) => op.def.__input),
500
+ shapeDeps,
501
+ );
502
+ // Discriminant enums: single-value enums required by a union-arm
503
+ // structure (e.g. the worker binding `type: "ai"` literals). These stay
504
+ // CLOSED even on the request side — consumers and the union's TS
505
+ // narrowing rely on the exact literal (v0 parity).
506
+ const discriminantEnums = new Set<string>();
507
+ for (const d of Object.values(shapes) as any[]) {
508
+ if (d?.type !== "union") continue;
509
+ for (const um of Object.values(d.members ?? {}) as any[]) {
510
+ const arm = shapes[um.target];
511
+ if (arm?.type !== "structure") continue;
512
+ for (const am of Object.values(arm.members ?? {}) as any[]) {
513
+ const t = shapes[am.target];
514
+ if (
515
+ (t?.type === "enum" || t?.type === "intEnum") &&
516
+ Object.keys(t.members ?? {}).length === 1 &&
517
+ am.traits?.["smithy.api#required"] !== undefined
518
+ ) {
519
+ discriminantEnums.add(am.target);
520
+ }
521
+ }
522
+ }
523
+ }
524
+ /**
525
+ * TS reference with direction-aware enum openness. Any reference inside a
526
+ * request-reachable shape re-opens the enum inline — including shapes
527
+ * shared with responses (a value you can SEND must accept undocumented
528
+ * members, and response runtime is open regardless). References inside
529
+ * pure response/error shapes stay the plain closed alias, and so do
530
+ * union-arm discriminant literals.
531
+ */
532
+ const tsRefAt = (target: string, ownerId: string): string => {
533
+ const base = tsRef(target);
534
+ if (!requestReachable.has(ownerId)) return base;
535
+ if (discriminantEnums.has(target)) return base;
536
+ const d = shapes[target];
537
+ if (d?.type === "enum") return `${base} | (string & {})`;
538
+ if (d?.type === "intEnum") return `${base} | (number & {})`;
539
+ return base;
540
+ };
541
+
542
+ const wireKind =
543
+ spec.wireKind ??
544
+ ((b: MemberBinding): "label" | "query" | "header" | "other" =>
545
+ b === "label"
546
+ ? "label"
547
+ : b === "query"
548
+ ? "query"
549
+ : b === "header"
550
+ ? "header"
551
+ : "other");
552
+
553
+ // The generic binding cascade; provider bindings slot in after headers.
554
+ const extraBindingOf = (
555
+ traits: Record<string, any>,
556
+ ): MemberBinding | undefined => {
557
+ for (const b of spec.extraBindings ?? []) {
558
+ if (b.trait in traits) return b.binding;
559
+ }
560
+ return undefined;
561
+ };
562
+ const bindingOf = (traits: Record<string, any>): MemberBinding =>
563
+ "smithy.api#httpLabel" in traits
564
+ ? "label"
565
+ : "smithy.api#httpQuery" in traits
566
+ ? "query"
567
+ : "smithy.api#httpHeader" in traits
568
+ ? "header"
569
+ : (extraBindingOf(traits) ??
570
+ ("smithy.api#httpPayload" in traits ? "rawBody" : "body"));
571
+
572
+ // Shapes reachable from any response/error root — used to scope the
573
+ // blanket-nullable-optionals rule to reads (the wire returns explicit
574
+ // nulls; requests only accept null where a nullable trait says so).
575
+ const responseReachable =
576
+ spec.optionalsNullable === true
577
+ ? reachableFrom(
578
+ shapes,
579
+ [
580
+ ...selected.map((op) => op.def.__output),
581
+ ...collectOpErrorIds(selected, shapes),
582
+ ],
583
+ shapeDeps,
584
+ )
585
+ : undefined;
586
+
587
+ const memberInfos = (d: any, ownerId?: string): EmittedMember[] =>
588
+ memberBases(d, memberName).map((base) => {
589
+ const traits = base.traits;
590
+ const binding = bindingOf(traits);
591
+ return {
592
+ ...base,
593
+ binding,
594
+ wire: smithyWireName(traits, base.name, wireKind(binding)),
595
+ nullable:
596
+ (spec.nullableTrait ? spec.nullableTrait in traits : false) ||
597
+ // Blanket-nullable optionals (v0 surface): every optional BODY
598
+ // member of a response-reachable shape accepts/announces null
599
+ // in addition to being omittable.
600
+ (responseReachable !== undefined &&
601
+ ownerId !== undefined &&
602
+ responseReachable.has(ownerId) &&
603
+ !base.required &&
604
+ binding === "body"),
605
+ };
606
+ });
607
+
608
+ // Generic pipes for the smithy bindings (the SDK's traits module exports
609
+ // core's Label/Query/Header/HttpBody/Body builders under these names);
610
+ // provider bindings and member traits append theirs via memberExtraPipes.
611
+ const genericPipes = (info: EmittedMember): string[] => {
612
+ switch (info.binding) {
613
+ case "label":
614
+ return [
615
+ info.wire === info.tsName ? "T.Label()" : `T.Label(${q(info.wire)})`,
616
+ ];
617
+ case "query":
618
+ return [
619
+ info.wire === info.tsName ? "T.Query()" : `T.Query(${q(info.wire)})`,
620
+ ];
621
+ case "header":
622
+ return [
623
+ info.wire === info.tsName
624
+ ? "T.Header()"
625
+ : `T.Header(${q(info.wire)})`,
626
+ ];
627
+ case "rawBody":
628
+ return ["T.HttpBody()"];
629
+ case "body":
630
+ return info.wire !== info.tsName ? [`T.Body(${q(info.wire)})`] : [];
631
+ default:
632
+ return [];
633
+ }
634
+ };
635
+
636
+ const memberPipes =
637
+ spec.memberPipes ??
638
+ ((info: EmittedMember) => [
639
+ ...genericPipes(info),
640
+ // The binding table's pipe (envelope payloads, file uploads, …).
641
+ ...(spec.extraBindings ?? [])
642
+ .filter((b) => b.binding === info.binding && b.trait in info.traits)
643
+ .map((b) => b.pipe),
644
+ // Trait-table pipes: trait value JSON-inlined as the argument.
645
+ ...Object.entries(spec.memberTraitPipes ?? {})
646
+ .filter(([trait]) => info.traits[trait] !== undefined)
647
+ .map(
648
+ ([trait, builder]) =>
649
+ `${builder}(${JSON.stringify(info.traits[trait])})`,
650
+ ),
651
+ ...(spec.memberExtraPipes?.(info) ?? []),
652
+ ]);
653
+
654
+ const memberTsTypeOf = (
655
+ info: EmittedMember,
656
+ tsRefFn: (target: string) => string,
657
+ ): string | undefined =>
658
+ spec.memberTsType?.(info, tsRefFn) ??
659
+ (spec.extraBindings ?? []).find(
660
+ (b) => b.binding === info.binding && b.tsType !== undefined,
661
+ )?.tsType;
662
+
663
+ const emitMember = (info: EmittedMember, selfIdx: number): string => {
664
+ let expr = ref(info.target, selfIdx);
665
+ if (info.nullable) expr = `S.NullOr(${expr})`;
666
+ const pipes = memberPipes(info);
667
+ if (pipes.length) expr = `${expr}.pipe(${pipes.join(", ")})`;
668
+ if (!info.required) expr = `S.optional(${expr})`;
669
+ return ` ${q(info.tsName)}: ${expr},`;
670
+ };
671
+
672
+ const opIoShapes = new Set<string>();
673
+ for (const op of selected) {
674
+ opIoShapes.add(op.def.__input);
675
+ opIoShapes.add(op.def.__output);
676
+ }
677
+
678
+ // 3. Validate pagination traits: a paginated op must actually carry its
679
+ // token on the input and its items member on the output, else it
680
+ // degrades to a plain operation.
681
+ const paginatedOutputs = new Set<string>();
682
+ const paginatedItemsRoot = new Map<string, string>();
683
+ /** Op id → its full (possibly dotted) items path, `""` when it has none. */
684
+ const paginatedItemsPath = new Map<string, string>();
685
+ /** Output shape id → the pagination profile that decodes it. */
686
+ const outputProfile = new Map<string, PaginationProfile>();
687
+ /** Op id → its pagination profile (drives protocol/strategy emission). */
688
+ const opProfile = new Map<string, PaginationProfile>();
689
+ const usedProfiles = new Set<PaginationProfile>();
690
+ const profileNames = Object.keys(spec.paginationProfiles ?? {});
691
+ if (profileNames.length > 0) {
692
+ for (const op of selected) {
693
+ const pg = op.def.traits?.[PAGINATED_TRAIT];
694
+ if (!pg) continue;
695
+ // Which profile decodes this op's pages: the selector's answer, or
696
+ // the sole declared profile.
697
+ const profileName =
698
+ spec.paginationProfileFor?.(pg, op) ??
699
+ (profileNames.length === 1 ? profileNames[0] : undefined);
700
+ const profile = profileName
701
+ ? spec.paginationProfiles![profileName]
702
+ : undefined;
703
+ if (!profile) continue;
704
+ const inNames = new Set(
705
+ memberInfos(shapes[op.def.__input] ?? {}).map((m) => m.tsName),
706
+ );
707
+ const outNames = new Set(
708
+ memberInfos(shapes[op.def.__output] ?? {}).map((m) => m.tsName),
709
+ );
710
+ const { ok, itemsRoot } = validatePaginated({
711
+ trait: pg,
712
+ inputNames: inNames,
713
+ outputNames: outNames,
714
+ itemsFallback: profile.itemsFallback,
715
+ syntheticOutputs: new Set(profile.syntheticOutputs ?? []),
716
+ });
717
+ if (ok) {
718
+ op.def.__pagination = pg;
719
+ paginatedOutputs.add(op.def.__output);
720
+ paginatedItemsRoot.set(op.def.__output, itemsRoot);
721
+ paginatedItemsPath.set(
722
+ op.id,
723
+ String(pg.items ?? profile.itemsFallback ?? ""),
724
+ );
725
+ outputProfile.set(op.def.__output, profile);
726
+ opProfile.set(op.id, profile);
727
+ usedProfiles.add(profile);
728
+ }
729
+ }
730
+ }
731
+
732
+ // 4. Error classes from the operations' errors lists.
733
+ const out: string[] = [];
734
+ // Set when any error carries CATEGORY_TRAIT, so the header only imports
735
+ // the category module when something actually uses it.
736
+ let usesCategories = false;
737
+ const errorIds = collectOpErrorIds(selected, shapes);
738
+ const errorIdSet = new Set(errorIds);
739
+ const errorNames = new Set(errorIds.map(local));
740
+
741
+ const shapeDocs = spec.shapeDocs ?? true;
742
+
743
+ for (const id of errorIds) {
744
+ const d = shapes[id];
745
+ const name = local(id);
746
+ const doc = oneLine(d.traits?.["smithy.api#documentation"]);
747
+ if (doc && shapeDocs) out.push(`/** ${doc} */`);
748
+ const overridden = spec.errors?.override?.({ id, def: d, name });
749
+ if (overridden) {
750
+ out.push(...overridden);
751
+ continue;
752
+ }
753
+ const errorField =
754
+ spec.errors?.field ??
755
+ ((mn: string, target: string) =>
756
+ ` ${tsKey(mn)}: ${prelude[local(target)] ?? "S.Unknown"},`);
757
+ const fields =
758
+ d.members && Object.keys(d.members).length
759
+ ? Object.entries(d.members).map(([mn, m]: [string, any]) =>
760
+ errorField(mn, m.target),
761
+ )
762
+ : (spec.errors?.defaultFields?.(prelude) ?? [
763
+ errorField("code", "smithy.api#Integer"),
764
+ errorField("message", "smithy.api#String"),
765
+ ]);
766
+ const matchers = spec.errorMatchersTrait
767
+ ? d.traits?.[spec.errorMatchersTrait]
768
+ : undefined;
769
+ const categories = categoryPipes(d.traits);
770
+ if (categories.length) usesCategories = true;
771
+ out.push(
772
+ errorClass({
773
+ name,
774
+ fields,
775
+ pipes: categories.length
776
+ ? `.pipe(${categories.join(", ")})`
777
+ : undefined,
778
+ wrap:
779
+ spec.errors?.wrap?.(d.traits ?? {}) ??
780
+ (matchers
781
+ ? (cls) =>
782
+ `T.applyErrorMatchers(\n${cls},\n${JSON.stringify(matchers)},\n)`
783
+ : undefined),
784
+ }),
785
+ );
786
+ }
787
+
788
+ // 5. Every reachable shape in dependency order: explicit TS type next to
789
+ // a schema const cast to `S.Schema<T>` (the compile-perf pattern).
790
+ order.forEach((id, i) => {
791
+ if (errorIdSet.has(id)) return; // emitted as an error class above
792
+ const d = shapes[id];
793
+ const name = local(id);
794
+ const doc = oneLine(d.traits?.["smithy.api#documentation"]);
795
+ if (doc && shapeDocs) out.push(`/** ${doc} */`);
796
+
797
+ const override = spec.shapeOverride?.({
798
+ id,
799
+ def: d,
800
+ name,
801
+ selfIdx: i,
802
+ ref,
803
+ tsRef,
804
+ members: memberInfos,
805
+ });
806
+ if (override) {
807
+ out.push(...override);
808
+ return;
809
+ }
810
+
811
+ if (d.type === "structure") {
812
+ // Bare-payload response: single trait-marked member — the response IS
813
+ // that member's value; emit its type + a root marker for the protocol.
814
+ const memberEntriesAll = Object.entries(d.members ?? {});
815
+ const soleMemberRoot =
816
+ !paginatedOutputs.has(id) && memberEntriesAll.length === 1
817
+ ? (spec.extraBindings ?? []).find(
818
+ (b) =>
819
+ b.rootPipe !== undefined &&
820
+ b.trait in ((memberEntriesAll[0]![1] as any).traits ?? {}),
821
+ )
822
+ : undefined;
823
+ if (soleMemberRoot) {
824
+ const [, m] = memberEntriesAll[0]! as [string, any];
825
+ // Alias responses are op roots too — they must carry the service
826
+ // key dictionary so opaque content (union cases, freeform maps)
827
+ // nested in the payload decodes with the same wire mapping as
828
+ // struct-form roots.
829
+ const rootPipes = [
830
+ soleMemberRoot.rootPipe,
831
+ ...(spec.rootKeyDictionary && opIoShapes.has(id)
832
+ ? [`T.KeyDictionary(KEY_DICTIONARY)`]
833
+ : []),
834
+ ];
835
+ out.push(`export type ${name} = ${tsRef(m.target)};`);
836
+ out.push(
837
+ suspendConst({
838
+ name,
839
+ pure,
840
+ multiline: true,
841
+ annotateIdentifier: true,
842
+ expr: `${ref(m.target, i)}.pipe(${rootPipes.join(", ")})`,
843
+ }),
844
+ );
845
+ return;
846
+ }
847
+
848
+ // Paginated outputs always deliver their items member — required.
849
+ const itemsRoot = paginatedItemsRoot.get(id);
850
+ const infos = memberInfos(d, id).map((info) =>
851
+ info.tsName === itemsRoot ? { ...info, required: true } : info,
852
+ );
853
+ const fields = infos.flatMap((info) =>
854
+ interfaceField({
855
+ name: info.tsName,
856
+ optional: !info.required,
857
+ doc: info.doc,
858
+ type:
859
+ memberTsTypeOf(info, tsRef) ??
860
+ `${tsRefAt(info.target, id)}${info.nullable ? " | null" : ""}`,
861
+ }),
862
+ );
863
+ const members = infos.map((info) => emitMember(info, i));
864
+ const inject = outputProfile.get(id)?.injectOutputMember;
865
+ if (inject && !infos.some((m) => m.tsName === inject.tsName)) {
866
+ fields.push(...inject.interfaceLines);
867
+ members.push(inject.structLine);
868
+ }
869
+ out.push(interfaceDecl(name, fields));
870
+ const struct = members.length
871
+ ? `S.Struct({\n${members.join("\n")}\n})`
872
+ : `S.Struct({})`;
873
+ const structCtx = {
874
+ id,
875
+ isOpIo: opIoShapes.has(id),
876
+ httpTrait: httpFor[id],
877
+ };
878
+ const pipes = spec.structPipes?.(structCtx) ?? [
879
+ ...(structCtx.httpTrait
880
+ ? [`T.Http(${JSON.stringify(structCtx.httpTrait)})`]
881
+ : []),
882
+ ...(spec.rootKeyDictionary && structCtx.isOpIo
883
+ ? [`T.KeyDictionary(KEY_DICTIONARY)`]
884
+ : []),
885
+ ];
886
+ const tail = pipes.map((p) => `.pipe(${p})`).join("");
887
+ out.push(
888
+ suspendConst({
889
+ name,
890
+ pure,
891
+ multiline: true,
892
+ annotateIdentifier: true,
893
+ expr: `${struct}${tail}`,
894
+ }),
895
+ );
896
+ } else if (d.type === "list") {
897
+ out.push(`export type ${name} = Array<${tsRefAt(d.member.target, id)}>;`);
898
+ out.push(
899
+ `export const ${name} = ${pure}S.Array(${ref(d.member.target, i)}) as any as S.Schema<${name}>;\n`,
900
+ );
901
+ } else if (d.type === "map") {
902
+ out.push(
903
+ `export type ${name} = { [key: string]: ${tsRefAt(d.value.target, id)} | undefined };`,
904
+ );
905
+ out.push(
906
+ `export const ${name} = ${pure}S.Record(S.String, ${ref(d.value.target, i)}) as any as S.Schema<${name}>;\n`,
907
+ );
908
+ } else if (d.type === "union") {
909
+ // A union arm targeting the union itself carries no information
910
+ // (`type X = X | A | B` ≡ `A | B`) and is an illegal circular type
911
+ // alias. Specs produce them: atlas's OnlineArchiveSchedule is a
912
+ // discriminated oneOf whose DEFAULT arm is `allOf: [$ref <the union
913
+ // itself>]`, so the arm resolves back to its own parent.
914
+ const caseTargets = Object.values(d.members ?? {})
915
+ .map((m: any) => m.target)
916
+ .filter((t: string) => t !== id);
917
+ const caseKeys = caseTargets.map((t: string) => {
918
+ const cd = shapes[t];
919
+ return cd?.type === "structure"
920
+ ? memberInfos(cd).map((mi) => mi.tsName)
921
+ : [];
922
+ });
923
+ if (spec.union) {
924
+ out.push(...spec.union({ name, caseTargets, caseKeys, tsRef }));
925
+ } else if (spec.unionStyle === "opaque-cases") {
926
+ out.push(
927
+ `export type ${name} = ${caseTargets.map((t) => tsRefAt(t, id)).join(" | ") || "unknown"};`,
928
+ `export const ${name} = ${pure}S.Unknown.pipe(T.UnionCases(${JSON.stringify(caseKeys)}));\n`,
929
+ );
930
+ } else {
931
+ throw new Error(
932
+ `no union emission configured for shape ${id} — set unionStyle or union`,
933
+ );
934
+ }
935
+ } else if (d.type === "enum") {
936
+ const values = Object.values(d.members ?? {})
937
+ .map((m: any) => m.traits?.["smithy.api#enumValue"])
938
+ .filter((v: unknown): v is string => typeof v === "string");
939
+ out.push(...enumDecl({ name, values, pure }));
940
+ } else if (d.type === "intEnum") {
941
+ // CLOSED numeric literal union alias (`type Y = 1 | 30`); INPUT
942
+ // references re-open it inline (`Y | (number & {})`). Schema stays
943
+ // S.Number (protocols never validate enum membership).
944
+ const values = Object.values(d.members ?? {})
945
+ .map((m: any) => m.traits?.["smithy.api#enumValue"])
946
+ .filter((v: unknown): v is number => typeof v === "number");
947
+ const union = values.length ? values.join(" | ") : "number";
948
+ out.push(
949
+ `export type ${name} = ${union};`,
950
+ `export const ${name} = ${pure}S.Number;\n`,
951
+ );
952
+ }
953
+ });
954
+
955
+ // 6. Operations — declarative emission from the names in operationDecl,
956
+ // unless the provider overrides the whole shape.
957
+ /**
958
+ * The element type `.items()` yields, resolved from the pagination
959
+ * trait's items PATH against the response shape.
960
+ *
961
+ * `makePaginated` can't infer this — the path is a runtime string — and
962
+ * the structural `API.PaginatedItem` fallback only recognizes bare arrays
963
+ * and `{ result: […] }` envelopes, so every other envelope degrades to
964
+ * `unknown` (distilled #302). Resolving it here and passing it as an
965
+ * explicit type argument is what makes `.items()` typed.
966
+ *
967
+ * Returns undefined when the path doesn't lead to a list, which leaves
968
+ * the annotation on the structural fallback rather than asserting a type
969
+ * the shape doesn't support.
970
+ */
971
+ const paginatedItemTsType = (
972
+ outputId: string,
973
+ itemsPath: string,
974
+ ): string | undefined => {
975
+ // No items path: `.items()` is a page passthrough at runtime, so an
976
+ // item IS a whole response.
977
+ if (!itemsPath) return tsRef(outputId);
978
+ let def = shapes[outputId];
979
+ for (const segment of itemsPath.split(".")) {
980
+ if (def?.type !== "structure") return undefined;
981
+ const info = memberInfos(def).find((m) => m.tsName === segment);
982
+ if (!info) return undefined;
983
+ def = shapes[info.target];
984
+ }
985
+ return def?.type === "list" ? tsRef(def.member.target) : undefined;
986
+ };
987
+
988
+ const emitOperation =
989
+ spec.operation ??
990
+ ((ctx: OperationEmit): string => {
991
+ const decl = spec.operationDecl;
992
+ if (!decl) {
993
+ throw new Error("SdkSpec needs either operationDecl or operation");
994
+ }
995
+ const errList = [...ctx.errorNames, ...decl.commonErrorClasses];
996
+ const paginated = ctx.pagination !== undefined;
997
+ const itemTsType = paginated
998
+ ? paginatedItemTsType(
999
+ ctx.op.def.__output,
1000
+ paginatedItemsPath.get(ctx.op.id) ?? "",
1001
+ )
1002
+ : undefined;
1003
+ const typeAnnotation =
1004
+ `API.${paginated ? "PaginatedOperationMethod" : "OperationMethod"}<\n` +
1005
+ ` ${ctx.inputName},\n` +
1006
+ ` ${ctx.outputTsType},\n` +
1007
+ ` ${ctx.opName}Error,\n` +
1008
+ ` ${decl.contextType}` +
1009
+ (itemTsType ? `,\n ${itemTsType}\n` : `\n`) +
1010
+ `>`;
1011
+ const config =
1012
+ `{\n` +
1013
+ ` input: ${ctx.inputName},\n` +
1014
+ ` output: ${ctx.outputSchema},\n` +
1015
+ ` errors: [${errList.join(", ")}],\n` +
1016
+ ` protocol: ${(paginated && opProfile.get(ctx.op.id)?.protocol) || decl.protocol},\n` +
1017
+ ` retry: ${decl.retry},\n` +
1018
+ (decl.extraConfig?.(ctx) ?? []).map((l) => ` ${l},\n`).join("") +
1019
+ (paginated
1020
+ ? ` pagination: ${JSON.stringify(ctx.pagination)} as const,\n`
1021
+ : "") +
1022
+ `}`;
1023
+ return [
1024
+ errorUnionAlias(ctx.opName, ctx.errorNames, decl.commonErrorType),
1025
+ ...(ctx.doc ? [`/** ${ctx.doc} */`] : []),
1026
+ operationConst({
1027
+ exportName: ctx.exportName,
1028
+ typeAnnotation,
1029
+ factory: paginated ? "API.makePaginated" : "API.make",
1030
+ pure,
1031
+ extraArg: paginated ? opProfile.get(ctx.op.id)?.strategy : undefined,
1032
+ config,
1033
+ // `makePaginated` infers the items element from the structural
1034
+ // fallback; an explicit item type needs the same `as any as`
1035
+ // idiom the schema consts use.
1036
+ castToAnnotation: itemTsType !== undefined,
1037
+ }),
1038
+ ].join("\n");
1039
+ });
1040
+
1041
+ for (const op of selected) {
1042
+ const opName = local(op.id);
1043
+ const errNames = ((op.def.errors ?? []) as Array<{ target: string }>)
1044
+ .map((e) => local(e.target))
1045
+ .filter((n) => errorNames.has(n));
1046
+ out.push(
1047
+ emitOperation({
1048
+ op,
1049
+ opName,
1050
+ exportName: opExportName(opName),
1051
+ inputName: local(op.def.__input),
1052
+ outputName: local(op.def.__output),
1053
+ outputTsType: tsRef(op.def.__output),
1054
+ outputSchema: ref(op.def.__output, indexOf.size),
1055
+ errorNames: errNames,
1056
+ doc: oneLine(op.def.traits?.["smithy.api#documentation"]),
1057
+ pagination: op.def.__pagination,
1058
+ }),
1059
+ );
1060
+ }
1061
+
1062
+ // 7. Alias re-exports, then provider trailing sections.
1063
+ const emittedOps = new Set(selected.map((op) => opExportName(local(op.id))));
1064
+ for (const { alias, target } of spec.opAliases ?? []) {
1065
+ if (!emittedOps.has(target) || emittedOps.has(alias)) continue;
1066
+ emittedOps.add(alias);
1067
+ const A = upperFirst(alias);
1068
+ const T2 = upperFirst(target);
1069
+ out.push(
1070
+ `// Alias of ${target} (same route, alternate export name upstream).\n` +
1071
+ `export const ${alias} = ${target};\n` +
1072
+ `export type ${A}Request = ${T2}Request;\n` +
1073
+ `export type ${A}Response = ${T2}Response;\n` +
1074
+ `export type ${A}Error = ${T2}Error;\n`,
1075
+ );
1076
+ }
1077
+ if (spec.footer) {
1078
+ out.push(...spec.footer({ emittedOps }));
1079
+ }
1080
+
1081
+ // Default header: banner + imports derived from operationDecl names and
1082
+ // the conventional SDK module layout, op error/context type re-exports,
1083
+ // and the KEY_DICTIONARY const when configured.
1084
+ const defaultHeader = (ctx: { hasPaginated: boolean }): string => {
1085
+ const decl = spec.operationDecl;
1086
+ if (!decl) {
1087
+ throw new Error(
1088
+ "the default header needs operationDecl — or pass header",
1089
+ );
1090
+ }
1091
+ const retryNs = decl.retry.split(".")[0];
1092
+ // Imports the used pagination profiles pull in: their protocol consts
1093
+ // (from the protocol module) and strategy/injected-member names (from
1094
+ // the pagination module).
1095
+ const profileProtocols = [
1096
+ ...new Set(
1097
+ [...usedProfiles]
1098
+ .map((p) => p.protocol)
1099
+ .filter((p): p is string => p !== undefined && p !== decl.protocol),
1100
+ ),
1101
+ ];
1102
+ const pagImports = [
1103
+ ...new Set(
1104
+ [...usedProfiles].flatMap((p) => [
1105
+ ...(p.strategy ? [p.strategy] : []),
1106
+ ...(p.injectOutputMember?.imports ?? []),
1107
+ ]),
1108
+ ),
1109
+ ];
1110
+ return (
1111
+ `// AUTO-GENERATED by scripts/generate.ts${
1112
+ spec.sourceNote ? ` from ${spec.sourceNote}` : ""
1113
+ }. Do not edit.\n` +
1114
+ `import * as S from "@distilled.cloud/core/schema";\n` +
1115
+ `import * as API from "@distilled.cloud/core/api";\n` +
1116
+ (usesCategories
1117
+ ? `import * as C from "@distilled.cloud/core/category";\n`
1118
+ : "") +
1119
+ `import * as T from "../traits.ts";\n` +
1120
+ `import {\n` +
1121
+ ` ${decl.protocol},\n` +
1122
+ profileProtocols.map((p) => ` ${p},\n`).join("") +
1123
+ ` type ${decl.commonErrorType},\n` +
1124
+ ` type ${decl.contextType},\n` +
1125
+ `} from "../protocol.ts";\n` +
1126
+ (ctx.hasPaginated && pagImports.length
1127
+ ? `import { ${pagImports.join(", ")} } from "../pagination.ts";\n`
1128
+ : "") +
1129
+ `import { ${[...decl.commonErrorClasses].sort().join(", ")} } from "../errors.ts";\n` +
1130
+ `import * as ${retryNs} from "../retry.ts";\n\n` +
1131
+ // Re-exported so inferred provider types downstream can always name them.
1132
+ `export type { ${decl.commonErrorType}, ${decl.contextType} };\n\n` +
1133
+ (spec.rootKeyDictionary
1134
+ ? `/** ${spec.rootKeyDictionary.doc} */\n` +
1135
+ `const KEY_DICTIONARY: Record<string, string | ReadonlyArray<string>> = ${JSON.stringify(spec.rootKeyDictionary.dict)};\n\n`
1136
+ : "")
1137
+ );
1138
+ };
1139
+
1140
+ const header = (spec.header ?? defaultHeader)({
1141
+ hasPaginated: paginatedOutputs.size > 0,
1142
+ model,
1143
+ });
1144
+ const code = header + out.join("\n") + "\n";
1145
+ return {
1146
+ code: spec.postProcess?.(code) ?? code,
1147
+ operations: selected.length,
1148
+ };
1149
+ };
1150
+
1151
+ // Re-exported so provider specs can be written against the same helpers the
1152
+ // driver uses, without importing every codegen module individually.
1153
+ export { errorUnionAlias, operationConst, upperFirst, tsKey, q, local };