@aestheticfunction/dspack-emit 0.4.0 → 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 (74) 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 +8 -7
  20. package/dist/transform/profile-load.js +101 -24
  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/profile-schema.d.ts +8 -0
  24. package/dist/transform/profile-schema.js +382 -0
  25. package/dist/transform/profiles.d.ts +31 -1
  26. package/dist/transform/scaffold.d.ts +29 -12
  27. package/dist/transform/scaffold.js +91 -31
  28. package/dist/transform/shadcn-v2-respelling.d.ts +12 -0
  29. package/dist/transform/shadcn-v2-respelling.js +49 -0
  30. package/dist/transform/validate-v2.d.ts +36 -0
  31. package/dist/transform/validate-v2.js +100 -0
  32. package/dist/types.d.ts +19 -0
  33. package/dist/validate/ajv.js +98 -29
  34. package/dist/validate/meta/catalog-meta.d.ts +10 -0
  35. package/dist/validate/meta/catalog-meta.js +157 -0
  36. package/package.json +3 -3
  37. package/src/__snapshots__/byte-neutral.test.ts.snap +66 -0
  38. package/src/browser-boundary.test.ts +47 -0
  39. package/src/byte-neutral.test.ts +246 -0
  40. package/src/cli.ts +60 -0
  41. package/src/dangling-ref.test.ts +118 -0
  42. package/src/desugar.test.ts +162 -0
  43. package/src/engine-boundary.test.ts +248 -0
  44. package/src/eval-fixture.test.ts +89 -0
  45. package/src/functions.test.ts +182 -0
  46. package/src/index.ts +4 -1
  47. package/src/profile-load.test.ts +99 -1
  48. package/src/profile-v2.test.ts +363 -0
  49. package/src/review-findings.test.ts +292 -0
  50. package/src/schema-mirrors.test.ts +35 -0
  51. package/src/surface-fidelity.test.ts +213 -0
  52. package/src/targets/a2ui/diagnostics.ts +136 -0
  53. package/src/targets/a2ui/surface.ts +920 -242
  54. package/src/transform/desugar.ts +194 -0
  55. package/src/transform/emit.ts +65 -0
  56. package/src/transform/index.ts +5 -0
  57. package/src/transform/mapping.ts +42 -0
  58. package/src/transform/model.ts +325 -0
  59. package/src/transform/parse-v2.ts +397 -0
  60. package/src/transform/profile-load.ts +107 -28
  61. package/src/transform/profile-schema-v2.ts +430 -0
  62. package/src/transform/profile-schema.ts +382 -0
  63. package/src/transform/profile.v2.schema.json +422 -0
  64. package/src/transform/profiles.ts +32 -1
  65. package/src/transform/scaffold.ts +124 -47
  66. package/src/transform/shadcn-v2-respelling.ts +61 -0
  67. package/src/transform/validate-v2.ts +138 -0
  68. package/src/types.ts +20 -0
  69. package/src/validate/ajv.ts +91 -32
  70. package/src/validate/meta/catalog-meta.ts +167 -0
  71. package/src/validate-v2.test.ts +173 -0
  72. package/dist/transform/profile.v1.schema.json +0 -153
  73. package/dist/validate/meta/a2ui-catalog.meta.0_9_1.json +0 -39
  74. package/dist/validate/meta/a2ui-catalog.meta.1_0.json +0 -34
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Desugaring is the ONLY compatibility boundary.
3
+ *
4
+ * The refactor's value is that the engine reads primitives, not directive
5
+ * names. That property decays silently: the next person to fix a v1 edge case
6
+ * can reach for `plan.surfacePlan.subTable` inside the emitter, everything
7
+ * passes, and the boundary is gone without anyone noticing. So assert it
8
+ * structurally — the engine source must not name a legacy directive at all.
9
+ *
10
+ * Plus focused behavioural coverage of the transformations the byte-gate's
11
+ * artifact digests exercise but do not EXPLAIN: when a digest moves, these say
12
+ * which rule broke.
13
+ */
14
+ import { readFileSync } from "node:fs";
15
+ import { fileURLToPath } from "node:url";
16
+ import { describe, expect, it } from "vitest";
17
+ import { emitSurface } from "./targets/a2ui/surface.js";
18
+ import { Band, compareKeys, Diagnostics, Phase } from "./targets/a2ui/diagnostics.js";
19
+ import { shadcnProfile } from "./transform/profiles.js";
20
+ import type { DspackDoc, DspackSurface } from "./types.js";
21
+
22
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
23
+ const doc = JSON.parse(readFileSync(repo("input/shadcn-ui.dspack.json"), "utf8")) as DspackDoc;
24
+ const src = (p: string) => readFileSync(repo(p), "utf8");
25
+
26
+ /** Every v1 directive name. The engine may not mention any of them. */
27
+ const LEGACY_DIRECTIVES = [
28
+ "subText",
29
+ "subButtonText",
30
+ "actionProp",
31
+ "textChildProp",
32
+ "textProp",
33
+ "childProp",
34
+ "childrenProp",
35
+ "structuralPassthrough",
36
+ "subTable",
37
+ "subFlatten",
38
+ ];
39
+
40
+ const surface = (root: unknown, intent = "record-collection"): DspackSurface =>
41
+ ({ dspackSurface: "0.1", system: doc.name as string, intent, root }) as DspackSurface;
42
+
43
+ const emit = (root: unknown, intent?: string) => emitSurface(surface(root, intent), doc, { profile: shadcnProfile });
44
+ const instances = (root: unknown, intent?: string) =>
45
+ (emit(root, intent).messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } })
46
+ .updateComponents.components;
47
+
48
+ describe("the engine reads only the internal model", () => {
49
+ it.each(LEGACY_DIRECTIVES.map((d) => [d] as const))("the surface engine never mentions '%s'", (directive) => {
50
+ const engine = src("src/targets/a2ui/surface.ts");
51
+ // `surfacePlan` itself is the container; naming it would also be a leak.
52
+ expect(engine).not.toContain(`.${directive}`);
53
+ expect(engine).not.toContain(`"${directive}"`);
54
+ });
55
+
56
+ it("the surface engine never reaches into surfacePlan at all", () => {
57
+ expect(src("src/targets/a2ui/surface.ts")).not.toContain("surfacePlan");
58
+ });
59
+
60
+ it("desugar.ts is where the directive names live — the boundary is somewhere", () => {
61
+ const desugar = src("src/transform/desugar.ts");
62
+ for (const directive of LEGACY_DIRECTIVES) expect(desugar).toContain(directive);
63
+ });
64
+ });
65
+
66
+ describe("diagnostic ordering is declared, not emergent", () => {
67
+ it("a parent's post-child diagnostics sort after its whole subtree", () => {
68
+ const d = new Diagnostics();
69
+ // Deliberately pushed out of order: the wrap (after children) first.
70
+ d.push({ code: "wrap", message: "w" }, [], Band.AfterChildren, Phase.Wrap);
71
+ d.push({ code: "child", message: "c" }, [Band.Children, 0], Band.BeforeChildren, Phase.PropMap);
72
+ d.push({ code: "parent", message: "p" }, [], Band.BeforeChildren, Phase.IdAllocation);
73
+ expect(d.ordered().map((w) => w.code)).toEqual(["parent", "child", "wrap"]);
74
+ });
75
+
76
+ it("children order by index, and deeper nodes sort inside their parent", () => {
77
+ const d = new Diagnostics();
78
+ d.push({ code: "child1", message: "" }, [Band.Children, 1], Band.BeforeChildren, Phase.PropMap);
79
+ d.push({ code: "grandchild0", message: "" }, [Band.Children, 0, Band.Children, 0], Band.BeforeChildren, Phase.PropMap);
80
+ d.push({ code: "child0", message: "" }, [Band.Children, 0], Band.BeforeChildren, Phase.IdAllocation);
81
+ expect(d.ordered().map((w) => w.code)).toEqual(["child0", "grandchild0", "child1"]);
82
+ });
83
+
84
+ it("equal keys fall back to production order, never to chance", () => {
85
+ const d = new Diagnostics();
86
+ d.push({ code: "first", message: "" }, [], Band.BeforeChildren, Phase.PropMap);
87
+ d.push({ code: "second", message: "" }, [], Band.BeforeChildren, Phase.PropMap);
88
+ expect(d.ordered().map((w) => w.code)).toEqual(["first", "second"]);
89
+ });
90
+
91
+ it("compareKeys is a total order (shorter key sorts first on a prefix tie)", () => {
92
+ expect(compareKeys([1, 2], [1, 2, 0])).toBeLessThan(0);
93
+ expect(compareKeys([1, 3], [1, 2, 9])).toBeGreaterThan(0);
94
+ expect(compareKeys([1, 2], [1, 2])).toBe(0);
95
+ });
96
+ });
97
+
98
+ describe("transformations keep their meaning", () => {
99
+ it("label fallback: a label-bearing component supplies the label", () => {
100
+ const [dialog] = instances(
101
+ {
102
+ component: "alert-dialog",
103
+ children: [
104
+ { component: "alert-dialog-trigger", children: [{ component: "button", text: "Delete" }] },
105
+ { component: "alert-dialog-content", children: [{ component: "alert-dialog-title", text: "Sure?" }] },
106
+ ],
107
+ },
108
+ "destructive-action",
109
+ );
110
+ expect(dialog.triggerLabel).toBe("Delete");
111
+ });
112
+
113
+ it("label fallback: with no label-bearer the audited lift runs and is recorded", () => {
114
+ const { messages, warnings } = emit(
115
+ {
116
+ component: "alert-dialog",
117
+ children: [
118
+ { component: "alert-dialog-trigger", text: "Remove" },
119
+ { component: "alert-dialog-content", children: [{ component: "alert-dialog-title", text: "Sure?" }] },
120
+ ],
121
+ },
122
+ "destructive-action",
123
+ );
124
+ const [dialog] = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } })
125
+ .updateComponents.components;
126
+ expect(dialog.triggerLabel).toBe("Remove");
127
+ expect(warnings.some((w) => w.code === "surface-label-lifted")).toBe(true);
128
+ });
129
+
130
+ it("consumption resolves in document order, not declaration order", () => {
131
+ // The trigger precedes the content, so triggerLabel is written first.
132
+ const [dialog] = instances(
133
+ {
134
+ component: "alert-dialog",
135
+ children: [
136
+ { component: "alert-dialog-trigger", children: [{ component: "button", text: "Delete" }] },
137
+ { component: "alert-dialog-content", children: [{ component: "alert-dialog-title", text: "Sure?" }] },
138
+ ],
139
+ },
140
+ "destructive-action",
141
+ );
142
+ expect(Object.keys(dialog)).toEqual(["id", "component", "triggerLabel", "title", "action"]);
143
+ });
144
+
145
+ it("first-write-wins: the first matching sub claims the destination", () => {
146
+ const [dialog] = instances(
147
+ {
148
+ component: "alert-dialog",
149
+ children: [
150
+ { component: "alert-dialog-content", children: [
151
+ { component: "alert-dialog-title", text: "First" },
152
+ { component: "alert-dialog-title", text: "Second" },
153
+ ] },
154
+ ],
155
+ },
156
+ "destructive-action",
157
+ );
158
+ expect(dialog.title).toBe("First");
159
+ });
160
+
161
+ it("collection: rows become records, header cells become one flat column list", () => {
162
+ const [table] = instances({
163
+ component: "table",
164
+ children: [
165
+ { component: "table-header", children: [{ component: "table-row", children: [
166
+ { component: "table-head", text: "A" }, { component: "table-head", text: "B" }] }] },
167
+ { component: "table-body", children: [
168
+ { component: "table-row", children: [{ component: "table-cell", text: "1" }, { component: "table-cell", text: "2" }] }] },
169
+ ],
170
+ });
171
+ expect(table.columns).toEqual(["A", "B"]);
172
+ expect(table.rows).toEqual([{ cells: ["1", "2"] }]);
173
+ });
174
+
175
+ it("collection: two header rows concatenate into one column list (v1 behaviour)", () => {
176
+ const [table] = instances({
177
+ component: "table",
178
+ children: [
179
+ { component: "table-header", children: [
180
+ { component: "table-row", children: [{ component: "table-head", text: "A" }] },
181
+ { component: "table-row", children: [{ component: "table-head", text: "B" }] },
182
+ ] },
183
+ ],
184
+ });
185
+ expect(table.columns).toEqual(["A", "B"]);
186
+ });
187
+
188
+ it("transparent grouping dissolves and its children rise in document order", () => {
189
+ const emitted = instances({
190
+ component: "card",
191
+ children: [
192
+ { component: "card-header", children: [{ component: "card-title", text: "Members" }] },
193
+ { component: "card-content", text: "Three people." },
194
+ ],
195
+ });
196
+ const texts = emitted.filter((c) => c.component === "Text").map((c) => c.text);
197
+ expect(texts).toContain("Members");
198
+ expect(texts).toContain("Three people.");
199
+ });
200
+
201
+ it("synthesized action: deterministic event name, and it is recorded", () => {
202
+ const { messages, warnings } = emit({ component: "button", text: "Save changes" });
203
+ const [button] = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } })
204
+ .updateComponents.components;
205
+ expect(button.action).toEqual({ event: { name: "save_changes", context: {} } });
206
+ expect(warnings.some((w) => w.code === "surface-synthesized-action")).toBe(true);
207
+ });
208
+
209
+ it("warning order across several transformations in one surface", () => {
210
+ // A card whose sub-family flattens, containing a button that synthesizes
211
+ // both a text child and an action, plus a second child forcing a wrap.
212
+ const { warnings } = emit({
213
+ component: "card",
214
+ children: [
215
+ { component: "card-header", children: [{ component: "card-title", text: "Actions" }] },
216
+ { component: "button", text: "Save" },
217
+ { component: "badge", text: "New" },
218
+ ],
219
+ });
220
+ const codes = warnings.map((w) => w.code);
221
+ // The child-list rewrite precedes any child's own diagnostics...
222
+ expect(codes.indexOf("surface-sub-flattened")).toBeLessThan(codes.indexOf("surface-synthesized-action"));
223
+ // ...and the wrap, which runs after every child, comes last.
224
+ expect(codes[codes.length - 1]).toBe("surface-synthesized-wrap");
225
+ });
226
+
227
+ it("id allocation stays deterministic and records every collision", () => {
228
+ const run = () =>
229
+ emit({
230
+ component: "card",
231
+ children: [
232
+ { component: "badge", id: "tag", text: "One" },
233
+ { component: "badge", id: "tag", text: "Two" },
234
+ { component: "badge", id: "tag", text: "Three" },
235
+ ],
236
+ });
237
+ const a = run();
238
+ const b = run();
239
+ expect(JSON.stringify(a.messages)).toBe(JSON.stringify(b.messages));
240
+ expect(JSON.stringify(a.warnings)).toBe(JSON.stringify(b.warnings));
241
+ const ids = (a.messages[1] as { updateComponents: { components: Array<{ id: string }> } })
242
+ .updateComponents.components.map((c) => c.id);
243
+ expect(ids).toContain("tag");
244
+ expect(ids).toContain("tag_2");
245
+ expect(ids).toContain("tag_3");
246
+ expect(a.warnings.filter((w) => w.code === "surface-id-deduplicated")).toHaveLength(2);
247
+ });
248
+ });
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The production-v3 coverage evaluation fixture: reproducible, honest, and
3
+ * NOT Studio's profile.
4
+ *
5
+ * Supersedes the /tmp-only measurement recorded in 2aac076 ("29 subs under 6
6
+ * compounds, 1 unresolved"): that profile's nine extra compound plans carried
7
+ * judgment that did not survive the reboot. This fixture transplants only
8
+ * COMMITTED mapping evidence (the six shipped plans, in their byte-proven v2
9
+ * re-spelling) onto a mechanical scaffold of the pinned v3 contract, declares
10
+ * zero casualties, and lets every open representation decision show as open:
11
+ *
12
+ * 106 sub-components under 19 mapped compounds
13
+ * 20 resolved — exactly the transplanted families (card 5, table 7,
14
+ * alert-dialog 8)
15
+ * 86 unresolved — real, deliberate, and the measure of the T1–T5 work
16
+ *
17
+ * The v2 contract gate refusing this fixture against the v3 contract is not a
18
+ * failure; it is the fatal coverage gate doing on the production corpus
19
+ * precisely what it was built to do.
20
+ */
21
+ import { readFileSync } from "node:fs";
22
+ import { fileURLToPath } from "node:url";
23
+ import { describe, expect, it } from "vitest";
24
+ import { transformFromJson } from "./transform/index.js";
25
+ import { loadProfile } from "./transform/profile-load.js";
26
+ import { ProfileContractError } from "./transform/validate-v2.js";
27
+ import { surfaceModelOf } from "./transform/desugar.js";
28
+ import { deriveSubCoverage } from "./transform/model.js";
29
+ import type { ComponentPlan } from "./transform/profiles.js";
30
+ import type { DspackDoc } from "./types.js";
31
+
32
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
33
+ const contract = JSON.parse(readFileSync(repo("eval/shadcn-v3.dspack.json"), "utf8")) as DspackDoc;
34
+ const fixtureJson = JSON.parse(readFileSync(repo("eval/shadcn-v3.eval.profile.json"), "utf8"));
35
+
36
+ describe("the production-v3 evaluation fixture", () => {
37
+ it("is reproducible: rebuilding from committed inputs equals the committed fixture", async () => {
38
+ const { buildEvalProfile } = await import(repo("eval/build-eval-profile.mjs"));
39
+ expect(JSON.stringify(buildEvalProfile(), null, 2) + "\n").toBe(
40
+ readFileSync(repo("eval/shadcn-v3.eval.profile.json"), "utf8"),
41
+ );
42
+ });
43
+
44
+ it("loads as a v2 profile and is labelled as measurement-only", () => {
45
+ const profile = loadProfile(structuredClone(fixtureJson));
46
+ expect(profile.language).toBe("v2");
47
+ const label = (profile as unknown as Record<string, { notStudioProfile?: string }>)["x-eval"];
48
+ expect(label.notStudioProfile).toContain("Studio");
49
+ expect(profile.casualtyComponents).toEqual([]);
50
+ });
51
+
52
+ it("the fatal coverage gate refuses it against the v3 contract: 86 unresolved decisions, each pathed", () => {
53
+ try {
54
+ transformFromJson(contract, { profile: loadProfile(structuredClone(fixtureJson)) });
55
+ expect.unreachable("86 open representation decisions must refuse, not emit");
56
+ } catch (e) {
57
+ expect(e).toBeInstanceOf(ProfileContractError);
58
+ const issues = (e as ProfileContractError).issues;
59
+ expect(issues).toHaveLength(86);
60
+ expect(issues.every((i) => i.message.includes("unresolved"))).toBe(true);
61
+ }
62
+ });
63
+
64
+ it("derived coverage: 106 subs, 20 resolved by the transplanted families, 86 open", () => {
65
+ const profile = loadProfile(structuredClone(fixtureJson));
66
+ const byId = new Map(profile.components.map((p: ComponentPlan) => [p.dspackId, p]));
67
+ let resolved = 0;
68
+ let unresolved = 0;
69
+ const resolvedByCompound = new Map<string, number>();
70
+ for (const [id, component] of Object.entries(contract.components ?? {})) {
71
+ const subs = ((component as { composition?: { subComponents?: Array<{ id: string }> } }).composition
72
+ ?.subComponents ?? []).map((s) => s.id);
73
+ const plan = byId.get(id);
74
+ if (subs.length === 0 || !plan) continue;
75
+ const covered = deriveSubCoverage(surfaceModelOf(plan), subs);
76
+ for (const sub of subs) {
77
+ if (covered.has(sub)) {
78
+ resolved++;
79
+ resolvedByCompound.set(id, (resolvedByCompound.get(id) ?? 0) + 1);
80
+ } else {
81
+ unresolved++;
82
+ }
83
+ }
84
+ }
85
+ expect(resolved + unresolved).toBe(106);
86
+ expect(unresolved).toBe(86);
87
+ expect(Object.fromEntries(resolvedByCompound)).toEqual({ card: 5, table: 7, "alert-dialog": 8 });
88
+ });
89
+ });
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Declared catalog functions: the fail-closed check vocabulary.
3
+ *
4
+ * The emitted catalog always carried A2UI's check types (Checkable, CheckRule,
5
+ * FunctionCall) — but our inlined FunctionCall had DROPPED the upstream
6
+ * anyFunction constraint (inline-defs.ts documents the drop), and no catalog
7
+ * ever declared a functions section. Net effect: an instance could `call` any
8
+ * name at all and gate A3 passed it silently. Declared checks resolved to
9
+ * nothing, invisibly.
10
+ *
11
+ * Now a v2 profile declares its function vocabulary as data; the catalog
12
+ * carries a `functions` section; FunctionCall.call is constrained to the
13
+ * declared names; and each call's args validate against the declared schema.
14
+ * Undeclared function -> A3 refusal. No functions declared (every v1
15
+ * profile) -> byte-identical emission to before, proven by the byte gate.
16
+ */
17
+ import { readFileSync } from "node:fs";
18
+ import { fileURLToPath } from "node:url";
19
+ import { describe, expect, it } from "vitest";
20
+ import { transformFromJson } from "./transform/index.js";
21
+ import { loadProfile } from "./transform/profile-load.js";
22
+ import type { A2uiVersion, DspackDoc } from "./types.js";
23
+
24
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
25
+ const doc = JSON.parse(readFileSync(repo("input/shadcn-ui.dspack.json"), "utf8")) as DspackDoc;
26
+
27
+ /** A v2 profile mapping `input`, with a checks slot and two declared functions. */
28
+ const profileDoc = (): Record<string, unknown> => ({
29
+ profileVersion: "2",
30
+ catalogTitle: "functions-bearing catalog",
31
+ catalogDescription: "d",
32
+ catalogIdBase: "https://example.test/catalogs/fn",
33
+ instructions: "",
34
+ primaryColorToken: { category: "color", name: "primary" },
35
+ surfaceSynthesis: { textComponent: "Text", textProp: "text", wrapComponent: "Column", wrapChildrenProp: "children" },
36
+ functions: {
37
+ checkRequired: {
38
+ description: "True when the bound value is non-empty.",
39
+ returns: "boolean",
40
+ },
41
+ matchesRegexp: {
42
+ description: "True when the bound value matches the pattern.",
43
+ returns: "boolean",
44
+ args: {
45
+ type: "object",
46
+ properties: { pattern: { type: "string" } },
47
+ required: ["pattern"],
48
+ additionalProperties: false,
49
+ },
50
+ },
51
+ },
52
+ synthesized: [
53
+ {
54
+ a2ui: "Text",
55
+ commons: ["ComponentCommon"],
56
+ structural: { text: { schema: { type: "string" }, description: "d", synthNote: "s" } },
57
+ required: ["text"],
58
+ },
59
+ {
60
+ a2ui: "Column",
61
+ commons: ["ComponentCommon"],
62
+ structural: { children: { schema: { type: "array", items: { $ref: "#/$defs/ComponentId" } }, description: "d", synthNote: "s" } },
63
+ required: ["children"],
64
+ },
65
+ ],
66
+ casualtyComponents: [],
67
+ components: [
68
+ {
69
+ a2ui: "TextField",
70
+ dspackId: "input",
71
+ commons: ["ComponentCommon", "Checkable"],
72
+ structural: {
73
+ label: { schema: { type: "string" }, description: "d", synthNote: "s" },
74
+ checks: {
75
+ schema: { type: "array", items: { $ref: "#/$defs/CheckRule" } },
76
+ description: "Client-side validation rules for this field.",
77
+ synthNote: "dspack has no check vocabulary; checks are authored on the surface node.",
78
+ },
79
+ },
80
+ required: ["label"],
81
+ surface: {
82
+ routes: [
83
+ { from: ["self.text"], to: "prop:label", overwrite: true },
84
+ { from: ["self.props.checks"], to: "prop:checks" },
85
+ ],
86
+ },
87
+ },
88
+ ],
89
+ });
90
+
91
+ const VERSIONS: A2uiVersion[] = ["0.9.1", "1.0"];
92
+
93
+ /** An instance whose check calls a declared function, correctly. */
94
+ const okSurface = (call: object) => ({
95
+ messages: [
96
+ { version: "v0.9", createSurface: { surfaceId: "s", catalogId: "https://example.test/catalogs/fn/v0_9_1/catalog.json", theme: {} } },
97
+ {
98
+ version: "v0.9",
99
+ updateComponents: {
100
+ surfaceId: "s",
101
+ components: [
102
+ {
103
+ id: "root",
104
+ component: "TextField",
105
+ label: "Email",
106
+ checks: [{ condition: call, message: "Required." }],
107
+ },
108
+ ],
109
+ },
110
+ },
111
+ ],
112
+ });
113
+
114
+ describe("declared functions reach the catalog and constrain every call", () => {
115
+ for (const version of VERSIONS) {
116
+ it(`the catalog carries the functions section and the call constraint (a2ui ${version})`, () => {
117
+ const out = transformFromJson(doc, { profile: loadProfile(profileDoc()), a2uiVersion: version });
118
+ const catalog = out.catalog as unknown as {
119
+ functions?: Record<string, { returnType: string }>;
120
+ $defs: { anyFunction?: { oneOf: unknown[] }; FunctionCall: { properties: { call: { enum?: string[] } } } };
121
+ };
122
+ expect(Object.keys(catalog.functions ?? {})).toEqual(["checkRequired", "matchesRegexp"]);
123
+ expect(catalog.functions!.checkRequired.returnType).toBe("boolean");
124
+ expect(catalog.$defs.anyFunction?.oneOf).toHaveLength(2);
125
+ expect(catalog.$defs.FunctionCall.properties.call.enum).toEqual(["checkRequired", "matchesRegexp"]);
126
+ // A1/A2 stay green with the section present.
127
+ expect(out.validation.gates.find((g) => g.name === "schema-compile + no-external-ref")?.pass).toBe(true);
128
+ expect(out.validation.gates.find((g) => g.name === "catalog-shape")?.pass).toBe(true);
129
+ });
130
+ }
131
+
132
+ it("a check calling a declared function passes gate A3", () => {
133
+ const out = transformFromJson(doc, {
134
+ profile: loadProfile(profileDoc()),
135
+ surface: okSurface({ call: "checkRequired" }),
136
+ });
137
+ expect(out.validation.gates.find((g) => g.name === "instance")?.pass).toBe(true);
138
+ });
139
+
140
+ it("declared args validate: a good pattern passes, a missing required arg refuses", () => {
141
+ const good = transformFromJson(doc, {
142
+ profile: loadProfile(profileDoc()),
143
+ surface: okSurface({ call: "matchesRegexp", args: { pattern: "^.+@.+$" } }),
144
+ });
145
+ expect(good.validation.gates.find((g) => g.name === "instance")?.pass).toBe(true);
146
+
147
+ const missing = transformFromJson(doc, {
148
+ profile: loadProfile(profileDoc()),
149
+ surface: okSurface({ call: "matchesRegexp" }),
150
+ });
151
+ expect(missing.validation.gates.find((g) => g.name === "instance")?.pass).toBe(false);
152
+ });
153
+
154
+ it("an UNDECLARED function call fails gate A3 — the hole this exists to close", () => {
155
+ const out = transformFromJson(doc, {
156
+ profile: loadProfile(profileDoc()),
157
+ surface: okSurface({ call: "checkVibes" }),
158
+ });
159
+ const gate = out.validation.gates.find((g) => g.name === "instance");
160
+ expect(gate?.pass).toBe(false);
161
+ });
162
+
163
+ it("without the functions section the same undeclared call passes — the pre-existing hole, kept for v1 byte-compatibility and closed only by declaring", () => {
164
+ const bare = profileDoc();
165
+ delete bare.functions;
166
+ const out = transformFromJson(doc, {
167
+ profile: loadProfile(bare),
168
+ surface: okSurface({ call: "checkVibes" }),
169
+ });
170
+ // Documenting reality, not endorsing it: no declaration, no constraint —
171
+ // exactly today's emitted shape, which the byte gate freezes for v1.
172
+ expect(out.validation.gates.find((g) => g.name === "instance")?.pass).toBe(true);
173
+ expect((out.catalog as { functions?: unknown }).functions).toBeUndefined();
174
+ });
175
+
176
+ it("v1 documents cannot declare functions — the field is v2 language", () => {
177
+ const v1 = { profileVersion: "1", ...profileDoc(), functions: { f: { description: "x", returns: "boolean" } } };
178
+ v1.profileVersion = "1";
179
+ // v1 schema refuses both the functions field and the surface blocks.
180
+ expect(() => loadProfile(v1)).toThrowError();
181
+ });
182
+ });
package/src/index.ts CHANGED
@@ -7,7 +7,10 @@
7
7
  */
8
8
  export { transform, transformFromJson, type TransformOutput } from "./transform/index.js";
9
9
  export { shadcnProfile, type Profile, type ComponentPlan, type SurfacePlanDirectives } from "./transform/profiles.js";
10
- export { loadProfile, profileSchema, ProfileLoadError, type ProfileLoadIssue } from "./transform/profile-load.js";
10
+ export { loadProfile, profileSchema, profileSchemaV2, ProfileLoadError, type ProfileLoadIssue } from "./transform/profile-load.js";
11
+ export { ProfileContractError, type ProfileContractIssue } from "./transform/validate-v2.js";
12
+ export { ProfileParseError, type ParseIssue, type SurfaceV2 } from "./transform/parse-v2.js";
13
+ export type { SurfaceFidelityEntry } from "./types.js";
11
14
  export { scaffoldProfile, type ScaffoldOptions, type ScaffoldResult, type ScaffoldNote } from "./transform/scaffold.js";
12
15
  export { validateCatalog, extractInstances, type ValidationReport, type GateResult } from "./validate/ajv.js";
13
16
  export {
@@ -103,12 +103,75 @@ describe("casualty refusal cites the authored reason", () => {
103
103
  });
104
104
  });
105
105
 
106
+ describe("a declared casualty cannot be consumed into a parent", () => {
107
+ /**
108
+ * The plan-lookup gate refuses a casualty emitted as its OWN node. A
109
+ * consuming strategy (subText / subButtonText / subTable / subFlatten)
110
+ * walks the subtree directly, so without an equivalent gate an author
111
+ * could fold a casualty's text into a parent prop and the authored
112
+ * refusal would vanish behind a warning. Consumption is how compounds
113
+ * carry their parts — never an escape hatch around "cannot represent".
114
+ */
115
+ it("refuses a casualty folded in by a parent's subText, citing the authored reason", () => {
116
+ const withFold = {
117
+ ...shadcnProfile,
118
+ components: shadcnProfile.components.map((plan) =>
119
+ plan.dspackId === "card"
120
+ ? {
121
+ ...plan,
122
+ surfacePlan: {
123
+ ...(plan.surfacePlan ?? {}),
124
+ subText: { ...(plan.surfacePlan?.subText ?? {}), "dropdown-menu": "title" },
125
+ },
126
+ }
127
+ : plan,
128
+ ),
129
+ };
130
+ const surface: DspackSurface = {
131
+ dspackSurface: "0.1",
132
+ system: shadcnDoc.name as string,
133
+ intent: "record-collection",
134
+ root: {
135
+ component: "card",
136
+ children: [{ component: "dropdown-menu", text: "Row actions" }],
137
+ },
138
+ } as DspackSurface;
139
+ try {
140
+ emitSurface(surface, shadcnDoc, { profile: withFold });
141
+ expect.unreachable("a consumed casualty must refuse, not fold silently");
142
+ } catch (e) {
143
+ expect(e).toBeInstanceOf(EmitSurfaceError);
144
+ const msg = (e as EmitSurfaceError).message;
145
+ expect(msg).toContain("declared casualty");
146
+ expect(msg).toContain("cannot be consumed into");
147
+ expect(msg).toContain("dropdown menu"); // the authored reason survives
148
+ // The refusal points at the casualty itself, not at the parent that
149
+ // would have consumed it — same locating precision as direct emission.
150
+ expect((e as EmitSurfaceError).path).toBe("$.root.children[0]");
151
+ }
152
+ });
153
+
154
+ it("still consumes ordinary sub-components (the gate is casualty-scoped)", () => {
155
+ const surface: DspackSurface = {
156
+ dspackSurface: "0.1",
157
+ system: shadcnDoc.name as string,
158
+ intent: "record-collection",
159
+ root: {
160
+ component: "card",
161
+ children: [{ component: "card-header", children: [{ component: "card-title", text: "Members" }] }],
162
+ },
163
+ } as DspackSurface;
164
+ const result = emitSurface(surface, shadcnDoc, { profile: shadcnProfile });
165
+ expect(JSON.stringify(result.messages)).toContain("Members");
166
+ });
167
+ });
168
+
106
169
  describe("scaffoldProfile", () => {
107
170
  it("produces a loadProfile-valid profile from a bare contract", () => {
108
171
  const { profile } = scaffoldProfile(astryxDoc, {
109
172
  catalogIdBase: "https://example.test/catalogs/astryx-scaffold",
110
173
  });
111
- // The scaffold is itself a valid v1 profile document.
174
+ // The scaffold is itself a valid v2 profile document.
112
175
  const loaded = loadProfile(profile);
113
176
  expect(loaded.catalogIdBase).toBe("https://example.test/catalogs/astryx-scaffold");
114
177
  });
@@ -128,6 +191,41 @@ describe("scaffoldProfile", () => {
128
191
  expect(notes.length).toBeGreaterThan(0);
129
192
  });
130
193
 
194
+ it("a scaffold's unresolved decisions, once resolved, transform — the authoring loop closes", () => {
195
+ const { profile, notes } = scaffoldProfile(shadcnDoc, {
196
+ catalogIdBase: "https://example.test/catalogs/shadcn-scaffold",
197
+ });
198
+ // The scaffold names every decision it refused to make...
199
+ const pending = notes.filter((n) => n.note.startsWith("unresolved sub-component"));
200
+ expect(pending.length).toBeGreaterThanOrEqual(10);
201
+ const xs = (profile["x-scaffold"] as { unresolved: Record<string, string[]> }).unresolved;
202
+ expect(Object.keys(xs)).toEqual(expect.arrayContaining(["card", "table", "alert-dialog"]));
203
+
204
+ // ...and an author resolving ONE compound's subs makes that compound emit.
205
+ const components = profile.components as Array<Record<string, unknown>>;
206
+ const card = components.find((c) => c.dspackId === "card")!;
207
+ card.surface = {
208
+ routes: [{ from: ["children"], to: "slots:children" }],
209
+ subs: {
210
+ "card-header": "transparent",
211
+ "card-content": "transparent",
212
+ "card-footer": "transparent",
213
+ "card-title": { asText: "h3" },
214
+ "card-description": { asText: "caption" },
215
+ },
216
+ };
217
+ // The other compounds stay undecided, so transform still refuses — but no
218
+ // longer about card: its family is resolved and gone from the findings.
219
+ try {
220
+ transformFromJson(shadcnDoc, { profile: loadProfile(profile) });
221
+ expect.unreachable("table and alert-dialog are still undecided");
222
+ } catch (e) {
223
+ const issues = (e as { issues: Array<{ message: string }> }).issues;
224
+ expect(issues.some((i) => i.message.includes("of 'card'"))).toBe(false);
225
+ expect(issues.some((i) => i.message.includes("of 'table'"))).toBe(true);
226
+ }
227
+ });
228
+
131
229
  it("seeds enum props verbatim (identity projection, no valueMap)", () => {
132
230
  const { profile } = scaffoldProfile(shadcnDoc, {
133
231
  catalogIdBase: "https://example.test/catalogs/shadcn-scaffold",