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

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 (235) hide show
  1. package/lib/api.d.ts +4 -4
  2. package/lib/api.d.ts.map +1 -1
  3. package/lib/api.js +3 -5
  4. package/lib/api.js.map +1 -1
  5. package/lib/category.d.ts.map +1 -1
  6. package/lib/category.js +3 -5
  7. package/lib/category.js.map +1 -1
  8. package/lib/codegen/boolean-string-enums.d.ts.map +1 -1
  9. package/lib/codegen/boolean-string-enums.js +2 -6
  10. package/lib/codegen/boolean-string-enums.js.map +1 -1
  11. package/lib/codegen/boolean-string-enums.test.js +3 -5
  12. package/lib/codegen/boolean-string-enums.test.js.map +1 -1
  13. package/lib/codegen/cli.d.ts +5 -4
  14. package/lib/codegen/cli.d.ts.map +1 -1
  15. package/lib/codegen/cli.js +12 -9
  16. package/lib/codegen/cli.js.map +1 -1
  17. package/lib/codegen/defer-naming.test.d.ts +2 -0
  18. package/lib/codegen/defer-naming.test.d.ts.map +1 -0
  19. package/lib/codegen/defer-naming.test.js +105 -0
  20. package/lib/codegen/defer-naming.test.js.map +1 -0
  21. package/lib/codegen/emit.d.ts.map +1 -1
  22. package/lib/codegen/emit.js +1 -3
  23. package/lib/codegen/emit.js.map +1 -1
  24. package/lib/codegen/format.d.ts +0 -12
  25. package/lib/codegen/format.d.ts.map +1 -1
  26. package/lib/codegen/format.js +10 -6
  27. package/lib/codegen/format.js.map +1 -1
  28. package/lib/codegen/generated-at.d.ts +29 -0
  29. package/lib/codegen/generated-at.d.ts.map +1 -0
  30. package/lib/codegen/generated-at.js +78 -0
  31. package/lib/codegen/generated-at.js.map +1 -0
  32. package/lib/codegen/generated-at.test.d.ts +2 -0
  33. package/lib/codegen/generated-at.test.d.ts.map +1 -0
  34. package/lib/codegen/generated-at.test.js +81 -0
  35. package/lib/codegen/generated-at.test.js.map +1 -0
  36. package/lib/codegen/generator.d.ts +4 -2
  37. package/lib/codegen/generator.d.ts.map +1 -1
  38. package/lib/codegen/generator.js +37 -75
  39. package/lib/codegen/generator.js.map +1 -1
  40. package/lib/codegen/generator.test.js +4 -9
  41. package/lib/codegen/generator.test.js.map +1 -1
  42. package/lib/codegen/graphql-client.d.ts.map +1 -1
  43. package/lib/codegen/graphql-client.js +12 -33
  44. package/lib/codegen/graphql-client.js.map +1 -1
  45. package/lib/codegen/graphql-client.test.js +4 -12
  46. package/lib/codegen/graphql-client.test.js.map +1 -1
  47. package/lib/codegen/graphql.d.ts.map +1 -1
  48. package/lib/codegen/graphql.js +7 -20
  49. package/lib/codegen/graphql.js.map +1 -1
  50. package/lib/codegen/model-diff.d.ts +10 -0
  51. package/lib/codegen/model-diff.d.ts.map +1 -0
  52. package/lib/codegen/model-diff.js +67 -0
  53. package/lib/codegen/model-diff.js.map +1 -0
  54. package/lib/codegen/naming.d.ts.map +1 -1
  55. package/lib/codegen/naming.js.map +1 -1
  56. package/lib/codegen/openapi-binary.test.js +1 -1
  57. package/lib/codegen/openapi-binary.test.js.map +1 -1
  58. package/lib/codegen/openapi-cli.d.ts +11 -11
  59. package/lib/codegen/openapi-cli.d.ts.map +1 -1
  60. package/lib/codegen/openapi-cli.js +26 -51
  61. package/lib/codegen/openapi-cli.js.map +1 -1
  62. package/lib/codegen/openapi.d.ts +9 -1
  63. package/lib/codegen/openapi.d.ts.map +1 -1
  64. package/lib/codegen/openapi.js +48 -42
  65. package/lib/codegen/openapi.js.map +1 -1
  66. package/lib/codegen/operations.d.ts.map +1 -1
  67. package/lib/codegen/operations.js.map +1 -1
  68. package/lib/codegen/pagination.d.ts.map +1 -1
  69. package/lib/codegen/pagination.js +2 -4
  70. package/lib/codegen/pagination.js.map +1 -1
  71. package/lib/codegen/patch-audit.d.ts +84 -0
  72. package/lib/codegen/patch-audit.d.ts.map +1 -0
  73. package/lib/codegen/patch-audit.js +366 -0
  74. package/lib/codegen/patch-audit.js.map +1 -0
  75. package/lib/codegen/patch-audit.test.d.ts +2 -0
  76. package/lib/codegen/patch-audit.test.d.ts.map +1 -0
  77. package/lib/codegen/patch-audit.test.js +141 -0
  78. package/lib/codegen/patch-audit.test.js.map +1 -0
  79. package/lib/codegen/patches.d.ts +59 -10
  80. package/lib/codegen/patches.d.ts.map +1 -1
  81. package/lib/codegen/patches.js +233 -63
  82. package/lib/codegen/patches.js.map +1 -1
  83. package/lib/codegen/patches.test.js +8 -4
  84. package/lib/codegen/patches.test.js.map +1 -1
  85. package/lib/codegen/prelude.js +1 -1
  86. package/lib/codegen/prelude.js.map +1 -1
  87. package/lib/codegen/proto.d.ts.map +1 -1
  88. package/lib/codegen/proto.js +2 -4
  89. package/lib/codegen/proto.js.map +1 -1
  90. package/lib/codegen/protocol-imports.test.d.ts +2 -0
  91. package/lib/codegen/protocol-imports.test.d.ts.map +1 -0
  92. package/lib/codegen/protocol-imports.test.js +36 -0
  93. package/lib/codegen/protocol-imports.test.js.map +1 -0
  94. package/lib/codegen/rewrite-operation-ids.d.ts +23 -0
  95. package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -1
  96. package/lib/codegen/rewrite-operation-ids.js +97 -59
  97. package/lib/codegen/rewrite-operation-ids.js.map +1 -1
  98. package/lib/codegen/rewrite-operation-ids.test.js +19 -101
  99. package/lib/codegen/rewrite-operation-ids.test.js.map +1 -1
  100. package/lib/codegen/spec-path.d.ts +1 -1
  101. package/lib/codegen/spec-path.d.ts.map +1 -1
  102. package/lib/codegen/spec-path.js +1 -1
  103. package/lib/codegen/spec-path.js.map +1 -1
  104. package/lib/codegen/untagged-unions.test.js +1 -1
  105. package/lib/codegen/untagged-unions.test.js.map +1 -1
  106. package/lib/error-category.d.ts.map +1 -1
  107. package/lib/error-category.js.map +1 -1
  108. package/lib/errors.d.ts.map +1 -1
  109. package/lib/errors.js +7 -5
  110. package/lib/errors.js.map +1 -1
  111. package/lib/graphql.d.ts +4 -8
  112. package/lib/graphql.d.ts.map +1 -1
  113. package/lib/graphql.js +20 -48
  114. package/lib/graphql.js.map +1 -1
  115. package/lib/graphql.test.js +6 -6
  116. package/lib/graphql.test.js.map +1 -1
  117. package/lib/graphql.types.d.ts.map +1 -1
  118. package/lib/graphql.types.js.map +1 -1
  119. package/lib/json-patch.d.ts +13 -6
  120. package/lib/json-patch.d.ts.map +1 -1
  121. package/lib/json-patch.js +34 -19
  122. package/lib/json-patch.js.map +1 -1
  123. package/lib/json-patch.test.d.ts +2 -0
  124. package/lib/json-patch.test.d.ts.map +1 -0
  125. package/lib/json-patch.test.js +65 -0
  126. package/lib/json-patch.test.js.map +1 -0
  127. package/lib/pagination.d.ts.map +1 -1
  128. package/lib/pagination.js +6 -16
  129. package/lib/pagination.js.map +1 -1
  130. package/lib/pagination.test.js +3 -6
  131. package/lib/pagination.test.js.map +1 -1
  132. package/lib/protocol-http.d.ts +20 -1
  133. package/lib/protocol-http.d.ts.map +1 -1
  134. package/lib/protocol-http.js +41 -47
  135. package/lib/protocol-http.js.map +1 -1
  136. package/lib/protocol-http.test.js +20 -10
  137. package/lib/protocol-http.test.js.map +1 -1
  138. package/lib/protocol-rest.d.ts.map +1 -1
  139. package/lib/protocol-rest.js +9 -18
  140. package/lib/protocol-rest.js.map +1 -1
  141. package/lib/protocol-rest.test.d.ts +2 -0
  142. package/lib/protocol-rest.test.d.ts.map +1 -0
  143. package/lib/protocol-rest.test.js +498 -0
  144. package/lib/protocol-rest.test.js.map +1 -0
  145. package/lib/response-validation.d.ts.map +1 -1
  146. package/lib/response-validation.js.map +1 -1
  147. package/lib/response-validation.test.js +10 -5
  148. package/lib/response-validation.test.js.map +1 -1
  149. package/lib/retry-after.d.ts.map +1 -1
  150. package/lib/retry-after.js +1 -1
  151. package/lib/retry-after.js.map +1 -1
  152. package/lib/retry-after.test.d.ts +2 -0
  153. package/lib/retry-after.test.d.ts.map +1 -0
  154. package/lib/retry-after.test.js +204 -0
  155. package/lib/retry-after.test.js.map +1 -0
  156. package/lib/retry.d.ts.map +1 -1
  157. package/lib/retry.js +1 -2
  158. package/lib/retry.js.map +1 -1
  159. package/lib/retry.test.d.ts +2 -0
  160. package/lib/retry.test.d.ts.map +1 -0
  161. package/lib/retry.test.js +407 -0
  162. package/lib/retry.test.js.map +1 -0
  163. package/lib/sdks.test.d.ts +2 -0
  164. package/lib/sdks.test.d.ts.map +1 -0
  165. package/lib/sdks.test.js +76 -0
  166. package/lib/sdks.test.js.map +1 -0
  167. package/lib/testing.d.ts +2 -2
  168. package/lib/testing.d.ts.map +1 -1
  169. package/lib/testing.js +1 -1
  170. package/lib/testing.js.map +1 -1
  171. package/lib/trait.d.ts.map +1 -1
  172. package/lib/trait.js.map +1 -1
  173. package/lib/xml.d.ts.map +1 -1
  174. package/lib/xml.js +3 -7
  175. package/lib/xml.js.map +1 -1
  176. package/lib/xml.test.js +11 -12
  177. package/lib/xml.test.js.map +1 -1
  178. package/package.json +7 -10
  179. package/src/api.ts +38 -55
  180. package/src/category.ts +21 -50
  181. package/src/codegen/boolean-string-enums.test.ts +12 -28
  182. package/src/codegen/boolean-string-enums.ts +2 -10
  183. package/src/codegen/cli.ts +29 -47
  184. package/src/codegen/defer-naming.test.ts +113 -0
  185. package/src/codegen/emit.ts +2 -5
  186. package/src/codegen/format.ts +12 -10
  187. package/src/codegen/generated-at.test.ts +89 -0
  188. package/src/codegen/generated-at.ts +88 -0
  189. package/src/codegen/generator.test.ts +8 -22
  190. package/src/codegen/generator.ts +72 -191
  191. package/src/codegen/graphql-client.test.ts +12 -42
  192. package/src/codegen/graphql-client.ts +30 -95
  193. package/src/codegen/graphql.ts +22 -94
  194. package/src/codegen/model-diff.ts +67 -0
  195. package/src/codegen/naming.ts +1 -2
  196. package/src/codegen/openapi-binary.test.ts +5 -12
  197. package/src/codegen/openapi-cli.ts +38 -79
  198. package/src/codegen/openapi.ts +79 -136
  199. package/src/codegen/operations.ts +2 -5
  200. package/src/codegen/pagination.ts +4 -11
  201. package/src/codegen/patch-audit.test.ts +160 -0
  202. package/src/codegen/patch-audit.ts +480 -0
  203. package/src/codegen/patches.test.ts +14 -21
  204. package/src/codegen/patches.ts +313 -103
  205. package/src/codegen/prelude.ts +1 -1
  206. package/src/codegen/proto.ts +18 -54
  207. package/src/codegen/protocol-imports.test.ts +39 -0
  208. package/src/codegen/rewrite-operation-ids.test.ts +23 -114
  209. package/src/codegen/rewrite-operation-ids.ts +111 -98
  210. package/src/codegen/spec-path.ts +3 -6
  211. package/src/codegen/untagged-unions.test.ts +3 -7
  212. package/src/error-category.ts +5 -17
  213. package/src/errors.ts +16 -31
  214. package/src/graphql.test.ts +6 -8
  215. package/src/graphql.ts +76 -219
  216. package/src/graphql.types.ts +10 -25
  217. package/src/json-patch.test.ts +77 -0
  218. package/src/json-patch.ts +54 -60
  219. package/src/pagination.test.ts +13 -35
  220. package/src/pagination.ts +44 -111
  221. package/src/protocol-http.test.ts +36 -30
  222. package/src/protocol-http.ts +73 -138
  223. package/src/protocol-rest.test.ts +703 -0
  224. package/src/protocol-rest.ts +24 -62
  225. package/src/response-validation.test.ts +12 -18
  226. package/src/response-validation.ts +3 -12
  227. package/src/retry-after.test.ts +267 -0
  228. package/src/retry-after.ts +4 -10
  229. package/src/retry.test.ts +566 -0
  230. package/src/retry.ts +6 -21
  231. package/src/sdks.test.ts +87 -0
  232. package/src/testing.ts +4 -10
  233. package/src/trait.ts +21 -67
  234. package/src/xml.test.ts +15 -33
  235. package/src/xml.ts +9 -25
@@ -54,18 +54,11 @@ export interface ValidatedPagination {
54
54
  * yield nothing. Returns the items-path root for emitters that promote it
55
55
  * to required.
56
56
  */
57
- export const validatePaginated = (
58
- o: ValidatePaginatedOptions,
59
- ): ValidatedPagination => {
60
- const itemsRoot = String(o.trait.items ?? o.itemsFallback ?? "").split(
61
- ".",
62
- )[0];
57
+ export const validatePaginated = (o: ValidatePaginatedOptions): ValidatedPagination => {
58
+ const itemsRoot = String(o.trait.items ?? o.itemsFallback ?? "").split(".")[0];
63
59
  const tokenOk =
64
60
  o.trait.mode === "single" ||
65
- (typeof o.trait.inputToken === "string" &&
66
- o.inputNames.has(o.trait.inputToken));
67
- const itemsOk =
68
- o.outputNames.has(itemsRoot) ||
69
- (o.syntheticOutputs?.has(itemsRoot) ?? false);
61
+ (typeof o.trait.inputToken === "string" && o.inputNames.has(o.trait.inputToken));
62
+ const itemsOk = o.outputNames.has(itemsRoot) || (o.syntheticOutputs?.has(itemsRoot) ?? false);
70
63
  return { ok: tokenOk && itemsOk, itemsRoot };
71
64
  };
@@ -0,0 +1,160 @@
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ mkdtempSync,
5
+ readdirSync,
6
+ readFileSync,
7
+ rmSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { afterEach, describe, expect, test } from "vitest";
13
+ import { auditPackage } from "./patch-audit.ts";
14
+
15
+ const dirs: string[] = [];
16
+ afterEach(() => {
17
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
18
+ });
19
+
20
+ // ---------------------------------------------------------------------------
21
+
22
+ const PATCHES_TS = join(import.meta.dirname, "patches.ts");
23
+
24
+ /**
25
+ * A package: `spec.json` lists field names, and every field becomes a
26
+ * member of `x#Thing`. `patches/spec/` edit the spec in the convert script
27
+ * itself (the way Railway patches its GraphQL schema, out of
28
+ * finalizeConvert's reach); `patches/svc/` are Smithy ops applied in
29
+ * finalizeConvert, whose transform drops a member named `dropped`.
30
+ */
31
+ const convertFixture = (patches: Record<string, unknown[]>): string => {
32
+ const parent = mkdtempSync(join(tmpdir(), "patch-audit-convert-"));
33
+ dirs.push(parent);
34
+ const root = join(parent, "pkg");
35
+ mkdirSync(join(root, "scripts"), { recursive: true });
36
+ writeFileSync(
37
+ join(root, "package.json"),
38
+ JSON.stringify({ name: "fixture", scripts: { convert: "node scripts/convert.ts" } }),
39
+ );
40
+ writeFileSync(join(root, "spec.json"), JSON.stringify({ fields: { a: true } }));
41
+ writeFileSync(
42
+ join(root, "scripts", "convert.ts"),
43
+ `
44
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
45
+ import { join } from "node:path";
46
+ import { applyRfc6902Files, finalizeConvert, isSmithyPatchPath, listRfc6902PatchFiles } from ${JSON.stringify(PATCHES_TS)};
47
+ const root = join(import.meta.dirname, "..");
48
+ const spec = JSON.parse(readFileSync(join(root, "spec.json"), "utf8"));
49
+ const files = await listRfc6902PatchFiles(join(root, "patches", "spec"));
50
+ const applied = await applyRfc6902Files(spec, files, { include: (op) => !isSmithyPatchPath(op.path) });
51
+ if (applied.errors.length) throw new Error(applied.errors.join("\\n"));
52
+ const members = Object.fromEntries(Object.keys(spec.fields).map((k) => [k, { target: "smithy.api#String" }]));
53
+ mkdirSync(join(root, ".generated-specs"), { recursive: true });
54
+ writeFileSync(join(root, ".generated-specs", "svc.json"), JSON.stringify({ smithy: "2.0", shapes: { "x#Thing": { type: "structure", members } } }));
55
+ await finalizeConvert({
56
+ root,
57
+ operationNaming: "as-is",
58
+ transform: (model) => { delete model.shapes["x#Thing"].members.dropped; },
59
+ });
60
+ `,
61
+ );
62
+ for (const [key, ops] of Object.entries(patches)) {
63
+ const dir = key.startsWith("spec/") ? "spec" : "svc";
64
+ mkdirSync(join(root, "patches", dir), { recursive: true });
65
+ const name = key.replace(/^spec\//, "");
66
+ writeFileSync(join(root, "patches", dir, name), JSON.stringify({ patches: ops }));
67
+ }
68
+ mkdirSync(join(root, ".generated-specs"));
69
+ writeFileSync(join(root, ".generated-specs", "svc.json"), "committed\n");
70
+ return root;
71
+ };
72
+
73
+ const addField = (name: string) => ({ op: "add", path: `/fields/${name}`, value: true });
74
+ const addMember = (name: string) => ({
75
+ op: "add",
76
+ path: `/shapes/x#Thing/members/${name}`,
77
+ value: { target: "smithy.api#String" },
78
+ });
79
+
80
+ describe("convert-stage patch audit", () => {
81
+ test("judges Smithy files in memory and the rest by convert", async () => {
82
+ const root = convertFixture({
83
+ "spec/1-spec.json": [addField("s")],
84
+ "2-member.json": [addMember("b")],
85
+ "3-noop.json": [{ op: "replace", path: "/shapes/x#Thing/type", value: "structure" }],
86
+ "4-dropped.json": [addMember("dropped")],
87
+ "5-uses-b.json": [{ op: "add", path: "/shapes/x#Thing/members/b/traits", value: {} }],
88
+ });
89
+ const result = await auditPackage(root, { jobs: 2 });
90
+ if (result.kind !== "audited") throw new Error(result.reason);
91
+ expect(Object.fromEntries(result.files.map((f) => [f.file.key, f.verdict]))).toEqual({
92
+ "spec/1-spec.json": { kind: "needed", diff: ["+ Thing/members/s"] },
93
+ "svc/2-member.json": { kind: "depended", error: expect.stringMatching(/members\/b/) },
94
+ "svc/3-noop.json": { kind: "unused" },
95
+ // The transform removes it again, so it changes nothing.
96
+ "svc/4-dropped.json": { kind: "unused" },
97
+ "svc/5-uses-b.json": { kind: "needed", diff: ["+ Thing/members/b/traits"] },
98
+ });
99
+ expect(result.judged).toEqual({ inMemory: 4, perFile: 1 });
100
+ });
101
+
102
+ test("--ops in memory finds the dead op", async () => {
103
+ const root = convertFixture({
104
+ "mixed.json": [
105
+ addMember("b"),
106
+ { op: "replace", path: "/shapes/x#Thing/type", value: "structure" },
107
+ ],
108
+ });
109
+ const result = await auditPackage(root, { ops: true, jobs: 1 });
110
+ if (result.kind !== "audited") throw new Error(result.reason);
111
+ expect(result.files[0]!.deadOps).toEqual([1]);
112
+ });
113
+
114
+ test("a file that only orders keys is needed", async () => {
115
+ const root = convertFixture({
116
+ "1-member.json": [addMember("b")],
117
+ "2-order.json": [
118
+ {
119
+ op: "move",
120
+ from: "/shapes/x#Thing/members/b",
121
+ path: "/shapes/x#Thing/members/b",
122
+ before: "a",
123
+ },
124
+ ],
125
+ });
126
+ const result = await auditPackage(root, { jobs: 1 });
127
+ if (result.kind !== "audited") throw new Error(result.reason);
128
+ expect(result.files.find((f) => f.file.key === "svc/2-order.json")!.verdict).toEqual({
129
+ kind: "needed",
130
+ diff: ["(key order only)"],
131
+ });
132
+ });
133
+
134
+ test("leaves the package as it was and removes its scratch copies", async () => {
135
+ const root = convertFixture({
136
+ "member.json": [addMember("b")],
137
+ "spec/s.json": [addField("s")],
138
+ });
139
+ const result = await auditPackage(root, { jobs: 2 });
140
+ expect(result.kind).toBe("audited");
141
+ expect(readFileSync(join(root, ".generated-specs", "svc.json"), "utf8")).toBe("committed\n");
142
+ expect(readdirSync(join(root, ".."))).toEqual(["pkg"]);
143
+ expect(existsSync(join(root, ".audit-request.json"))).toBe(false);
144
+ });
145
+
146
+ test("a patch that changes nothing has no effect", async () => {
147
+ const root = convertFixture({
148
+ "noop.json": [{ op: "replace", path: "/shapes/x#Thing/type", value: "structure" }],
149
+ });
150
+ const result = await auditPackage(root, { jobs: 1 });
151
+ if (result.kind !== "audited") throw new Error(result.reason);
152
+ expect(result.files[0]!.verdict).toEqual({ kind: "unused" });
153
+ });
154
+
155
+ test("a baseline that fails to convert is skipped", async () => {
156
+ const root = convertFixture({ "stale.json": [{ op: "remove", path: "/shapes/x#Gone" }] });
157
+ const result = await auditPackage(root, { jobs: 1 });
158
+ expect(result.kind).toBe("skipped");
159
+ });
160
+ });
@@ -0,0 +1,480 @@
1
+ /**
2
+ * Patch audit (dev-time only): does each RFC-6902 patch still change the
3
+ * model? A patch earns its keep by changing the patched model. The audit
4
+ * builds the model once with every patch (the baseline), then once per
5
+ * patch file with that file left out, and diffs:
6
+ *
7
+ * unused the model is identical without it — delete the file
8
+ * needed the model differs; the diff lists the JSON pointers
9
+ * depended the build fails without it — a later patch targets what it
10
+ * adds, so the two go together
11
+ *
12
+ * The model is built by running the package's `convert` on a scratch copy
13
+ * of the package (`packages/.audit-<pkg>-<n>`), so the spec mirror must be
14
+ * fetched. A file whose ops all target the Smithy model is judged in
15
+ * memory by `finalizeConvert` ({@link PATCH_AUDIT_ENV}): one convert, then
16
+ * only the finalize steps re-run per file. A file finalizeConvert does not
17
+ * apply (Railway's GraphQL patches) costs one convert per file
18
+ * ({@link SKIP_PATCHES_ENV}). Up to `jobs` copies run at once.
19
+ *
20
+ * The package itself is never written: its `.generated-*` dirs stay as
21
+ * committed.
22
+ *
23
+ * Every verdict is one-at-a-time: two patches that add the same thing each
24
+ * look unused alone, and only the second deletion changes the model.
25
+ */
26
+ import { spawn } from "node:child_process";
27
+ import {
28
+ cpSync,
29
+ existsSync,
30
+ mkdirSync,
31
+ readdirSync,
32
+ readFileSync,
33
+ rmSync,
34
+ statSync,
35
+ symlinkSync,
36
+ writeFileSync,
37
+ } from "node:fs";
38
+ import { availableParallelism, freemem } from "node:os";
39
+ import { basename, dirname, join, relative, sep } from "node:path";
40
+ import { diffModels, type Models } from "./model-diff.ts";
41
+ import {
42
+ isSmithyPatchPath,
43
+ PATCH_AUDIT_ENV,
44
+ PATCH_AUDIT_MARKER,
45
+ RENAME_MAP_ENV,
46
+ SKIP_PATCHES_ENV,
47
+ type InMemoryVerdict,
48
+ } from "./patches.ts";
49
+
50
+ export { diffModels, type Models };
51
+
52
+ export type Run =
53
+ | { readonly ok: true; readonly models: Models }
54
+ | { readonly ok: false; readonly error: string };
55
+
56
+ /** Builds the patched model, optionally with a skip-list entry left out. */
57
+ export interface ModelBuilder {
58
+ readonly build: (skip?: string) => Run;
59
+ readonly restore: (baseline: Models) => void;
60
+ }
61
+
62
+ export interface PatchFileInfo {
63
+ /** Path relative to the package's `patches/` — the skip-list entry. */
64
+ readonly key: string;
65
+ readonly ops: number;
66
+ /** Whether every op targets the Smithy model (`/shapes`, `/metadata`, …). */
67
+ readonly smithyOnly: boolean;
68
+ }
69
+
70
+ export type Verdict =
71
+ | { readonly kind: "unused" }
72
+ | { readonly kind: "needed"; readonly diff: readonly string[] }
73
+ | { readonly kind: "depended"; readonly error: string };
74
+
75
+ export interface FileVerdict {
76
+ readonly file: PatchFileInfo;
77
+ readonly verdict: Verdict;
78
+ /** With `ops`: indices of ops inside a needed file that change nothing alone. */
79
+ readonly deadOps: readonly number[];
80
+ }
81
+
82
+ export type PackageAudit =
83
+ | {
84
+ readonly kind: "audited";
85
+ readonly files: readonly FileVerdict[];
86
+ /** Files under `patches/` without a `patches` array (e.g. AWS typed configs). */
87
+ readonly notAudited: readonly string[];
88
+ /** How many files were judged in memory, and how many by one convert each. */
89
+ readonly judged: { readonly inMemory: number; readonly perFile: number };
90
+ }
91
+ | { readonly kind: "skipped"; readonly reason: string };
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // files
95
+
96
+ const walkJson = (dir: string): string[] => {
97
+ if (!existsSync(dir)) return [];
98
+ const out: string[] = [];
99
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
100
+ a.name.localeCompare(b.name),
101
+ )) {
102
+ const p = join(dir, entry.name);
103
+ if (entry.isDirectory()) out.push(...walkJson(p));
104
+ else if (entry.name.endsWith(".json")) out.push(p);
105
+ }
106
+ return out;
107
+ };
108
+
109
+ /** RFC-6902 files under `patchesDir`; anything without a `patches` array is returned separately. */
110
+ export const listPatchFiles = (patchesDir: string): { files: PatchFileInfo[]; other: string[] } => {
111
+ const files: PatchFileInfo[] = [];
112
+ const other: string[] = [];
113
+ for (const file of walkJson(patchesDir)) {
114
+ const key = relative(patchesDir, file).split(sep).join("/");
115
+ let parsed: unknown;
116
+ try {
117
+ parsed = JSON.parse(readFileSync(file, "utf8"));
118
+ } catch {
119
+ other.push(key);
120
+ continue;
121
+ }
122
+ const ops = (parsed as { patches?: unknown })?.patches;
123
+ if (!Array.isArray(ops)) {
124
+ other.push(key);
125
+ continue;
126
+ }
127
+ const smithyOnly = ops.every(
128
+ (op) => typeof op?.path === "string" && isSmithyPatchPath(op.path),
129
+ );
130
+ files.push({ key, ops: ops.length, smithyOnly });
131
+ }
132
+ return { files, other };
133
+ };
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // scratch copies
137
+
138
+ /**
139
+ * A scratch copy of the package next to it (same depth, so relative imports
140
+ * and `node_modules` resolve the same; the dot keeps it out of the pnpm
141
+ * workspace). `scripts/` and `package.json` are copied — Node resolves a
142
+ * symlinked script to its real path, which would make the copy's convert
143
+ * write to the real package — `.generated-*` dirs start empty, and
144
+ * everything else is a symlink.
145
+ */
146
+ const scratchCopy = (pkgDir: string, index: number): string => {
147
+ const dir = join(dirname(pkgDir), `.audit-${basename(pkgDir)}-${index}`);
148
+ rmSync(dir, { recursive: true, force: true });
149
+ mkdirSync(dir);
150
+ for (const entry of readdirSync(pkgDir, { withFileTypes: true })) {
151
+ const from = join(pkgDir, entry.name);
152
+ const to = join(dir, entry.name);
153
+ // Every convert output dir (`.generated-specs`, Railway's
154
+ // `.generated-graphql`) starts empty, so convert never writes through a
155
+ // symlink into the package.
156
+ if (entry.name.startsWith(".generated")) mkdirSync(to);
157
+ else if (entry.name === "scripts" || entry.name === "package.json") {
158
+ cpSync(from, to, { recursive: true });
159
+ } else symlinkSync(from, to);
160
+ }
161
+ return dir;
162
+ };
163
+
164
+ /** Every model convert wrote in a copy, keyed `<.generated-* dir>/<path>`. */
165
+ const outputs = (copy: string): Models => {
166
+ const out: Models = new Map();
167
+ for (const entry of readdirSync(copy, { withFileTypes: true })) {
168
+ if (!entry.isDirectory() || !entry.name.startsWith(".generated")) continue;
169
+ const dir = join(copy, entry.name);
170
+ for (const f of walkJson(dir))
171
+ out.set(`${entry.name}/${relative(dir, f)}`, readFileSync(f, "utf8"));
172
+ }
173
+ return out;
174
+ };
175
+
176
+ interface ConvertResult {
177
+ readonly ok: boolean;
178
+ /** convert's own report when it failed: the `❌` lines, or its last lines. */
179
+ readonly error: string;
180
+ }
181
+
182
+ /**
183
+ * Run the package's convert command in `cwd`. Marker lines from an
184
+ * in-memory audit go to `onVerdict`; everything else is only kept for the
185
+ * error report.
186
+ */
187
+ const runConvert = (
188
+ command: string,
189
+ cwd: string,
190
+ env: NodeJS.ProcessEnv,
191
+ onVerdict: (v: InMemoryVerdict) => void = () => {},
192
+ ): Promise<ConvertResult> =>
193
+ new Promise((resolve) => {
194
+ const child = spawn(command, { cwd, env, shell: true, stdio: ["ignore", "pipe", "pipe"] });
195
+ const reported: string[] = [];
196
+ const tail: string[] = [];
197
+ const keep = (line: string) => {
198
+ const l = line.trim();
199
+ if (l === "" || l.startsWith(`⚠ ${SKIP_PATCHES_ENV}`)) return;
200
+ if (l.startsWith("❌")) reported.push(l);
201
+ tail.push(l);
202
+ if (tail.length > 20) tail.shift();
203
+ };
204
+ const lines = (stream: NodeJS.ReadableStream, onLine: (line: string) => void) => {
205
+ let buffer = "";
206
+ stream.setEncoding("utf8");
207
+ stream.on("data", (chunk: string) => {
208
+ buffer += chunk;
209
+ let nl: number;
210
+ while ((nl = buffer.indexOf("\n")) !== -1) {
211
+ onLine(buffer.slice(0, nl));
212
+ buffer = buffer.slice(nl + 1);
213
+ }
214
+ });
215
+ stream.on("end", () => buffer && onLine(buffer));
216
+ };
217
+ lines(child.stdout!, (line) => {
218
+ if (line.startsWith(PATCH_AUDIT_MARKER)) {
219
+ onVerdict(JSON.parse(line.slice(PATCH_AUDIT_MARKER.length)) as InMemoryVerdict);
220
+ } else keep(line);
221
+ });
222
+ lines(child.stderr!, keep);
223
+ child.on("error", (e) => keep(String(e)));
224
+ child.on("close", (code) => {
225
+ // convert reports each bad patch on its own `❌` line before throwing;
226
+ // those name the pointer, the stack trace below them does not.
227
+ const shown = reported.length > 0 ? reported : tail.slice(-2);
228
+ resolve({ ok: code === 0, error: shown.slice(0, 3).join("\n ") });
229
+ });
230
+ });
231
+
232
+ /** Copies to run at once: one core and ~1.5 GB of free memory each. */
233
+ const defaultJobs = (): number =>
234
+ Math.max(1, Math.min(availableParallelism() - 1, Math.floor(freemem() / 1.5e9)));
235
+
236
+ /**
237
+ * Split keys into at most `n` shards of about equal cost. A key costs about
238
+ * the size of the model its patch dir applies to (every judgement re-runs
239
+ * finalize over that model), so a dir is kept whole when it fits in one
240
+ * shard's share and cut into chunks when it does not — each chunk pays one
241
+ * more convert, which is cheap next to hundreds of re-finalized copies of a
242
+ * large model.
243
+ */
244
+ const shard = (keys: readonly string[], n: number, cost: (dir: string) => number): string[][] => {
245
+ const groups = new Map<string, string[]>();
246
+ for (const key of keys) {
247
+ const dir = key.includes("/") ? key.slice(0, key.lastIndexOf("/")) : "";
248
+ groups.set(dir, [...(groups.get(dir) ?? []), key]);
249
+ }
250
+ const weighted = [...groups].map(([dir, ks]) => ({ keys: ks, each: cost(dir) }));
251
+ const total = weighted.reduce((sum, g) => sum + g.keys.length * g.each, 0);
252
+ const share = total / n;
253
+ const pieces: { keys: string[]; cost: number }[] = [];
254
+ for (const g of weighted) {
255
+ const chunks = Math.min(
256
+ g.keys.length,
257
+ Math.max(1, Math.ceil((g.keys.length * g.each) / share)),
258
+ );
259
+ const size = Math.ceil(g.keys.length / chunks);
260
+ for (let i = 0; i < g.keys.length; i += size) {
261
+ const ks = g.keys.slice(i, i + size);
262
+ pieces.push({ keys: ks, cost: ks.length * g.each });
263
+ }
264
+ }
265
+ const shards = Array.from({ length: Math.min(n, pieces.length) }, () => ({
266
+ keys: [] as string[],
267
+ cost: 0,
268
+ }));
269
+ for (const piece of pieces.sort((a, b) => b.cost - a.cost)) {
270
+ const min = shards.reduce((a, b) => (b.cost < a.cost ? b : a));
271
+ min.keys.push(...piece.keys);
272
+ min.cost += piece.cost;
273
+ }
274
+ return shards.map((s) => s.keys).filter((ks) => ks.length > 0);
275
+ };
276
+
277
+ /** Merge one file's verdicts from every model its patch dir applies to. */
278
+ const mergeVerdicts = (vs: readonly InMemoryVerdict[]): Omit<FileVerdict, "file"> => {
279
+ const failed = vs.find((v) => v.verdict.kind === "depended" || v.verdict.kind === "baseline");
280
+ if (failed && "error" in failed.verdict) {
281
+ return { verdict: { kind: "depended", error: failed.verdict.error }, deadOps: [] };
282
+ }
283
+ const needed = vs.filter((v) => v.verdict.kind === "needed");
284
+ if (needed.length === 0) return { verdict: { kind: "unused" }, deadOps: [] };
285
+ const diff = needed.flatMap((v) =>
286
+ v.verdict.kind === "needed"
287
+ ? v.verdict.diff.map((line) => (needed.length > 1 ? `${v.model}: ${line}` : line))
288
+ : [],
289
+ );
290
+ // An op is dead only if it changes nothing in any of the models.
291
+ const deadOps = needed.map((v) => v.deadOps).reduce((a, b) => a.filter((i) => b.includes(i)));
292
+ return { verdict: { kind: "needed", diff }, deadOps };
293
+ };
294
+
295
+ /** Bounded-concurrency map over a pool of scratch copies. */
296
+ const withCopies = async <A>(
297
+ copies: readonly string[],
298
+ tasks: readonly A[],
299
+ run: (task: A, copy: string) => Promise<void>,
300
+ ): Promise<void> => {
301
+ let next = 0;
302
+ await Promise.all(
303
+ copies.map(async (copy) => {
304
+ while (next < tasks.length) await run(tasks[next++]!, copy);
305
+ }),
306
+ );
307
+ };
308
+
309
+ const auditConvertStage = async (
310
+ pkgDir: string,
311
+ command: string,
312
+ files: readonly PatchFileInfo[],
313
+ options: AuditOptions,
314
+ report: (v: FileVerdict) => void,
315
+ ): Promise<{ inMemory: number; perFile: number } | { error: string }> => {
316
+ const jobs = Math.max(1, options.jobs ?? defaultJobs());
317
+ const inMemoryKeys =
318
+ options.inMemory === false ? [] : files.filter((f) => f.smithyOnly).map((f) => f.key);
319
+ // A dir's cost: the size of the committed model it patches (1 MB when
320
+ // there is none to go by, e.g. a root-level file patching every model).
321
+ const specsDir = join(pkgDir, ".generated-specs");
322
+ const cost = (dir: string): number => {
323
+ const model = join(specsDir, `${dir}.json`);
324
+ return dir !== "" && existsSync(model) ? Math.max(1, statSync(model).size / 1e6) : 1;
325
+ };
326
+ const shards = shard(inMemoryKeys, jobs, cost);
327
+ // Even with nothing to judge in memory, one convert builds the baseline.
328
+ if (shards.length === 0) shards.push([]);
329
+ const copies = Array.from({ length: Math.max(1, Math.min(jobs, files.length)) }, (_, i) =>
330
+ scratchCopy(pkgDir, i),
331
+ );
332
+ const cleanup = () => {
333
+ for (const c of copies) rmSync(c, { recursive: true, force: true });
334
+ };
335
+ const onSignal = () => {
336
+ cleanup();
337
+ process.exit(130);
338
+ };
339
+ process.once("SIGINT", onSignal);
340
+ process.once("SIGTERM", onSignal);
341
+ const byKey = new Map(files.map((f) => [f.key, f]));
342
+ try {
343
+ // 1. In memory: one convert per shard, each on its own copy.
344
+ const verdicts = new Map<string, InMemoryVerdict[]>();
345
+ let baselineError: string | undefined;
346
+ await withCopies(copies, shards, async (keys, copy) => {
347
+ const request = join(copy, ".audit-request.json");
348
+ writeFileSync(request, JSON.stringify({ keys, ops: options.ops === true }));
349
+ const result = await runConvert(
350
+ command,
351
+ copy,
352
+ { ...process.env, [PATCH_AUDIT_ENV]: request, [SKIP_PATCHES_ENV]: "" },
353
+ (v) => {
354
+ verdicts.set(v.key, [...(verdicts.get(v.key) ?? []), v]);
355
+ options.onProgress?.();
356
+ },
357
+ );
358
+ if (!result.ok) baselineError ??= result.error;
359
+ // A key is complete once its convert has exited: GCP judges one
360
+ // patch dir against both its stable and unstable model.
361
+ for (const key of keys) {
362
+ const vs = verdicts.get(key);
363
+ if (vs) report({ file: byKey.get(key)!, ...mergeVerdicts(vs) });
364
+ }
365
+ });
366
+ if (baselineError !== undefined) return { error: baselineError };
367
+
368
+ // 2. Everything else: one convert per file, diffed against the baseline
369
+ // a copy just wrote.
370
+ const perFile = files.filter((f) => !verdicts.has(f.key));
371
+ if (perFile.length > 0) {
372
+ const baseline = outputs(copies[0]!);
373
+ const judge = async (skip: string, copy: string): Promise<Verdict> => {
374
+ const result = await runConvert(command, copy, {
375
+ ...process.env,
376
+ [SKIP_PATCHES_ENV]: skip,
377
+ });
378
+ if (!result.ok) return { kind: "depended", error: result.error };
379
+ const diff = diffModels(baseline, outputs(copy));
380
+ return diff.length === 0 ? { kind: "unused" } : { kind: "needed", diff };
381
+ };
382
+ await withCopies(copies, perFile, async (file, copy) => {
383
+ const verdict = await judge(file.key, copy);
384
+ options.onProgress?.();
385
+ const deadOps: number[] = [];
386
+ if (options.ops && verdict.kind === "needed" && file.ops > 1) {
387
+ for (let index = 0; index < file.ops; index++) {
388
+ if ((await judge(`${file.key}:${index}`, copy)).kind === "unused") deadOps.push(index);
389
+ }
390
+ }
391
+ report({ file, verdict, deadOps });
392
+ });
393
+ }
394
+ return { inMemory: verdicts.size, perFile: perFile.length };
395
+ } finally {
396
+ process.off("SIGINT", onSignal);
397
+ process.off("SIGTERM", onSignal);
398
+ cleanup();
399
+ }
400
+ };
401
+
402
+ // ---------------------------------------------------------------------------
403
+ // audit
404
+
405
+ export interface AuditOptions {
406
+ /** Also judge every op inside each needed file. */
407
+ readonly ops?: boolean;
408
+ /** Only files whose key contains this substring. */
409
+ readonly only?: string;
410
+ /** Scratch copies converting at once; default from cores and free memory. */
411
+ readonly jobs?: number;
412
+ /** `false` judges every file by one convert each (the slow path; for comparing). */
413
+ readonly inMemory?: boolean;
414
+ /** Called after each file's verdict, in completion order. */
415
+ readonly onFile?: (verdict: FileVerdict) => void;
416
+ /** Called as each file is judged, before its verdict is final. */
417
+ readonly onProgress?: () => void;
418
+ }
419
+
420
+ /** Audit one package directory. Never throws for a broken baseline — that is `skipped`. */
421
+ export const auditPackage = async (
422
+ pkgDir: string,
423
+ options: AuditOptions = {},
424
+ ): Promise<PackageAudit> => {
425
+ const patchesDir = join(pkgDir, "patches");
426
+ if (!existsSync(patchesDir)) return { kind: "skipped", reason: "no patches/ directory" };
427
+ const listed = listPatchFiles(patchesDir);
428
+ const files =
429
+ options.only === undefined
430
+ ? listed.files
431
+ : listed.files.filter((f) => f.key.includes(options.only!));
432
+ const order = new Map(files.map((f, i) => [f.key, i]));
433
+ const verdicts: FileVerdict[] = [];
434
+ const report = (v: FileVerdict) => {
435
+ verdicts.push(v);
436
+ options.onFile?.(v);
437
+ };
438
+ const done = (judged: { inMemory: number; perFile: number }): PackageAudit => ({
439
+ kind: "audited",
440
+ files: verdicts.sort((a, b) => order.get(a.file.key)! - order.get(b.file.key)!),
441
+ notAudited: listed.other,
442
+ judged,
443
+ });
444
+ if (files.length === 0) return done({ inMemory: 0, perFile: 0 });
445
+
446
+ const command = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")).scripts?.convert;
447
+ if (!command) return { kind: "skipped", reason: "no `convert` script applies patches" };
448
+ const result = await auditConvertStage(pkgDir, command, files, options, report);
449
+ if ("error" in result)
450
+ return { kind: "skipped", reason: `baseline build fails: ${result.error}` };
451
+ return done(result);
452
+ };
453
+
454
+ // ---------------------------------------------------------------------------
455
+ // names
456
+
457
+ /**
458
+ * Each model's deferred rename — upstream shape id → the final id in
459
+ * `.generated-specs` — from one convert on a scratch copy. Smithy patches
460
+ * apply before the rename, so they use the upstream ids.
461
+ */
462
+ export const renameMaps = async (
463
+ pkgDir: string,
464
+ ): Promise<
465
+ { ok: true; maps: Record<string, Record<string, string>> } | { ok: false; error: string }
466
+ > => {
467
+ const command = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")).scripts?.convert;
468
+ if (!command) return { ok: false, error: "no `convert` script" };
469
+ const copy = scratchCopy(pkgDir, 0);
470
+ try {
471
+ const out = join(copy, ".rename-map.json");
472
+ const result = await runConvert(command, copy, { ...process.env, [RENAME_MAP_ENV]: out });
473
+ // The maps are recorded before the Smithy patches apply, so a convert
474
+ // that fails on a stale patch still names its shapes.
475
+ if (existsSync(out)) return { ok: true, maps: JSON.parse(readFileSync(out, "utf8")) };
476
+ return result.ok ? { ok: true, maps: {} } : { ok: false, error: result.error };
477
+ } finally {
478
+ rmSync(copy, { recursive: true, force: true });
479
+ }
480
+ };