@aestheticfunction/dspack-emit 0.4.1 → 0.6.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 (72) 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 +1004 -222
  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 +66 -2
  15. package/dist/transform/model.d.ts +368 -0
  16. package/dist/transform/model.js +169 -0
  17. package/dist/transform/parse-v2.d.ts +109 -0
  18. package/dist/transform/parse-v2.js +479 -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 +608 -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 +77 -0
  27. package/dist/transform/shadcn-v2-respelling.js +456 -0
  28. package/dist/transform/validate-v2.d.ts +36 -0
  29. package/dist/transform/validate-v2.js +136 -0
  30. package/dist/types.d.ts +23 -0
  31. package/dist/validate/ajv.js +96 -25
  32. package/dist/validate/meta/a2ui-catalog.meta.0_9_1.json +39 -0
  33. package/dist/validate/meta/a2ui-catalog.meta.1_0.json +34 -0
  34. package/package.json +2 -2
  35. package/src/__snapshots__/byte-neutral.test.ts.snap +66 -0
  36. package/src/a0.test.ts +235 -0
  37. package/src/byte-neutral.test.ts +246 -0
  38. package/src/cli.ts +60 -0
  39. package/src/dangling-ref.test.ts +118 -0
  40. package/src/desugar.test.ts +162 -0
  41. package/src/engine-boundary.test.ts +248 -0
  42. package/src/eval-fixture.test.ts +102 -0
  43. package/src/functions.test.ts +182 -0
  44. package/src/index.ts +4 -1
  45. package/src/layered-dissolution.test.ts +139 -0
  46. package/src/profile-load.test.ts +99 -1
  47. package/src/profile-v2.test.ts +369 -0
  48. package/src/review-findings.test.ts +292 -0
  49. package/src/schema-mirrors.test.ts +5 -0
  50. package/src/surface-fidelity.test.ts +213 -0
  51. package/src/t1.test.ts +369 -0
  52. package/src/t2.test.ts +222 -0
  53. package/src/t3.test.ts +304 -0
  54. package/src/t4.test.ts +278 -0
  55. package/src/targets/a2ui/diagnostics.ts +136 -0
  56. package/src/targets/a2ui/surface.ts +1468 -235
  57. package/src/transform/desugar.ts +194 -0
  58. package/src/transform/emit.ts +65 -0
  59. package/src/transform/index.ts +5 -0
  60. package/src/transform/mapping.ts +60 -2
  61. package/src/transform/model.ts +427 -0
  62. package/src/transform/parse-v2.ts +608 -0
  63. package/src/transform/profile-load.ts +104 -22
  64. package/src/transform/profile-schema-v2.ts +608 -0
  65. package/src/transform/profile.v2.schema.json +600 -0
  66. package/src/transform/profiles.ts +32 -1
  67. package/src/transform/scaffold.ts +124 -47
  68. package/src/transform/shadcn-v2-respelling.ts +475 -0
  69. package/src/transform/validate-v2.ts +174 -0
  70. package/src/types.ts +32 -0
  71. package/src/validate/ajv.ts +89 -26
  72. package/src/validate-v2.test.ts +173 -0
@@ -0,0 +1,479 @@
1
+ import { WriteOrder, emptySurfaceModel, isCollect, } from "./model.js";
2
+ export class ProfileParseError extends Error {
3
+ issues;
4
+ constructor(issues) {
5
+ super(`profile v2 surface syntax is invalid (${issues.length} issue${issues.length === 1 ? "" : "s"}): ` +
6
+ issues
7
+ .slice(0, 3)
8
+ .map((i) => `${i.path || "$"}: ${i.message}`)
9
+ .join("; ") +
10
+ (issues.length > 3 ? "; …" : ""));
11
+ this.issues = issues;
12
+ this.name = "ProfileParseError";
13
+ }
14
+ }
15
+ // ---------------------------------------------------------------------------
16
+ // Selector / destination string grammar
17
+ // ---------------------------------------------------------------------------
18
+ const ID = "[a-z][a-z0-9-]*";
19
+ const PROP = "[A-Za-z][A-Za-z0-9]*";
20
+ const SELECTOR = new RegExp(`^(self\\.text|self\\.id|self\\.props\\.(${PROP})|sub\\((${ID}(?:\\|${ID})*)\\)\\.(text|label|firstText|subtreeText|children)|children|synthesized\\.action)$`);
21
+ const DESTINATION = new RegExp(`^(prop|textChild|slot|slots|action):(${PROP})$`);
22
+ export function parseSelector(raw) {
23
+ const m = SELECTOR.exec(raw);
24
+ if (!m)
25
+ return null;
26
+ if (m[1] === "self.text")
27
+ return { kind: "self-text" };
28
+ if (m[1] === "self.id")
29
+ return { kind: "self-id" };
30
+ if (m[1] === "children")
31
+ return { kind: "children" };
32
+ if (m[1] === "synthesized.action")
33
+ return { kind: "synthesized-action" };
34
+ if (m[2])
35
+ return { kind: "self-prop", prop: m[2] };
36
+ const subs = m[3].split("|");
37
+ switch (m[4]) {
38
+ case "text":
39
+ return { kind: "sub-text", subs };
40
+ case "label":
41
+ return { kind: "sub-label", subs };
42
+ case "firstText":
43
+ return { kind: "sub-text-lift", subs };
44
+ case "children":
45
+ return { kind: "sub-children", subs };
46
+ default:
47
+ return { kind: "subtree-text", subs };
48
+ }
49
+ }
50
+ export function parseDestination(raw) {
51
+ const m = DESTINATION.exec(raw);
52
+ if (!m)
53
+ return null;
54
+ const name = m[2];
55
+ switch (m[1]) {
56
+ case "prop":
57
+ return { kind: "prop", name };
58
+ case "textChild":
59
+ return { kind: "text-child", name };
60
+ case "slot":
61
+ return { kind: "slot", name };
62
+ case "slots":
63
+ return { kind: "slots", name };
64
+ default:
65
+ return { kind: "action", name };
66
+ }
67
+ }
68
+ // ---------------------------------------------------------------------------
69
+ // Derived write order — v2 authors never write WriteOrder; it is a function
70
+ // of what the route reads and writes, reproducing v1's phase semantics.
71
+ // ---------------------------------------------------------------------------
72
+ function orderOfSelector(s, to) {
73
+ switch (s.kind) {
74
+ case "self-prop":
75
+ return WriteOrder.Verbatim;
76
+ case "sub-text":
77
+ case "sub-label":
78
+ case "sub-text-lift":
79
+ return WriteOrder.Consume;
80
+ case "subtree-text":
81
+ return WriteOrder.CollectLead;
82
+ case "self-text":
83
+ return to.kind === "text-child" ? WriteOrder.SelfTextChild : WriteOrder.SelfText;
84
+ case "self-id":
85
+ return WriteOrder.SelfText; // unreachable in routes: `compatible` refuses it
86
+ case "synthesized-action":
87
+ return WriteOrder.Action;
88
+ case "sub-children":
89
+ return WriteOrder.Slot;
90
+ case "children":
91
+ return WriteOrder.Children;
92
+ }
93
+ }
94
+ /** Selector-kind → destination-kind compatibility (closed, refused otherwise). */
95
+ function compatible(s, to) {
96
+ switch (s.kind) {
97
+ case "children":
98
+ return to.kind === "slot" || to.kind === "slots";
99
+ case "sub-children":
100
+ // T4: instance emission from a named region lands in exactly one slot.
101
+ return to.kind === "slot";
102
+ case "synthesized-action":
103
+ return to.kind === "action";
104
+ case "self-text":
105
+ return to.kind === "prop" || to.kind === "text-child";
106
+ case "self-id":
107
+ return false; // item-field-only: a route may not read self.id
108
+ default:
109
+ return to.kind === "prop";
110
+ }
111
+ }
112
+ // ---------------------------------------------------------------------------
113
+ // The parser
114
+ // ---------------------------------------------------------------------------
115
+ /**
116
+ * Parse and statically validate one plan's v2 surface block.
117
+ *
118
+ * `path` roots the pathed findings (e.g. `/components/3/surface`). Validation
119
+ * here needs only the plan itself: destinations against its own declared
120
+ * structural slots and propMap targets, conflict detection under the write
121
+ * discipline, and grammar closure. Contract-facing checks (sub ids exist,
122
+ * self-props are declared, derived coverage is complete) run at transform
123
+ * time, where the contract is in hand — see validate-v2.ts.
124
+ */
125
+ /** Parses one donate entry; donation selectors and destinations are narrower than routes'. */
126
+ function parseDonation(d, at, issues, origin) {
127
+ const from = parseSelector(d.from);
128
+ if (!from || (from.kind !== "self-text" && from.kind !== "sub-text")) {
129
+ issues.push({ path: `${at}/from`, message: `'${d.from}' is not a donation source (donations harvest text: self.text or sub(<id>|…).text)` });
130
+ return null;
131
+ }
132
+ const to = parseDestination(d.to);
133
+ if (!to || to.kind !== "prop") {
134
+ issues.push({ path: `${at}/to`, message: `'${d.to}' is not a donation destination (donations write prop:<name> on the receiving control)` });
135
+ return null;
136
+ }
137
+ return { from, to, origin };
138
+ }
139
+ export function parseSurfaceV2(surface, plan, path) {
140
+ const issues = [];
141
+ const model = emptySurfaceModel();
142
+ // T1: transparent identity. A transparent plan emits nothing, so nothing it
143
+ // could declare for an instance is meaningful — routes, collects, structural
144
+ // slots, propMap, required all refuse. Only sub dispositions (for its own
145
+ // dissolved subtree) and donations survive.
146
+ if (surface.transparent !== undefined) {
147
+ model.transparent = true;
148
+ if (typeof surface.transparent === "object") {
149
+ surface.transparent.donate.forEach((d, i) => {
150
+ const parsed = parseDonation(d, `${path}/transparent/donate/${i}`, issues, `v2:transparent/donate/${i}`);
151
+ if (parsed)
152
+ model.transparentDonate.push(parsed);
153
+ });
154
+ }
155
+ if ((surface.routes ?? []).length > 0 || (surface.collects ?? []).length > 0) {
156
+ issues.push({ path, message: "a transparent plan emits no instance; routes and collects have nowhere to land (donations are the only writes it may carry)" });
157
+ }
158
+ for (const [field, label] of [
159
+ [plan.structural ?? {}, "structural"],
160
+ [plan.propMap ?? {}, "propMap"],
161
+ ]) {
162
+ if (Object.keys(field).length > 0) {
163
+ issues.push({ path, message: `a transparent plan declares no catalog surface; remove its ${label} block` });
164
+ }
165
+ }
166
+ if ((plan.required ?? []).length > 0) {
167
+ issues.push({ path, message: "a transparent plan declares no catalog surface; remove its required list" });
168
+ }
169
+ }
170
+ // The plan's own declared destination names: structural slots plus the
171
+ // a2ui-side names its propMap writes. Gate A3 catches an OMITTED property
172
+ // but silently passes an INVENTED one, so this is where invention dies.
173
+ const declared = new Set([
174
+ ...Object.keys(plan.structural ?? {}),
175
+ ...Object.values(plan.propMap ?? {}).map((p) => p.a2ui),
176
+ ]);
177
+ // Write-conflict detection under the declared discipline. Two writers on one
178
+ // destination are LEGAL when they resolve in distinct write orders — the
179
+ // outcome is then fully determined by order plus the overwrite flag (v1's
180
+ // Table does exactly this: a passthrough prop wins over the collect harvest
181
+ // because Verbatim runs first and later writers are first-wins). What is
182
+ // refused is a SAME-order double-claim, where nothing but declaration order
183
+ // would decide the winner — that is ambiguity, not layering.
184
+ const claimed = new Map();
185
+ const claim = (name, order, by, at) => {
186
+ const prior = claimed.get(name) ?? [];
187
+ // The children destination is exclusive in BOTH directions (see the
188
+ // children-route check below for the rationale).
189
+ const children = prior.find((c) => c.order === WriteOrder.Children);
190
+ if (children && order !== WriteOrder.Children) {
191
+ issues.push({
192
+ path: at,
193
+ message: `destination '${name}' is claimed by the children route (${children.by}); instance references do not participate in first-wins layering`,
194
+ });
195
+ }
196
+ const clash = prior.find((c) => c.order === order);
197
+ if (clash) {
198
+ issues.push({
199
+ path: at,
200
+ message: `destination '${name}' is already claimed in the same write phase by ${clash.by}; two same-phase writers would be ordered only by declaration position (fallbacks belong inside a single route's 'from' chain)`,
201
+ });
202
+ }
203
+ prior.push({ order, by });
204
+ claimed.set(name, prior);
205
+ };
206
+ let childrenRoutes = 0;
207
+ for (const [i, r] of (surface.routes ?? []).entries()) {
208
+ const at = `${path}/routes/${i}`;
209
+ const to = parseDestination(r.to);
210
+ if (!to) {
211
+ issues.push({ path: `${at}/to`, message: `'${r.to}' is not a destination (expected prop:|textChild:|slot:|slots:|action: followed by a name)` });
212
+ continue;
213
+ }
214
+ if (!declared.has(to.name)) {
215
+ issues.push({
216
+ path: `${at}/to`,
217
+ message: `destination '${to.name}' is not declared by this plan (declare it in structural or map a prop onto it; inventing properties is refused because gate A3 cannot catch them)`,
218
+ });
219
+ }
220
+ const from = [];
221
+ let order;
222
+ for (const [j, rawSel] of r.from.entries()) {
223
+ const sel = parseSelector(rawSel);
224
+ if (!sel) {
225
+ issues.push({ path: `${at}/from/${j}`, message: `'${rawSel}' is not a selector (closed forms: self.text, self.props.<prop>, sub(<id>|…).<text|label|firstText|subtreeText>, children, synthesized.action)` });
226
+ continue;
227
+ }
228
+ if (!compatible(sel, to)) {
229
+ issues.push({ path: `${at}/from/${j}`, message: `selector '${rawSel}' cannot feed destination kind '${to.kind}'` });
230
+ continue;
231
+ }
232
+ const selOrder = orderOfSelector(sel, to);
233
+ if (order === undefined)
234
+ order = selOrder;
235
+ else if (order !== selOrder) {
236
+ issues.push({
237
+ path: `${at}/from/${j}`,
238
+ message: `fallback chain mixes write phases ('${rawSel}' resolves in a different phase than the first selector); a route resolves in exactly one phase`,
239
+ });
240
+ continue;
241
+ }
242
+ from.push(sel);
243
+ }
244
+ if (from.length === 0) {
245
+ issues.push({ path: `${at}/from`, message: "route has no valid selectors" });
246
+ continue;
247
+ }
248
+ // firstText is a FALLBACK selector: the engine serves it only after a
249
+ // primary label/text selector yielded nothing. As a primary it would
250
+ // parse, derive Consume, and then never resolve — consuming the subtree
251
+ // while writing nothing. Refuse the dead spelling instead of shipping it.
252
+ if (from[0].kind === "sub-text-lift") {
253
+ issues.push({
254
+ path: `${at}/from/0`,
255
+ message: "sub(…).firstText is a fallback selector and cannot lead a route; give the route a primary (sub(…).label or sub(…).text) and put firstText after it",
256
+ });
257
+ continue;
258
+ }
259
+ if (from[0].kind === "children") {
260
+ childrenRoutes++;
261
+ if (from.length > 1) {
262
+ issues.push({ path: `${at}/from`, message: "a children route takes no fallbacks" });
263
+ }
264
+ if (childrenRoutes > 1) {
265
+ issues.push({ path: at, message: "only one children route is supported (multiple named slots arrive with capability class T4)" });
266
+ }
267
+ // A children route produces INSTANCES, not a value: it cannot join
268
+ // first-wins layering, so its destination is exclusively its own. Two
269
+ // writers here would either orphan a synthesized instance in the hashed
270
+ // artifact or silently discard the children — refuse the pair.
271
+ const shared = claimed.get(to.name);
272
+ if (shared && shared.length > 0) {
273
+ issues.push({
274
+ path: `${at}/to`,
275
+ message: `destination '${to.name}' is already claimed by ${shared[0].by}; a children route's destination cannot be layered with value routes (instance references do not participate in first-wins)`,
276
+ });
277
+ }
278
+ }
279
+ claim(to.name, order, `routes/${i}`, `${at}/to`);
280
+ const route = { order: order, from, to, origin: `v2:routes/${i}` };
281
+ if (r.overwrite)
282
+ route.overwrite = true;
283
+ model.routes.push(route);
284
+ }
285
+ for (const [i, c] of (surface.collects ?? []).entries()) {
286
+ const at = `${path}/collects/${i}`;
287
+ const into = parseDestination(c.into);
288
+ if (!into || into.kind !== "prop") {
289
+ issues.push({ path: `${at}/into`, message: `'${c.into}' is not an array-valued destination (collects write prop:<name>)` });
290
+ continue;
291
+ }
292
+ if (!declared.has(into.name)) {
293
+ issues.push({ path: `${at}/into`, message: `destination '${into.name}' is not declared by this plan` });
294
+ }
295
+ // T2 item-mode and table-mode are distinct shapes; mixing them is a
296
+ // contradiction, not a preference.
297
+ const itemMode = c.item !== undefined;
298
+ const tableKeys = [c.shape, c.field, c.row, c.cells].some((v) => v !== undefined);
299
+ if (itemMode && tableKeys) {
300
+ issues.push({ path: at, message: "a collect is either item-mode (item) or table-mode (shape/row/cells/field), never both" });
301
+ continue;
302
+ }
303
+ if (itemMode) {
304
+ const fields = {};
305
+ let ok = true;
306
+ for (const [fieldName, raw] of Object.entries(c.item)) {
307
+ const sel = parseSelector(raw);
308
+ const itemLocal = sel && (sel.kind === "self-text" || sel.kind === "self-prop" || sel.kind === "self-id");
309
+ if (!itemLocal) {
310
+ issues.push({
311
+ path: `${at}/item/${fieldName}`,
312
+ message: `'${raw}' is not an item field source (item fields resolve on the item's own node: self.text, self.props.<prop>, self.id — sibling reads and joins are T3)`,
313
+ });
314
+ ok = false;
315
+ continue;
316
+ }
317
+ fields[fieldName] = sel;
318
+ }
319
+ if (!ok || Object.keys(fields).length === 0) {
320
+ if (Object.keys(c.item).length === 0)
321
+ issues.push({ path: `${at}/item`, message: "an item-mode collect names at least one field" });
322
+ continue;
323
+ }
324
+ // T3 join, only on item-mode collects.
325
+ let join;
326
+ if (c.join) {
327
+ const jAt = `${at}/join`;
328
+ const left = parseSelector(c.join.on.left);
329
+ const right = parseSelector(c.join.on.right);
330
+ const itemLocal = (sel) => sel !== null && (sel.kind === "self-text" || sel.kind === "self-prop" || sel.kind === "self-id");
331
+ let jOk = true;
332
+ if (!itemLocal(left)) {
333
+ issues.push({ path: `${jAt}/on/left`, message: `'${c.join.on.left}' is not a join key source (item-local: self.id, self.props.<prop>, self.text)` });
334
+ jOk = false;
335
+ }
336
+ if (!itemLocal(right)) {
337
+ issues.push({ path: `${jAt}/on/right`, message: `'${c.join.on.right}' is not a join key source (item-local: self.id, self.props.<prop>, self.text)` });
338
+ jOk = false;
339
+ }
340
+ const jFields = {};
341
+ for (const [fieldName, raw] of Object.entries(c.join.fields)) {
342
+ if (raw === "children") {
343
+ jFields[fieldName] = { kind: "joined-children" };
344
+ continue;
345
+ }
346
+ const sel = parseSelector(raw);
347
+ if (!itemLocal(sel)) {
348
+ issues.push({ path: `${jAt}/fields/${fieldName}`, message: `'${raw}' is not a joined-side field source (item-local selectors, or "children" for the slot-valued field)` });
349
+ jOk = false;
350
+ continue;
351
+ }
352
+ jFields[fieldName] = sel;
353
+ }
354
+ for (const fieldName of Object.keys(jFields)) {
355
+ if (fieldName in fields) {
356
+ issues.push({ path: `${jAt}/fields/${fieldName}`, message: `field '${fieldName}' is already sourced from the left item; one record field, one source` });
357
+ jOk = false;
358
+ }
359
+ }
360
+ if (Object.keys(jFields).length === 0) {
361
+ issues.push({ path: `${jAt}/fields`, message: "a join names at least one joined-side field — a join that contributes nothing is not a relation" });
362
+ jOk = false;
363
+ }
364
+ if (jOk) {
365
+ join = { with: c.join.with, leftKey: left, rightKey: right, fields: jFields, optional: c.join.optional === true, origin: `v2:collects/${i}/join` };
366
+ }
367
+ else {
368
+ continue;
369
+ }
370
+ }
371
+ claim(into.name, WriteOrder.Collect, `collects/${i}`, `${at}/into`);
372
+ model.collects.push({
373
+ order: WriteOrder.Collect,
374
+ flatten: false,
375
+ of: c.of,
376
+ as: into,
377
+ fields,
378
+ ...(join ? { join } : {}),
379
+ origin: `v2:collects/${i}`,
380
+ });
381
+ continue;
382
+ }
383
+ if (c.shape === undefined || c.row === undefined || c.cells === undefined) {
384
+ issues.push({ path: at, message: "a table-mode collect declares shape, row, and cells (or use item-mode with `item`)" });
385
+ continue;
386
+ }
387
+ if (c.shape === "records" && !c.field) {
388
+ issues.push({ path: `${at}/field`, message: "a records collect names the field its rows' cells land in" });
389
+ continue;
390
+ }
391
+ claim(into.name, WriteOrder.Collect, `collects/${i}`, `${at}/into`);
392
+ const origin = `v2:collects/${i}`;
393
+ const inner = {
394
+ order: WriteOrder.Collect,
395
+ flatten: false,
396
+ of: c.row,
397
+ as: { kind: "inline" },
398
+ scalar: {
399
+ order: WriteOrder.Collect,
400
+ from: [{ kind: "subtree-text", subs: c.cells }],
401
+ to: { kind: "prop", name: c.field ?? "cells" },
402
+ origin,
403
+ },
404
+ origin,
405
+ };
406
+ model.collects.push({
407
+ order: WriteOrder.Collect,
408
+ flatten: c.shape === "flat",
409
+ of: c.of,
410
+ as: into,
411
+ item: { [c.field ?? "cells"]: inner },
412
+ origin,
413
+ });
414
+ }
415
+ for (const [sub, disposition] of Object.entries(surface.subs ?? {})) {
416
+ const at = `${path}/subs/${sub}`;
417
+ if (disposition === "transparent") {
418
+ model.subIdentity[sub] = { kind: "transparent" };
419
+ }
420
+ else if (typeof disposition === "object" && "transparent" in disposition) {
421
+ const donate = [];
422
+ if (typeof disposition.transparent === "object") {
423
+ disposition.transparent.donate.forEach((d, i) => {
424
+ const parsed = parseDonation(d, `${at}/transparent/donate/${i}`, issues, `v2:subs/${sub}/donate/${i}`);
425
+ if (parsed)
426
+ donate.push(parsed);
427
+ });
428
+ }
429
+ model.subIdentity[sub] = donate.length > 0 ? { kind: "transparent", donate } : { kind: "transparent" };
430
+ }
431
+ else if ("asText" in disposition) {
432
+ model.subIdentity[sub] = { kind: "as-text", variant: disposition.asText };
433
+ }
434
+ else {
435
+ model.drops[sub] = disposition.drop;
436
+ }
437
+ // A sub with an identity/drop must not also be a route or collect source —
438
+ // two dispositions for one sub is a contradiction, not a preference.
439
+ const alsoRouted = model.routes.some((r) => r.from.some((s) => "subs" in s && s.subs.includes(sub)));
440
+ const inCollect = (col) => col.of.includes(sub) ||
441
+ Boolean(col.scalar?.from.some((s) => "subs" in s && s.subs.includes(sub))) ||
442
+ Object.values(col.item ?? {}).some((f) => (isCollect(f) ? inCollect(f) : f.from.some((s) => "subs" in s && s.subs.includes(sub))));
443
+ const alsoCollected = model.collects.some(inCollect);
444
+ if (alsoRouted || alsoCollected) {
445
+ issues.push({ path: at, message: `sub-component '${sub}' has a disposition here and is also consumed by a ${alsoRouted ? "route" : "collect"}; one sub, one disposition` });
446
+ }
447
+ }
448
+ // Derived, never authored: a plan that reads its subtree into props does not
449
+ // also emit that subtree as children.
450
+ model.consumesSubtree =
451
+ model.collects.length > 0 ||
452
+ model.routes.some((r) => r.order === WriteOrder.Consume || r.order === WriteOrder.CollectLead || r.order === WriteOrder.Slot);
453
+ // T4: one region, one slot — a sub named by several sub-children routes
454
+ // (or the same route naming several subs) would make one child list land
455
+ // twice; and a mixed from-list has no fallback semantics for regions.
456
+ const slotRoutes = model.routes.filter((r) => r.from.some((sel) => sel.kind === "sub-children"));
457
+ for (const r of slotRoutes) {
458
+ if (r.from.length !== 1 || r.from[0].kind !== "sub-children") {
459
+ issues.push({ path, message: `a sub(x).children route takes exactly one selector — regions have no fallback chain` });
460
+ }
461
+ else if (r.from[0].subs.length !== 1) {
462
+ issues.push({ path, message: `sub(${r.from[0].subs.join("|")}).children names ${r.from[0].subs.length} subs; a slot route names exactly one region` });
463
+ }
464
+ }
465
+ const slotSources = slotRoutes.flatMap((r) => (r.from[0].kind === "sub-children" ? r.from[0].subs : []));
466
+ for (const dup of slotSources.filter((id, i) => slotSources.indexOf(id) !== i)) {
467
+ issues.push({ path, message: `sub-component '${dup}' is the source of more than one slot route; one region, one slot` });
468
+ }
469
+ const childrenRoute = model.routes.find((r) => r.from[0].kind === "children");
470
+ if (model.consumesSubtree && childrenRoute) {
471
+ issues.push({
472
+ path,
473
+ message: "this plan both consumes its subtree into props and routes children as instances; the two are contradictory (the consumed subtree has no children left to emit)",
474
+ });
475
+ }
476
+ if (issues.length > 0)
477
+ throw new ProfileParseError(issues);
478
+ return model;
479
+ }
@@ -1,6 +1,7 @@
1
1
  import type { Profile } from "./profiles.js";
2
- /** The profile schema, as shipped (also exported for hosts that surface it in UI). */
2
+ /** The profile schemas, as shipped (also exported for hosts that surface them in UI). */
3
3
  export { profileSchema } from "./profile-schema.js";
4
+ export { profileSchemaV2 } from "./profile-schema-v2.js";
4
5
  export interface ProfileLoadIssue {
5
6
  /** JSON path into the offending document (ajv instancePath). */
6
7
  path: string;
@@ -8,12 +9,12 @@ export interface ProfileLoadIssue {
8
9
  }
9
10
  export declare class ProfileLoadError extends Error {
10
11
  readonly issues: ProfileLoadIssue[];
11
- constructor(issues: ProfileLoadIssue[]);
12
+ constructor(issues: ProfileLoadIssue[], schemaName?: string);
12
13
  }
13
14
  /**
14
- * Validate `json` as a v1 profile document and return the engine-ready
15
- * `Profile`. The `profileVersion` envelope field is stripped — it belongs to
16
- * the document format, not the engine. Top-level `x-` extension keys are
17
- * preserved (the engine ignores them; provenance tools may not).
15
+ * Validate `json` as a profile document and return the engine-ready `Profile`.
16
+ * The `profileVersion` envelope field is stripped — it belongs to the document
17
+ * format, not the engine. Top-level `x-` extension keys are preserved (the
18
+ * engine ignores them; provenance tools may not).
18
19
  */
19
20
  export declare function loadProfile(json: unknown): Profile;
@@ -2,11 +2,23 @@
2
2
  * Profile-as-data: load a mapping Profile from JSON.
3
3
  *
4
4
  * The Profile has always been pure data (profiles.ts); this module makes it
5
- * *reachable* as data. `loadProfile` validates an untrusted JSON value against
6
- * schema `profile.v1.schema.json` (a one-to-one mirror of the TypeScript
7
- * `Profile` interface plus a `profileVersion` envelope const) and returns the
8
- * engine-ready `Profile`. Validation gates shape only — every judgment call
9
- * (valueMaps, casualties, surface plans) stays with the profile's author.
5
+ * *reachable* as data. `loadProfile` dispatches EXPLICITLY on the document's
6
+ * `profileVersion`:
7
+ *
8
+ * "1" — the original surface-plan directive language, validated against
9
+ * profile.v1.schema.json. Frozen: v1 documents keep loading and
10
+ * emitting byte-identically, indefinitely.
11
+ * "2" — the primitive language, validated against profile.v2.schema.json,
12
+ * then every plan's `surface` block is parsed and statically checked
13
+ * (parse-v2.ts) so that a v2 profile that loads is a profile the
14
+ * engine can emit. The returned Profile is stamped `language: "v2"`,
15
+ * which is what keys the transform layer's fail-closed contract
16
+ * validation — no document is ever silently interpreted under the
17
+ * wrong version.
18
+ *
19
+ * Anything else refuses with a pathed finding naming the supported versions.
20
+ * Validation gates shape and coherence only — every judgment call (valueMaps,
21
+ * casualties, routes) stays with the profile's author.
10
22
  *
11
23
  * Toolchain: ajv draft 2020-12, `strict: false`, ajv-formats — the same
12
24
  * convention as the catalog gates (src/validate/ajv.ts) and the dspack
@@ -15,12 +27,15 @@
15
27
  import Ajv2020 from "ajv/dist/2020.js";
16
28
  import addFormats from "ajv-formats";
17
29
  import { profileSchema } from "./profile-schema.js";
18
- /** The profile schema, as shipped (also exported for hosts that surface it in UI). */
30
+ import { profileSchemaV2 } from "./profile-schema-v2.js";
31
+ import { ProfileParseError, parseSurfaceV2 } from "./parse-v2.js";
32
+ /** The profile schemas, as shipped (also exported for hosts that surface them in UI). */
19
33
  export { profileSchema } from "./profile-schema.js";
34
+ export { profileSchemaV2 } from "./profile-schema-v2.js";
20
35
  export class ProfileLoadError extends Error {
21
36
  issues;
22
- constructor(issues) {
23
- super(`profile does not conform to profile.v1.schema.json (${issues.length} issue${issues.length === 1 ? "" : "s"}): ` +
37
+ constructor(issues, schemaName = "profile.v1.schema.json") {
38
+ super(`profile does not conform to ${schemaName} (${issues.length} issue${issues.length === 1 ? "" : "s"}): ` +
24
39
  issues
25
40
  .slice(0, 3)
26
41
  .map((i) => `${i.path || "$"}: ${i.message}`)
@@ -30,27 +45,91 @@ export class ProfileLoadError extends Error {
30
45
  this.name = "ProfileLoadError";
31
46
  }
32
47
  }
33
- let compiled;
34
- function validator() {
35
- if (!compiled) {
48
+ const compiled = new Map();
49
+ function validator(version) {
50
+ let v = compiled.get(version);
51
+ if (!v) {
36
52
  const ajv = new Ajv2020({ strict: false, allErrors: true, validateFormats: true });
37
53
  addFormats(ajv);
38
- compiled = ajv.compile(profileSchema);
54
+ v = ajv.compile(version === "1" ? profileSchema : profileSchemaV2);
55
+ compiled.set(version, v);
39
56
  }
40
- return compiled;
57
+ return v;
58
+ }
59
+ function ajvIssues(validate) {
60
+ const errors = (validate.errors ?? []);
61
+ return errors.map((e) => ({ path: e.instancePath ?? "", message: e.message ?? "invalid" }));
41
62
  }
42
63
  /**
43
- * Validate `json` as a v1 profile document and return the engine-ready
44
- * `Profile`. The `profileVersion` envelope field is stripped — it belongs to
45
- * the document format, not the engine. Top-level `x-` extension keys are
46
- * preserved (the engine ignores them; provenance tools may not).
64
+ * Validate `json` as a profile document and return the engine-ready `Profile`.
65
+ * The `profileVersion` envelope field is stripped — it belongs to the document
66
+ * format, not the engine. Top-level `x-` extension keys are preserved (the
67
+ * engine ignores them; provenance tools may not).
47
68
  */
48
69
  export function loadProfile(json) {
49
- const validate = validator();
70
+ const version = json?.profileVersion;
71
+ if (version !== "1" && version !== "2") {
72
+ throw new ProfileLoadError([
73
+ {
74
+ path: "/profileVersion",
75
+ message: `unknown profile version ${JSON.stringify(version)} — this loader speaks "1" (surface-plan directives) and "2" (the primitive language)`,
76
+ },
77
+ ], "any supported profile schema");
78
+ }
79
+ const validate = validator(version);
50
80
  if (!validate(json)) {
51
- const errors = (validate.errors ?? []);
52
- throw new ProfileLoadError(errors.map((e) => ({ path: e.instancePath ?? "", message: e.message ?? "invalid" })));
81
+ throw new ProfileLoadError(ajvIssues(validate), `profile.v${version}.schema.json`);
53
82
  }
54
83
  const { profileVersion: _envelope, ...profile } = json;
84
+ if (version === "2") {
85
+ // Declared function args must be SELF-CONTAINED schemas. A $ref inside
86
+ // them couples the function's signature to emit internals at best and, at
87
+ // worst, is a dangling reference that ajv defers past gate A1's compile
88
+ // and then throws raw out of gate A3 — pass-or-crash, never a finding.
89
+ // Refuse the whole class at load, with the path.
90
+ const functions = profile.functions ?? {};
91
+ const refIssues = [];
92
+ const findRefs = (value, at) => {
93
+ if (Array.isArray(value))
94
+ value.forEach((v, i) => findRefs(v, `${at}/${i}`));
95
+ else if (value && typeof value === "object") {
96
+ for (const [k, v] of Object.entries(value)) {
97
+ if (k === "$ref")
98
+ refIssues.push({ path: at, message: `function args must be self-contained schemas; '$ref' is refused (found ${JSON.stringify(v)})` });
99
+ else
100
+ findRefs(v, `${at}/${k}`);
101
+ }
102
+ }
103
+ };
104
+ for (const [name, fn] of Object.entries(functions)) {
105
+ if (fn?.args)
106
+ findRefs(fn.args, `/functions/${name}/args`);
107
+ }
108
+ if (refIssues.length > 0)
109
+ throw new ProfileLoadError(refIssues, "profile.v2.schema.json (functions)");
110
+ // Parse every plan's surface block now, so a v2 profile that LOADS is a
111
+ // profile the engine can EMIT — grammar errors surface at load with
112
+ // pathed findings, not mid-emission.
113
+ const collections = [
114
+ ["components", profile.components ?? []],
115
+ ["synthesized", profile.synthesized ?? []],
116
+ ];
117
+ for (const [key, plans] of collections) {
118
+ for (const [i, plan] of plans.entries()) {
119
+ if (!plan.surface)
120
+ continue;
121
+ try {
122
+ parseSurfaceV2(plan.surface, plan, `/${key}/${i}/surface`);
123
+ }
124
+ catch (e) {
125
+ if (e instanceof ProfileParseError) {
126
+ throw new ProfileLoadError(e.issues, "profile.v2.schema.json (surface syntax)");
127
+ }
128
+ throw e;
129
+ }
130
+ }
131
+ }
132
+ profile.language = "v2";
133
+ }
55
134
  return profile;
56
135
  }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Runtime mirror of profile.v2.schema.json — same convention as
3
+ * profile-schema.ts: the .json file stays the reviewable schema document,
4
+ * this constant is what loadProfile imports so the loader bundles for the
5
+ * browser (dspack-studio composer) without filesystem access.
6
+ * src/schema-mirrors.test.ts asserts mirror and JSON stay identical — edit
7
+ * both together.
8
+ */
9
+ export declare const profileSchemaV2: Record<string, unknown>;