@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,581 +0,0 @@
1
- /**
2
- * RFC-6902 patch application (dev-time only). Every package's convert ends
3
- * in {@link finalizeConvert}, which applies the Smithy ops (`/shapes`,
4
- * `/metadata`, `/smithy`) of `patches/<model>/` to the freshly converted
5
- * model, under the names the spec gives, then the deferred names; so
6
- * `.generated-specs` is the patched model and generate never patches.
7
- */
8
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
9
- import * as fs from "node:fs/promises";
10
- import * as path from "node:path";
11
- import {
12
- applyOperation,
13
- isStaleTargetError,
14
- type JsonPatchOperation,
15
- type PatchFile,
16
- } from "../json-patch.ts";
17
- import { diffModels } from "./model-diff.ts";
18
- import {
19
- applyDeferredRename,
20
- RENAME_METADATA_KEY,
21
- verbNounSmithyModel,
22
- } from "./rewrite-operation-ids.ts";
23
-
24
- export type OnStalePatch = "fail" | "warn";
25
-
26
- export interface ApplyPatchesResult {
27
- files: number;
28
- applied: number;
29
- stale: number;
30
- errors: string[];
31
- }
32
-
33
- /** Smithy-model JSON pointers — OpenAPI has no `/shapes` tree. */
34
- export const isSmithyPatchPath = (pointer: string): boolean =>
35
- pointer.startsWith("/shapes") || pointer.startsWith("/metadata") || pointer.startsWith("/smithy");
36
-
37
- const exists = async (p: string): Promise<boolean> => {
38
- try {
39
- await fs.access(p);
40
- return true;
41
- } catch {
42
- return false;
43
- }
44
- };
45
-
46
- /**
47
- * Leave patches out of one convert run (dev-time only; the seam
48
- * `scripts/patches.ts audit` uses to find patches the spec no longer
49
- * needs). Comma-separated entries:
50
- *
51
- * all skip every patch file
52
- * <file> skip a file — its basename, or a path suffix
53
- * (`svc/a.json`) when basenames repeat
54
- * <file>:<index> skip one op of a file, by its index in `patches`
55
- *
56
- * Like `DISTILLED_SPECS_LOCAL`, it lives in one command's environment: a
57
- * model written under it is announced on stderr and must not be committed.
58
- */
59
- export const SKIP_PATCHES_ENV = "DISTILLED_SKIP_PATCHES";
60
-
61
- interface SkipList {
62
- readonly all: boolean;
63
- readonly files: readonly string[];
64
- readonly ops: ReadonlyMap<string, ReadonlySet<number>>;
65
- }
66
-
67
- const parseSkipList = (): SkipList | undefined => {
68
- const raw = (process.env[SKIP_PATCHES_ENV] ?? "").trim();
69
- if (raw === "") return undefined;
70
- const files: string[] = [];
71
- const ops = new Map<string, Set<number>>();
72
- for (const entry of raw.split(",")) {
73
- const item = entry.trim();
74
- if (item === "") continue;
75
- if (item === "all") return { all: true, files: [], ops: new Map() };
76
- const at = item.lastIndexOf(":");
77
- const index = at === -1 ? NaN : Number(item.slice(at + 1));
78
- if (Number.isInteger(index) && index >= 0) {
79
- const file = item.slice(0, at);
80
- ops.set(file, (ops.get(file) ?? new Set()).add(index));
81
- } else {
82
- files.push(item);
83
- }
84
- }
85
- return { all: false, files, ops };
86
- };
87
-
88
- const skipMatches = (file: string, entry: string): boolean =>
89
- path.basename(file) === entry || file.endsWith(path.sep + entry);
90
-
91
- let skipAnnounced = false;
92
-
93
- const skipList = (): SkipList | undefined => {
94
- const list = parseSkipList();
95
- if (list && !skipAnnounced) {
96
- skipAnnounced = true;
97
- // stderr for the same reason as the DISTILLED_SPECS_LOCAL notice.
98
- console.error(
99
- `⚠ ${SKIP_PATCHES_ENV}=${process.env[SKIP_PATCHES_ENV]} — this model is missing patches; do not commit it.`,
100
- );
101
- }
102
- return list;
103
- };
104
-
105
- const skipsFile = (list: SkipList | undefined, file: string): boolean =>
106
- list !== undefined && (list.all || list.files.some((entry) => skipMatches(file, entry)));
107
-
108
- const skipsOp = (list: SkipList | undefined, file: string, index: number): boolean => {
109
- if (list === undefined) return false;
110
- for (const [entry, indices] of list.ops) {
111
- if (indices.has(index) && skipMatches(file, entry)) return true;
112
- }
113
- return false;
114
- };
115
-
116
- /**
117
- * RFC-6902 files in `dir`: every `*.json`, `*.manual.json` last (those
118
- * usually target post-rename shape names). Missing dir → `[]`. Files named
119
- * by {@link SKIP_PATCHES_ENV} are left out.
120
- */
121
- export const listRfc6902PatchFiles = async (dir: string): Promise<string[]> => {
122
- if (!(await exists(dir))) return [];
123
- const skip = skipList();
124
- return (await fs.readdir(dir))
125
- .filter((f) => f.endsWith(".json"))
126
- .sort(
127
- (a, b) =>
128
- Number(a.endsWith(".manual.json")) - Number(b.endsWith(".manual.json")) ||
129
- a.localeCompare(b),
130
- )
131
- .map((f) => path.join(dir, f))
132
- .filter((f) => !skipsFile(skip, f));
133
- };
134
-
135
- export const applyRfc6902Files = async (
136
- target: unknown,
137
- files: readonly string[],
138
- opts: {
139
- readonly onStalePatch?: OnStalePatch;
140
- readonly include?: (op: JsonPatchOperation) => boolean;
141
- readonly label?: (file: string) => string;
142
- } = {},
143
- ): Promise<ApplyPatchesResult> => {
144
- const onStalePatch = opts.onStalePatch ?? "fail";
145
- const include = opts.include ?? (() => true);
146
- const result: ApplyPatchesResult = {
147
- files: 0,
148
- applied: 0,
149
- stale: 0,
150
- errors: [],
151
- };
152
- const skip = skipList();
153
- for (const file of files) {
154
- if (skipsFile(skip, file)) continue;
155
- const parsed = JSON.parse(await fs.readFile(file, "utf8")) as PatchFile;
156
- const label = opts.label?.(file) ?? path.basename(file);
157
- result.files++;
158
- for (const [index, patchOp] of (parsed.patches ?? []).entries()) {
159
- if (!include(patchOp) || skipsOp(skip, file, index)) continue;
160
- try {
161
- applyOperation(target, patchOp);
162
- result.applied++;
163
- } catch (e) {
164
- const msg = e instanceof Error ? e.message : String(e);
165
- const line = `${label} [${patchOp.op} ${patchOp.path}]`;
166
- if (isStaleTargetError(e)) {
167
- result.stale++;
168
- if (onStalePatch === "fail") {
169
- result.errors.push(`${line}: stale target (${msg})`);
170
- } else {
171
- console.warn(` ⚠️ stale: ${line}`);
172
- }
173
- } else {
174
- result.errors.push(`${line}: ${msg}`);
175
- }
176
- }
177
- }
178
- }
179
- return result;
180
- };
181
-
182
- /**
183
- * An RFC-6902 `move` that renames an operation shape leaves the service's
184
- * `operations` list pointing at the old id. Drop entries whose target no
185
- * longer exists and append operation shapes the list is missing, keeping
186
- * the existing order. Returns the number of services whose list changed.
187
- */
188
- export const syncServiceOperations = (model: { shapes?: Record<string, any> }): number => {
189
- const shapes = model.shapes ?? {};
190
- const opIds = Object.keys(shapes).filter((id) => shapes[id]?.type === "operation");
191
- let changed = 0;
192
- for (const def of Object.values(shapes)) {
193
- if (def?.type !== "service") continue;
194
- const current: Array<{ target: string }> = def.operations ?? [];
195
- const kept = current.filter((o) => shapes[o.target]?.type === "operation");
196
- const listed = new Set(kept.map((o) => o.target));
197
- const after = [...kept, ...opIds.filter((id) => !listed.has(id)).map((target) => ({ target }))];
198
- if (JSON.stringify(current) !== JSON.stringify(after)) {
199
- def.operations = after;
200
- changed++;
201
- }
202
- }
203
- return changed;
204
- };
205
-
206
- /**
207
- * Every `target` in a Smithy model must resolve to a shape or a prelude
208
- * (`smithy.api#…`) id. Returns the dangling ones as `"<owner> → <target>"`.
209
- * A convert that produces any is broken — generate would emit references
210
- * to types that do not exist.
211
- */
212
- export const danglingTargets = (model: { shapes?: Record<string, any> }): string[] => {
213
- const shapes = model.shapes ?? {};
214
- const ids = new Set(Object.keys(shapes));
215
- const out: string[] = [];
216
- const walk = (owner: string, node: unknown): void => {
217
- if (Array.isArray(node)) {
218
- for (const item of node) walk(owner, item);
219
- return;
220
- }
221
- if (node === null || typeof node !== "object") return;
222
- for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
223
- if (key === "target" && typeof value === "string") {
224
- if (!value.startsWith("smithy.") && !ids.has(value)) {
225
- out.push(`${owner} → ${value}`);
226
- }
227
- } else {
228
- walk(owner, value);
229
- }
230
- }
231
- };
232
- for (const [id, def] of Object.entries(shapes)) walk(id, def);
233
- return out;
234
- };
235
-
236
- export interface FinalizeOptions {
237
- readonly root: string;
238
- readonly outDir?: string;
239
- readonly patchesDir?: string | false;
240
- /**
241
- * The directory holding a model's patches, relative to `patchesDir`.
242
- * Default `<resource>`; `""` for a single-model package whose patches sit
243
- * at the root of `patchesDir`; `undefined` for none.
244
- */
245
- readonly patchesFor?: (resource: string) => string | undefined;
246
- readonly exclude?: (file: string) => boolean;
247
- readonly include?: (resource: string) => boolean;
248
- readonly transform?: (model: any, resource: string) => string | void;
249
- readonly operationNaming?: "as-is" | "verbNoun";
250
- readonly onStalePatch?: OnStalePatch;
251
- }
252
-
253
- /** A patch file read once, with only its Smithy ops. */
254
- interface LoadedPatchFile {
255
- /** Path relative to the patches dir, `/`-separated — the audit's key. */
256
- readonly key: string;
257
- readonly file: string;
258
- readonly ops: readonly JsonPatchOperation[];
259
- }
260
-
261
- const loadSmithyPatches = async (
262
- patchesDir: string,
263
- dir: string | undefined,
264
- ): Promise<LoadedPatchFile[]> => {
265
- if (dir === undefined) return [];
266
- const out: LoadedPatchFile[] = [];
267
- for (const file of await listRfc6902PatchFiles(path.join(patchesDir, dir))) {
268
- const parsed = JSON.parse(await fs.readFile(file, "utf8")) as PatchFile;
269
- const key = path.relative(patchesDir, file).split(path.sep).join("/");
270
- const spec = (parsed.patches ?? []).find((op) => !isSmithyPatchPath(op.path));
271
- if (spec) {
272
- // Patches edit the converted model under upstream names, never the
273
- // spec: one kind of patch, and one the audit can judge in memory.
274
- throw new Error(
275
- `patches/${key} [${spec.op} ${spec.path}]: patches target the Smithy model (/shapes, /metadata), not the spec — see the distilled-sdk-patch skill`,
276
- );
277
- }
278
- out.push({ key, file, ops: parsed.patches ?? [] });
279
- }
280
- return out;
281
- };
282
-
283
- type FinalizeRun =
284
- | { readonly ok: true; readonly model: any }
285
- | { readonly ok: false; readonly stage: "patch" | "rename" | "dangling"; readonly error: string };
286
-
287
- /**
288
- * One model through the finalize steps: Smithy patches, verbNoun names,
289
- * the package's transform, the service operation list, and the reference
290
- * check. `skip` leaves out a patch file (`key`) or one of its ops
291
- * (`key:index`); `quiet` silences the progress lines for audit re-runs.
292
- */
293
- const finalizeModel = (
294
- model: any,
295
- resource: string,
296
- patches: readonly LoadedPatchFile[],
297
- o: FinalizeOptions,
298
- skip: { readonly key: string; readonly index?: number } | undefined,
299
- quiet: boolean,
300
- ): FinalizeRun => {
301
- const log = quiet ? () => {} : console.log;
302
- const deferred = model.metadata?.[RENAME_METADATA_KEY];
303
- if (deferred && !quiet) recordRename(resource, deferred);
304
- const envSkip = skipList();
305
- let files = 0;
306
- let applied = 0;
307
- let stale = 0;
308
- const errors: string[] = [];
309
- for (const p of patches) {
310
- if (skip && skip.key === p.key && skip.index === undefined) continue;
311
- files++;
312
- for (const [index, op] of p.ops.entries()) {
313
- if (skip && skip.key === p.key && skip.index === index) continue;
314
- if (skipsOp(envSkip, p.file, index)) continue;
315
- try {
316
- // A cloned op: `add`/`replace` insert the value by reference, and
317
- // the audit applies the same parsed ops to many fresh models.
318
- applyOperation(model, structuredClone(op));
319
- applied++;
320
- } catch (e) {
321
- const line = `${p.key} [${op.op} ${op.path}]`;
322
- const msg = e instanceof Error ? e.message : String(e);
323
- if (isStaleTargetError(e) && o.onStalePatch === "warn") {
324
- stale++;
325
- if (!quiet) console.warn(` ⚠️ stale: ${line}`);
326
- } else {
327
- errors.push(`${line}: ${isStaleTargetError(e) ? `stale target (${msg})` : msg}`);
328
- }
329
- }
330
- }
331
- }
332
- if (errors.length) {
333
- if (!quiet) for (const err of errors) console.error(`❌ bad patch: ${err}`);
334
- return {
335
- ok: false,
336
- stage: "patch",
337
- error: `${errors.length} patch operation(s) failed for ${resource}: ${errors[0]}`,
338
- };
339
- }
340
- if (applied > 0) {
341
- log(
342
- ` patched ${resource}: ${files} file(s), ${applied} op(s)` +
343
- (stale ? `, ${stale} stale` : ""),
344
- );
345
- }
346
-
347
- try {
348
- const renamed = applyDeferredRename(model);
349
- if (renamed > 0) log(` named ${resource}: ${renamed} shape(s)`);
350
- } catch (e) {
351
- const error = `${resource}: ${e instanceof Error ? e.message : String(e)}`;
352
- if (!quiet) console.error(`❌ ${error}`);
353
- return { ok: false, stage: "rename", error };
354
- }
355
-
356
- if ((o.operationNaming ?? "verbNoun") === "verbNoun") {
357
- const { renamed, collisions } = verbNounSmithyModel(model);
358
- if (renamed > 0) log(` verbNoun ${resource}: renamed ${renamed} operation(s)`);
359
- if (!quiet) {
360
- for (const c of collisions) {
361
- console.warn(` ⚠️ verbNoun collision ${resource}: ${c} (kept original)`);
362
- }
363
- }
364
- }
365
-
366
- const note = o.transform?.(model, resource);
367
- if (note) log(` ${note}`);
368
-
369
- syncServiceOperations(model);
370
-
371
- const dangling = danglingTargets(model);
372
- if (dangling.length) {
373
- if (!quiet) {
374
- for (const d of dangling.slice(0, 5)) console.error(` ❌ ${d}`);
375
- if (dangling.length > 5) console.error(` … ${dangling.length - 5} more`);
376
- }
377
- return {
378
- ok: false,
379
- stage: "dangling",
380
- error: `${resource}: ${dangling.length} dangling target(s), e.g. ${dangling[0]}`,
381
- };
382
- }
383
- model.metadata = { ...model.metadata, [FINALIZED_KEY]: true };
384
- return { ok: true, model };
385
- };
386
-
387
- const modelText = (model: unknown): string => `${JSON.stringify(model, null, 2)}\n`;
388
-
389
- /**
390
- * Last step of every convert: Smithy RFC-6902 patches, then verbNoun
391
- * operation names, then an optional model transform, then a reference
392
- * check. Writes models back so `.generated-specs` is what generate
393
- * compiles. `outDir` may be nested (GCP `stable/` / `unstable/`).
394
- *
395
- * Input must be FRESHLY converted models. Smithy patches are `move`/`add`
396
- * ops that are not idempotent, and a `transform` may not be either, so
397
- * running this over a model that already went through it is an error —
398
- * re-run the package's `convert` instead.
399
- *
400
- * Under {@link PATCH_AUDIT_ENV} it also judges the requested patch files
401
- * in memory (see `./patch-audit.ts`).
402
- */
403
- export const finalizeConvert = async (o: FinalizeOptions): Promise<void> => {
404
- const specsRoot = path.resolve(o.root, ".generated-specs");
405
- const specsDir = path.resolve(o.root, o.outDir ?? ".generated-specs");
406
- if (!(await exists(specsDir))) return;
407
- const patchesDir =
408
- o.patchesDir === false ? undefined : path.resolve(o.root, o.patchesDir ?? "patches");
409
- const audit = patchesDir ? await readAuditRequest() : undefined;
410
-
411
- const walk = async (dir: string): Promise<string[]> => {
412
- const out: string[] = [];
413
- for (const ent of await fs.readdir(dir, { withFileTypes: true })) {
414
- const p = path.join(dir, ent.name);
415
- if (ent.isDirectory()) {
416
- out.push(...(await walk(p)));
417
- } else if (ent.name.endsWith(".json") && !(o.exclude?.(ent.name) ?? false)) {
418
- out.push(p);
419
- }
420
- }
421
- return out;
422
- };
423
-
424
- const files = (await walk(specsDir)).sort((a, b) => a.localeCompare(b));
425
- const broken: string[] = [];
426
- for (const modelPath of files) {
427
- const resource = path.basename(modelPath, ".json");
428
- if (o.include && !o.include(resource)) continue;
429
- const text = await fs.readFile(modelPath, "utf8");
430
- const model = JSON.parse(text);
431
- if (model.metadata?.[FINALIZED_KEY]) {
432
- throw new Error(
433
- `${path.relative(o.root, modelPath)} was already finalized — finalizeConvert is not idempotent; re-run this package's convert from the spec instead`,
434
- );
435
- }
436
- const patches = patchesDir
437
- ? await loadSmithyPatches(patchesDir, o.patchesFor ? o.patchesFor(resource) : resource)
438
- : [];
439
- const run = finalizeModel(model, resource, patches, o, undefined, false);
440
- const label = path.relative(specsRoot, modelPath).split(path.sep).join("/");
441
- if (!run.ok) {
442
- if (audit) auditModel(audit, label, resource, text, patches, o, run);
443
- if (run.stage === "patch") {
444
- throw new Error(`${run.error.split(": ")[0]} — fix the pointers or delete the patch`);
445
- }
446
- if (run.stage === "rename") {
447
- throw new Error(`${run.error} — a patch added a shape under a name the rename needs`);
448
- }
449
- broken.push(run.error.split(", e.g.")[0]!);
450
- // Leave the unfinalized model on disk for inspection; never stamp
451
- // a model that generate cannot compile.
452
- continue;
453
- }
454
- const finalized = modelText(run.model);
455
- await fs.writeFile(modelPath, finalized);
456
- if (audit) auditModel(audit, label, resource, text, patches, o, { ok: true, text: finalized });
457
- }
458
- if (broken.length) {
459
- throw new Error(
460
- `finalizeConvert: ${broken.length} model(s) reference shapes that do not exist:\n ${broken.join("\n ")}`,
461
- );
462
- }
463
- };
464
-
465
- /**
466
- * Path of a JSON file finalizeConvert adds each model's deferred rename to
467
- * (`{ <model>: { <upstream id>: <final id> } }`). Set by
468
- * `pnpm patches:names`, which tells a patch author the upstream name of a
469
- * shape they see in `.generated-specs`.
470
- */
471
- export const RENAME_MAP_ENV = "DISTILLED_RENAME_MAP";
472
-
473
- const recordRename = (resource: string, rename: Record<string, string>): void => {
474
- const file = process.env[RENAME_MAP_ENV];
475
- if (!file) return;
476
- const all = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
477
- all[resource] = { ...all[resource], ...rename };
478
- writeFileSync(file, JSON.stringify(all));
479
- };
480
-
481
- // ---------------------------------------------------------------------------
482
- // in-memory patch audit
483
-
484
- /**
485
- * Path of a JSON request (`{ keys: string[], ops: boolean }`) asking
486
- * finalizeConvert to judge those patch files in memory. Set only by
487
- * `pnpm patches:audit` on a scratch copy of the package; the models it
488
- * writes are the normal, fully patched ones.
489
- *
490
- * Each verdict is printed to stdout as one line, {@link PATCH_AUDIT_MARKER}
491
- * followed by JSON. A requested key no finalizeConvert call owns (its ops
492
- * are applied somewhere else, e.g. before conversion) gets no line, and the
493
- * audit judges it by re-running convert.
494
- */
495
- export const PATCH_AUDIT_ENV = "DISTILLED_PATCH_AUDIT";
496
- export const PATCH_AUDIT_MARKER = "@@distilled-patch-audit ";
497
-
498
- interface AuditRequest {
499
- readonly keys: ReadonlySet<string>;
500
- readonly ops: boolean;
501
- }
502
-
503
- /** One finalizeConvert's answer for one patch file. */
504
- export interface InMemoryVerdict {
505
- readonly key: string;
506
- /** Path of the model relative to the package's `.generated-specs`. */
507
- readonly model: string;
508
- readonly verdict:
509
- | { readonly kind: "unused" }
510
- | { readonly kind: "needed"; readonly diff: readonly string[] }
511
- | { readonly kind: "depended"; readonly error: string }
512
- | { readonly kind: "baseline"; readonly error: string };
513
- readonly deadOps: readonly number[];
514
- }
515
-
516
- const readAuditRequest = async (): Promise<AuditRequest | undefined> => {
517
- const file = process.env[PATCH_AUDIT_ENV];
518
- if (!file) return undefined;
519
- const raw = JSON.parse(await fs.readFile(file, "utf8")) as { keys: string[]; ops?: boolean };
520
- return { keys: new Set(raw.keys), ops: raw.ops === true };
521
- };
522
-
523
- const emitVerdict = (v: InMemoryVerdict): void => {
524
- process.stdout.write(`${PATCH_AUDIT_MARKER}${JSON.stringify(v)}\n`);
525
- };
526
-
527
- const auditModel = (
528
- audit: AuditRequest,
529
- model: string,
530
- resource: string,
531
- text: string,
532
- patches: readonly LoadedPatchFile[],
533
- o: FinalizeOptions,
534
- baseline:
535
- | { readonly ok: true; readonly text: string }
536
- | { readonly ok: false; readonly error: string },
537
- ): void => {
538
- const owned = patches.filter((p) => audit.keys.has(p.key) && p.ops.length > 0);
539
- for (const p of owned) {
540
- if (!baseline.ok) {
541
- emitVerdict({
542
- key: p.key,
543
- model,
544
- verdict: { kind: "baseline", error: baseline.error },
545
- deadOps: [],
546
- });
547
- continue;
548
- }
549
- const judge = (index?: number): InMemoryVerdict["verdict"] => {
550
- const run = finalizeModel(
551
- JSON.parse(text),
552
- resource,
553
- patches,
554
- o,
555
- { key: p.key, index },
556
- true,
557
- );
558
- if (!run.ok) return { kind: "depended", error: run.error };
559
- const without = modelText(run.model);
560
- if (without === baseline.text) return { kind: "unused" };
561
- const diff = diffModels(new Map([[model, baseline.text]]), new Map([[model, without]]));
562
- // The committed model is compared byte for byte, so a patch that only
563
- // orders keys (`before`, a `move` onto itself) is needed too.
564
- return { kind: "needed", diff: diff.length === 0 ? ["(key order only)"] : diff };
565
- };
566
- const verdict = judge();
567
- const deadOps: number[] = [];
568
- if (audit.ops && verdict.kind === "needed" && p.ops.length > 1) {
569
- for (let index = 0; index < p.ops.length; index++) {
570
- if (judge(index).kind === "unused") deadOps.push(index);
571
- }
572
- }
573
- emitVerdict({ key: p.key, model, verdict, deadOps });
574
- }
575
- };
576
-
577
- /**
578
- * Metadata marker stamped by {@link finalizeConvert}. Guards against a
579
- * second pass over the same file (see the note on finalizeConvert).
580
- */
581
- export const FINALIZED_KEY = "distilled.finalized";
@@ -1,70 +0,0 @@
1
- import { isForwardRef } from "./graph.ts";
2
- /**
3
- * Smithy prelude scalar baselines + reference resolvers for the SDK
4
- * generators (dev-time only).
5
- *
6
- * The JSON flavor maps timestamps/blobs to plain strings — the baseline for
7
- * SDKs whose wire format is JSON-over-docs (cloudflare). Generators with
8
- * richer models (AWS) emit real timestamp/blob schemas themselves and only
9
- * fall back here for untyped scalars.
10
- */
11
- import { isPrelude, local } from "./naming.ts";
12
-
13
- /** Prelude shape → schema expression (JSON-wire flavor). */
14
- export const JSON_PRELUDE: Record<string, string> = {
15
- String: "S.String",
16
- Boolean: "S.Boolean",
17
- Double: "S.Number",
18
- Float: "S.Number",
19
- Integer: "S.Number",
20
- Long: "S.Number",
21
- BigInteger: "S.Number",
22
- BigDecimal: "S.Number",
23
- Timestamp: "S.String",
24
- Blob: "S.String",
25
- Document: "S.Unknown",
26
- Unit: "S.Struct({})",
27
- };
28
-
29
- /** TypeScript type for each prelude shape, mirroring {@link JSON_PRELUDE}. */
30
- export const TS_JSON_PRELUDE: Record<string, string> = {
31
- String: "string",
32
- Boolean: "boolean",
33
- Double: "number",
34
- Float: "number",
35
- Integer: "number",
36
- Long: "number",
37
- BigInteger: "number",
38
- BigDecimal: "number",
39
- Timestamp: "string",
40
- Blob: "string",
41
- Document: "unknown",
42
- Unit: "{}",
43
- };
44
-
45
- /**
46
- * Schema reference resolver: prelude shapes map through the prelude table,
47
- * forward references (including into cycles) wrap in `S.suspend`.
48
- */
49
- export const makeSchemaRef =
50
- (
51
- prelude: Record<string, string>,
52
- indexOf: ReadonlyMap<string, number>,
53
- ): ((target: string, selfIdx: number) => string) =>
54
- (target, selfIdx) => {
55
- if (isPrelude(target)) return prelude[local(target)] ?? "S.Unknown";
56
- const name = local(target);
57
- if (isForwardRef(indexOf, target, selfIdx)) {
58
- return `S.suspend(() => ${name})`;
59
- }
60
- return name;
61
- };
62
-
63
- /**
64
- * TypeScript type reference resolver. Named shapes all get an emitted
65
- * interface / type alias, so forward references are always fine.
66
- */
67
- export const makeTsRef =
68
- (tsPrelude: Record<string, string>): ((target: string) => string) =>
69
- (target) =>
70
- isPrelude(target) ? (tsPrelude[local(target)] ?? "unknown") : local(target);