@nodii/dev 0.6.121 → 0.6.123

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.
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.121";
7
+ export const VERSION = "0.6.123";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/lanes.js CHANGED
@@ -812,6 +812,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
812
812
  const run = await runLaneCheck(ref, flags, {
813
813
  request, lane, freeze, current, cwd: context.worktree, store,
814
814
  ...(checkDeps.exceptions ? { exceptions: checkDeps.exceptions } : {}),
815
+ ...(checkDeps.templates ? { templates: checkDeps.templates } : {}),
815
816
  diff,
816
817
  deltaGather: checkDeps.deltaGather ?? ((key, paths, pick) => laneCommand("gather", [key], deltaGatherFlags(paths, pick), deps)),
817
818
  catalog: checkDeps.catalog ?? catalog,
@@ -1105,7 +1106,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
1105
1106
  if (missing.length) throw new CliError("REVIEW_FINDING_NOT_FOUND", `${ref}: the last lane check round (head ${last.head}) has no finding ${missing.map((x) => x.id).join(", ")}; nothing was treated.`, 1);
1106
1107
  // MW2-41: Dev refuses these too; saying so here saves a round trip.
1107
1108
  const fixOnly = items.filter((x) => !treatable(found.get(x.id)));
1108
- if (fixOnly.length) throw new CliError("REVIEW_TREATMENT_FORBIDDEN", `${ref}: ${fixOnly.map((x) => x.id).join(", ")} ${fixOnly.length === 1 ? "is a code-check finding or a blocker" : "are code-check findings or blockers"}, which may only be fixed (MW2-41); nothing was treated.`, 1);
1109
+ if (fixOnly.length) throw new CliError("REVIEW_TREATMENT_FORBIDDEN", `${ref}: ${fixOnly.map((x) => x.id).join(", ")} ${fixOnly.length === 1 ? "is a code-check finding, a blocker or file debt" : "are code-check findings, blockers or file debt"}: the first two may only be fixed (MW2-41), and file debt is not counted for CLEAN, so it needs no treatment; nothing was treated.`, 1);
1109
1110
  const generatedPaths = await repoGeneratedPaths(request, context.repo);
1110
1111
  const committed = await (checkDeps.committed ?? worktreeCommitted)(context.worktree);
1111
1112
  const digest = diffDigest((await (checkDeps.diff ?? laneDiff)(context.worktree, { generatedPaths })).text);
@@ -1160,7 +1161,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
1160
1161
  ...(run.checks ?? []).map((check) => ` check ${check.check}\t${check.outcome}\t${check.iterationCount} iteration(s)${check.reviewerErrors?.length ? `\t${check.reviewerErrors.length} reviewer error(s)` : ""}`),
1161
1162
  ...run.findings.map(
1162
1163
  (finding) =>
1163
- ` ${finding.severity}\t${finding.perspective}\t${finding.perspective === "figma" ? `${finding.frameUrl ?? "-"} [${finding.state ?? "-"}]` : finding.clauseId ?? "-"}\t${finding.summary}${finding.missedTrigger ? "\tMISSED_TRIGGER" : ""}${finding.disposition && finding.disposition !== "unresolved" ? `\t${finding.disposition}` : ""}${finding.treatmentKind ? ` (${finding.treatmentKind} ${finding.treatmentRef}, by ${finding.treatedByLabel})` : ""}`,
1164
+ ` ${finding.severity}\t${finding.perspective}\t${finding.perspective === "figma" ? `${finding.frameUrl ?? "-"} [${finding.state ?? "-"}]` : finding.clauseId ?? "-"}\t${finding.summary}${finding.missedTrigger ? "\tMISSED_TRIGGER" : ""}${finding.scope === "context" ? "\tfile debt" : ""}${finding.disposition && finding.disposition !== "unresolved" ? `\t${finding.disposition}` : ""}${finding.treatmentKind ? ` (${finding.treatmentKind} ${finding.treatmentRef}, by ${finding.treatedByLabel})` : ""}`,
1164
1165
  ),
1165
1166
  ].join("\n");
1166
1167
  })
package/dist/review.js CHANGED
@@ -531,13 +531,13 @@ export async function boundaryFrames(figma, { catalog, lookupSet = designCatalog
531
531
  * lane withdrew are left out; rejected items stay in until withdrawn. A
532
532
  * removed item's node is gone from Figma, so there is nothing to check.
533
533
  */
534
- export async function laneChangeSetNodes(request, agentId, fileKeys) {
535
- if (!agentId || !fileKeys.length) return {};
534
+ export async function laneChangeSetNodes(request, agentId, fileKeys, templates = []) {
535
+ if (!fileKeys.length || (!agentId && !templates.length)) return {};
536
536
  const files = (await request("GET", "/api/v1/design/files")).data ?? [];
537
537
  const ds = new Set(files.filter((file) => file.kind === "design-system").map((file) => file.fileKey));
538
538
  const scoped = {};
539
539
  for (const fileKey of [...new Set(fileKeys)].filter((key) => ds.has(key))) {
540
- const rows = (await request("GET", `/api/v1/design/change-sets?holderAgentId=${encodeURIComponent(agentId)}&fileKey=${encodeURIComponent(fileKey)}&limit=500`)).data ?? [];
540
+ const rows = agentId ? (await request("GET", `/api/v1/design/change-sets?holderAgentId=${encodeURIComponent(agentId)}&fileKey=${encodeURIComponent(fileKey)}&limit=500`)).data ?? [] : [];
541
541
  const held = rows.filter((row) => row.holder?.agent?.id === agentId && row.fileKey === fileKey && row.state !== "abandoned");
542
542
  const nodes = new Set();
543
543
  const changeSets = [];
@@ -552,11 +552,68 @@ export async function laneChangeSetNodes(request, agentId, fileKeys) {
552
552
  nodes.add(item.figmaNodeId);
553
553
  }
554
554
  }
555
- if (nodes.size) scoped[fileKey] = { changeSets, nodes: [...nodes], items };
555
+ // hub-324: a Code Connect template the change touches is a unit too.
556
+ const touched = templates.filter((unit) => unit.fileKey === fileKey);
557
+ for (const unit of touched) {
558
+ if (!nodes.has(unit.nodeId)) items.push({ nodeId: unit.nodeId, template: unit.template });
559
+ nodes.add(unit.nodeId);
560
+ }
561
+ if (nodes.size) scoped[fileKey] = { changeSets, nodes: [...nodes], items, templates: [...new Set(touched.map((unit) => unit.template))] };
556
562
  }
557
563
  return scoped;
558
564
  }
559
565
 
566
+ /** A Figma link's file key and node id (`1-2` in a link, `1:2` in the API), or null. */
567
+ export function figmaLinkNode(url) {
568
+ let parsed;
569
+ try { parsed = new URL(url); } catch { return null; }
570
+ const fileKey = /^\/(?:design|file|proto)\/([^/]+)/.exec(parsed.pathname)?.[1];
571
+ const nodeId = parsed.searchParams.get("node-id")?.replace(/-/g, ":");
572
+ return fileKey && nodeId ? { fileKey, nodeId } : null;
573
+ }
574
+
575
+ /** The repository path a template's `// source=` header names: a GitHub blob link or a plain path. */
576
+ const sourcePath = (source) => {
577
+ const blob = /^https:\/\/github\.com\/[^/]+\/[^/]+\/blob\/[^/]+\/(.+)$/.exec(source);
578
+ if (blob) return decodeURIComponent(blob[1]);
579
+ return /^[a-z]+:/i.test(source) ? null : source.replace(/^\.\//, "");
580
+ };
581
+
582
+ /**
583
+ * hub-324: the Figma nodes the change's Code Connect templates point
584
+ * at, as [{ fileKey, nodeId, template }]. A template (`*.figma.ts(x)`) is
585
+ * touched when its own file changed or when the file its `// source=` header
586
+ * names changed. Its `// url=` header is resolved through the repository's
587
+ * figma.config.json documentUrlSubstitutions. The template is the stable
588
+ * reference (MW8-20): the node id is read from it now, never declared. A
589
+ * repository without figma.config.json has no templates.
590
+ */
591
+ export async function codeConnectUnits(cwd, paths, { exec = execFileAsync, read = (path) => readFile(join(cwd, path), "utf8") } = {}) {
592
+ let config;
593
+ try { config = JSON.parse(await read("figma.config.json")); }
594
+ catch (error) { if (error?.code === "ENOENT") return []; throw error; }
595
+ const substitutions = Object.entries(config?.codeConnect?.documentUrlSubstitutions ?? {});
596
+ const changed = new Set(paths);
597
+ const listed = (await exec("git", ["-C", cwd, "ls-files", "-z", "--", "*.figma.ts", "*.figma.tsx"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 })).stdout.split("\0").filter(Boolean);
598
+ const templates = [...new Set([...listed, ...paths.filter((path) => /\.figma\.tsx?$/.test(path))])].sort();
599
+ const units = [];
600
+ const seen = new Set();
601
+ for (const template of templates) {
602
+ const text = await read(template).catch((error) => { if (error?.code === "ENOENT") return null; throw error; });
603
+ if (text === null) continue;
604
+ const header = (name) => new RegExp(`^//\\s*${name}=(\\S+)`, "m").exec(text)?.[1] ?? null;
605
+ const source = header("source");
606
+ if (!changed.has(template) && !(source && changed.has(sourcePath(source)))) continue;
607
+ const url = header("url");
608
+ if (!url) continue;
609
+ const node = figmaLinkNode(substitutions.reduce((link, [from, to]) => link.split(from).join(to), url));
610
+ if (!node || seen.has(`${node.fileKey}|${node.nodeId}`)) continue;
611
+ seen.add(`${node.fileKey}|${node.nodeId}`);
612
+ units.push({ ...node, template });
613
+ }
614
+ return units;
615
+ }
616
+
560
617
  /**
561
618
  * MW8-5: the Swaps in Dev, each as { ref, from, to, text }. A Swap is a Dev
562
619
  * Swap record, or an issue titled "Swap" that carries one in its From and To
@@ -635,6 +692,17 @@ export async function figmaFindings(figma, { catalog, check, changeSets = {}, sw
635
692
  known ??= await swaps().catch(() => []);
636
693
  return swapFor(known, frame, cachedSet);
637
694
  };
695
+ const finding = (severity, found, frame, extra = {}) => ({
696
+ perspective: "figma",
697
+ severity,
698
+ summary: `${found.check} at ${found.nodeId}`.slice(0, 500),
699
+ detail: (found.detail || found.check).slice(0, 10_000),
700
+ frameUrl: frameUrl(frame.fileKey, frame.nodeId ?? found.nodeId),
701
+ state: frame.state,
702
+ ...extra,
703
+ });
704
+ // What each unit check returned, by file, so file debt is only what they did not.
705
+ const unitFound = new Map();
638
706
  for (const frame of frames) {
639
707
  const result = await check(frame.fileKey, frame.nodeId ? { nodes: frame.nodeId } : {});
640
708
  const data = result.payload.data;
@@ -644,28 +712,41 @@ export async function figmaFindings(figma, { catalog, check, changeSets = {}, sw
644
712
  removed.push({ frame, nodeId: frame.nodeId, changeSet: swap.changeSet, swap: swap.ref, url: frameUrl(frame.fileKey, frame.nodeId) });
645
713
  continue;
646
714
  }
647
- for (const finding of data.findings ?? []) {
648
- findings.push({
649
- perspective: "figma",
650
- severity: "major",
651
- summary: `${finding.check} at ${finding.nodeId}`.slice(0, 500),
652
- detail: (finding.detail || finding.check).slice(0, 10_000),
653
- frameUrl: frameUrl(frame.fileKey, frame.nodeId ?? finding.nodeId),
654
- state: frame.state,
655
- });
656
- }
715
+ if (!unitFound.has(frame.fileKey)) unitFound.set(frame.fileKey, new Set());
716
+ for (const found of [...(data.findings ?? []), ...(data.warnings ?? [])]) unitFound.get(frame.fileKey).add(`${found.check}|${found.nodeId}`);
717
+ for (const found of data.findings ?? []) findings.push(finding("major", found, frame));
657
718
  // A component key Figma can't resolve is a finding, never a frame without
658
719
  // its url (NODII-DEV-CLI-66). Minor: nothing was checked against a main.
659
- for (const warning of data.warnings ?? [])
660
- findings.push({
661
- perspective: "figma",
662
- severity: "minor",
663
- summary: `${warning.check} at ${warning.nodeId}`.slice(0, 500),
664
- detail: (warning.detail || warning.check).slice(0, 10_000),
665
- frameUrl: frameUrl(frame.fileKey, frame.nodeId ?? warning.nodeId),
666
- state: frame.state,
667
- });
720
+ for (const warning of data.warnings ?? []) findings.push(finding("minor", warning, frame));
668
721
  }
722
+ // hub-324: a DS file checked on its units is also read whole, once.
723
+ // A finding there that no unit check returned is file debt (scope context):
724
+ // recorded, never counted for CLEAN. One on a unit's own node stays a unit
725
+ // finding, so it still blocks (MW2-41). A failed read leaves the unit
726
+ // verdict as it is (a whole-file DS check is never required, MW2-38.3).
727
+ const fileDebt = [];
728
+ for (const [fileKey, scoped] of Object.entries(changeSets)) {
729
+ const units = new Set(scoped.nodes);
730
+ let data;
731
+ try { data = (await check(fileKey, {})).payload.data; }
732
+ catch (error) {
733
+ fileDebt.push({ fileKey, checked: false, reason: `${error?.code ?? "ERROR"}: ${error?.message ?? error}`.slice(0, 500) });
734
+ continue;
735
+ }
736
+ const seen = unitFound.get(fileKey) ?? new Set();
737
+ let count = 0;
738
+ for (const [severity, list] of [["major", data.findings ?? []], ["minor", data.warnings ?? []]])
739
+ for (const found of list) {
740
+ if (seen.has(`${found.check}|${found.nodeId}`)) continue;
741
+ seen.add(`${found.check}|${found.nodeId}`);
742
+ const frame = { fileKey, nodeId: found.nodeId, state: "default" };
743
+ if (units.has(found.nodeId)) { findings.push(finding(severity, found, frame)); continue; }
744
+ findings.push(finding(severity, found, frame, { scope: "context" }));
745
+ count += 1;
746
+ }
747
+ fileDebt.push({ fileKey, checked: true, findings: count });
748
+ }
749
+ const scopedFiles = Object.entries(changeSets);
669
750
  return {
670
751
  findings,
671
752
  inputs: {
@@ -674,7 +755,10 @@ export async function figmaFindings(figma, { catalog, check, changeSets = {}, sw
674
755
  libraryVersions: [...versions],
675
756
  frameComparison: "not_built",
676
757
  ...(removed.length ? { removed: removed.map(({ frame: _frame, ...entry }) => entry) } : {}),
677
- ...(scopedFrames.length ? { changeSets: Object.entries(changeSets).map(([fileKey, scoped]) => ({ fileKey, ids: scoped.changeSets, nodes: scoped.nodes.length })), rule: "MW2-38.3" } : {}),
758
+ ...(scopedFrames.length ? { rule: "MW2-38.3" } : {}),
759
+ ...(scopedFiles.some(([, scoped]) => scoped.changeSets.length) ? { changeSets: scopedFiles.filter(([, scoped]) => scoped.changeSets.length).map(([fileKey, scoped]) => ({ fileKey, ids: scoped.changeSets, nodes: (scoped.items ?? []).filter((x) => x.changeSet).length || scoped.nodes.length })) } : {}),
760
+ ...(scopedFiles.some(([, scoped]) => scoped.templates?.length) ? { templates: scopedFiles.filter(([, scoped]) => scoped.templates?.length).map(([fileKey, scoped]) => ({ fileKey, paths: scoped.templates, nodes: (scoped.items ?? []).filter((x) => x.template).map((x) => x.nodeId) })) } : {}),
761
+ ...(fileDebt.length ? { fileDebt } : {}),
678
762
  },
679
763
  };
680
764
  }
@@ -684,15 +768,18 @@ export async function figmaFindings(figma, { catalog, check, changeSets = {}, sw
684
768
  // way each time: the clause (and frame and state) it cites, or for code the file.
685
769
  // Never the wording, which changes between rounds.
686
770
  export const findingKey = (finding) => (finding.perspective === "code" ? ["code", finding.path ?? ""] : [finding.perspective, finding.clauseId ?? "", finding.frameUrl ?? "", finding.state ?? ""]).join("|");
687
- const blockingOf = (findings) => findings.filter((finding) => finding.severity !== "minor");
771
+ /** hub-324: file debt, elsewhere in a boundary file the change does not touch. */
772
+ export const isFileDebt = (finding) => finding.scope === "context";
773
+ // File debt never blocks: Dev leaves it out of CLEAN too.
774
+ const blockingOf = (findings) => findings.filter((finding) => finding.severity !== "minor" && !isFileDebt(finding));
688
775
  /**
689
776
  * NODII-DEV-CLI-74: the id lane check prints for a finding, the same in every
690
777
  * round. Finer than the loop's key: the clause (or frame and state) and the
691
778
  * file, so a treatment covers that finding, not every finding on its clause.
692
779
  */
693
780
  export const findingId = (finding) => `f-${createHash("sha256").update(`${findingKey(finding)}|${finding.path ?? ""}`).digest("hex").slice(0, 8)}`;
694
- /** MW2-41: a code-check finding and a blocker are only ever fixed (Dev refuses the same). */
695
- export const treatable = (finding) => finding.perspective !== "code" && finding.severity !== "blocker";
781
+ /** MW2-41: a code-check finding and a blocker are only ever fixed (Dev refuses the same). File debt is left as found. */
782
+ export const treatable = (finding) => finding.perspective !== "code" && finding.severity !== "blocker" && !isFileDebt(finding);
696
783
  /** A finding with a P-21 treatment applied when one names it and it may be treated; else as it was. */
697
784
  export function treatFinding(finding, treatments = {}) {
698
785
  const treated = treatments[findingId(finding)];
@@ -745,7 +832,8 @@ export function runBody(checks, current) {
745
832
  appliedPatches: [],
746
833
  unresolvedProposals: [],
747
834
  reviewerErrors: checks.flatMap((x) => x.reviewerErrors),
748
- findings: checks.flatMap((x) => x.findings).slice(0, 500),
835
+ // File debt last, so a cap never drops a finding that counts.
836
+ findings: [...checks.flatMap((x) => x.findings.filter((f) => !isFileDebt(f))), ...checks.flatMap((x) => x.findings.filter(isFileDebt))].slice(0, 500),
749
837
  checks: checks.map(({ check, outcome, iterationCount, reviewerErrors: errors, inputs, notRequired }) => ({ check, outcome, iterationCount, reviewerErrors: errors, inputs, ...(notRequired ? { notRequired } : {}) })),
750
838
  via: "nodii-dev",
751
839
  };
@@ -760,7 +848,7 @@ const errorCheck = (check, error, iterationCount, inputs) => ({ check, outcome:
760
848
  * caller saves the round (saveLoop) once it is kept: still looping, or
761
849
  * recorded; a run that records nothing leaves the loop where it was.
762
850
  */
763
- export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now, exceptions = exceptionFiles }) {
851
+ export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now, exceptions = exceptionFiles, templates = codeConnectUnits }) {
764
852
  const critical = flags.critical === true;
765
853
  const maxIterations = flags["max-iterations"] === undefined ? MAX_ITERATIONS : Number(flags["max-iterations"]);
766
854
  if (!Number.isInteger(maxIterations) || maxIterations < 1 || maxIterations > 100)
@@ -822,8 +910,13 @@ export async function runLaneCheck(ref, flags, { request, lane, freeze, current,
822
910
  } else {
823
911
  const boundary = freeze.boundaries.figma;
824
912
  try {
913
+ let touched;
914
+ try { touched = await templates(cwd, changed.paths); }
915
+ catch (error) {
916
+ throw new ReviewerError(UNAVAILABLE, `the Code Connect templates this change touches could not be read (${error?.code ?? "ERROR"}: ${error?.message ?? error}), so the Figma check cannot be scoped to their nodes (hub-324)`);
917
+ }
825
918
  let changeSets;
826
- try { changeSets = await laneChangeSetNodes(request, lane.agentId, boundary.map((file) => file.fileKey)); }
919
+ try { changeSets = await laneChangeSetNodes(request, lane.agentId, boundary.map((file) => file.fileKey), touched); }
827
920
  catch (error) {
828
921
  throw new ReviewerError(UNAVAILABLE, `the lane's change sets could not be read from Dev (${error?.code ?? "ERROR"}: ${error?.message ?? error}), so the Figma check cannot be scoped to their nodes (MW2-38.3) and did not fall back to the whole file`);
829
922
  }
@@ -886,9 +979,15 @@ export function checkReviewChecks(body) {
886
979
  }
887
980
 
888
981
  const counts = (findings) => {
889
- const n = (severity) => findings.filter((x) => x.severity === severity && x.disposition === "unresolved").length;
890
- return `${n("blocker")} blocker, ${n("major")} major, ${n("minor")} minor`;
982
+ const n = (severity) => findings.filter((x) => x.severity === severity && x.disposition === "unresolved" && !isFileDebt(x)).length;
983
+ const debt = findings.filter(isFileDebt).length;
984
+ return `${n("blocker")} blocker, ${n("major")} major, ${n("minor")} minor${debt ? `, ${debt} file debt` : ""}`;
891
985
  };
986
+ const debtLines = (x) => [
987
+ ...(x.inputs?.fileDebt ?? []).map((file) => (file.checked
988
+ ? ` file debt: ${file.findings} finding(s) elsewhere in ${file.fileKey}, outside the units this change touches; recorded, not counted for CLEAN`
989
+ : ` file debt: ${file.fileKey} could not be read whole (${file.reason}); the units' verdict stands`)),
990
+ ];
892
991
  /** A treatment's citation as one phrase: DEC-0085 or issue KEY. */
893
992
  export const citationText = (cite) => (!cite ? "-" : cite.decision ?? `issue ${cite.issue}`);
894
993
  const findingLine = (x) => ` ${x.severity}\t${x.clauseId ?? (x.frameUrl ? `${x.frameUrl} [${x.state}]` : "-")}\t${x.path ? `${x.path}${x.line ? `:${x.line}` : ""}\t` : ""}${x.summary}\t${findingId(x)}${TREATED.includes(x.disposition) ? `\t${x.disposition}: ${citationText(x.treatment)}` : ""}`;
@@ -898,6 +997,7 @@ export function checkLines(checks, maxIterations) {
898
997
  return checks.flatMap((x) => [
899
998
  `${x.check}\t${x.outcome ?? `NOT CLEAN, round ${x.iterationCount} of ${maxIterations}`}\t${x.iterationCount} iteration(s)\t${counts(x.findings)}`,
900
999
  ...x.reviewerErrors.map((error) => ` error: ${error}`),
901
- ...x.findings.filter((f) => f.disposition !== "fixed").map(findingLine),
1000
+ ...x.findings.filter((f) => f.disposition !== "fixed" && !isFileDebt(f)).map(findingLine),
1001
+ ...debtLines(x),
902
1002
  ]);
903
1003
  }
package/dist/surface.js CHANGED
@@ -32,7 +32,7 @@ import { CliError, VERSION, devRequest, readConfig } from "./core.js";
32
32
  import { createRenderer } from "./vendor/render-templates.mjs";
33
33
 
34
34
  /** Bumped whenever the emitted code changes shape for the same inputs. */
35
- export const GENERATOR_FORMAT = 7;
35
+ export const GENERATOR_FORMAT = 8;
36
36
  export const TREE_DIR = "docs/figma-ux-ds/figma/surface-trees";
37
37
  export const GENERATED_SUFFIX = ".surface.generated.tsx";
38
38
  /** Where every generated product page lives, as a git glob (NODII-DEV-CLI-77). */
@@ -324,12 +324,33 @@ export function trimTree(entry, { row, version }) {
324
324
 
325
325
  if (node.type === "INSTANCE") {
326
326
  const main = components[node.componentId] ?? {};
327
- const propsOf = (instance) =>
328
- Object.fromEntries(
327
+ // An instance's own layers, down to (not into) its slots, which are the Surface's.
328
+ const layersOf = function* (parent) {
329
+ for (const child of parent.children ?? []) {
330
+ if (child.type === "SLOT") continue;
331
+ yield child;
332
+ yield* layersOf(child);
333
+ }
334
+ };
335
+ // A swap keeps the swapped instance's own property values: a Field's
336
+ // control is a swap, and its typed value is an override on that instance, not the default.
337
+ const propsOf = (instance) => {
338
+ const swapped = new Map();
339
+ for (const layer of layersOf(instance)) {
340
+ const ref = layer.type === "INSTANCE" ? layer.componentPropertyReferences?.mainComponent : null;
341
+ if (ref && !swapped.has(ref)) swapped.set(ref, layer);
342
+ }
343
+ return Object.fromEntries(
329
344
  Object.entries(instance.componentProperties ?? {})
330
345
  .filter(([, p]) => p.type !== "SLOT")
331
- .map(([name, p]) => [stripPropId(name), p.type === "INSTANCE_SWAP" ? { swap: keyOf(p.value) } : p.value]),
346
+ .map(([name, p]) => {
347
+ if (p.type !== "INSTANCE_SWAP") return [stripPropId(name), p.value];
348
+ const layer = swapped.get(name);
349
+ const own = layer?.componentProperties && keyOf(layer.componentId) === keyOf(p.value) ? propsOf(layer) : null;
350
+ return [stripPropId(name), own && Object.keys(own).length ? { swap: keyOf(p.value), props: own } : { swap: keyOf(p.value) }];
351
+ }),
332
352
  );
353
+ };
333
354
  out.instance = {
334
355
  key: main.key ?? null,
335
356
  component: main.name ?? null,
@@ -337,17 +358,18 @@ export function trimTree(entry, { row, version }) {
337
358
  remote: Boolean(main.remote),
338
359
  props: propsOf(node),
339
360
  };
340
- // An exposed nested instance is set on the Surface, and only a template's
341
- // findInstance can read it, so its properties are kept by layer name.
342
- if (main.remote && node.exposedInstances?.length) {
361
+ // A nested instance the Surface sets (an exposed one, or one whose properties it
362
+ // overrides, as a Tabs Group's tab1..tab6 labels) is read only by a template's
363
+ // findInstance, so its properties are kept by layer name (DESIGN-SYSTEM-324).
364
+ if (main.remote) {
365
+ const overridden = new Set((node.overrides ?? []).filter((o) => o.overriddenFields?.length).map((o) => o.id));
343
366
  const exposed = {};
344
- const walk = (parent) => {
345
- for (const child of parent.children ?? []) {
346
- if (child.isExposedInstance && !exposed[child.name]) exposed[child.name] = { key: keyOf(child.componentId), props: propsOf(child) };
347
- walk(child);
367
+ for (const layer of layersOf(node)) {
368
+ if (layer.type !== "INSTANCE" || exposed[layer.name]) continue;
369
+ if (layer.isExposedInstance || overridden.has(layer.id) || layer.overrides?.some((o) => o.overriddenFields?.length)) {
370
+ exposed[layer.name] = { key: keyOf(layer.componentId), props: propsOf(layer) };
348
371
  }
349
- };
350
- walk(node);
372
+ }
351
373
  if (Object.keys(exposed).length) out.instance.exposed = exposed;
352
374
  }
353
375
  // A library instance is the template's to draw: only its slots' content is the Surface's.
@@ -467,13 +489,14 @@ export function emitSurface(tree, row, ds) {
467
489
  throw new CliError("SURFACE_TREE_STALE", `${row.id}: the committed tree names its variants by node id; refetch it with \`nodii-dev surface generate ${row.componentSetKey} --fetch --write\``, 1);
468
490
  }
469
491
  const used = new Set();
492
+ const scopes = new Map();
470
493
  const views = tree.variants.map((variant) => {
471
494
  let state = variant.state;
472
495
  while (used.has(state)) state += "-x";
473
496
  used.add(state);
474
497
  const fn = `${pascal(state)}View`;
475
498
  const note = (path, kind, detail) => unmapped.push({ variant: variant.name, path, kind, detail });
476
- const emitted = emitNode(variant.root, { depth: 2, parent: null, path: variant.name, ds, imports, note, root: true }) ?? "";
499
+ const emitted = emitNode(variant.root, { depth: 2, parent: null, path: variant.name, ds, imports, note, root: true, scopes }) ?? "";
477
500
  // A refused root is only a comment, and `return ({/* … */})` is an object, not JSX.
478
501
  const body = emitted.trimStart().startsWith("{/*") ? [" <>", indent(emitted.trim(), 3), " </>"].join("\n") : emitted;
479
502
  return { state, fn, body };
@@ -481,8 +504,10 @@ export function emitSurface(tree, row, ds) {
481
504
  const component = `${pascal(row.id)}Surface`;
482
505
  const stateType = `${component}State`;
483
506
  const propsType = `${component}Props`;
507
+ resolveScopes(views, scopes);
484
508
  const data = dataProps(views);
485
509
  const reactTypes = [data.size && "ComponentProps", [...data.values()].some((d) => d.child) && "ReactNode"].filter(Boolean);
510
+ const drawn = [...data.values()].some((d) => [...d.attrs.values(), ...[...d.members.values()].flatMap((refs) => [...refs.values()])].some((r) => r.keys));
486
511
  const header = [
487
512
  "// GENERATED by `nodii-dev surface generate` from Code Connect (MW8-17). Do not edit:",
488
513
  `// regenerate with \`nodii-dev surface generate ${row.componentSetKey} --write\`.`,
@@ -495,6 +520,7 @@ export function emitSurface(tree, row, ds) {
495
520
  "",
496
521
  `export type ${stateType} = ${views.map((v) => JSON.stringify(v.state)).join(" | ")};`,
497
522
  "",
523
+ ...(drawn ? [...DRAWN_TYPE, ""] : []),
498
524
  `export const ${pascal(row.id).replace(/^./, (c) => c.toLowerCase())}SurfaceStates: readonly ${stateType}[] = [${views.map((v) => JSON.stringify(v.state)).join(", ")}];`,
499
525
  "",
500
526
  ...(data.size
@@ -527,20 +553,79 @@ export function emitSurface(tree, row, ds) {
527
553
  */
528
554
  const JS_LITERALS = new Set(["true", "false", "null", "undefined", "this"]);
529
555
 
556
+ /** Strings blanked to spaces of the same length, so a position still points into `code`. */
557
+ const maskStrings = (code) => code.replace(/"(?:[^"\\\n]|\\.)*"|`[^`]*`/g, (s) => `"${" ".repeat(s.length - 2)}"`);
558
+
559
+ /** Every free identifier a template emits in `code`: [{ at, name }], in the three forms dataProps reads. */
560
+ function freeIdentifiers(code) {
561
+ const masked = maskStrings(code);
562
+ const found = new Map();
563
+ const add = (at, name) => {
564
+ if (!JS_LITERALS.has(name)) found.set(at, name);
565
+ };
566
+ for (const m of masked.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.[A-Za-z][A-Za-z0-9]*)?\}/g)) add(m.index + m[1].length + 2, m[2]);
567
+ for (const m of masked.matchAll(/(^|>)(\s*)\{([a-z][A-Za-z0-9]*)\}/gm)) add(m.index + m[1].length + m[2].length + 1, m[3]);
568
+ for (const m of masked.matchAll(/\b[A-Za-z_]\w*:\s*([a-z][A-Za-z0-9]*)(?=\s*[,}\]])/g)) add(m.index + m[0].length - m[1].length, m[1]);
569
+ return [...found.entries()].map(([at, name]) => ({ at, name })).sort((a, b) => a.at - b.at);
570
+ }
571
+
572
+ /**
573
+ * The name a DS instance's data is grouped under: its label
574
+ * or title property, else its layer name, in camelCase (`Subject kind` →
575
+ * `subjectKind`).
576
+ */
577
+ function scopeName(node) {
578
+ const props = node.instance?.props ?? {};
579
+ const text = [props.label, props.title].find((v) => typeof v === "string" && /[A-Za-z0-9]/.test(v)) ?? node.name ?? "";
580
+ const words = text.match(/[A-Za-z0-9]+/g) ?? [];
581
+ const name = words.map((w, i) => (i === 0 ? w.toLowerCase() : w[0].toUpperCase() + w.slice(1).toLowerCase())).join("");
582
+ return /^[a-z]/.test(name) ? name : `field${name.replace(/^./, (c) => c.toUpperCase())}`;
583
+ }
584
+
585
+ /**
586
+ * Marks each free identifier in one instance's code with its instance's
587
+ * scope (`__s<n>_date`); resolveScopes later keeps the plain name or scopes it.
588
+ * An identifier already marked (an inner instance's, in a slot) keeps its own.
589
+ */
590
+ function scopeIdentifiers(code, scope, scopes) {
591
+ if (!scopes.has(scope)) scopes.set(scope, scopes.size);
592
+ const n = scopes.get(scope);
593
+ let out = code;
594
+ for (const { at, name } of freeIdentifiers(code).reverse()) out = `${out.slice(0, at)}__s${n}_${name}${out.slice(at + name.length)}`;
595
+ return out;
596
+ }
597
+
598
+ /**
599
+ * Each identifier two or more instances emit becomes one per instance: a
600
+ * Date Picker's `date` and `setDate` under "Expires" become
601
+ * `expiresDate` and `setExpiresDate`, so two inputs never share a value, a list
602
+ * of options or a setter. An identifier one instance alone emits keeps its name.
603
+ */
604
+ function resolveScopes(views, scopes) {
605
+ const names = [...scopes.keys()];
606
+ const marked = /__s(\d+)_([a-z][A-Za-z0-9]*)/g;
607
+ const users = new Map();
608
+ for (const view of views) for (const m of view.body.matchAll(marked)) (users.get(m[2]) ?? users.set(m[2], new Set()).get(m[2])).add(m[1]);
609
+ const scoped = (scope, name) => {
610
+ const cap = (s) => s[0].toUpperCase() + s.slice(1);
611
+ const m = /^(set|on)([A-Z]\w*)$/.exec(name);
612
+ return m ? `${m[1]}${cap(scope)}${m[2]}` : `${scope}${cap(name)}`;
613
+ };
614
+ for (const view of views) view.body = view.body.replace(marked, (_, n, name) => (users.get(name).size > 1 ? scoped(names[Number(n)], name) : name));
615
+ }
616
+
530
617
  function dataProps(views) {
531
618
  const data = new Map();
532
- const entry = (name) => data.get(name) ?? data.set(name, { attrs: new Set(), child: false, nested: false, members: new Map() }).get(name);
619
+ const entry = (name) => data.get(name) ?? data.set(name, { attrs: new Map(), child: false, nested: false, members: new Map() }).get(name);
533
620
  for (const view of views) {
534
621
  view.uses = new Set();
535
622
  const body = view.body;
536
623
  for (const m of body.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.([A-Za-z][A-Za-z0-9]*))?\}/g)) {
537
624
  if (JS_LITERALS.has(m[2])) continue;
538
- const tag = openingTag(body, m.index);
539
- if (!tag) continue;
540
- const ref = `ComponentProps<typeof ${tag}>[${JSON.stringify(m[1])}]`;
625
+ const start = openingTag(body, m.index);
626
+ if (start === null) continue;
541
627
  const d = entry(m[2]);
542
- if (m[3]) (d.members.get(m[3]) ?? d.members.set(m[3], new Set()).get(m[3])).add(ref);
543
- else d.attrs.add(ref);
628
+ addDrawn(m[3] ? (d.members.get(m[3]) ?? d.members.set(m[3], new Map()).get(m[3])) : d.attrs, drawnProps(body, start), m[1]);
544
629
  view.uses.add(m[2]);
545
630
  }
546
631
  for (const m of body.matchAll(/(^|>)\s*\{([a-z][A-Za-z0-9]*)\}/gm)) {
@@ -560,7 +645,7 @@ function dataProps(views) {
560
645
  return data;
561
646
  }
562
647
 
563
- /** The component whose opening tag holds position `at`, walking back over balanced braces. */
648
+ /** Where the opening tag of the component holding position `at` starts, walking back over balanced braces. */
564
649
  function openingTag(body, at) {
565
650
  let depth = 0;
566
651
  for (let i = at - 1; i >= 0; i--) {
@@ -568,15 +653,126 @@ function openingTag(body, at) {
568
653
  if (c === "}") depth++;
569
654
  else if (c === "{") depth--;
570
655
  else if (depth === 0 && c === ">" && body[i - 1] !== "=") return null;
571
- else if (depth === 0 && c === "<") return /^<([A-Z][\w.]*)/.exec(body.slice(i))?.[1] ?? null;
656
+ else if (depth === 0 && c === "<") return /^<[A-Z]/.test(body.slice(i, i + 2)) ? i : null;
657
+ }
658
+ return null;
659
+ }
660
+
661
+ /**
662
+ * The props of the component whose opening tag starts at `start`, narrowed to
663
+ * the member of its props union this tag draws: a DS
664
+ * component whose props are a union (DatePicker single | range) types a data
665
+ * prop as that member's, not the union's. The tag's attribute names (and
666
+ * `children` unless it closes itself) are what it passes; a literal attribute
667
+ * (`mode="range"`, a bare `showReject`, `={false}`) is what it picks. A tag that
668
+ * spreads props is not narrowed.
669
+ */
670
+ function drawnProps(body, start) {
671
+ const tag = /^<([A-Z][\w.]*)/.exec(body.slice(start))[1];
672
+ const attrs = tagAttributes(body, start + tag.length + 1);
673
+ if (!attrs) return { tag, keys: null, literals: null };
674
+ return { tag, keys: new Set([...attrs.names, ...(attrs.selfClosing ? [] : ["children"])]), literals: attrs.literals };
675
+ }
676
+
677
+ /**
678
+ * One prop read through the same component's same attribute at several tags
679
+ * (a PiiText in every row, a page-size select in every view) is one reference:
680
+ * the keys every tag passes and the literals every tag gives alike.
681
+ */
682
+ function addDrawn(refs, drawn, attr) {
683
+ const id = `${drawn.tag}\u0000${attr}`;
684
+ const had = refs.get(id);
685
+ if (!had) return refs.set(id, { ...drawn, attr });
686
+ if (!had.keys || !drawn.keys) return refs.set(id, { tag: drawn.tag, attr, keys: null, literals: null });
687
+ refs.set(id, {
688
+ tag: drawn.tag,
689
+ attr,
690
+ keys: new Set([...had.keys].filter((k) => drawn.keys.has(k))),
691
+ literals: new Map([...had.literals].filter(([k, v]) => drawn.literals.get(k) === v)),
692
+ });
693
+ }
694
+
695
+ /** A prop's type: `Drawn<ComponentProps<typeof Tag>, keys, literals>["attr"]`, or the plain props when unnarrowed. */
696
+ function drawnRef({ tag, attr, keys, literals }) {
697
+ const props = `ComponentProps<typeof ${tag}>`;
698
+ if (!keys) return `${props}[${JSON.stringify(attr)}]`;
699
+ const lits = [...literals.entries()].sort(([a], [b]) => a.localeCompare(b));
700
+ const lit = lits.length ? `, { ${lits.map(([k, v]) => `${/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k)}: ${v}`).join("; ")} }` : "";
701
+ return `Drawn<${props}, ${keys.size ? [...keys].sort().map((k) => JSON.stringify(k)).join(" | ") : "never"}${lit}>[${JSON.stringify(attr)}]`;
702
+ }
703
+
704
+ /** The type the generated file declares for drawnProps (see there). */
705
+ const DRAWN_TYPE = [
706
+ "/** A DS component's props, narrowed to the member of their union this call draws: every required prop passed, every literal one fitting. */",
707
+ "type Drawn<P, K extends PropertyKey, L = {}> = [DrawnOf<P, K, L>] extends [never] ? P : DrawnOf<P, K, L>;",
708
+ "type DrawnOf<P, K extends PropertyKey, L> = P extends unknown",
709
+ " ? [Exclude<{ [k in keyof P]-?: {} extends Pick<P, k> ? never : k }[keyof P], K>] extends [never]",
710
+ " ? [{ [k in keyof L]: k extends keyof P ? (L[k] extends P[k] ? never : k) : never }[keyof L]] extends [never]",
711
+ " ? P",
712
+ " : never",
713
+ " : never",
714
+ " : never;",
715
+ ];
716
+
717
+ /**
718
+ * An opening tag's attributes from `at` (just after its name) to its `>`:
719
+ * every name, the literal ones' values as TS literal types, and whether it
720
+ * closes itself. Null for a spread or a tag it cannot read.
721
+ */
722
+ function tagAttributes(body, at) {
723
+ const names = [];
724
+ const literals = new Map();
725
+ let i = at;
726
+ const skipString = (q) => {
727
+ for (i++; i < body.length && body[i] !== q; i++) if (body[i] === "\\") i++;
728
+ i++;
729
+ };
730
+ const braced = () => {
731
+ const from = i;
732
+ let depth = 0;
733
+ for (; i < body.length; i++) {
734
+ const c = body[i];
735
+ if (c === '"' || c === "'" || c === "`") {
736
+ skipString(c);
737
+ i--;
738
+ } else if (c === "{") depth++;
739
+ else if (c === "}" && --depth === 0) return body.slice(from + 1, i++);
740
+ }
741
+ return null;
742
+ };
743
+ while (i < body.length) {
744
+ while (/\s/.test(body[i] ?? "")) i++;
745
+ if (body.startsWith("/>", i)) return { names, literals, selfClosing: true };
746
+ if (body[i] === ">") return { names, literals, selfClosing: false };
747
+ if (body[i] === "{") return null;
748
+ const name = /^[A-Za-z_][\w:-]*/.exec(body.slice(i))?.[0];
749
+ if (!name) return null;
750
+ names.push(name);
751
+ i += name.length;
752
+ if (body[i] !== "=") {
753
+ literals.set(name, "true");
754
+ continue;
755
+ }
756
+ i++;
757
+ if (body[i] === '"' || body[i] === "'") {
758
+ const from = i;
759
+ skipString(body[i]);
760
+ literals.set(name, JSON.stringify(body.slice(from + 1, i - 1)));
761
+ continue;
762
+ }
763
+ if (body[i] !== "{") return null;
764
+ const inner = braced();
765
+ if (inner === null) return null;
766
+ const value = inner.trim();
767
+ if (/^(true|false|-?\d+(\.\d+)?|"(?:[^"\\\n]|\\.)*")$/.test(value)) literals.set(name, value);
572
768
  }
573
769
  return null;
574
770
  }
575
771
 
576
772
  const propType = (d) => {
577
773
  // A value nested in an object prop has no ComponentProps path the generator can name.
578
- const parts = [...d.attrs, ...(d.child ? ["ReactNode"] : []), ...(d.nested ? ["any"] : [])];
579
- if (d.members.size) parts.push(`{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs].join(" & ")}`).join("; ")} }`);
774
+ const parts = [...[...d.attrs.values()].map(drawnRef), ...(d.child ? ["ReactNode"] : []), ...(d.nested ? ["any"] : [])];
775
+ if (d.members.size) parts.push(`{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs.values()].map(drawnRef).join(" & ")}`).join("; ")} }`);
580
776
  return parts.join(" & ");
581
777
  };
582
778
 
@@ -691,8 +887,13 @@ function emitNode(node, ctx) {
691
887
  // A DS library instance: exactly what its Code Connect template emits for this instance's properties.
692
888
  if (node.instance?.remote) {
693
889
  const dsNode = node.instance.key ? ds.byKey.get(node.instance.key) : null;
890
+ // A swap is the swapped component's node id, with its own values when the Surface set any.
891
+ const swapOf = (value) => {
892
+ const nodeId = ds.byKey.get(value.swap) ?? value.swap;
893
+ return value.props ? { nodeId, values: valuesOf(value.props) } : nodeId;
894
+ };
694
895
  const valuesOf = (props) =>
695
- Object.fromEntries(Object.entries(props).map(([name, value]) => [name, value && typeof value === "object" && "swap" in value ? (ds.byKey.get(value.swap) ?? value.swap) : value]));
896
+ Object.fromEntries(Object.entries(props).map(([name, value]) => [name, value && typeof value === "object" && "swap" in value ? swapOf(value) : value]));
696
897
  const values = valuesOf(node.instance.props);
697
898
  const nested = Object.fromEntries(
698
899
  Object.entries(node.instance.exposed ?? {})
@@ -718,7 +919,7 @@ function emitNode(node, ctx) {
718
919
  }
719
920
  ctx.imports.push(...rendered.imports);
720
921
  const sizing = ctx.bare ? [] : sizeClasses(node, parent, false);
721
- const code = rendered.code.trim();
922
+ const code = ctx.scopes ? scopeIdentifiers(rendered.code.trim(), scopeName(node), ctx.scopes) : rendered.code.trim();
722
923
  // A Table part is valid only inside the DS Table. One the generator could not assemble
723
924
  // into a Table stays reported, never passed off as mapped (MW8-17.3).
724
925
  const tag = /^<([A-Za-z]+)/.exec(code)?.[1];
@@ -318,8 +318,11 @@ export function createRenderer(root, docs, options = {}) {
318
318
  getEnum: (name, options) =>
319
319
  mapValue(name, options, need(name, "VARIANT").value),
320
320
  getInstanceSwap: (name) => {
321
- const target = String(need(name, "INSTANCE_SWAP").value);
322
- return swapHandle(context, target, depth, label);
321
+ // A swap is a node id, or { nodeId, values } when the caller has the
322
+ // swapped instance's own property values (renderInstance's `values`).
323
+ const value = need(name, "INSTANCE_SWAP").value;
324
+ const swap = value && typeof value === "object" ? value : { nodeId: value };
325
+ return swapHandle(context, String(swap.nodeId), depth, label, swap.values);
323
326
  },
324
327
  getSlot: (name) => {
325
328
  need(name, "SLOT");
@@ -344,7 +347,7 @@ export function createRenderer(root, docs, options = {}) {
344
347
  };
345
348
  }
346
349
 
347
- function swapHandle(context, targetId, depth, label) {
350
+ function swapHandle(context, targetId, depth, label, values = {}) {
348
351
  const { byId } = context;
349
352
  const found = docForComponent(context, targetId);
350
353
  const node = byId.get(targetId);
@@ -376,7 +379,7 @@ export function createRenderer(root, docs, options = {}) {
376
379
  makeInstance(
377
380
  context,
378
381
  setNode,
379
- propsFor(setNode, found.node, {}),
382
+ propsFor(setNode, found.node, values),
380
383
  depth + 1,
381
384
  `${label} > ${setNode.name}`
382
385
  )
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.121",
3
+ "version": "0.6.123",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {