@reqvire-org/ads 0.5.1 → 0.5.3

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 (136) hide show
  1. package/dist/ads-errors.mjs +143 -51
  2. package/dist/analysis/composition-axes.mjs +48 -0
  3. package/dist/analysis/construction-memo.mjs +38 -0
  4. package/dist/analysis/context.mjs +19 -0
  5. package/dist/analysis/design-reads.mjs +177 -0
  6. package/dist/analysis/design-usage.mjs +4 -20
  7. package/dist/analysis/factored-classes.mjs +90 -0
  8. package/dist/analysis/helpers.mjs +5 -7
  9. package/dist/analysis/mock-check.mjs +4 -5
  10. package/dist/analysis/native-project.mjs +12 -0
  11. package/dist/analysis/owner-accessibility.mjs +4 -4
  12. package/dist/analysis/owner-analysis-cache.mjs +86 -23
  13. package/dist/analysis/owner-analysis-key.mjs +42 -10
  14. package/dist/analysis/owner-choices.mjs +56 -7
  15. package/dist/analysis/owner-composition.mjs +179 -45
  16. package/dist/analysis/owner-reuse.mjs +8 -6
  17. package/dist/analysis/owner-source.mjs +304 -110
  18. package/dist/analysis/scenario-keys.mjs +10 -7
  19. package/dist/analysis/service.mjs +50 -3
  20. package/dist/analysis/standalone.mjs +7 -4
  21. package/dist/analysis/syntax.mjs +59 -1
  22. package/dist/analysis/worker-protocol.mjs +14 -2
  23. package/dist/analysis/worker.mjs +32 -10
  24. package/dist/architecture-report.mjs +26 -0
  25. package/dist/asset-view-facts.mjs +16 -2
  26. package/dist/boundaries.mjs +26 -10
  27. package/dist/bun-compiler.mjs +2 -2
  28. package/dist/check-service.mjs +29 -17
  29. package/dist/check.mjs +13 -6
  30. package/dist/cli.mjs +1 -1
  31. package/dist/composed-contrast.mjs +143 -62
  32. package/dist/composed-keyline.mjs +2 -2
  33. package/dist/config.mjs +2 -1
  34. package/dist/construction-output.mjs +9 -3
  35. package/dist/construction-spec.d.mts +145 -31
  36. package/dist/construction-spec.mjs +204 -74
  37. package/dist/corner-overpaint.mjs +20 -7
  38. package/dist/derived-states.mjs +182 -0
  39. package/dist/design-foundation.mjs +16 -0
  40. package/dist/design-inputs.mjs +18 -3
  41. package/dist/design-system-closure.mjs +12 -7
  42. package/dist/design-usage.mjs +2 -8
  43. package/dist/emit/contract.mjs +24 -5
  44. package/dist/emit/emission.mjs +6 -9
  45. package/dist/emit/integrity.mjs +8 -2
  46. package/dist/emit/output-watch.mjs +120 -0
  47. package/dist/emit/owner-emission-cache.mjs +4 -4
  48. package/dist/emit/preview-emitter.mjs +4 -2
  49. package/dist/emit/preview-tree.mjs +1 -1
  50. package/dist/emit/service.mjs +8 -2
  51. package/dist/finding-rules.mjs +3 -0
  52. package/dist/form-states.mjs +8 -0
  53. package/dist/frame-regions.mjs +29 -9
  54. package/dist/grid-lowering.mjs +3 -1
  55. package/dist/hover-geometry.mjs +15 -0
  56. package/dist/input-digests.mjs +17 -10
  57. package/dist/linaria/delivery.mjs +2 -0
  58. package/dist/lowering-enter.mjs +6 -6
  59. package/dist/lowering-properties.mjs +5 -0
  60. package/dist/lowering-region-layout.mjs +7 -2
  61. package/dist/lowering-session.mjs +10 -0
  62. package/dist/mcp/build-status.mjs +9 -1
  63. package/dist/mcp/compiler-channel.mjs +11 -4
  64. package/dist/mcp/mutations.mjs +1 -0
  65. package/dist/mcp/preview-http.bundle.js +1 -1
  66. package/dist/mcp/preview-watch.mjs +2 -1
  67. package/dist/mcp/preview-widget.bundle.js +1 -1
  68. package/dist/mcp/server-observation.mjs +6 -4
  69. package/dist/mcp/server-project.mjs +4 -1
  70. package/dist/motion-model.mjs +1 -1
  71. package/dist/owner-analysis-check.mjs +23 -6
  72. package/dist/owner-errors.mjs +6 -3
  73. package/dist/owner-lowering.mjs +78 -13
  74. package/dist/owner-scenarios.mjs +6 -23
  75. package/dist/ownership-model.mjs +24 -8
  76. package/dist/paint-contrast.mjs +6 -0
  77. package/dist/placeholder-contrast.mjs +17 -1
  78. package/dist/platform-features.mjs +10 -1
  79. package/dist/profile-macro.d.mts +7 -0
  80. package/dist/profile-view-facts.mjs +1 -1
  81. package/dist/recipe-macro.d.mts +103 -40
  82. package/dist/recipe-model.mjs +18 -13
  83. package/dist/region-lowering.mjs +266 -123
  84. package/dist/render-audit/layout-shift.page.mjs +24 -0
  85. package/dist/render-audit/render-states.mjs +122 -1
  86. package/dist/render-audit/render-states.page.mjs +140 -0
  87. package/dist/render-audit/worker.mjs +18 -3
  88. package/dist/render-audit.mjs +114 -1
  89. package/dist/role-vocabulary.d.mts +9 -0
  90. package/dist/role-vocabulary.mjs +16 -1
  91. package/dist/runtime-paint-contrast.mjs +5 -2
  92. package/dist/scenarios-compiler.mjs +20 -6
  93. package/dist/showcase/assets-view.mjs +29 -13
  94. package/dist/showcase/client.bundle.js +50 -50
  95. package/dist/showcase/http-client.bundle.js +15 -15
  96. package/dist/showcase/ui/ui.css +1 -1
  97. package/dist/showcase/ui/ui.js +5 -5
  98. package/dist/skills/ads-designer/references/accessibility.md +10 -4
  99. package/dist/skills/ads-designer/references/branding.md +13 -3
  100. package/dist/skills/ads-designer/references/contracts.md +5 -2
  101. package/dist/skills/ads-designer/references/design-data.md +13 -7
  102. package/dist/skills/ads-designer/references/layout.md +12 -4
  103. package/dist/skills/ads-designer/references/motion.md +11 -2
  104. package/dist/skills/ads-designer/references/recipes.md +49 -15
  105. package/dist/skills/ads-import/references/contracts.md +5 -2
  106. package/dist/skills/ads-import/references/design-data.md +13 -7
  107. package/dist/skills/ads-import/references/layout.md +12 -4
  108. package/dist/skills/ads-import/references/recipes.md +49 -15
  109. package/dist/skills/ads-migrate/SKILL.md +2 -0
  110. package/dist/skills/ads-migrate/references/0.5.1-to-0.5.2.md +185 -0
  111. package/dist/skills/ads-migrate/references/0.5.2-to-0.5.3.md +71 -0
  112. package/dist/skills/ads-port/references/contracts.md +5 -2
  113. package/dist/skills/ads-port/references/design-data.md +13 -7
  114. package/dist/skills/ads-port/references/layout.md +12 -4
  115. package/dist/skills/ads-port/references/recipes.md +49 -15
  116. package/dist/spatial-model.mjs +2 -2
  117. package/dist/surface-contrast.mjs +7 -2
  118. package/dist/surface-effects.mjs +5 -3
  119. package/dist/target-size.mjs +21 -3
  120. package/dist/task-cache.mjs +8 -18
  121. package/dist/validation-checks.mjs +1 -1
  122. package/docs/ADS.md +9 -3
  123. package/docs/ARCHITECTURE.md +96 -30
  124. package/docs/CACHING.md +152 -24
  125. package/docs/CHANGELOG.md +307 -23
  126. package/docs/GUIDE.md +109 -20
  127. package/docs/LANGUAGE.md +262 -117
  128. package/docs/MCP.md +5 -1
  129. package/docs/MOTION.md +15 -4
  130. package/docs/PROFILE-KINDS.md +54 -4
  131. package/docs/RULES.md +34 -25
  132. package/docs/TOKEN-ROLES.md +7 -1
  133. package/package.json +1 -1
  134. package/dist/analysis/prose-owners.mjs +0 -57
  135. package/dist/prose-model.d.mts +0 -81
  136. package/dist/prose-model.mjs +0 -101
@@ -0,0 +1,182 @@
1
+ import postcss from "postcss";
2
+ const NOT_A_STATE = /^:(?:dir|first-child|last-child|nth-child|only-child|not\(:first-child\))/, INTERACTION = /^:(?:hover|focus|focus-visible|focus-within|active)(?![\w-])/, PROPERTY = /^:(?:disabled|enabled|checked|indeterminate)(?![\w-])/;
3
+ function simples(compound) {
4
+ const parts = [];
5
+ let index = 0;
6
+ while (index < compound.length) {
7
+ const start = index;
8
+ if (compound[index] === "[") {
9
+ const end = compound.indexOf("]", index);
10
+ if (end === -1)
11
+ return null;
12
+ index = end + 1;
13
+ } else if (compound[index] === ":") {
14
+ index++;
15
+ while (index < compound.length && /[\w-]/.test(compound[index] ?? ""))
16
+ index++;
17
+ if (compound[index] === "(") {
18
+ let depth = 0;
19
+ for (;index < compound.length; index++)
20
+ if (compound[index] === "(")
21
+ depth++;
22
+ else if (compound[index] === ")" && --depth === 0)
23
+ break;
24
+ index++;
25
+ }
26
+ } else
27
+ return null;
28
+ parts.push(compound.slice(start, index));
29
+ }
30
+ return parts;
31
+ }
32
+ export function stateOf(selector, root) {
33
+ const prefix = `.${root}`;
34
+ if (!selector.startsWith(prefix))
35
+ return null;
36
+ let rest = selector.slice(prefix.length), depth = 0, end = rest.length;
37
+ for (let index = 0;index < rest.length; index++) {
38
+ const char = rest[index];
39
+ if (char === "(" || char === "[")
40
+ depth++;
41
+ else if (char === ")" || char === "]")
42
+ depth--;
43
+ else if (depth === 0 && /[\s>+~]/.test(char ?? "")) {
44
+ end = index;
45
+ break;
46
+ }
47
+ }
48
+ rest = rest.slice(0, end);
49
+ const parts = simples(rest);
50
+ if (parts === null || parts.length === 0)
51
+ return null;
52
+ const states = parts.filter((part) => !part.startsWith(":not(") && !NOT_A_STATE.test(part));
53
+ if (states.length === 0)
54
+ return null;
55
+ const condition = `&${parts.filter((part) => !NOT_A_STATE.test(part)).join("")}`;
56
+ if (states.every((part) => part.startsWith("[")))
57
+ return { condition, kind: "attribute" };
58
+ if (states.some((part) => INTERACTION.test(part)))
59
+ return { condition, kind: "interaction" };
60
+ if (states.every((part) => part.startsWith("[") || PROPERTY.test(part) || /^:has\(>\s*\.[\w-]+(?::(?:checked|indeterminate|disabled))?\)$/.test(part)))
61
+ return { condition, kind: "property" };
62
+ return { condition, kind: "unsupported" };
63
+ }
64
+ export function constructionStates(css, root) {
65
+ const found = new Map;
66
+ postcss.parse(css).walkRules((rule) => {
67
+ if (rule.parent?.type === "atrule" && rule.parent.name.endsWith("keyframes"))
68
+ return;
69
+ for (const selector of rule.selectors) {
70
+ const state = stateOf(selector.trim(), root);
71
+ if (state !== null && !found.has(state.condition))
72
+ found.set(state.condition, state);
73
+ }
74
+ });
75
+ return [...found.values()];
76
+ }
77
+ export function constructionBounds(css) {
78
+ const found = [];
79
+ postcss.parse(css).walkAtRules("media", (rule) => {
80
+ for (const match of rule.params.matchAll(/\(\s*(?:min-|max-)?width\s*(?:[<>]=?|:)\s*([\d.]+(?:rem|em|px))\s*\)/g)) {
81
+ const bound = match[1];
82
+ if (bound !== void 0 && !found.includes(bound))
83
+ found.push(bound);
84
+ }
85
+ });
86
+ return found;
87
+ }
88
+ export function derivedAudit(owners) {
89
+ const audit = {};
90
+ for (const [owner, constructions] of [...owners].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
91
+ const list = [];
92
+ for (const { root, css, classes, paints = [], glyphs = [], content = [] } of constructions) {
93
+ if (classes === void 0 || classes.trim() === "")
94
+ continue;
95
+ const states = constructionStates(css, root), bounds = constructionBounds(css);
96
+ if (states.length === 0 && paints.length === 0 && glyphs.length === 0 && bounds.length === 0)
97
+ continue;
98
+ if (list.some((known) => known.classes === classes.trim()))
99
+ continue;
100
+ list.push({
101
+ classes: classes.trim(),
102
+ states,
103
+ ...paints.length === 0 ? {} : { paints },
104
+ ...glyphs.length === 0 ? {} : { glyphs },
105
+ ...content.length === 0 ? {} : { content: [...new Set(content)].sort() },
106
+ ...bounds.length === 0 ? {} : { bounds }
107
+ });
108
+ }
109
+ if (list.length > 0)
110
+ audit[owner] = list;
111
+ }
112
+ return audit;
113
+ }
114
+ export const derivedAuditText = (audit) => `${JSON.stringify(audit, null, 2)}
115
+ `;
116
+ const STATE_KINDS = ["attribute", "property", "interaction", "unsupported"];
117
+ export function parseDerivedAudit(text) {
118
+ try {
119
+ const read = JSON.parse(text);
120
+ if (typeof read !== "object" || read === null || Array.isArray(read))
121
+ return {};
122
+ const audit = {};
123
+ for (const [owner, list] of Object.entries(read)) {
124
+ if (!Array.isArray(list))
125
+ continue;
126
+ audit[owner] = list.flatMap((item) => {
127
+ if (typeof item !== "object" || item === null)
128
+ return [];
129
+ const classes = Reflect.get(item, "classes"), states = Reflect.get(item, "states");
130
+ if (typeof classes !== "string" || !Array.isArray(states))
131
+ return [];
132
+ const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [], paints = (Array.isArray(Reflect.get(item, "paints")) ? Reflect.get(item, "paints") : []).flatMap((paint) => {
133
+ if (typeof paint !== "object" || paint === null)
134
+ return [];
135
+ const name = Reflect.get(paint, "name"), property = Reflect.get(paint, "property");
136
+ return typeof name === "string" && typeof property === "string" ? [{ name, property, values: strings(Reflect.get(paint, "values")) }] : [];
137
+ }), glyphs = (Array.isArray(Reflect.get(item, "glyphs")) ? Reflect.get(item, "glyphs") : []).flatMap((glyph) => {
138
+ if (typeof glyph !== "object" || glyph === null)
139
+ return [];
140
+ const part = Reflect.get(glyph, "part"), members = Reflect.get(glyph, "members");
141
+ if (typeof part !== "string" || typeof members !== "object" || members === null)
142
+ return [];
143
+ return [{ part, members: Object.fromEntries(Object.entries(members).filter((entry) => typeof entry[1] === "string")) }];
144
+ }), content = strings(Reflect.get(item, "content"));
145
+ return [
146
+ {
147
+ classes,
148
+ states: states.flatMap((state) => {
149
+ if (typeof state !== "object" || state === null)
150
+ return [];
151
+ const condition = Reflect.get(state, "condition"), kind = Reflect.get(state, "kind");
152
+ return typeof condition === "string" && typeof kind === "string" && STATE_KINDS.includes(kind) ? [{ condition, kind }] : [];
153
+ }),
154
+ ...paints.length === 0 ? {} : { paints },
155
+ ...glyphs.length === 0 ? {} : { glyphs },
156
+ ...content.length === 0 ? {} : { content },
157
+ ...strings(Reflect.get(item, "bounds")).length === 0 ? {} : { bounds: strings(Reflect.get(item, "bounds")) }
158
+ }
159
+ ];
160
+ });
161
+ }
162
+ return audit;
163
+ } catch {
164
+ return {};
165
+ }
166
+ }
167
+ export const ROOT_FONT_PX = 16;
168
+ export function boundWidths(bounds, fixed, { min = 320, max = 1920, limit = 8 } = {}) {
169
+ const px = new Set;
170
+ for (const bound of bounds) {
171
+ const match = /^([\d.]+)(rem|em|px)$/.exec(bound);
172
+ if (match === null)
173
+ continue;
174
+ const value = Number(match[1]) * (match[2] === "px" ? 1 : ROOT_FONT_PX);
175
+ if (!Number.isFinite(value))
176
+ continue;
177
+ for (const width of [Math.ceil(value) - 1, Math.ceil(value)])
178
+ if (width >= min && width <= max && !fixed.includes(width))
179
+ px.add(width);
180
+ }
181
+ return [...px].sort((a, b) => a - b).slice(0, limit);
182
+ }
@@ -117,9 +117,23 @@ export function readFoundation(captured, contexts) {
117
117
  const roles = profileTokenRoles[selected.value.kind];
118
118
  for (const variant of variants.value)
119
119
  for (const [field, value] of Object.entries(variant.fields)) {
120
+ if (field.startsWith("--")) {
121
+ const own = tokens.get(field)?.role ?? null;
122
+ if (own !== "paint")
123
+ return reject({ kind: "token-role", profile: name, field, token: field, role: own, expected: ["paint"] });
124
+ for (const token of references(value)) {
125
+ const role = tokens.get(token)?.role ?? null;
126
+ if (role !== "paint")
127
+ return reject({ kind: "token-role", profile: name, field, token, role, expected: ["paint"] });
128
+ }
129
+ continue;
130
+ }
120
131
  const expected = roles?.[field];
121
132
  if (expected === void 0)
122
133
  continue;
134
+ for (const token of references(value))
135
+ if (field !== token && Object.hasOwn(variant.fields, token) && token.startsWith("--"))
136
+ return reject({ kind: "provided-role-self", profile: name, token, field });
123
137
  for (const token of references(value)) {
124
138
  const role = tokens.get(token)?.role ?? null;
125
139
  if (role === null || !expected.includes(role))
@@ -514,6 +528,8 @@ export function describeFoundationFailure(failure) {
514
528
  return `Profile ${failure.profile} (${failure.profileKind}) declares unknown field ${failure.field}`;
515
529
  case "token-role":
516
530
  return `Wrong role ${failure.profile}.${failure.field}: ${failure.token}`;
531
+ case "provided-role-self":
532
+ return `Profile ${failure.profile} provides ${failure.token} and reads it in ${failure.field}`;
517
533
  case "document-profile-kind":
518
534
  return `foundation.ads.ts ${failure.field}: ${failure.reference} is a ${failure.actual} profile, not a ${failure.field} profile`;
519
535
  }
@@ -13,6 +13,7 @@ import {
13
13
  } from "./design-contexts.mjs";
14
14
  import { documentProfiles, readFoundation, sheetFileOf } from "./design-foundation.mjs";
15
15
  import { digest } from "./digest.mjs";
16
+ import { relocateOutcome } from "./analysis/owner-analysis-key.mjs";
16
17
  import { assetFolderMacro, exampleDeclarations } from "./example-literals.mjs";
17
18
  import { fontCatalog, fontRecord } from "./font-model.mjs";
18
19
  import { parseGlyphSet } from "./glyph-set-declaration.mjs";
@@ -128,7 +129,8 @@ export function capturedDesignFiles(dsRoot) {
128
129
  return new Map(files.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
129
130
  }
130
131
  const contentIdentity = (content) => typeof content === "string" ? content : { sha256: createHash("sha256").update(content).digest("hex") };
131
- export const designFilesDigest = (files) => digest([...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, content]) => [name, contentIdentity(content)])), designInputKey = (captured, settings) => digest([settings.dsRoot, designFilesDigest([...captured].filter(([name]) => isDesignInput(name)))]);
132
+ export const designFilesDigest = (files) => digest([...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, content]) => [name, contentIdentity(content)])), designInputKey = (captured, _settings) => digest(designFilesDigest([...captured].filter(([name]) => isDesignInput(name))));
133
+ const ROOTS_PER_ENTRY = 4;
132
134
  export function createDesignInputCache(limit = 16) {
133
135
  const entries = new Map, stats = { reads: 0 };
134
136
  return {
@@ -138,13 +140,26 @@ export function createDesignInputCache(limit = 16) {
138
140
  if (hit !== void 0) {
139
141
  entries.delete(key);
140
142
  entries.set(key, hit);
141
- return ok(hit);
143
+ const root = path.resolve(settings.dsRoot);
144
+ let moved = hit.byRoot.get(root);
145
+ if (moved === void 0) {
146
+ moved = relocateOutcome(hit.byRoot.get(hit.origin), hit.origin, root);
147
+ hit.byRoot.set(root, moved);
148
+ for (const oldest of hit.byRoot.keys()) {
149
+ if (hit.byRoot.size <= ROOTS_PER_ENTRY)
150
+ break;
151
+ if (oldest !== hit.origin)
152
+ hit.byRoot.delete(oldest);
153
+ }
154
+ }
155
+ return ok(moved);
142
156
  }
143
157
  stats.reads++;
144
158
  const inputs = readDesignInputs(captured, settings);
145
159
  if (inputs.kind === "err")
146
160
  return inputs;
147
- entries.set(key, inputs.value);
161
+ const origin = path.resolve(settings.dsRoot);
162
+ entries.set(key, { origin, byRoot: new Map([[origin, inputs.value]]) });
148
163
  for (const oldest of entries.keys()) {
149
164
  if (entries.size <= limit)
150
165
  break;
@@ -1,7 +1,8 @@
1
1
  import path from "node:path";
2
- import { currentAnalysis, memoFact, memoProgram } from "./analysis/context.mjs";
2
+ import { currentAnalysis, memoFact, memoProgram, throwIfCancelled } from "./analysis/context.mjs";
3
3
  import { capturedTreeFiles, location, optionalSourceText, resolveModuleDetails, sourceAst } from "./analysis/helpers.mjs";
4
4
  import { createOwnerAnalysisCache } from "./analysis/owner-analysis-cache.mjs";
5
+ import { canonical, relocateOutcome, rootRelative } from "./analysis/owner-analysis-key.mjs";
5
6
  import { digest } from "./digest.mjs";
6
7
  import { isDraftFile } from "./draft-boundary.mjs";
7
8
  import ts from "./analysis/syntax.mjs";
@@ -81,25 +82,29 @@ async function fileViolations(root, file, compilerOptions, excluded) {
81
82
  }
82
83
  return violations;
83
84
  }
84
- const CLOSURE_SCHEMA = "ads-design-system-closure/1", closureFacts = createOwnerAnalysisCache({ limit: 8192, variants: 1 });
85
+ const CLOSURE_SCHEMA = "ads-design-system-closure/2", closureFacts = createOwnerAnalysisCache({ limit: 8192, variants: 1 });
85
86
  export const closureStats = { computed: 0, reused: 0 }, releaseClosureFacts = (root) => closureFacts.release(root);
86
87
  const membershipOf = (context) => memoFact(context, `design-system-closure:membership:${context.root}`, () => {
87
88
  const files = capturedTreeFiles(context.root);
88
- return files === null ? null : digest([...files].sort());
89
+ return files === null ? null : digest([...files].map((file) => path.relative(context.root, file)).sort());
89
90
  });
90
91
  export async function designSystemClosure({ dsRoot, files, compilerOptions, excluded }) {
91
- const root = path.resolve(dsRoot), context = currentAnalysis(), options = JSON.stringify([compilerOptions, excluded]), environment = context?.environment?.(), membership = context === void 0 ? null : membershipOf(context), violations = [];
92
+ const root = path.resolve(dsRoot), context = currentAnalysis(), options = JSON.stringify([compilerOptions, excluded]), environment = context?.environment?.(), membership = context === void 0 ? null : membershipOf(context), violations = [], shared = context === void 0 || environment === void 0 || membership === null ? null : digest(rootRelative(canonical([CLOSURE_SCHEMA, root, compilerOptions, excluded, membership, environment]), context.root));
92
93
  for (const file of files) {
94
+ throwIfCancelled();
93
95
  const check = () => {
94
96
  closureStats.computed++;
95
97
  return fileViolations(root, file, compilerOptions, excluded);
96
98
  }, reuse = async () => {
97
99
  const text = optionalSourceText(file);
98
- if (environment === void 0 || membership === null || text === null)
100
+ if (context === void 0 || shared === null || text === null)
99
101
  return check();
100
- const key = digest([CLOSURE_SCHEMA, root, file, options, digest(text), membership, environment]), obtained = await closureFacts.obtain({ key, root, tokens: "" }, async () => ({ outcome: await check(), tokens: { kind: "token-independent" } }));
101
- if (obtained.kind === "reused")
102
+ const projectRoot = context.root, key = digest([shared, path.relative(projectRoot, file), digest(text)]), obtained = await closureFacts.obtain({ key, root: projectRoot, tokens: "" }, async () => ({ outcome: await check(), tokens: { kind: "token-independent" } }), relocateOutcome);
103
+ if (obtained.kind === "reused") {
102
104
  closureStats.reused++;
105
+ if (process.env.ADS_VERIFY_OWNER_REUSE === "1" && canonical(await fileViolations(root, file, compilerOptions, excluded)) !== canonical(obtained.outcome))
106
+ throw Error(`Reused design-system closure violations of ${file} differ from a fresh check (ADS_VERIFY_OWNER_REUSE=1).`);
107
+ }
103
108
  return obtained.outcome;
104
109
  }, key = `design-system-closure:${root}:${file}:${options}`, revision = context?.revision;
105
110
  violations.push(...await (context ? memoFact(context, key, () => revision ? memoProgram(revision, key, reuse) : reuse()) : check()));
@@ -1,9 +1,8 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { isExportDeclaration, isNamedExports, isStringLiteral } from "typescript/ast";
4
4
  import { designUsageProblems } from "./analysis/design-usage.mjs";
5
5
  import { closeSyntax, parseSource } from "./analysis/syntax.mjs";
6
- import { PROSE_MANIFEST, parseProseManifest } from "./prose-model.mjs";
7
6
  const wording = {
8
7
  "design-import": (problem) => [`${problem.specifier} authors design, which belongs to the design system.`, "Declare the design in the design system and import the owner from its public entry."],
9
8
  "component-outside-pattern": (problem) => [
@@ -11,10 +10,6 @@ const wording = {
11
10
  "Render it inside the pattern that arranges this screen (as its child or in a slot prop); if no pattern does, add one to the design system."
12
11
  ],
13
12
  "local-markup": (problem) => [`<${problem.tag}> is not imported from the design system.`, "Render a design-system owner; an arrangement or element the screen needs belongs in a pattern of the design system."],
14
- "prose-element-undeclared": (problem) => [
15
- `<${problem.tag}> is content of ${problem.owner}, whose recipe declares no such element: it is drawn without a design.`,
16
- `Declare the element in the prose recipe of ${problem.owner} (\`elements\`), or write the content with the elements it declares.`
17
- ],
18
13
  "spread-props": () => ["A spread passes props nothing can see.", "Pass each prop explicitly."],
19
14
  "design-prop": (problem) => [`${problem.attribute} supplies design from outside the design system.`, "Remove it; choose the treatment through the owner's own props."],
20
15
  "imperative-design": (problem) => [`${problem.member} writes styles or creates DOM by hand.`, "Remove the write; render design-system owners with props."],
@@ -48,7 +43,6 @@ export async function designSystemEntry(publicEntry, entryFile) {
48
43
  patterns.add(element.name.text);
49
44
  }
50
45
  }
51
- const manifest = path.join(path.dirname(path.resolve(entryFile)), PROSE_MANIFEST), prose = existsSync(manifest) ? parseProseManifest(readFileSync(manifest, "utf8")) : new Map;
52
- return { publicEntry, patterns, prose };
46
+ return { publicEntry, patterns };
53
47
  }
54
48
  export const closeDesignUsage = () => closeSyntax();
@@ -109,16 +109,35 @@ export function listOutput(directory) {
109
109
  }
110
110
  export const driftless = (drift) => drift.modified.length === 0 && drift.missing.length === 0 && drift.foreign.length === 0;
111
111
  export function outputDrift(contract, listing) {
112
+ return driftOf(contract, [...listing.files.keys()], (name) => {
113
+ const bytes = listing.files.get(name);
114
+ return bytes === void 0 ? void 0 : sha256(bytes);
115
+ }, listing.irregular);
116
+ }
117
+ export function driftOf(contract, names, digest, irregular) {
112
118
  const modified = [], missing = [];
113
119
  for (const [name, entry] of Object.entries(contract.files)) {
114
- const bytes = listing.files.get(name);
115
- if (bytes === void 0)
120
+ const hash = digest(name);
121
+ if (hash === void 0)
116
122
  missing.push(name);
117
- else if (sha256(bytes) !== entry.sha256)
123
+ else if (hash !== entry.sha256)
118
124
  modified.push(name);
119
125
  }
120
- const foreign = [...listing.files.keys()].filter((name) => name !== CONTRACT_FILE && !Object.hasOwn(contract.files, name));
121
- return { modified, missing, foreign: [...foreign, ...listing.irregular].sort(order) };
126
+ const foreign = names.filter((name) => name !== CONTRACT_FILE && !Object.hasOwn(contract.files, name));
127
+ return { modified, missing, foreign: [...foreign, ...irregular].sort(order) };
128
+ }
129
+ export function outputVerdict(listed) {
130
+ if (listed === null)
131
+ return { kind: "absent" };
132
+ if (listed === "not-a-folder")
133
+ return { kind: "not-a-folder" };
134
+ const names = [...listed.files.keys()];
135
+ if (listed.contract === void 0)
136
+ return { kind: "unrecorded", files: [...names, ...listed.irregular].sort(order), problem: null };
137
+ const contract = parseContract(listed.contract);
138
+ if (contract.kind === "err")
139
+ return { kind: "unrecorded", files: [...names, ...listed.irregular].sort(order), problem: contract.error };
140
+ return { kind: "recorded", contract: contract.value, drift: driftOf(contract.value, names, (name) => listed.files.get(name), listed.irregular) };
122
141
  }
123
142
  export const readOutputState = (directory) => outputState(listOutput(directory));
124
143
  export function outputState(listing) {
@@ -3,7 +3,8 @@ import { foundationGridExamples, foundationGrids, ownerSpatialProfiles, previewF
3
3
  import { tokenViewFacts, tokenViewSheet } from "../token-view-facts.mjs";
4
4
  import { profileViewFacts } from "../profile-view-facts.mjs";
5
5
  import { assetViewFacts } from "../asset-view-facts.mjs";
6
- import { PREVIEW_FACTS_FILE, PREVIEW_CONTROLS_FILE, PREVIEW_TOKENS_SHEET } from "./preview-tree.mjs";
6
+ import { PREVIEW_AUDIT_FILE, PREVIEW_FACTS_FILE, PREVIEW_CONTROLS_FILE, PREVIEW_TOKENS_SHEET } from "./preview-tree.mjs";
7
+ import { derivedAudit, derivedAuditText } from "../derived-states.mjs";
7
8
  import { previewControlsText } from "../preview-controls.mjs";
8
9
  import { optionalSourceText } from "../analysis/helpers.mjs";
9
10
  import { failAt } from "../analysis/owner-choices.mjs";
@@ -32,8 +33,6 @@ import { encodeEmittedBytes } from "./operation-reply.mjs";
32
33
  import { preloadedFaces } from "../font-checks.mjs";
33
34
  import { ownerEmissionKey, projectEmissionCache } from "./owner-emission-cache.mjs";
34
35
  import { moduleProperties, namespacedClasses, namespacedSheet } from "./namespace.mjs";
35
- import { publicProse } from "../analysis/prose-owners.mjs";
36
- import { PROSE_MANIFEST, proseManifestText } from "../prose-model.mjs";
37
36
  const designSystemFolder = ({ root, dsRoot }) => path.relative(root, dsRoot).split(path.sep).join("/");
38
37
  function packageManifest(root) {
39
38
  const text = optionalSourceText(path.join(root, "package.json"));
@@ -78,7 +77,7 @@ export async function revisionEmission(project) {
78
77
  return classes === void 0 || namespace === null ? classes : namespacedClasses(namespace, classes);
79
78
  }, emissionKeys = new Map, sources = new Map, reused = [];
80
79
  for (const [name, owner] of outcomes) {
81
- const analysisKey = keys.get(name), key = analysisKey === void 0 ? null : ownerEmissionKey({ analysisKey, outcome: owner, classes: [...owner.styles.keys()].map((id) => classOf(id) ?? null) });
80
+ const analysisKey = keys.get(name), key = analysisKey === void 0 ? null : ownerEmissionKey({ analysisKey, root: project.dsRoot, outcome: owner, classes: [...owner.styles.keys()].map((id) => classOf(id) ?? null) });
82
81
  emissionKeys.set(name, key);
83
82
  const known = key === null ? void 0 : cache.get(key);
84
83
  if (known === void 0)
@@ -133,9 +132,6 @@ export async function revisionEmission(project) {
133
132
  }
134
133
  const fonts = fontEmission(checked.fonts, preloadedFaces(foundation, checked.document, checked.fonts));
135
134
  withFontsModule(files, fonts, PUBLIC_BARREL);
136
- const prose = await publicProse(project.dsRoot);
137
- if (prose.size > 0)
138
- files.set(PROSE_MANIFEST, proseManifestText(prose));
139
135
  const icon = await timing.timeStage("emit-app-icon", () => appIconEmission(checked.appIcon));
140
136
  withAppIconsModule(files, icon, PUBLIC_BARREL);
141
137
  files.set(DEPENDENCY_MANIFEST, dependencyManifestText(check.graph, { packageManifest: packageManifest(project.root), framework: project.config.framework }));
@@ -145,9 +141,10 @@ export async function revisionEmission(project) {
145
141
  files: [...files],
146
142
  binaries: [...fonts.files, ...icon.files].map(([name, bytes]) => [name, encodeEmittedBytes(bytes)]),
147
143
  previewFiles: [
148
- [PREVIEW_FACTS_FILE, previewFactsText(foundationGrids(foundation), foundationGridExamples(foundation), tokenViewFacts(foundation, designSystemFolder(project)), ownerSpatialProfiles(outcomes), profileViewFacts(foundation), assetViewFacts(checked.assets, project.dsRoot, foundation))],
144
+ [PREVIEW_FACTS_FILE, previewFactsText(foundationGrids(foundation), foundationGridExamples(foundation), tokenViewFacts(foundation, designSystemFolder(project)), ownerSpatialProfiles(outcomes), profileViewFacts(foundation), assetViewFacts(checked.assets, project.dsRoot, foundation, outcomes))],
149
145
  [PREVIEW_TOKENS_SHEET, tokenViewSheet(foundation)],
150
- [PREVIEW_CONTROLS_FILE, previewControlsText(outcomes.values())]
146
+ [PREVIEW_CONTROLS_FILE, previewControlsText(outcomes.values())],
147
+ [PREVIEW_AUDIT_FILE, derivedAuditText(derivedAudit([...outcomes].map(([name, owner]) => [name, [...owner.styles].map(([id, construction]) => ({ root: construction.root, css: construction.css, classes: classOf(id), paints: construction.paints, glyphs: construction.glyphs, content: construction.content }))])))]
151
148
  ],
152
149
  owners: {
153
150
  total: outcomes.size,
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
- import { digest } from "../digest.mjs";
3
+ import { architectureEvidence } from "../evidence.mjs";
4
4
  import { findingRules } from "../finding-rules.mjs";
5
5
  import { CONTRACT_FILE, parseContract, readOutputState } from "./contract.mjs";
6
6
  import { outputDirectory } from "./output-location.mjs";
@@ -58,4 +58,10 @@ export function recordedOutputRevision({ root, config }) {
58
58
  const contract = parseContract(text);
59
59
  return contract.kind === "ok" ? contract.value.revision : null;
60
60
  }
61
- export const outputIntegrityFingerprint = (options) => digest(outputIntegrityFindings(options));
61
+ export function withCurrentOutput(report, options, current = outputIntegrityFindings(options)) {
62
+ const kept = report.diagnostics.filter((finding) => finding.rule !== GENERATED_MODIFIED_RULE);
63
+ if (current.length === 0 && kept.length === report.diagnostics.length)
64
+ return report;
65
+ const diagnostics = [...kept, ...current];
66
+ return { ...report, ...architectureEvidence({ ...report, diagnostics, ok: diagnostics.length === 0 }) };
67
+ }
@@ -0,0 +1,120 @@
1
+ import { lstatSync, readFileSync, readdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { loadConfig } from "../config.mjs";
4
+ import { createInputDigests } from "../input-digests.mjs";
5
+ import { CONTRACT_FILE, outputVerdict, sha256 } from "./contract.mjs";
6
+ import { generatedFindings } from "./integrity.mjs";
7
+ import { outputDirectory } from "./output-location.mjs";
8
+ const FOLDER = "folder", NOT_A_FOLDER = "not-a-folder", IRREGULAR = "irregular", isMissing = (error) => error instanceof Error && ("code" in error) && (error.code === "ENOENT" || error.code === "ENOTDIR"), inFolder = (relative, outDir) => {
9
+ const name = path.basename(outDir);
10
+ return relative === name || relative.startsWith(`${name}/`);
11
+ };
12
+ function outputInputSet(root) {
13
+ let files = new Set, directories = [];
14
+ return {
15
+ load: () => {
16
+ const { config } = loadConfig(root);
17
+ return outputDirectory(root, config);
18
+ },
19
+ key: (outDir) => outDir,
20
+ capture(outDir, { onFile }) {
21
+ const name = path.basename(outDir), result = {}, seen = new Set, folders = [path.dirname(outDir)];
22
+ let stat;
23
+ try {
24
+ stat = lstatSync(outDir);
25
+ } catch (error) {
26
+ if (!isMissing(error))
27
+ throw error;
28
+ }
29
+ if (stat !== void 0 && !stat.isDirectory())
30
+ result[name] = NOT_A_FOLDER;
31
+ else if (stat !== void 0) {
32
+ result[name] = FOLDER;
33
+ const visit = (folder, prefix) => {
34
+ folders.push(folder);
35
+ for (const entry of readdirSync(folder, { withFileTypes: !0 })) {
36
+ const relative = `${prefix}/${entry.name}`, file = path.join(folder, entry.name);
37
+ if (entry.isDirectory())
38
+ visit(file, relative);
39
+ else if (entry.isFile()) {
40
+ const content = readFileSync(file), revision = `sha256:${sha256(content)}`;
41
+ result[relative] = revision;
42
+ seen.add(relative);
43
+ onFile?.(relative, content, revision);
44
+ } else
45
+ result[relative] = IRREGULAR;
46
+ }
47
+ };
48
+ visit(outDir, name);
49
+ }
50
+ files = seen;
51
+ directories = folders;
52
+ return Promise.resolve(result);
53
+ },
54
+ signature: () => "",
55
+ structural: (relative, outDir) => inFolder(relative, outDir) && !files.has(relative),
56
+ ignored: (relative, outDir) => !inFolder(relative, outDir),
57
+ directories: () => directories
58
+ };
59
+ }
60
+ const watched = new Map;
61
+ function verdictOf(outDir, digests, entry) {
62
+ const name = path.basename(outDir), folder = digests[name];
63
+ if (folder === void 0 || folder === null)
64
+ return outputVerdict(null);
65
+ if (folder === NOT_A_FOLDER)
66
+ return outputVerdict(NOT_A_FOLDER);
67
+ const files = new Map, irregular = [];
68
+ for (const [key, value] of Object.entries(digests)) {
69
+ if (!key.startsWith(`${name}/`) || value === null)
70
+ continue;
71
+ const relative = key.slice(name.length + 1);
72
+ if (value === IRREGULAR)
73
+ irregular.push(relative);
74
+ else
75
+ files.set(relative, value.slice(7));
76
+ }
77
+ const recorded = files.get(CONTRACT_FILE);
78
+ let contract;
79
+ if (recorded !== void 0) {
80
+ if (entry.contract?.digest !== recorded) {
81
+ let bytes;
82
+ try {
83
+ bytes = readFileSync(path.join(outDir, CONTRACT_FILE));
84
+ } catch {
85
+ return null;
86
+ }
87
+ if (sha256(bytes) !== recorded)
88
+ return null;
89
+ entry.contract = { digest: recorded, text: bytes.toString("utf8") };
90
+ }
91
+ contract = entry.contract.text;
92
+ }
93
+ return outputVerdict({ files, irregular, contract });
94
+ }
95
+ export async function watchedOutputFindings(root) {
96
+ const project = path.resolve(root), outDir = outputDirectory(project, loadConfig(project).config);
97
+ let entry = watched.get(project);
98
+ if (entry !== void 0 && entry.digests.root !== path.dirname(outDir)) {
99
+ entry.digests.close();
100
+ watched.delete(project);
101
+ entry = void 0;
102
+ }
103
+ if (entry === void 0) {
104
+ entry = { digests: createInputDigests(path.dirname(outDir), outputInputSet(project), { onError: () => {} }), contract: void 0 };
105
+ watched.set(project, entry);
106
+ }
107
+ try {
108
+ const verdict = verdictOf(outDir, await entry.digests.current(), entry);
109
+ return verdict === null ? void 0 : generatedFindings(project, outDir, verdict);
110
+ } catch {
111
+ entry.digests.invalidate();
112
+ return;
113
+ }
114
+ }
115
+ export function releaseOutputWatch(root) {
116
+ const project = path.resolve(root);
117
+ watched.get(project)?.digests.close();
118
+ watched.delete(project);
119
+ }
120
+ export const outputWatchStats = (root) => watched.get(path.resolve(root))?.digests.stats();
@@ -1,5 +1,5 @@
1
1
  import { digest } from "../digest.mjs";
2
- import { canonical } from "../analysis/owner-analysis-key.mjs";
2
+ import { canonical, rootRelative } from "../analysis/owner-analysis-key.mjs";
3
3
  export const OWNER_EMISSION_LIMIT = 512;
4
4
  const PROJECT_LIMIT = 8;
5
5
  export function createOwnerEmissionCache(limit = OWNER_EMISSION_LIMIT) {
@@ -41,12 +41,12 @@ export function clearOwnerEmissions() {
41
41
  projects.clear();
42
42
  }
43
43
  const outcomeDigests = new WeakMap;
44
- export function outcomeDigest(owner) {
44
+ export function outcomeDigest(owner, root) {
45
45
  const known = outcomeDigests.get(owner);
46
46
  if (known !== void 0)
47
47
  return known;
48
- const computed = digest(canonical(owner));
48
+ const computed = digest(rootRelative(canonical(owner), root));
49
49
  outcomeDigests.set(owner, computed);
50
50
  return computed;
51
51
  }
52
- export const ownerEmissionKey = (inputs) => digest(["ads-owner-emission/1", inputs.analysisKey, outcomeDigest(inputs.outcome), inputs.classes]);
52
+ export const ownerEmissionKey = (inputs) => digest(["ads-owner-emission/1", inputs.analysisKey, outcomeDigest(inputs.outcome, inputs.root), inputs.classes]);
@@ -56,7 +56,8 @@ export function startPreviewEmitter(root, { onEmitted, onFreshness, onError, deb
56
56
  const { update } = written.value, holds = written.value.emittedFrom ?? emittedFrom;
57
57
  shown = update.revision;
58
58
  publish({ kind: "current", revision: shown });
59
- onEmitted(update, holds.sources, holds.capturedAt);
59
+ const checked = !written.value.superseded && emitted.value.checked?.revision === update.revision ? emitted.value.checked : void 0;
60
+ onEmitted(update, holds.sources, holds.capturedAt, checked);
60
61
  return ok(update);
61
62
  },
62
63
  onEvent: (event) => {
@@ -72,9 +73,10 @@ function designSystemSources(root, inputs) {
72
73
  export async function emitPreviewTreeOnce(root, {
73
74
  signal,
74
75
  analysis,
76
+ trackingRoot,
75
77
  onTree
76
78
  } = {}) {
77
- const emitted = await timing.timeStage("preview-emit", () => emitRevision(root, { signal, analysis }));
79
+ const emitted = await timing.timeStage("preview-emit", () => emitRevision(root, { signal, analysis, trackingRoot }));
78
80
  if (emitted.kind === "err")
79
81
  return err(emitted.error);
80
82
  onTree?.(emitted.value);
@@ -6,7 +6,7 @@ import { readFileSync } from "node:fs";
6
6
  import { listOutput } from "./contract.mjs";
7
7
  import { acquireOutputLock, processLiveness } from "./lock.mjs";
8
8
  import { nodeWriterFs, planOutput } from "./writer.mjs";
9
- export const PREVIEW_FACTS_FILE = "ads-preview-facts.json", PREVIEW_TOKENS_SHEET = "ads-preview-tokens.css", PREVIEW_CONTROLS_FILE = "ads-preview-controls.json", previewOnlyFiles = [PREVIEW_CONTROLS_FILE, PREVIEW_FACTS_FILE, PREVIEW_TOKENS_SHEET], previewTreeDirectory = (root) => path.join(root, ".ds", "emitted", "live"), previewTreeState = (tree) => `${tree}.state.json`;
9
+ export const PREVIEW_FACTS_FILE = "ads-preview-facts.json", PREVIEW_TOKENS_SHEET = "ads-preview-tokens.css", PREVIEW_CONTROLS_FILE = "ads-preview-controls.json", PREVIEW_AUDIT_FILE = "ads-preview-audit.json", previewOnlyFiles = [PREVIEW_AUDIT_FILE, PREVIEW_CONTROLS_FILE, PREVIEW_FACTS_FILE, PREVIEW_TOKENS_SHEET], previewTreeDirectory = (root) => path.join(root, ".ds", "emitted", "live"), previewTreeState = (tree) => `${tree}.state.json`;
10
10
  const TEMPORARY = ".ads-tmp-", aborted = (signal) => signal?.aborted === !0, isTemporary = (name) => path.basename(name).includes(TEMPORARY);
11
11
  function replaceFile(fs, file, content) {
12
12
  const temporary = path.join(path.dirname(file), `.${path.basename(file)}${TEMPORARY}${randomUUID()}`);