@aestheticfunction/dspack-emit 0.3.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 (62) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +285 -0
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +186 -0
  5. package/dist/index.d.ts +16 -0
  6. package/dist/index.js +15 -0
  7. package/dist/targets/a2ui/surface.d.ts +43 -0
  8. package/dist/targets/a2ui/surface.js +219 -0
  9. package/dist/targets/csr.d.ts +15 -0
  10. package/dist/targets/csr.js +9 -0
  11. package/dist/targets/json-render/codegen.d.ts +35 -0
  12. package/dist/targets/json-render/codegen.js +91 -0
  13. package/dist/targets/json-render/emit.d.ts +66 -0
  14. package/dist/targets/json-render/emit.js +142 -0
  15. package/dist/targets/json-render/model.d.ts +57 -0
  16. package/dist/targets/json-render/model.js +99 -0
  17. package/dist/targets/json-render/profile.d.ts +23 -0
  18. package/dist/targets/json-render/profile.js +3 -0
  19. package/dist/transform/color.d.ts +11 -0
  20. package/dist/transform/color.js +53 -0
  21. package/dist/transform/emit.d.ts +15 -0
  22. package/dist/transform/emit.js +100 -0
  23. package/dist/transform/index.d.ts +26 -0
  24. package/dist/transform/index.js +26 -0
  25. package/dist/transform/inline-defs.d.ts +22 -0
  26. package/dist/transform/inline-defs.js +172 -0
  27. package/dist/transform/mapping.d.ts +24 -0
  28. package/dist/transform/mapping.js +322 -0
  29. package/dist/transform/profiles.d.ts +120 -0
  30. package/dist/transform/profiles.js +282 -0
  31. package/dist/transform/report.d.ts +13 -0
  32. package/dist/transform/report.js +76 -0
  33. package/dist/types.d.ts +103 -0
  34. package/dist/types.js +6 -0
  35. package/dist/validate/ajv.d.ts +15 -0
  36. package/dist/validate/ajv.js +132 -0
  37. package/dist/validate/meta/a2ui-catalog.meta.0_9_1.json +39 -0
  38. package/dist/validate/meta/a2ui-catalog.meta.1_0.json +34 -0
  39. package/package.json +41 -0
  40. package/src/cli.ts +197 -0
  41. package/src/index.ts +39 -0
  42. package/src/ingestion.test.ts +156 -0
  43. package/src/json-render-emit.test.ts +196 -0
  44. package/src/surface-emit.test.ts +184 -0
  45. package/src/targets/a2ui/surface.ts +287 -0
  46. package/src/targets/csr.ts +23 -0
  47. package/src/targets/json-render/codegen.ts +135 -0
  48. package/src/targets/json-render/emit.ts +227 -0
  49. package/src/targets/json-render/model.ts +170 -0
  50. package/src/targets/json-render/profile.ts +26 -0
  51. package/src/transform/color.ts +52 -0
  52. package/src/transform/emit.ts +128 -0
  53. package/src/transform/index.ts +54 -0
  54. package/src/transform/inline-defs.ts +209 -0
  55. package/src/transform/mapping.ts +391 -0
  56. package/src/transform/profiles.ts +425 -0
  57. package/src/transform/report.ts +105 -0
  58. package/src/transform.test.ts +112 -0
  59. package/src/types.ts +145 -0
  60. package/src/validate/ajv.ts +151 -0
  61. package/src/validate/meta/a2ui-catalog.meta.0_9_1.json +39 -0
  62. package/src/validate/meta/a2ui-catalog.meta.1_0.json +34 -0
@@ -0,0 +1,34 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://rdombrowski.dev/meta/a2ui-catalog.v1_0.json",
4
+ "title": "A2UI catalog shape (v1.0)",
5
+ "description": "Structural invariants an A2UI v1.0 catalog must satisfy, derived from the checked-in basic catalog fixture. The version-distinguishing requirement is $defs.surfaceProperties (and the absence of $defs.theme).",
6
+ "type": "object",
7
+ "required": ["$schema", "$id", "catalogId", "title", "description", "components", "$defs"],
8
+ "properties": {
9
+ "catalogId": { "type": "string", "format": "uri" },
10
+ "$id": { "type": "string", "format": "uri" },
11
+ "instructions": { "type": "string" },
12
+ "components": {
13
+ "type": "object",
14
+ "minProperties": 1,
15
+ "additionalProperties": {
16
+ "type": "object",
17
+ "required": ["allOf", "unevaluatedProperties"],
18
+ "properties": {
19
+ "allOf": { "type": "array", "minItems": 1 },
20
+ "unevaluatedProperties": { "const": false }
21
+ }
22
+ }
23
+ },
24
+ "$defs": {
25
+ "type": "object",
26
+ "required": ["anyComponent", "surfaceProperties"],
27
+ "not": { "required": ["theme"] },
28
+ "properties": {
29
+ "anyComponent": { "type": "object", "required": ["oneOf"] },
30
+ "surfaceProperties": { "type": "object", "required": ["properties"] }
31
+ }
32
+ }
33
+ }
34
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@aestheticfunction/dspack-emit",
3
+ "version": "0.3.0",
4
+ "type": "module",
5
+ "description": "dspack emitters: compile a dspack design-system contract and dspack surfaces into protocol targets — an A2UI catalog + surface messages (gates A1-A3) and json-render catalog/registry modules + specs (gates J1-J3).",
6
+ "license": "Apache-2.0",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "src",
16
+ "LICENSE",
17
+ "README.md"
18
+ ],
19
+ "scripts": {
20
+ "transform": "tsx src/cli.ts",
21
+ "build": "tsc -p tsconfig.json && mkdir -p dist/validate/meta && cp src/validate/meta/*.json dist/validate/meta/",
22
+ "prepare": "npm run build",
23
+ "build:catalogs": "tsx src/cli.ts --in input/shadcn-ui.dspack.json --a2ui-version 0.9.1 --out out && tsx src/cli.ts --in input/shadcn-ui.dspack.json --a2ui-version 1.0 --out out",
24
+ "test": "vitest run",
25
+ "test:pack": "bash scripts/pack-test.sh",
26
+ "test:json-render": "bash scripts/json-render-gate.sh",
27
+ "check:sync": "node scripts/check-sync.mjs"
28
+ },
29
+ "dependencies": {
30
+ "ajv": "^8.17.1",
31
+ "ajv-formats": "^3.0.1"
32
+ },
33
+ "devDependencies": {
34
+ "@a2ui/web_core": "0.10.3",
35
+ "@types/node": "^22.10.2",
36
+ "tsx": "^4.19.2",
37
+ "typescript": "^5.7.2",
38
+ "vitest": "^2.1.8",
39
+ "zod": "3.25.76"
40
+ }
41
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env -S npx tsx
2
+ /**
3
+ * dspack-emit CLI.
4
+ *
5
+ * tsx src/cli.ts --in <dspack.json> --a2ui-version <0.9.1|1.0> --out <dir> [--surface <surface.json>]
6
+ * [--emit-surface <surface.dsurface.json>]
7
+ * tsx src/cli.ts --target json-render --in <dspack.json> --out <dir>
8
+ * [--emit-surface <surface.dsurface.json>]
9
+ *
10
+ * Default target (a2ui): emits a versioned A2UI catalog + a
11
+ * validation/fidelity report. Exits non-zero if the hard gate (catalog schema
12
+ * validation) fails, so it is CI-friendly. With --emit-surface, additionally
13
+ * compiles a dspack surface document (CSR) into A2UI surface messages
14
+ * (out/<name>.surface.json), instance-validated against the freshly generated
15
+ * catalog (gate A3). A malformed or out-of-vocabulary surface exits 4.
16
+ *
17
+ * json-render target: generates catalog.ts + registry.tsx (Zod component
18
+ * defs + typed stub registry) from the contract. With --emit-surface,
19
+ * additionally compiles the CSR into a json-render spec
20
+ * (out/<name>.spec.json), validated against the catalog model — failure
21
+ * exits 4, mirroring the a2ui path. The framework-level gates J1–J3 (tsc +
22
+ * real Zod parse) run in gates/json-render, not here.
23
+ */
24
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
25
+ import { basename, join, resolve } from "node:path";
26
+ import type { A2uiVersion, DspackDoc, DspackSurface } from "./types.js";
27
+ import { transform } from "./transform/index.js";
28
+ import { emitSurface, EmitSurfaceError } from "./targets/a2ui/surface.js";
29
+ import { generateJsonRenderModules } from "./targets/json-render/codegen.js";
30
+ import { emitJsonRenderSpec, EmitJsonRenderError, validateSpecAgainstModel } from "./targets/json-render/emit.js";
31
+
32
+ interface Args {
33
+ target: "a2ui" | "json-render";
34
+ in: string;
35
+ version: A2uiVersion;
36
+ out: string;
37
+ surface: string;
38
+ emitSurface?: string;
39
+ strictCoverage: boolean;
40
+ }
41
+
42
+ /** Flags that take no value; their presence means `true`. */
43
+ const BOOLEAN_FLAGS = new Set(["strict-coverage"]);
44
+
45
+ function parseArgs(argv: string[]): Args {
46
+ // Supports `--key value`, `--key=value`, and valueless boolean flags; fails fast
47
+ // on a malformed flag or a value-taking `--key` missing its value.
48
+ const m = new Map<string, string>();
49
+ for (let i = 0; i < argv.length; i++) {
50
+ const tok = argv[i];
51
+ if (!tok.startsWith("--")) fail(`unexpected argument '${tok}' (flags must start with --)`);
52
+ const eq = tok.indexOf("=");
53
+ if (eq !== -1) {
54
+ m.set(tok.slice(2, eq), tok.slice(eq + 1));
55
+ } else if (BOOLEAN_FLAGS.has(tok.slice(2))) {
56
+ m.set(tok.slice(2), "true");
57
+ } else {
58
+ const value = argv[++i];
59
+ if (value === undefined) fail(`flag '${tok}' is missing a value`);
60
+ m.set(tok.slice(2), value);
61
+ }
62
+ }
63
+ const target = m.get("target") ?? "a2ui";
64
+ if (target !== "a2ui" && target !== "json-render") {
65
+ fail("--target must be 'a2ui' or 'json-render'");
66
+ }
67
+ const version = m.get("a2ui-version");
68
+ if (target === "a2ui" && version !== "0.9.1" && version !== "1.0") {
69
+ fail("--a2ui-version must be '0.9.1' or '1.0'");
70
+ }
71
+ if (target === "json-render" && version !== undefined) {
72
+ fail("--a2ui-version does not apply to --target json-render");
73
+ }
74
+ const input = m.get("in");
75
+ if (!input) fail("--in <dspack.json> is required");
76
+ return {
77
+ target,
78
+ in: input!,
79
+ version: (version ?? "0.9.1") as A2uiVersion,
80
+ out: m.get("out") ?? "out",
81
+ surface: m.get("surface") ?? "surface/settings-card.surface.json",
82
+ emitSurface: m.get("emit-surface"),
83
+ strictCoverage: m.get("strict-coverage") === "true",
84
+ };
85
+ }
86
+
87
+ function fail(msg: string): never {
88
+ console.error(`error: ${msg}`);
89
+ process.exit(2);
90
+ }
91
+
92
+ function jsonRenderMain(args: Args, doc: DspackDoc): void {
93
+ const tag = "[json-render]";
94
+ const { catalogTs, registryTsx, model } = generateJsonRenderModules(doc);
95
+ mkdirSync(resolve(args.out), { recursive: true });
96
+ const base = resolve(args.out);
97
+ writeFileSync(join(base, "catalog.ts"), catalogTs);
98
+ writeFileSync(join(base, "registry.tsx"), registryTsx);
99
+ console.log(`${tag} catalog -> ${join(args.out, "catalog.ts")} (${model.components.length} components)`);
100
+ console.log(`${tag} registry -> ${join(args.out, "registry.tsx")} (stub implementations)`);
101
+ for (const component of model.components) {
102
+ for (const excluded of component.excludedProps) {
103
+ console.log(`${tag} note prop-excluded: ${component.dspackId}.${excluded.name} — ${excluded.reason}`);
104
+ }
105
+ }
106
+
107
+ if (args.emitSurface) {
108
+ const csr = JSON.parse(readFileSync(resolve(args.emitSurface), "utf8")) as DspackSurface;
109
+ let emitted;
110
+ try {
111
+ emitted = emitJsonRenderSpec(csr, doc);
112
+ } catch (e) {
113
+ if (e instanceof EmitJsonRenderError) {
114
+ console.error(`${tag} EMIT-SPEC FAILED: ${e.message}`);
115
+ process.exit(4);
116
+ }
117
+ throw e;
118
+ }
119
+ const name = basename(args.emitSurface).replace(/\.dsurface\.json$|\.json$/, "");
120
+ const outPath = join(base, `${name}.spec.json`);
121
+ writeFileSync(outPath, JSON.stringify(emitted.spec, null, 2) + "\n");
122
+ for (const w of emitted.warnings) console.log(`${tag} note ${w.code}: ${w.message}`);
123
+ // Offline mirror of gates J2/J3 over the emitted spec; the framework-level
124
+ // gates (tsc + real Zod parse) run in gates/json-render.
125
+ const findings = validateSpecAgainstModel(emitted.spec, model);
126
+ console.log(`${tag} emitted spec -> ${outPath}`);
127
+ console.log(`${tag} ${findings.length === 0 ? "PASS" : "FAIL"} model-vocabulary (emitted spec vs generated catalog model)`);
128
+ if (findings.length > 0) {
129
+ for (const f of findings) console.error(`${tag} ${f.path}: ${f.message}`);
130
+ process.exit(4);
131
+ }
132
+ }
133
+ }
134
+
135
+ function main(): void {
136
+ const args = parseArgs(process.argv.slice(2));
137
+ const seg = args.version === "0.9.1" ? "v0_9_1" : "v1_0";
138
+
139
+ const doc = JSON.parse(readFileSync(resolve(args.in), "utf8")) as DspackDoc;
140
+ if (args.target === "json-render") {
141
+ jsonRenderMain(args, doc);
142
+ return;
143
+ }
144
+ const surface = JSON.parse(readFileSync(resolve(args.surface), "utf8"));
145
+
146
+ const { catalog, mapping, validation, report } = transform(doc, args.version, surface);
147
+
148
+ mkdirSync(resolve(args.out), { recursive: true });
149
+ const base = resolve(args.out);
150
+ writeFileSync(join(base, `catalog.${seg}.json`), JSON.stringify(catalog, null, 2) + "\n");
151
+ writeFileSync(join(base, `validation-report.${seg}.md`), report.md);
152
+ writeFileSync(join(base, `validation-report.${seg}.json`), JSON.stringify(report.json, null, 2) + "\n");
153
+
154
+ const tag = `[a2ui ${args.version}]`;
155
+ console.log(`${tag} catalog -> ${join(args.out, `catalog.${seg}.json`)}`);
156
+ console.log(`${tag} report -> ${join(args.out, `validation-report.${seg}.md`)}`);
157
+ for (const g of validation.gates) console.log(`${tag} ${g.pass ? "PASS" : "FAIL"} ${g.name}`);
158
+ console.log(`${tag} ${validation.pass ? "VALIDATION PASSED" : "VALIDATION FAILED"}`);
159
+
160
+ const unclassified = mapping.coverage.filter((c) => c.disposition === "unclassified");
161
+ if (unclassified.length) {
162
+ console.log(`${tag} COVERAGE: ${unclassified.length} unclassified component(s): ${unclassified.map((c) => c.id).join(", ")}`);
163
+ }
164
+
165
+ if (!validation.pass) process.exit(1);
166
+ if (args.strictCoverage && unclassified.length) process.exit(3);
167
+
168
+ if (args.emitSurface) {
169
+ const csr = JSON.parse(readFileSync(resolve(args.emitSurface), "utf8")) as DspackSurface;
170
+ let emitted;
171
+ try {
172
+ emitted = emitSurface(csr, doc);
173
+ } catch (e) {
174
+ if (e instanceof EmitSurfaceError) {
175
+ console.error(`${tag} EMIT-SURFACE FAILED: ${e.message}`);
176
+ process.exit(4);
177
+ }
178
+ throw e;
179
+ }
180
+ const name = basename(args.emitSurface).replace(/\.dsurface\.json$|\.json$/, "");
181
+ const outPath = join(base, `${name}.surface.json`);
182
+ writeFileSync(outPath, JSON.stringify({ messages: emitted.messages }, null, 2) + "\n");
183
+ for (const w of emitted.warnings) console.log(`${tag} note ${w.code}: ${w.message}`);
184
+ // Gate A3 over the emitted surface: its instances must validate against the
185
+ // catalog generated in this same run.
186
+ const check = transform(doc, args.version, { messages: emitted.messages });
187
+ const instanceGate = check.validation.gates.find((g) => g.name === "instance");
188
+ console.log(`${tag} emitted surface -> ${outPath}`);
189
+ console.log(`${tag} ${instanceGate?.pass ? "PASS" : "FAIL"} instance (emitted surface vs generated catalog)`);
190
+ if (!instanceGate?.pass) {
191
+ for (const err of instanceGate?.errors ?? []) console.error(`${tag} ${err}`);
192
+ process.exit(4);
193
+ }
194
+ }
195
+ }
196
+
197
+ main();
package/src/index.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Public library surface of dspack-emit (the multi-target dspack emitter).
3
+ *
4
+ * Consumers (dspack-gen) depend on exactly this module; everything not
5
+ * re-exported here is internal. The CLI (src/cli.ts) is a thin wrapper over
6
+ * the same functions.
7
+ */
8
+ export { transform, transformFromJson, type TransformOutput } from "./transform/index.js";
9
+ export { shadcnProfile, type Profile, type ComponentPlan, type SurfacePlanDirectives } from "./transform/profiles.js";
10
+ export { validateCatalog, extractInstances, type ValidationReport, type GateResult } from "./validate/ajv.js";
11
+ export {
12
+ emitSurface,
13
+ slug,
14
+ EmitSurfaceError,
15
+ type EmitSurfaceResult,
16
+ type EmitSurfaceOptions,
17
+ } from "./targets/a2ui/surface.js";
18
+ export {
19
+ emitJsonRenderSpec,
20
+ validateSpecAgainstModel,
21
+ EmitJsonRenderError,
22
+ type EmitJsonRenderResult,
23
+ type EmitJsonRenderOptions,
24
+ type JsonRenderSpec,
25
+ type JsonRenderElement,
26
+ type SpecFinding,
27
+ } from "./targets/json-render/emit.js";
28
+ export { generateJsonRenderModules, type JsonRenderModules } from "./targets/json-render/codegen.js";
29
+ export { buildCatalogModel, type CatalogModel, type CatalogComponent, type CatalogProp } from "./targets/json-render/model.js";
30
+ export { shadcnJsonRenderProfile, type JsonRenderProfile } from "./targets/json-render/profile.js";
31
+ export type {
32
+ A2uiCatalog,
33
+ A2uiVersion,
34
+ DspackDoc,
35
+ DspackSurface,
36
+ SurfaceNode,
37
+ Json,
38
+ Warning,
39
+ } from "./types.js";
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Ingestion acceptance gates (Phase 2).
3
+ *
4
+ * These run the REAL transform (compiler) on dspack fixtures and feed the resulting catalog
5
+ * JSON to the UNCHANGED ingestion adapter (demo/src/ingest). The acceptance boundary is:
6
+ * recompiling a changed contract changes the renderer's accepted vocabulary, accepted props,
7
+ * or accept/refuse behavior with NO edit to the adapter or registry (demo/src/ingest/*).
8
+ * The transform + profile are the compiler and are expected to change.
9
+ */
10
+ import { describe, expect, it } from "vitest";
11
+ import { readFileSync } from "node:fs";
12
+ import { fileURLToPath } from "node:url";
13
+ import { scrapeSchemaBehavior } from "@a2ui/web_core/v0_9";
14
+ import { transformFromJson } from "./transform/index.js";
15
+ import { shadcnProfile, type Profile, type ComponentPlan } from "./transform/profiles.js";
16
+ import type { DspackDoc } from "./types.js";
17
+ import { buildComponentApi } from "../demo/src/ingest/buildComponentApi";
18
+ import { planRegistry } from "../demo/src/ingest/classify";
19
+ import { registry } from "../demo/src/ingest/registry";
20
+
21
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
22
+ const load = (p: string) => JSON.parse(readFileSync(p, "utf8")) as DspackDoc;
23
+
24
+ // The canonical input now includes the `table` component (the updated contract).
25
+ const doc = load(repo("input/shadcn-ui.dspack.json"));
26
+
27
+ const names = (cat: any): string[] => Object.keys(cat.components ?? {});
28
+
29
+ /** The shadcn profile with the Table mapping removed (Table is neither mapped nor a casualty). */
30
+ const tableLessProfile: Profile = {
31
+ ...shadcnProfile,
32
+ components: shadcnProfile.components.filter((c) => c.a2ui !== "Table"),
33
+ };
34
+
35
+ /** A profile that maps dropdown-menu to a component the registry has NO visual for. */
36
+ const DROPDOWN_PLAN: ComponentPlan = {
37
+ a2ui: "DropdownMenu",
38
+ dspackId: "dropdown-menu",
39
+ commons: ["ComponentCommon"],
40
+ structural: {
41
+ triggerLabel: {
42
+ schema: { $ref: "#/$defs/DynamicString" },
43
+ description: "Trigger label.",
44
+ synthNote: "synth",
45
+ },
46
+ },
47
+ required: ["triggerLabel"],
48
+ };
49
+ const dropdownProfile: Profile = {
50
+ ...shadcnProfile,
51
+ components: [...shadcnProfile.components, DROPDOWN_PLAN],
52
+ casualtyComponents: shadcnProfile.casualtyComponents.filter((c) => c.dspackId !== "dropdown-menu"),
53
+ };
54
+
55
+ describe("Gate A — vocabulary is catalog-driven (no adapter edit)", () => {
56
+ it("mapping Table in the compiled contract adds it to the renderer's accepted vocabulary", () => {
57
+ const withTable = transformFromJson(doc, { profile: shadcnProfile }).catalog;
58
+ const withoutTable = transformFromJson(doc, { profile: tableLessProfile }).catalog;
59
+
60
+ const added = names(withTable).filter((n) => !names(withoutTable).includes(n));
61
+ expect(added).toEqual(["Table"]);
62
+ // The adapter builds a real ComponentApi for the new name with zero adapter changes.
63
+ expect(buildComponentApi(withTable, "Table").name).toBe("Table");
64
+ });
65
+ });
66
+
67
+ describe("Gate B — accepted props are catalog-driven (no adapter edit)", () => {
68
+ it("adding a Button variant in the contract makes the ingested schema accept it", () => {
69
+ const base = transformFromJson(doc, { profile: shadcnProfile }).catalog;
70
+
71
+ const modProfile: Profile = structuredClone(shadcnProfile);
72
+ const button = modProfile.components.find((c) => c.a2ui === "Button")!;
73
+ button.propMap!.variant.targetEnum = [...button.propMap!.variant.targetEnum!, "subtle"];
74
+ const mod = transformFromJson(doc, { profile: modProfile }).catalog;
75
+
76
+ const validProps = { child: "lbl", action: { event: { name: "save", context: {} } }, variant: "subtle" };
77
+ expect(buildComponentApi(base, "Button").schema.safeParse(validProps).success).toBe(false);
78
+ expect(buildComponentApi(mod, "Button").schema.safeParse(validProps).success).toBe(true);
79
+ });
80
+ });
81
+
82
+ describe("Gate C — refusal vs unimplemented are distinct and non-silent", () => {
83
+ it("a catalog name without a visual is 'unimplemented'; a name absent from the catalog is refused", () => {
84
+ const cat = transformFromJson(doc, { profile: dropdownProfile }).catalog;
85
+ const plan = planRegistry(names(cat), registry);
86
+
87
+ // DropdownMenu is in the catalog (accepted vocabulary) but has no registered visual.
88
+ expect(plan.unimplemented).toContain("DropdownMenu");
89
+ // Reused basics and hand-authored visuals are not flagged unimplemented.
90
+ expect(plan.reuseBasic).toEqual(expect.arrayContaining(["Button", "Card", "TextField"]));
91
+ expect(plan.custom).toEqual(expect.arrayContaining(["Table", "Badge", "AlertDialog"]));
92
+ // A name absent from the catalog is a different state: the renderer refuses it (Unknown).
93
+ expect(names(cat)).not.toContain("Nonexistent");
94
+ });
95
+
96
+ it("the default catalog has no unimplemented components (all have a visual)", () => {
97
+ const base = transformFromJson(doc, { profile: shadcnProfile }).catalog;
98
+ expect(planRegistry(names(base), registry).unimplemented).toEqual([]);
99
+ });
100
+ });
101
+
102
+ describe("Binding fidelity — the linchpin", () => {
103
+ const cat = transformFromJson(doc, { profile: shadcnProfile }).catalog;
104
+ const shapeOf = (name: string) => (scrapeSchemaBehavior(buildComponentApi(cat, name).schema) as any).shape;
105
+
106
+ it("dynamic, action, child-list, and checkable props are recognized by scrapeSchemaBehavior", () => {
107
+ const tf = shapeOf("TextField");
108
+ expect(tf.value.type).toBe("DYNAMIC");
109
+ expect(tf.label.type).toBe("DYNAMIC");
110
+ expect(tf.variant.type).toBe("STATIC");
111
+
112
+ const btn = shapeOf("Button");
113
+ expect(btn.action.type).toBe("ACTION");
114
+ expect(btn.checks.type).toBe("CHECKABLE");
115
+
116
+ const col = shapeOf("Column");
117
+ expect(col.children.type).toBe("STRUCTURAL");
118
+ });
119
+ });
120
+
121
+ describe("Tier independence — Tier 1 works with no x-a2ui hints", () => {
122
+ it("stripping all x-a2ui keys leaves binding + enum classification intact", () => {
123
+ const cat = transformFromJson(doc, { profile: shadcnProfile }).catalog;
124
+ const stripped = JSON.parse(
125
+ JSON.stringify(cat, (k, v) => (k.startsWith("x-a2ui") ? undefined : v)),
126
+ );
127
+ const tf = (scrapeSchemaBehavior(buildComponentApi(stripped, "TextField").schema) as any).shape;
128
+ expect(tf.value.type).toBe("DYNAMIC");
129
+ const btnVariant = buildComponentApi(stripped, "Button").schema;
130
+ expect(btnVariant.safeParse({ child: "x", action: { event: { name: "e", context: {} } }, variant: "primary" }).success).toBe(true);
131
+ });
132
+ });
133
+
134
+ describe("Coverage — no silent drops (P1)", () => {
135
+ it("an unmapped dspack component is reported as unclassified, not silently dropped", () => {
136
+ // A profile that does not map `table` (and doesn't list it a casualty) must still account for it.
137
+ const r = transformFromJson(doc, { profile: tableLessProfile });
138
+ const cov = r.mapping.coverage.find((c) => c.id === "table");
139
+ expect(cov?.disposition).toBe("unclassified");
140
+ expect(r.mapping.warnings.map((w) => w.code)).toContain("unclassified-component:table");
141
+ // ...and it is NOT silently present in the emitted catalog.
142
+ expect(names(r.catalog)).not.toContain("Table");
143
+ });
144
+ });
145
+
146
+ describe("Negative control — the adapter has no hardcoded component-name list", () => {
147
+ it("buildComponentApi and buildCatalog name no components", () => {
148
+ for (const file of ["buildComponentApi.ts", "buildCatalog.tsx"]) {
149
+ const src = readFileSync(repo(`demo/src/ingest/${file}`), "utf8");
150
+ for (const name of ["Button", "TextField", "Table", "Card", "Column"]) {
151
+ expect(src.includes(`"${name}"`), `${file} must not name component '${name}'`).toBe(false);
152
+ expect(src.includes(`'${name}'`), `${file} must not name component '${name}'`).toBe(false);
153
+ }
154
+ }
155
+ });
156
+ });
@@ -0,0 +1,196 @@
1
+ /**
2
+ * PR-9 acceptance gates: the json-render target.
3
+ *
4
+ * THE THESIS TEST, with its guarantee stated precisely: governance runs
5
+ * pre-emission on the CSR (gates S1–S3, dspack-gen), so governed/violating
6
+ * status is identical across emitters BY CONSTRUCTION. What this test
7
+ * demonstrates is that every governed CSR this repo carries — the contract's
8
+ * worked example and the delete-account fixture — is ACCEPTED BY BOTH
9
+ * emitters: the a2ui target (emitter gates A1–A3, both A2UI versions) and
10
+ * the json-render target (emission + catalog-model vocabulary). It does NOT
11
+ * claim protocol expressiveness equivalence.
12
+ *
13
+ * The framework-level json-render gates (J1 generated modules compile, J2
14
+ * validateSpec, J3 catalog.validate with real zod v4) run in
15
+ * scripts/json-render-gate.sh — a separate pinned package, because
16
+ * @a2ui/web_core pins the root tree to zod v3 while json-render requires
17
+ * zod v4. This file asserts everything that is assertable offline.
18
+ */
19
+ import { readFileSync } from "node:fs";
20
+ import { describe, expect, it } from "vitest";
21
+ import type { DspackDoc, DspackSurface, SurfaceNode } from "./types.js";
22
+ import { transform } from "./transform/index.js";
23
+ import { emitSurface } from "./targets/a2ui/surface.js";
24
+ import {
25
+ emitJsonRenderSpec,
26
+ EmitJsonRenderError,
27
+ validateSpecAgainstModel,
28
+ } from "./targets/json-render/emit.js";
29
+ import { generateJsonRenderModules } from "./targets/json-render/codegen.js";
30
+ import { buildCatalogModel } from "./targets/json-render/model.js";
31
+ import { shadcnJsonRenderProfile } from "./targets/json-render/profile.js";
32
+
33
+ const doc = JSON.parse(readFileSync("input/shadcn-ui.dspack.json", "utf8")) as DspackDoc & {
34
+ examples: Array<{ id: string; surface: DspackSurface }>;
35
+ };
36
+ const workedExample = doc.examples.find((e) => e.id === "ex.delete-account-confirmation")!;
37
+ const deleteAccountFixture = JSON.parse(
38
+ readFileSync("surface/delete-account.dsurface.json", "utf8"),
39
+ ) as DspackSurface;
40
+
41
+ const governedCorpus: Array<[string, DspackSurface]> = [
42
+ ["worked example ex.delete-account-confirmation", workedExample.surface],
43
+ ["surface/delete-account.dsurface.json", deleteAccountFixture],
44
+ ];
45
+
46
+ describe("thesis test: governed CSRs are accepted by both emitters", () => {
47
+ for (const [label, surface] of governedCorpus) {
48
+ it(`${label}: a2ui target accepts (gates A1–A3, both A2UI versions)`, () => {
49
+ const { messages } = emitSurface(surface, doc);
50
+ for (const version of ["0.9.1", "1.0"] as const) {
51
+ const { validation } = transform(doc, version, { messages });
52
+ expect(
53
+ Object.fromEntries(validation.gates.map((g) => [g.name, g.pass])),
54
+ `a2ui gates for ${version}`,
55
+ ).toEqual({
56
+ "schema-compile + no-external-ref": true,
57
+ "catalog-shape": true,
58
+ instance: true,
59
+ });
60
+ }
61
+ });
62
+
63
+ it(`${label}: json-render target accepts (emission + catalog-model vocabulary)`, () => {
64
+ const { spec } = emitJsonRenderSpec(surface, doc);
65
+ const model = buildCatalogModel(doc, shadcnJsonRenderProfile);
66
+ expect(validateSpecAgainstModel(spec, model)).toEqual([]);
67
+ });
68
+ }
69
+ });
70
+
71
+ describe("emitJsonRenderSpec: composition survives (no flattening)", () => {
72
+ const { spec, warnings } = emitJsonRenderSpec(workedExample.surface, doc);
73
+
74
+ it("the root emits under key 'root' and nesting is preserved by reference", () => {
75
+ expect(spec.root).toBe("root");
76
+ expect(spec.elements.root.type).toBe("Card");
77
+ // Card -> AlertDialog -> AlertDialogTrigger -> Button: the chain the a2ui
78
+ // target flattens onto AlertDialog props exists here as real elements.
79
+ const dialogKey = spec.elements.root.children[0];
80
+ expect(spec.elements[dialogKey].type).toBe("AlertDialog");
81
+ const triggerKey = spec.elements[dialogKey].children[0];
82
+ expect(spec.elements[triggerKey].type).toBe("AlertDialogTrigger");
83
+ const buttonKey = spec.elements[triggerKey].children[0];
84
+ expect(spec.elements[buttonKey].type).toBe("Button");
85
+ expect(spec.elements[buttonKey].props).toMatchObject({ variant: "destructive", text: "Delete account" });
86
+ });
87
+
88
+ it("sub-components are first-class elements with their text carried verbatim", () => {
89
+ const title = Object.values(spec.elements).find((e) => e.type === "AlertDialogTitle")!;
90
+ expect(title.props.text).toBe("Delete your account?");
91
+ const cancel = Object.values(spec.elements).find((e) => e.type === "AlertDialogCancel")!;
92
+ expect(cancel.props.text).toBe("Cancel");
93
+ });
94
+
95
+ it("emits no flattening/synthesis warnings for a slot-free compound surface", () => {
96
+ expect(warnings).toEqual([]);
97
+ });
98
+
99
+ it("every element satisfies json-render's element shape (children keys resolve, visible present)", () => {
100
+ for (const element of Object.values(spec.elements)) {
101
+ expect(element.visible).toBe(true);
102
+ for (const child of element.children) expect(spec.elements[child]).toBeDefined();
103
+ }
104
+ });
105
+
106
+ it("is deterministic", () => {
107
+ expect(emitJsonRenderSpec(workedExample.surface, doc)).toEqual(
108
+ emitJsonRenderSpec(workedExample.surface, doc),
109
+ );
110
+ });
111
+ });
112
+
113
+ describe("emitJsonRenderSpec: honesty of the recorded projections", () => {
114
+ it("rejects unknown components with a typed error", () => {
115
+ const surface = structuredClone(workedExample.surface);
116
+ surface.root.children![0].component = "not-a-component";
117
+ expect(() => emitJsonRenderSpec(surface, doc)).toThrow(EmitJsonRenderError);
118
+ });
119
+
120
+ it("drops props.text with a warning — the CSR `text` leaf is the universal text prop's only source", () => {
121
+ const surface = structuredClone(workedExample.surface);
122
+ const button = surface.root.children![0].children![0].children![0]; // the trigger button
123
+ button.props = { ...button.props, text: "smuggled" };
124
+ const { spec, warnings } = emitJsonRenderSpec(surface, doc);
125
+ const emitted = Object.values(spec.elements).find((e) => e.type === "Button")!;
126
+ expect(emitted.props.text).toBe("Delete account"); // node.text, not props.text
127
+ expect(warnings.some((w) => w.code === "jr-prop-dropped" && w.message.includes("reserved for the CSR"))).toBe(
128
+ true,
129
+ );
130
+ });
131
+
132
+ it("drops handler props with a warning (declarative-catalog boundary)", () => {
133
+ const surface = structuredClone(workedExample.surface);
134
+ surface.root.children![0].props = { onOpenChange: "noop" };
135
+ const { spec, warnings } = emitJsonRenderSpec(surface, doc);
136
+ const dialog = Object.values(spec.elements).find((e) => e.type === "AlertDialog")!;
137
+ expect(dialog.props.onOpenChange).toBeUndefined();
138
+ expect(warnings.map((w) => w.code)).toContain("jr-prop-dropped");
139
+ });
140
+
141
+ it("flattens slotted children into child order with a warning (slot names are not representable)", () => {
142
+ const badge: SurfaceNode = { component: "badge", text: "beta" };
143
+ const surface: DspackSurface = {
144
+ dspackSurface: "0.1",
145
+ system: doc.name,
146
+ intent: "destructive-action",
147
+ root: { component: "card", children: [{ component: "button", text: "b" }], slots: { footer: [badge] } },
148
+ };
149
+ const { spec, warnings } = emitJsonRenderSpec(surface, doc);
150
+ expect(spec.elements.root.children.map((k) => spec.elements[k].type)).toEqual(["Button", "Badge"]);
151
+ expect(warnings.map((w) => w.code)).toContain("jr-slot-names-flattened");
152
+ });
153
+
154
+ it("the offline model check is non-vacuous (bad enum value, dangling child, unknown type all found)", () => {
155
+ const model = buildCatalogModel(doc, shadcnJsonRenderProfile);
156
+ const { spec } = emitJsonRenderSpec(workedExample.surface, doc);
157
+ const bad = structuredClone(spec);
158
+ const buttonKey = Object.keys(bad.elements).find((k) => bad.elements[k].type === "Button")!;
159
+ bad.elements[buttonKey].props.variant = "not-a-variant";
160
+ bad.elements[buttonKey].children.push("dangling");
161
+ bad.elements.rogue = { type: "Rogue", props: {}, children: [], visible: true };
162
+ const messages = validateSpecAgainstModel(bad, model).map((f) => f.message);
163
+ expect(messages.some((m) => m.includes("not in enum vocabulary"))).toBe(true);
164
+ expect(messages.some((m) => m.includes("'dangling' not found"))).toBe(true);
165
+ expect(messages.some((m) => m.includes("unknown component type 'Rogue'"))).toBe(true);
166
+ });
167
+ });
168
+
169
+ describe("codegen: generated modules match the reviewed goldens", () => {
170
+ // The goldens are the hand-review artifact for the generated code: any
171
+ // change to what the codegen emits shows up as a reviewable diff here.
172
+ const { catalogTs, registryTsx, model } = generateJsonRenderModules(doc);
173
+
174
+ it("catalog.ts equals golden", () => {
175
+ expect(catalogTs).toBe(readFileSync("golden/json-render/catalog.ts.golden", "utf8"));
176
+ });
177
+
178
+ it("registry.tsx equals golden", () => {
179
+ expect(registryTsx).toBe(readFileSync("golden/json-render/registry.tsx.golden", "utf8"));
180
+ });
181
+
182
+ it("catalogs the full contract vocabulary: components + sub-components, 1:1", () => {
183
+ const contractIds = Object.entries(doc.components ?? {}).flatMap(([id, c]) => [
184
+ id,
185
+ ...(((c as { composition?: { subComponents?: Array<{ id: string }> } }).composition?.subComponents) ?? []).map(
186
+ (s) => s.id,
187
+ ),
188
+ ]);
189
+ expect(model.components.map((c) => c.dspackId)).toEqual(contractIds);
190
+ });
191
+
192
+ it("excludes exactly the handler props, with reasons recorded", () => {
193
+ const excluded = model.components.flatMap((c) => c.excludedProps.map((e) => `${c.dspackId}.${e.name}`));
194
+ expect(excluded).toEqual(["alert-dialog.onOpenChange", "dialog.onOpenChange", "dropdown-menu.onOpenChange"]);
195
+ });
196
+ });