@aestheticfunction/dspack-emit 0.4.1 → 0.5.0

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 (64) hide show
  1. package/README.md +16 -6
  2. package/dist/cli.js +56 -0
  3. package/dist/index.d.ts +4 -1
  4. package/dist/index.js +3 -1
  5. package/dist/targets/a2ui/diagnostics.d.ts +110 -0
  6. package/dist/targets/a2ui/diagnostics.js +94 -0
  7. package/dist/targets/a2ui/surface.d.ts +28 -9
  8. package/dist/targets/a2ui/surface.js +566 -224
  9. package/dist/transform/desugar.d.ts +32 -0
  10. package/dist/transform/desugar.js +156 -0
  11. package/dist/transform/emit.js +59 -0
  12. package/dist/transform/index.js +4 -0
  13. package/dist/transform/mapping.d.ts +0 -6
  14. package/dist/transform/mapping.js +50 -0
  15. package/dist/transform/model.d.ts +275 -0
  16. package/dist/transform/model.js +148 -0
  17. package/dist/transform/parse-v2.d.ts +78 -0
  18. package/dist/transform/parse-v2.js +305 -0
  19. package/dist/transform/profile-load.d.ts +7 -6
  20. package/dist/transform/profile-load.js +99 -20
  21. package/dist/transform/profile-schema-v2.d.ts +9 -0
  22. package/dist/transform/profile-schema-v2.js +430 -0
  23. package/dist/transform/profiles.d.ts +31 -1
  24. package/dist/transform/scaffold.d.ts +29 -12
  25. package/dist/transform/scaffold.js +91 -31
  26. package/dist/transform/shadcn-v2-respelling.d.ts +12 -0
  27. package/dist/transform/shadcn-v2-respelling.js +49 -0
  28. package/dist/transform/validate-v2.d.ts +36 -0
  29. package/dist/transform/validate-v2.js +100 -0
  30. package/dist/types.d.ts +19 -0
  31. package/dist/validate/ajv.js +96 -25
  32. package/package.json +2 -2
  33. package/src/__snapshots__/byte-neutral.test.ts.snap +66 -0
  34. package/src/byte-neutral.test.ts +246 -0
  35. package/src/cli.ts +60 -0
  36. package/src/dangling-ref.test.ts +118 -0
  37. package/src/desugar.test.ts +162 -0
  38. package/src/engine-boundary.test.ts +248 -0
  39. package/src/eval-fixture.test.ts +89 -0
  40. package/src/functions.test.ts +182 -0
  41. package/src/index.ts +4 -1
  42. package/src/profile-load.test.ts +99 -1
  43. package/src/profile-v2.test.ts +363 -0
  44. package/src/review-findings.test.ts +292 -0
  45. package/src/schema-mirrors.test.ts +5 -0
  46. package/src/surface-fidelity.test.ts +213 -0
  47. package/src/targets/a2ui/diagnostics.ts +136 -0
  48. package/src/targets/a2ui/surface.ts +920 -242
  49. package/src/transform/desugar.ts +194 -0
  50. package/src/transform/emit.ts +65 -0
  51. package/src/transform/index.ts +5 -0
  52. package/src/transform/mapping.ts +42 -0
  53. package/src/transform/model.ts +325 -0
  54. package/src/transform/parse-v2.ts +397 -0
  55. package/src/transform/profile-load.ts +104 -22
  56. package/src/transform/profile-schema-v2.ts +430 -0
  57. package/src/transform/profile.v2.schema.json +422 -0
  58. package/src/transform/profiles.ts +32 -1
  59. package/src/transform/scaffold.ts +124 -47
  60. package/src/transform/shadcn-v2-respelling.ts +61 -0
  61. package/src/transform/validate-v2.ts +138 -0
  62. package/src/types.ts +20 -0
  63. package/src/validate/ajv.ts +89 -26
  64. package/src/validate-v2.test.ts +173 -0
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Regression pins for the adversarial review of the v2 foundation (workflow
3
+ * wf_1c1cc374-ced: 17 agents, 13 confirmed findings, 10 distinct defects —
4
+ * every one in the new v2/ledger surface, none in the byte-frozen v1 paths).
5
+ *
6
+ * Each test is named for its finding and failed against the pre-fix code.
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+ import { fileURLToPath } from "node:url";
10
+ import { describe, expect, it } from "vitest";
11
+ import { transformFromJson } from "./transform/index.js";
12
+ import { emitSurface } from "./targets/a2ui/surface.js";
13
+ import { loadProfile, ProfileLoadError } from "./transform/profile-load.js";
14
+ import { ProfileContractError } from "./transform/validate-v2.js";
15
+ import type { DspackDoc, DspackSurface } from "./types.js";
16
+
17
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
18
+ const doc = JSON.parse(readFileSync(repo("input/shadcn-ui.dspack.json"), "utf8")) as DspackDoc;
19
+
20
+ const surface = (root: unknown, intent = "record-collection"): DspackSurface =>
21
+ ({ dspackSurface: "0.1", system: doc.name as string, intent, root }) as DspackSurface;
22
+
23
+ const CARD_SUBS = {
24
+ "card-header": "transparent",
25
+ "card-content": "transparent",
26
+ "card-footer": "transparent",
27
+ "card-title": { asText: "h3" },
28
+ "card-description": { asText: "caption" },
29
+ };
30
+
31
+ const v2Doc = (
32
+ cardSurface: unknown,
33
+ opts: { collection?: "components" | "synthesized"; functions?: unknown } = {},
34
+ ): Record<string, unknown> => {
35
+ const cardPlan = {
36
+ a2ui: "Card",
37
+ dspackId: "card",
38
+ commons: ["ComponentCommon"],
39
+ structural: {
40
+ child: { schema: { type: "string" }, description: "d", synthNote: "s" },
41
+ label: { schema: { type: "string" }, description: "d", synthNote: "s" },
42
+ extra: { schema: { type: "string" }, description: "d", synthNote: "s" },
43
+ },
44
+ required: [],
45
+ ...(cardSurface === undefined ? {} : { surface: cardSurface }),
46
+ };
47
+ return {
48
+ profileVersion: "2",
49
+ catalogTitle: "t",
50
+ catalogDescription: "d",
51
+ catalogIdBase: "https://example.test/catalogs/x",
52
+ instructions: "",
53
+ primaryColorToken: { category: "color", name: "primary" },
54
+ surfaceSynthesis: { textComponent: "Text", textProp: "text", wrapComponent: "Column", wrapChildrenProp: "children" },
55
+ ...(opts.functions ? { functions: opts.functions } : {}),
56
+ synthesized: [
57
+ {
58
+ a2ui: "Text",
59
+ commons: ["ComponentCommon"],
60
+ structural: { text: { schema: { type: "string" }, description: "d", synthNote: "s" } },
61
+ propMap: { variant: { a2ui: "variant", kind: "enum", targetEnum: ["body", "h3", "caption"] } },
62
+ required: ["text"],
63
+ },
64
+ {
65
+ a2ui: "Column",
66
+ commons: ["ComponentCommon"],
67
+ structural: { children: { schema: { type: "array" }, description: "d", synthNote: "s" } },
68
+ required: ["children"],
69
+ },
70
+ ...(opts.collection === "synthesized" ? [cardPlan] : []),
71
+ ],
72
+ casualtyComponents: [],
73
+ components: opts.collection === "synthesized" ? [] : [cardPlan],
74
+ };
75
+ };
76
+
77
+ describe("the contract gate has no side doors (findings 1, 6, 8, 9)", () => {
78
+ it("a mapped compound in `synthesized` is validated exactly like one in `components`", () => {
79
+ const withBogusSub = {
80
+ routes: [{ from: ["sub(card-sidebar).text"], to: "prop:label" }],
81
+ subs: CARD_SUBS,
82
+ };
83
+ for (const collection of ["components", "synthesized"] as const) {
84
+ expect(
85
+ () => transformFromJson(doc, { profile: loadProfile(v2Doc(withBogusSub, { collection })) }),
86
+ collection,
87
+ ).toThrowError(ProfileContractError);
88
+ }
89
+ });
90
+
91
+ it("omitting the surface block is exactly as unresolved as `surface: {}`", () => {
92
+ for (const spelling of [undefined, {}]) {
93
+ try {
94
+ transformFromJson(doc, { profile: loadProfile(v2Doc(spelling)) });
95
+ expect.unreachable("a compound with undecided subs must refuse either way");
96
+ } catch (e) {
97
+ expect(e).toBeInstanceOf(ProfileContractError);
98
+ const issues = (e as ProfileContractError).issues;
99
+ expect(issues).toHaveLength(5);
100
+ expect(issues.every((i) => i.message.includes("unresolved"))).toBe(true);
101
+ }
102
+ }
103
+ });
104
+ });
105
+
106
+ describe("an authored drop is warn-and-discard everywhere (finding 2)", () => {
107
+ it("a dropped sub on a non-collecting plan is skipped with its reason, not crashed", () => {
108
+ const profile = loadProfile(
109
+ v2Doc({
110
+ routes: [{ from: ["children"], to: "slot:child" }],
111
+ subs: { ...CARD_SUBS, "card-description": { drop: "descriptions are not carried here" } },
112
+ }),
113
+ );
114
+ const { messages, warnings, fidelity } = emitSurface(
115
+ surface({
116
+ component: "card",
117
+ children: [
118
+ { component: "card-description", text: "gone" },
119
+ { component: "card-content", text: "kept" },
120
+ ],
121
+ }),
122
+ doc,
123
+ { profile },
124
+ );
125
+ expect(JSON.stringify(messages)).not.toContain("gone");
126
+ expect(JSON.stringify(messages)).toContain("kept");
127
+ const warn = warnings.find((w) => w.code === "surface-sub-dropped");
128
+ expect(warn?.message).toContain("descriptions are not carried here");
129
+ expect(fidelity.find((f) => f.origin === "drops.card-description")).toMatchObject({ kind: "dropped", class: "lossy" });
130
+ });
131
+ });
132
+
133
+ describe("a renamed self-prop read does not suppress the prop's own projection (finding 3)", () => {
134
+ it("badge keeps its projected variant while the route writes the extra copy", () => {
135
+ // The contract's `badge` declares `variant`, so the renamed read
136
+ // (self.props.variant -> prop:extra) is gate-legal — and must not
137
+ // suppress the propMap projection of variant itself.
138
+ const withBadge = v2Doc({ routes: [{ from: ["children"], to: "slot:child" }], subs: CARD_SUBS });
139
+ (withBadge.components as Array<Record<string, unknown>>).push({
140
+ a2ui: "Badge",
141
+ dspackId: "badge",
142
+ commons: ["ComponentCommon"],
143
+ structural: {
144
+ label: { schema: { type: "string" }, description: "d", synthNote: "s" },
145
+ extra: { schema: { type: "string" }, description: "d", synthNote: "s" },
146
+ },
147
+ propMap: { variant: { a2ui: "variant", kind: "enum", targetEnum: ["default", "secondary", "destructive", "outline"] } },
148
+ required: [],
149
+ surface: {
150
+ routes: [
151
+ { from: ["self.text"], to: "prop:label", overwrite: true },
152
+ { from: ["self.props.variant"], to: "prop:extra" },
153
+ ],
154
+ },
155
+ });
156
+ const { messages } = emitSurface(
157
+ surface({ component: "badge", text: "New", props: { variant: "outline" } }),
158
+ doc,
159
+ { profile: loadProfile(withBadge) },
160
+ );
161
+ const [badge] = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } })
162
+ .updateComponents.components;
163
+ expect(badge.variant).toBe("outline"); // the projection survived
164
+ expect(badge.extra).toBe("outline"); // and the routed copy landed too
165
+ });
166
+ });
167
+
168
+ describe("dead and contradictory spellings refuse at load (findings 4, 5, 13)", () => {
169
+ const refusal = (s: unknown): string => {
170
+ try {
171
+ loadProfile(v2Doc(s));
172
+ return "LOADED";
173
+ } catch (e) {
174
+ if (e instanceof ProfileLoadError) return e.issues.map((i) => `${i.path}: ${i.message}`).join("\n");
175
+ throw e;
176
+ }
177
+ };
178
+
179
+ it("firstText cannot lead a route — it is a fallback selector", () => {
180
+ const out = refusal({ routes: [{ from: ["sub(card-title).firstText"], to: "prop:label" }], subs: CARD_SUBS });
181
+ expect(out).toContain("cannot lead a route");
182
+ // ...while the fallback position stays legal (card-title consumed by the
183
+ // route, so it carries no separate disposition).
184
+ const { "card-title": _consumed, ...rest } = CARD_SUBS;
185
+ expect(
186
+ refusal({
187
+ routes: [{ from: ["sub(card-title).label", "sub(card-title).firstText"], to: "prop:label" }],
188
+ subs: rest,
189
+ }),
190
+ ).toBe("LOADED");
191
+ });
192
+
193
+ it("a children route's destination is exclusive in both directions", () => {
194
+ const childrenFirst = refusal({
195
+ routes: [
196
+ { from: ["children"], to: "slot:child" },
197
+ { from: ["self.text"], to: "textChild:child" },
198
+ ],
199
+ subs: CARD_SUBS,
200
+ });
201
+ expect(childrenFirst).toContain("children route");
202
+ const childrenSecond = refusal({
203
+ routes: [
204
+ { from: ["self.text"], to: "textChild:child" },
205
+ { from: ["children"], to: "slot:child" },
206
+ ],
207
+ subs: CARD_SUBS,
208
+ });
209
+ expect(childrenSecond).toContain("first-wins");
210
+ });
211
+
212
+ it("a collect cell source cannot also carry a disposition", () => {
213
+ const out = refusal({
214
+ collects: [
215
+ { of: ["card-header"], into: "prop:label", shape: "flat", row: ["card-content"], cells: ["card-title"] },
216
+ ],
217
+ subs: { "card-title": { drop: "also a cell — contradiction" }, "card-description": { asText: "caption" }, "card-footer": "transparent" },
218
+ });
219
+ expect(out).toContain("one sub, one disposition");
220
+ });
221
+ });
222
+
223
+ describe("the ledger never reports a discarded value as landed (findings 7, 11, 12)", () => {
224
+ it("a first-wins-skipped harvest ledgers as dropped/lossy, not moved", () => {
225
+ // The shipped v1 Table: authored caption prop beats the harvested one.
226
+ const { fidelity } = emitSurface(
227
+ surface({
228
+ component: "table",
229
+ props: { caption: "Authored" },
230
+ children: [{ component: "table-caption", text: "Harvested" }],
231
+ }),
232
+ doc,
233
+ {},
234
+ );
235
+ const discarded = fidelity.find((f) => f.kind === "dropped" && f.note?.includes("already written"));
236
+ expect(discarded).toBeDefined();
237
+ expect(discarded!.destination).toBe("(discarded)");
238
+ // And only ONE entry claims the caption landed.
239
+ expect(fidelity.filter((f) => f.destination === "caption")).toHaveLength(1);
240
+ });
241
+
242
+ it("unrouted node text is a ledgered loss (warnings stay byte-frozen)", () => {
243
+ const { warnings, fidelity } = emitSurface(
244
+ surface({ component: "card", text: "orphaned words", children: [{ component: "badge", text: "x" }] }),
245
+ doc,
246
+ {},
247
+ );
248
+ // Warnings are byte-frozen: the discard appears in NO warning...
249
+ expect(warnings.every((w) => !w.message.includes("orphaned words"))).toBe(true);
250
+ // ...and in exactly one ledger entry.
251
+ const entry = fidelity.find((f) => f.note?.includes("no self.text route"));
252
+ expect(entry).toMatchObject({ kind: "dropped", class: "lossy", destination: "(discarded)" });
253
+ });
254
+
255
+ it("asText that destroys nested structure records flattened/lossy like the cell path", () => {
256
+ const { fidelity } = emitSurface(
257
+ surface({
258
+ component: "card",
259
+ children: [
260
+ {
261
+ component: "card-title",
262
+ children: [{ component: "badge", text: "Urgent" }],
263
+ },
264
+ ],
265
+ }),
266
+ doc,
267
+ {},
268
+ );
269
+ const loss = fidelity.find((f) => f.kind === "flattened" && f.source.includes("card-title"));
270
+ expect(loss).toMatchObject({ class: "lossy" });
271
+ expect(loss!.source).toContain("'badge'");
272
+ });
273
+ });
274
+
275
+ describe("function args are self-contained (finding 10)", () => {
276
+ it("a $ref inside declared args refuses at load with its path", () => {
277
+ try {
278
+ loadProfile(
279
+ v2Doc(
280
+ { routes: [{ from: ["children"], to: "slot:child" }], subs: CARD_SUBS },
281
+ { functions: { probe: { description: "d", returns: "boolean", args: { $ref: "#/$defs/DoesNotExist" } } } },
282
+ ),
283
+ );
284
+ expect.unreachable("a $ref in function args must refuse");
285
+ } catch (e) {
286
+ expect(e).toBeInstanceOf(ProfileLoadError);
287
+ const issue = (e as ProfileLoadError).issues[0];
288
+ expect(issue.path).toBe("/functions/probe/args");
289
+ expect(issue.message).toContain("self-contained");
290
+ }
291
+ });
292
+ });
@@ -11,6 +11,7 @@ import { fileURLToPath } from "node:url";
11
11
  import { describe, expect, it } from "vitest";
12
12
  import { catalogMetaSchemas } from "./validate/meta/catalog-meta.js";
13
13
  import { profileSchema } from "./transform/profile-schema.js";
14
+ import { profileSchemaV2 } from "./transform/profile-schema-v2.js";
14
15
 
15
16
  const doc = (rel: string): unknown =>
16
17
  JSON.parse(readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8"));
@@ -27,4 +28,8 @@ describe("schema mirrors", () => {
27
28
  it("profile-schema mirror equals profile.v1.schema.json", () => {
28
29
  expect(profileSchema).toStrictEqual(doc("./transform/profile.v1.schema.json"));
29
30
  });
31
+
32
+ it("profile-schema-v2 mirror equals profile.v2.schema.json", () => {
33
+ expect(profileSchemaV2).toStrictEqual(doc("./transform/profile.v2.schema.json"));
34
+ });
30
35
  });
@@ -0,0 +1,213 @@
1
+ /**
2
+ * The surface transformation ledger, and the strict gate over it.
3
+ *
4
+ * Every route, collect, projection, and synthesis reports what it DID —
5
+ * source, destination, originating profile rule, kind, fidelity class. The
6
+ * ledger is additive: messages and warnings stay byte-frozen (the byte gate
7
+ * proves that separately); this file proves the ledger itself is complete,
8
+ * ordered, and honest for each transformation the engine performs.
9
+ */
10
+ import { readFileSync } from "node:fs";
11
+ import { execFileSync } from "node:child_process";
12
+ import { fileURLToPath } from "node:url";
13
+ import { describe, expect, it } from "vitest";
14
+ import { emitSurface } from "./targets/a2ui/surface.js";
15
+ import { shadcnProfile } from "./transform/profiles.js";
16
+ import type { DspackDoc, DspackSurface, SurfaceFidelityEntry } from "./types.js";
17
+
18
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
19
+ const doc = JSON.parse(readFileSync(repo("input/shadcn-ui.dspack.json"), "utf8")) as DspackDoc;
20
+
21
+ const surface = (root: unknown, intent = "record-collection"): DspackSurface =>
22
+ ({ dspackSurface: "0.1", system: doc.name as string, intent, root }) as DspackSurface;
23
+
24
+ const fidelityOf = (root: unknown, intent?: string): SurfaceFidelityEntry[] =>
25
+ emitSurface(surface(root, intent), doc, { profile: shadcnProfile }).fidelity;
26
+
27
+ describe("every transformation reports itself", () => {
28
+ it("propMap projection: clean, default-substituted, and dropped are distinguished", () => {
29
+ const entries = fidelityOf({ component: "button", text: "Save", props: { variant: "default" } });
30
+ // 'default' -> 'primary' is a valueMap HIT: projected, maps-cleanly.
31
+ const projected = entries.find((e) => e.origin === "propMap.variant");
32
+ expect(projected).toMatchObject({ kind: "projected", class: "maps-cleanly", destination: "variant" });
33
+
34
+ const dropped = fidelityOf({ component: "button", text: "Save", props: { hovercolor: "red" } });
35
+ expect(dropped.find((e) => e.source.includes("hovercolor"))).toMatchObject({
36
+ kind: "dropped",
37
+ class: "lossy",
38
+ destination: "(discarded)",
39
+ });
40
+ });
41
+
42
+ it("synthesized action and synthesized text child carry synthesis-defaults and their origin rule", () => {
43
+ const entries = fidelityOf({ component: "button", text: "Save changes" });
44
+ const action = entries.find((e) => e.kind === "synthesized" && e.destination === "action");
45
+ expect(action).toMatchObject({ class: "synthesis-defaults", origin: "actionProp" });
46
+ expect(action!.source).toContain("no source");
47
+ const text = entries.find((e) => e.kind === "synthesized" && e.destination.includes("Text"));
48
+ expect(text).toMatchObject({ class: "synthesis-defaults", origin: "surfaceSynthesis.textComponent" });
49
+ });
50
+
51
+ it("consuming a compound records each moved harvest, the lift, and one lossy flatten", () => {
52
+ const entries = fidelityOf(
53
+ {
54
+ component: "alert-dialog",
55
+ children: [
56
+ { component: "alert-dialog-trigger", text: "Remove" },
57
+ {
58
+ component: "alert-dialog-content",
59
+ children: [
60
+ { component: "alert-dialog-title", text: "Sure?" },
61
+ { component: "alert-dialog-description", text: "Gone forever." },
62
+ ],
63
+ },
64
+ ],
65
+ },
66
+ "destructive-action",
67
+ );
68
+ const moved = entries.filter((e) => e.kind === "moved");
69
+ expect(moved.map((e) => e.destination)).toEqual(expect.arrayContaining(["title", "description"]));
70
+ // Source paths locate the harvested node, not just the compound.
71
+ expect(moved.find((e) => e.destination === "title")!.source).toContain("alert-dialog-title");
72
+ const lift = entries.find((e) => e.kind === "lifted");
73
+ expect(lift).toMatchObject({ destination: "triggerLabel", class: "maps-cleanly" });
74
+ expect(lift!.note).toContain("audited");
75
+ const flatten = entries.filter((e) => e.kind === "flattened" && e.class === "lossy");
76
+ expect(flatten).toHaveLength(1);
77
+ expect(flatten[0].origin).toContain("subText");
78
+ });
79
+
80
+ it("collection records the gathered rows, per-cell flattening losses, and drops", () => {
81
+ const entries = fidelityOf({
82
+ component: "table",
83
+ children: [
84
+ { component: "table-caption", text: "Orders" },
85
+ {
86
+ component: "table-body",
87
+ children: [
88
+ {
89
+ component: "table-row",
90
+ children: [
91
+ { component: "table-cell", children: [{ component: "badge", text: "Paid" }] },
92
+ { component: "table-cell", text: "#1" },
93
+ ],
94
+ },
95
+ ],
96
+ },
97
+ { component: "table-footer", text: "1 order" },
98
+ ],
99
+ });
100
+ expect(entries.find((e) => e.destination === "rows")).toMatchObject({ kind: "moved", class: "maps-cleanly" });
101
+ const cellFlatten = entries.find((e) => e.kind === "flattened" && e.source.includes("badge"));
102
+ expect(cellFlatten).toMatchObject({ class: "lossy" });
103
+ const footerDrop = entries.find((e) => e.kind === "dropped" && e.source.includes("table-footer"));
104
+ expect(footerDrop).toMatchObject({ class: "lossy", origin: "drops.table-footer" });
105
+ expect(footerDrop!.note).toContain("summary rows");
106
+ });
107
+
108
+ it("transparent grouping and the wrap both report; dedup reports as clean", () => {
109
+ const entries = fidelityOf({
110
+ component: "card",
111
+ children: [
112
+ { component: "card-header", children: [{ component: "card-title", text: "T" }] },
113
+ { component: "badge", id: "b", text: "One" },
114
+ { component: "badge", id: "b", text: "Two" },
115
+ ],
116
+ });
117
+ expect(entries.find((e) => e.kind === "flattened" && e.source.includes("card-header"))).toMatchObject({
118
+ class: "lossy",
119
+ origin: "subs.card-header",
120
+ });
121
+ expect(entries.find((e) => e.kind === "wrapped")).toMatchObject({ class: "synthesis-defaults" });
122
+ expect(entries.find((e) => e.kind === "deduplicated")).toMatchObject({ class: "maps-cleanly" });
123
+ });
124
+
125
+ it("the ledger is deterministic and ordered like the warnings", () => {
126
+ const run = () =>
127
+ fidelityOf({
128
+ component: "card",
129
+ children: [
130
+ { component: "card-header", children: [{ component: "card-title", text: "T" }] },
131
+ { component: "button", text: "Go" },
132
+ { component: "badge", text: "New" },
133
+ ],
134
+ });
135
+ expect(JSON.stringify(run())).toBe(JSON.stringify(run()));
136
+ const entries = run();
137
+ // The wrap (after children) is last, exactly like its warning.
138
+ expect(entries[entries.length - 1].kind).toBe("wrapped");
139
+ });
140
+
141
+ it("a clean emission reports maps-cleanly entries and nothing lossy", () => {
142
+ const entries = fidelityOf({ component: "input", text: "Email" });
143
+ expect(entries.length).toBeGreaterThan(0);
144
+ expect(entries.every((e) => e.class === "maps-cleanly" || e.class === "synthesis-defaults")).toBe(true);
145
+ });
146
+ });
147
+
148
+ describe("--strict-surface", () => {
149
+ const cli = (args: string[]): { status: number; output: string } => {
150
+ try {
151
+ const out = execFileSync("npx", ["tsx", "src/cli.ts", ...args], {
152
+ cwd: repo(""),
153
+ encoding: "utf8",
154
+ stdio: ["ignore", "pipe", "pipe"],
155
+ });
156
+ return { status: 0, output: out };
157
+ } catch (e) {
158
+ const err = e as { status: number; stdout?: string; stderr?: string };
159
+ return { status: err.status, output: `${err.stdout ?? ""}${err.stderr ?? ""}` };
160
+ }
161
+ };
162
+
163
+ // A surface whose emission is lossy: a card whose transparent header dissolves.
164
+ const SCRATCH = repo("node_modules/.zz-fidelity-scratch");
165
+ const LOSSY = `${SCRATCH}/zz-lossy.dsurface.json`;
166
+ const CLEAN = `${SCRATCH}/zz-clean.dsurface.json`;
167
+
168
+ it("fails on configured classes with exit 5, naming each failing transformation", () => {
169
+ const fs = require("node:fs") as typeof import("node:fs");
170
+ fs.mkdirSync(SCRATCH, { recursive: true });
171
+ fs.writeFileSync(
172
+ LOSSY,
173
+ JSON.stringify(
174
+ surface({
175
+ component: "card",
176
+ children: [{ component: "card-header", children: [{ component: "card-title", text: "T" }] }],
177
+ }),
178
+ ),
179
+ );
180
+ const strict = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-lossy.dsurface.json", "--strict-surface"]);
181
+ expect(strict.status).toBe(5);
182
+ expect(strict.output).toContain("STRICT-SURFACE");
183
+ expect(strict.output).toContain("[lossy]");
184
+ expect(strict.output).toContain("subs.card-header");
185
+
186
+ // Without the flag the same emission succeeds — loss is visible, not fatal.
187
+ const loose = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-lossy.dsurface.json"]);
188
+ expect(loose.status).toBe(0);
189
+ expect(loose.output).toContain("fidelity");
190
+ });
191
+
192
+ it("passes a clean surface, and the class set is configurable", () => {
193
+ const fs = require("node:fs") as typeof import("node:fs");
194
+ fs.writeFileSync(CLEAN, JSON.stringify(surface({ component: "input", text: "Email" })));
195
+ const strict = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-clean.dsurface.json", "--strict-surface"]);
196
+ expect(strict.status).toBe(0);
197
+ expect(strict.output).toContain("PASS strict-surface");
198
+
199
+ // synthesis-defaults included -> a button's synthesized Text child and
200
+ // action now fail it (input stays clean even then: textProp is a plain
201
+ // move, which is exactly why the class set is worth configuring).
202
+ const fs2 = require("node:fs") as typeof import("node:fs");
203
+ fs2.writeFileSync(`${SCRATCH}/zz-synth.dsurface.json`, JSON.stringify(surface({ component: "button", text: "Go" })));
204
+ const strictest = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-synth.dsurface.json", "--strict-surface=lossy,synthesis-defaults"]);
205
+ expect(strictest.status).toBe(5);
206
+ expect(strictest.output).toContain("[synthesis-defaults]");
207
+
208
+ // An unknown class is a usage error, not a silent no-op.
209
+ const bad = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-clean.dsurface.json", "--strict-surface=vibes"]);
210
+ expect(bad.status).toBe(2);
211
+ expect(bad.output).toContain("unknown fidelity class");
212
+ });
213
+ });
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Ordered surface diagnostics.
3
+ *
4
+ * The v1 engine emitted warnings by pushing them onto an array wherever it
5
+ * happened to be. That made the emitted order an ACCIDENT of method order and
6
+ * traversal — invisible while one implementation existed, and load-bearing the
7
+ * moment a second one appeared, because the byte gate hashes warnings.
8
+ *
9
+ * An engine driven by routes and collects resolves work in declaration order,
10
+ * which is NOT v1's method order. Left implicit, the rewrite would emit the
11
+ * same warnings in a different sequence and fail the gate for a reason that has
12
+ * nothing to do with correctness — and the temptation would be to "fix" it by
13
+ * re-baselining the hashes, which would silently discard the guarantee.
14
+ *
15
+ * So order becomes explicit data. Every diagnostic carries a sort key; the
16
+ * engine collects them in whatever order it likes and sorts once at the end.
17
+ * The key reproduces v1 exactly, and — because it is declared rather than
18
+ * emergent — keeps reproducing it under later refactors.
19
+ *
20
+ * The phases below are DERIVED from the v1 engine, not designed: each is the
21
+ * point in `emitNode` where that warning was pushed. They are numbered in that
22
+ * method's execution order, and the numbering is the compatibility contract.
23
+ */
24
+ import type { SurfaceFidelityEntry, Warning } from "../../types.js";
25
+
26
+ /**
27
+ * Legacy emission phases, in v1 `emitNode` execution order.
28
+ *
29
+ * Read alongside the pre-rewrite `emitNode`: id allocation happened first, then
30
+ * prop projection, then the two consuming strategies (each ending with its own
31
+ * composition warning), then text-child synthesis, then the synthesized action,
32
+ * then the child-list rewrite — and only after every child had emitted did the
33
+ * single-slot wrap run.
34
+ */
35
+ export enum Phase {
36
+ /** `allocateId` for this node — v1 allocated before any projection. */
37
+ IdAllocation = 0,
38
+ /** `applyPropMap`: dropped props and unprojectable values. */
39
+ PropMap = 1,
40
+ /** `applySubContent`'s audited label lift. */
41
+ LabelLift = 2,
42
+ /** `applySubContent`'s closing composition-flattened warning. */
43
+ SubContentFlatten = 3,
44
+ /** `applySubTable`'s per-cell flattening and per-sub drops. */
45
+ TableBody = 4,
46
+ /** `applySubTable`'s closing composition-flattened warning. */
47
+ TableFlatten = 5,
48
+ /** `emitTextPrimitive` invoked by the text-child route. */
49
+ TextChild = 6,
50
+ /** The synthesized declarative action. */
51
+ Action = 7,
52
+ /** `flattenSubs` rewriting the child list before children emit. */
53
+ ChildRewrite = 8,
54
+ /** `wrapInColumn` — runs AFTER every child has emitted. */
55
+ Wrap = 9,
56
+ }
57
+
58
+ /**
59
+ * Where a diagnostic sits relative to this node's children. v1's array order is
60
+ * a pre-order walk in which a parent's pre-child warnings precede all of its
61
+ * descendants' warnings, and its post-child warnings follow all of them — so a
62
+ * flat `(node, phase)` sort would wrongly hoist the wrap warning above the
63
+ * children it wraps.
64
+ */
65
+ export enum Band {
66
+ BeforeChildren = 0,
67
+ Children = 1,
68
+ AfterChildren = 2,
69
+ }
70
+
71
+ export interface Diagnostic {
72
+ warning: Warning;
73
+ /**
74
+ * Lexicographically ordered key. Shape, per tree level:
75
+ * [...ancestorPath, Band.Children, childIndex] repeated to reach the node,
76
+ * then [band, phase, rule, seq].
77
+ * Nesting bands this way is what makes a parent's post-child diagnostics sort
78
+ * after its whole subtree without any special case.
79
+ */
80
+ key: number[];
81
+ }
82
+
83
+ /** Compares two diagnostic keys lexicographically; shorter sorts first on a tie. */
84
+ export function compareKeys(a: number[], b: number[]): number {
85
+ const n = Math.min(a.length, b.length);
86
+ for (let i = 0; i < n; i++) {
87
+ if (a[i] !== b[i]) return a[i] - b[i];
88
+ }
89
+ return a.length - b.length;
90
+ }
91
+
92
+ /**
93
+ * Collects diagnostics with explicit ordering and returns them in legacy order.
94
+ *
95
+ * `seq` is a monotonic counter used only as the final tie-breaker, so two
96
+ * diagnostics identical in every declared dimension still order deterministically
97
+ * — by the order the engine produced them, which is itself deterministic.
98
+ */
99
+ export class Diagnostics {
100
+ private readonly items: Diagnostic[] = [];
101
+ private readonly fidelityItems: Array<{ entry: SurfaceFidelityEntry; key: number[] }> = [];
102
+ private seq = 0;
103
+
104
+ /**
105
+ * @param path the node's tree path (alternating Band.Children / child index)
106
+ * @param band where this sits relative to the node's children
107
+ * @param phase the legacy emission phase
108
+ * @param rule index of the desugared rule that produced it, for stable order
109
+ * among several routes writing in the same phase
110
+ */
111
+ push(warning: Warning, path: readonly number[], band: Band, phase: Phase, rule = 0): void {
112
+ this.items.push({ warning, key: [...path, band, phase, rule, this.seq++] });
113
+ }
114
+
115
+ /** Legacy-ordered warnings. Sorting once at the end is the whole point. */
116
+ ordered(): Warning[] {
117
+ return [...this.items].sort((a, b) => compareKeys(a.key, b.key)).map((d) => d.warning);
118
+ }
119
+
120
+ /**
121
+ * The fidelity ledger rides the same ordering discipline as the warnings —
122
+ * an entry's position is declared by (path, band, phase, rule), never by
123
+ * when the engine happened to record it.
124
+ */
125
+ pushFidelity(entry: SurfaceFidelityEntry, path: readonly number[], band: Band, phase: Phase, rule = 0): void {
126
+ this.fidelityItems.push({ entry, key: [...path, band, phase, rule, this.seq++] });
127
+ }
128
+
129
+ orderedFidelity(): SurfaceFidelityEntry[] {
130
+ return [...this.fidelityItems].sort((a, b) => compareKeys(a.key, b.key)).map((d) => d.entry);
131
+ }
132
+
133
+ get length(): number {
134
+ return this.items.length;
135
+ }
136
+ }