@reqvire-org/ads 0.4.3 → 0.4.4

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/README.md CHANGED
@@ -151,7 +151,7 @@ Linaria; integrate its extraction with your build as described in the
151
151
  | `ads check` | Check tokens, styles, imports, and ADS ownership; errors fail, review items are listed |
152
152
  | `ads validate` | Run the full gate: `ads check`, project scripts, every behavior test and the render audit |
153
153
  | `ads validate --changed` | The same gate for what changed since the last successful full run |
154
- | `ads compile` | Compile all previews with Bun; `--watch` rebuilds on edits |
154
+ | `ads compile` | Compile complete previews with Bun; `--watch` uses incremental module updates |
155
155
  | `ads tokens` | Inspect token values and themes |
156
156
  | `ads behaviors` | Inspect registered behavior guarantees and current evidence |
157
157
  | `ads verify --unit <id>` | Run an owner's registered behavior checks |
@@ -3,14 +3,15 @@ import { fileURLToPath } from "node:url";
3
3
  import { restoreCompiledPreviews, runScenarioCompiler } from "./scenarios-compiler.mjs";
4
4
  import { loadConfig } from "./config.mjs";
5
5
  import { withPreviewSession } from "./preview-scope.mjs";
6
- import { createBunPreviewBuilder, previewFrameFiles } from "./preview-bun.mjs";
6
+ import { previewFrameFiles } from "./preview-bun.mjs";
7
+ import { createIncrementalPreviewBuilder } from "./preview-incremental.mjs";
7
8
  import { checkCandidate } from "./validation-checks.mjs";
8
9
  import { renderStoppingRules } from "./finding-rules.mjs";
9
10
 
10
11
  const compilerFiles = [
11
12
  import.meta.filename,
12
13
  ...previewFrameFiles,
13
- ...["preview-bun.mjs", "preview-imports.mjs", "bun-worker.mjs", "construction-styles.cjs", "lockup-model.cjs", "spatial-model.cjs", "spatial-inputs.cjs", "spatial-contexts.cjs", "spatial-css.cjs", "linaria/spatial-inputs.cjs", "linaria/preserve-values.cjs"].map((file) => fileURLToPath(new URL(file, import.meta.url))),
14
+ ...["preview-bun.mjs", "preview-incremental.mjs", "preview-resources.mjs", "preview-imports.mjs", "bun-worker.mjs", "construction-styles.cjs", "lockup-model.cjs", "spatial-model.cjs", "spatial-inputs.cjs", "spatial-contexts.cjs", "spatial-css.cjs", "linaria/spatial-inputs.cjs", "linaria/preserve-values.cjs"].map((file) => fileURLToPath(new URL(file, import.meta.url))),
14
15
  ];
15
16
 
16
17
  function validator(root) {
@@ -25,19 +26,19 @@ function validator(root) {
25
26
  };
26
27
  }
27
28
 
28
- /** The same ADS-owned Bun compiler serves MCP, standalone builds and CI. */
29
+ /** One ADS scheduler serves watched module graphs and complete Bun builds. */
29
30
  export async function compilePreviews(directory = process.cwd(), { watched = false } = {}) {
30
31
  const root = path.resolve(directory);
31
32
  if (!watched) {
32
33
  const restored = await restoreCompiledPreviews(withPreviewSession(loadConfig(root), process.env.ADS_MCP_BUILD_SESSION), compilerFiles);
33
34
  if (restored) return restored;
34
35
  }
35
- // Each root, the project's and every hosted draft's, gets its own validator and Bun builder.
36
+ // The project and each hosted draft own separate validators and compiler graphs.
36
37
  const main = await runScenarioCompiler(root, (projectRoot) => ({
37
38
  watched,
38
39
  compilerFiles,
39
40
  validate: validator(projectRoot),
40
- buildGraph: createBunPreviewBuilder(),
41
+ buildGraph: createIncrementalPreviewBuilder(),
41
42
  }));
42
43
  if (watched) for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, async () => main?.stop());
43
44
  return main;
package/dist/check.mjs CHANGED
@@ -37,7 +37,7 @@ import { inspectScenarioCoverage } from "./scenarios.mjs";
37
37
  import { uiOperation, importedUiApi } from "./ui-framework.mjs";
38
38
  import { inspectStyleBoundaries, pointerCaptureAdvisories } from "./style-boundaries.mjs";
39
39
  import { inspectBehaviors, inspectControllers } from "./behaviors.mjs";
40
- import { numericCssUnit, tokenLengthLiteral } from "./css-values.mjs";
40
+ import { styleTokenViolations } from "./style-token-rules.mjs";
41
41
  import { foundationDeclaration, foundationSelector } from "./foundation.mjs";
42
42
  import { inspectUnits } from "./units.mjs";
43
43
  import { generatedEntryDiagnostics } from "./generated-entries.mjs";
@@ -49,7 +49,7 @@ import { createScenarioSelectors } from "./scenario-selectors.mjs";
49
49
  import { architectureEvidence, failure } from "./evidence.mjs";
50
50
  import { propertyRegistration } from "./property-registrations.mjs";
51
51
  import { createLayerBoundaries, layerSourceFiles } from "./layers.mjs";
52
- import { createDesignValues, designTemplateVariants, inspectDesignAliases, isColorKeyword } from "./design-values.mjs";
52
+ import { createDesignValues, designTemplateVariants, inspectDesignAliases } from "./design-values.mjs";
53
53
  import { inspectTestBoundaries } from "./test-boundaries.mjs";
54
54
  import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
55
55
  import { inspectUsage } from "./usage.mjs";
@@ -575,47 +575,7 @@ async function checkCapturedProject(directory, { trackingRoot }) {
575
575
  report(file, "token-reference", `Undefined shared token ${ref.name}.`, offset.line + decl.source.start.line - 1, decl.source.start.column);
576
576
  }
577
577
  if (fontDescriptor || propertyDescriptor) return; // Font metadata defines source assets, not token-backed UI styles.
578
- const violations = new Set();
579
- if (decl.value.includes("__ds_expression__"))
580
- violations.add(
581
- "Cannot establish this interpolated design value from source. Use a source-resolvable shared token/mapping; unknown interpolation does not grant permission for private design values.",
582
- );
583
- valueParser(decl.value).walk((node) => {
584
- if (node.type === "function" && node.value === "url") return false;
585
- if (node.type === "word" && decl.prop.startsWith("--") && isColorKeyword(node.value))
586
- violations.add("Component variables map shared Data; named colors also require shared tokens.");
587
- if (
588
- node.type === "word" &&
589
- (/^#[\da-f]{3,8}$/i.test(node.value) ||
590
- (tokenLengthLiteral(node.value) &&
591
- !(
592
- isReviewFile(file, options) &&
593
- /^(?:(?:min-|max-)?(?:width|height|inline-size|block-size)|flex-basis|grid-template-columns|grid-template-rows)$/.test(decl.prop)
594
- )) ||
595
- ["s", "ms"].includes(numericCssUnit(node.value)))
596
- )
597
- violations.add(
598
- "Use a token for colors, absolute/font-relative lengths (including ch), and durations. Unitless geometry and structural angle/viewport/container relationships remain valid.",
599
- );
600
- if (node.type === "function" && /^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix|cubic-bezier)$/.test(node.value))
601
- violations.add("Define color formulas and easing in tokens.");
602
- if (node.type === "function" && /^(?:blur|brightness|contrast|drop-shadow|grayscale|hue-rotate|invert|saturate|sepia)$/.test(node.value))
603
- violations.add("Define visual filter effects in tokens.");
604
- if (node.type === "word" && /^ease(?:-in|-out|-in-out)?$/.test(node.value)) violations.add("Use a motion token for easing.");
605
- if (
606
- node.type === "word" &&
607
- /^(?:color|background-color|(?:border|outline|caret|text-decoration|column-rule)(?:-[a-z]+)?-color|fill|stroke)$/.test(decl.prop) &&
608
- /^[a-z]+$/i.test(node.value) &&
609
- !/^(?:inherit|initial|unset|revert|currentcolor|transparent|none)$/i.test(node.value)
610
- )
611
- violations.add("Use a semantic color token.");
612
- });
613
- if (
614
- /^(?:font-family|font-weight|z-index)$/.test(decl.prop) &&
615
- !/^(?:var\(|inherit$|initial$|unset$|revert(?:-layer)?$|auto$)/.test(decl.value) &&
616
- !(foundation && decl.prop === "font-weight" && /^(?:bolder|lighter)$/.test(decl.value))
617
- )
618
- violations.add("Use a semantic typography or layering token.");
578
+ const violations = styleTokenViolations(decl, { review: isReviewFile(file, options), foundation });
619
579
  for (const message of violations) report(file, "style-token", message, offset.line + decl.source.start.line - 1, decl.source.start.column);
620
580
  });
621
581
  }
@@ -1,8 +1,8 @@
1
1
  import path from "node:path";
2
2
  import { location } from "./analysis/helpers.mjs";
3
+ import { createContrastStyles } from "./contrast-styles.mjs";
3
4
  import { renderComposition } from "./render-composition.mjs";
4
5
 
5
- const properties = new Set(["color", "background", "background-color", "background-image", "font", "font-size", "font-weight", "opacity", "filter", "backdrop-filter", "mix-blend-mode", "transform", "text-shadow", "position", "display", "visibility", "all"]);
6
6
  const initialText = new Set(["a", "button", "input", "select", "textarea", "option"]);
7
7
  const initialFont = new Set(["button", "input", "select", "textarea", "option"]);
8
8
  const nativeFill = new Set(["button", "input", "select", "textarea", "option", "progress", "meter"]);
@@ -15,70 +15,16 @@ const isAbsent = value => value?.kind === "literal" && value.value == null;
15
15
  /** Bind already-parsed CSS to captured render facts. This is deliberately a
16
16
  * proof of simple owned cascades, not a replacement for browser CSS evaluation. */
17
17
  export function createContrastComposition(program, options, contrast) {
18
- const templates = new Map();
19
- let hasColor = false, externalStyles = false;
18
+ const styles = createContrastStyles();
20
19
  const relative = node => ({ ...location(node), file: path.relative(options.root, node.getSourceFile().fileName).replaceAll("\\", "/") });
21
- function record(template, css, file, offset) {
22
- const entries = new Map();
23
- let reason;
24
- css.walkDecls(decl => {
25
- const prop = decl.prop.startsWith("--") ? decl.prop : decl.prop.toLowerCase();
26
- if (!properties.has(prop) && !prop.startsWith("--")) return;
27
- if (prop === "color") hasColor = true;
28
- // Keyframes and @property describe other contexts, not the base element.
29
- for (let parent = decl.parent; parent && parent.type !== "root"; parent = parent.parent) {
30
- if (parent.type === "atrule" && /^(?:property|(?:-\w+-)?keyframes)$/.test(parent.name)) return;
31
- if (parent.type === "rule" && parent.selector.trim() !== "&" || parent.type === "atrule") {
32
- reason = "Conditional or descendant paint selectors need the rendered cascade.";
33
- return;
34
- }
35
- }
36
- const at = { file, line: offset.line + decl.source.start.line - 1, column: decl.source.start.column + (decl.source.start.line === 1 ? offset.column - 1 : 0) };
37
- const entry = { value: decl.value, prop, important: !!decl.important, at, decl, template };
38
- const old = entries.get(prop);
39
- if (!old?.important || entry.important) entries.set(prop, entry);
40
- if (prop === "background" && (!entries.get("background-color")?.important || entry.important)) entries.delete("background-color");
41
- if (prop === "background-color" && entries.get("background")?.important && !entry.important) entries.delete("background-color");
42
- });
43
- if (!template) { externalStyles ||= !!entries.size || !!reason; return; }
44
- const fact = { entries, reason };
45
- const signature = JSON.stringify([[...entries].map(([name, entry]) => [name, entry.value, entry.important]), reason]);
46
- const variants = templates.get(template) ?? new Map();
47
- variants.set(signature, fact);
48
- templates.set(template, variants);
49
- }
50
- function style(item) {
51
- const entries = new Map();
52
- let reason = item.classes.reason ?? (item.classes.names.length ? "Named classes outside captured style templates need the rendered cascade." : undefined);
53
- for (const template of item.classes.templates) {
54
- const variants = templates.get(template);
55
- if (!variants) { reason ??= "A style template has no complete captured paint facts."; continue; }
56
- if (variants.size !== 1) {
57
- reason ??= "Interpolated paint alternatives do not establish one definite cascade.";
58
- continue;
59
- }
60
- const fact = variants.values().next().value;
61
- reason ??= fact.reason;
62
- for (const [name, entry] of fact.entries) {
63
- const old = entries.get(name);
64
- // Class order alone does not prove stylesheet order (including core css
65
- // classes and shorthand/longhand conflicts). Do not guess a winner.
66
- if (old && old.value !== entry.value) reason ??= "Composed classes set competing paint declarations.";
67
- if (name === "background" && entries.has("background-color") || name === "background-color" && entries.has("background"))
68
- reason ??= "Composed background shorthand and longhand declarations need the rendered cascade.";
69
- entries.set(name, entry);
70
- }
71
- }
72
- return { entries, reason };
73
- }
74
20
  async function check() {
75
- if (!hasColor) return;
21
+ if (!styles.hasColor) return;
76
22
  const graph = await renderComposition(program, options);
77
23
  const memo = new Map();
78
24
  function effective(item) {
79
25
  if (memo.has(item)) return memo.get(item);
80
26
  const parent = item.parent && effective(item.parent);
81
- const own = style(item), entries = own.entries;
27
+ const own = styles.get(item.classes), entries = own.entries;
82
28
  const state = {
83
29
  foreground: initialText.has(item.tag) ? undefined : parent?.foreground,
84
30
  backgrounds: [...(parent?.backgrounds ?? [])],
@@ -113,7 +59,7 @@ export function createContrastComposition(program, options, contrast) {
113
59
  if (entries.has("all") || ["absolute", "fixed"].includes(entries.get("position")?.value.toLowerCase())) state.reason ??= "A reset or out-of-flow position prevents establishing the backdrop.";
114
60
  if (["hidden", "disabled", "aria-disabled"].some(name => item.attributes[name]?.kind !== "literal")) state.reason ??= "Dynamic visibility or disabled state needs a rendered check.";
115
61
  if (!isAbsent(item.attributes.style)) state.reason ??= "Inline styles may override the composed paint.";
116
- if (externalStyles) state.reason ??= "Additional authored CSS needs the rendered selector cascade.";
62
+ if (styles.externalStyles) state.reason ??= "Additional authored CSS needs the rendered selector cascade.";
117
63
  return state;
118
64
  }
119
65
  for (const item of graph.nodes) {
@@ -130,5 +76,5 @@ export function createContrastComposition(program, options, contrast) {
130
76
  }
131
77
  for (const item of graph.limits) if (item.node) contrast.incomplete(relative(item.node), item.reason);
132
78
  }
133
- return { record, check };
79
+ return { record: styles.record, check };
134
80
  }
@@ -0,0 +1,88 @@
1
+ import selectorParser from "postcss-selector-parser";
2
+
3
+ const properties = new Set(["color", "background", "background-color", "background-image", "font", "font-size", "font-weight", "opacity", "filter", "backdrop-filter", "mix-blend-mode", "transform", "text-shadow", "position", "display", "visibility", "all"]);
4
+ const signature = fact => JSON.stringify([[...fact.entries].map(([name, entry]) => [name, entry.value, entry.important]).sort(([a], [b]) => a.localeCompare(b)), fact.reason]);
5
+
6
+ /** Check-owned paint facts from the already captured/parsed CSS. Class choices
7
+ * stay factored: comparing each choice avoids exponential class combinations. */
8
+ export function createContrastStyles() {
9
+ const templates = new Map(), targetedHooks = new Set(), selectors = new WeakSet(), memo = new WeakMap();
10
+ let hasColor = false, externalStyles = false, unknownTargets = false;
11
+ function targets(rule) {
12
+ if (selectors.has(rule)) return;
13
+ selectors.add(rule);
14
+ try {
15
+ if (rule.selector.length > 4096) { unknownTargets = true; return; }
16
+ const ast = selectorParser().astSync(rule.selector);
17
+ for (const branch of ast.nodes) {
18
+ const subject = branch.nodes.slice(branch.nodes.findLastIndex(node => node.type === "combinator") + 1);
19
+ // `.card:hover &` styles the attached template, not the card hook.
20
+ // Its uncertainty is already retained on that template's own fact.
21
+ if (subject.some(node => node.type === "nesting")) continue;
22
+ branch.walkClasses(node => targetedHooks.add(node.value));
23
+ }
24
+ } catch { unknownTargets = true; }
25
+ }
26
+ function record(template, css, file, offset) {
27
+ const entries = new Map();
28
+ let reason;
29
+ css.walkDecls(decl => {
30
+ const prop = decl.prop.startsWith("--") ? decl.prop : decl.prop.toLowerCase();
31
+ if (!properties.has(prop) && !prop.startsWith("--")) return;
32
+ const parents = [];
33
+ for (let parent = decl.parent; parent && parent.type !== "root"; parent = parent.parent) parents.push(parent);
34
+ if (parents.some(parent => parent.type === "atrule" && /^(?:property|(?:-\w+-)?keyframes)$/.test(parent.name))) return;
35
+ if (prop === "color") hasColor = true;
36
+ let conditional = false;
37
+ for (const parent of parents) {
38
+ if (parent.type === "rule" && parent.selector.trim() !== "&") { targets(parent); conditional = true; }
39
+ if (parent.type === "atrule") conditional = true;
40
+ }
41
+ if (conditional) { reason = `Conditional or descendant ${prop} at ${file}:${offset.line + decl.source.start.line - 1} needs the rendered cascade.`; return; }
42
+ const at = { file, line: offset.line + decl.source.start.line - 1, column: decl.source.start.column + (decl.source.start.line === 1 ? offset.column - 1 : 0) };
43
+ const entry = { value: decl.value, prop, important: !!decl.important, at, decl, template };
44
+ const old = entries.get(prop);
45
+ if (!old?.important || entry.important) entries.set(prop, entry);
46
+ if (prop === "background" && (!entries.get("background-color")?.important || entry.important)) entries.delete("background-color");
47
+ if (prop === "background-color" && entries.get("background")?.important && !entry.important) entries.delete("background-color");
48
+ });
49
+ if (!template) { externalStyles ||= !!entries.size || !!reason; return; }
50
+ const fact = { entries, reason }, variants = templates.get(template) ?? new Map();
51
+ variants.set(signature(fact), fact);
52
+ templates.set(template, variants);
53
+ }
54
+ function get(classes) {
55
+ if (memo.has(classes)) return memo.get(classes);
56
+ const entries = new Map();
57
+ let reason = classes.reason ?? (classes.names.some(name => unknownTargets || targetedHooks.has(name)) ? "A named class may be targeted by captured paint selectors." : undefined);
58
+ function merge(fact) {
59
+ reason ??= fact.reason;
60
+ for (const [name, entry] of fact.entries) {
61
+ const old = entries.get(name);
62
+ // Class order does not establish stylesheet order, even across choices.
63
+ if (old && old.value !== entry.value) reason ??= "Composed classes set competing paint declarations.";
64
+ if (name === "background" && entries.has("background-color") || name === "background-color" && entries.has("background"))
65
+ reason ??= "Composed background shorthand and longhand declarations need the rendered cascade.";
66
+ entries.set(name, entry);
67
+ }
68
+ }
69
+ for (const template of classes.templates) {
70
+ const variants = templates.get(template);
71
+ if (!variants) { reason ??= "A style template has no complete captured paint facts."; continue; }
72
+ if (variants.size !== 1) { reason ??= "Interpolated paint alternatives do not establish one definite cascade."; continue; }
73
+ merge(variants.values().next().value);
74
+ }
75
+ for (const choice of classes.choices ?? []) {
76
+ const alternatives = choice.map(get), first = alternatives[0];
77
+ if (!first || alternatives.some(fact => fact.reason || signature(fact) !== signature(first))) {
78
+ reason ??= "Class alternatives do not establish identical paint and visibility.";
79
+ continue;
80
+ }
81
+ merge(first);
82
+ }
83
+ const fact = { entries, reason };
84
+ memo.set(classes, fact);
85
+ return fact;
86
+ }
87
+ return { record, get, get hasColor() { return hasColor; }, get externalStyles() { return externalStyles; } };
88
+ }
@@ -267,9 +267,12 @@ export async function inspectBuildStatus(root, config, { session, previewSession
267
267
  if (session && report.session !== session) report = undefined;
268
268
  }
269
269
  } catch (error) {
270
- reportError = `Invalid preview build status: ${error.message.slice(0, 500)}`;
270
+ // A watcher restart can remove its report between exists/realpath/read.
271
+ // Absence is pending evidence, just as when existsSync returned false;
272
+ // malformed or unsafe reports still fail closed.
273
+ if (error.code !== "ENOENT") reportError = `Invalid preview build status: ${error.message.slice(0, 500)}`;
271
274
  }
272
- let graphError;
275
+ let graphError, verifiedGraph;
273
276
  let sourceRevision, sourceError;
274
277
  if (report?.live || report?.previews.some((entry) => entry.state === "ready")) {
275
278
  try {
@@ -290,7 +293,8 @@ export async function inspectBuildStatus(root, config, { session, previewSession
290
293
  }
291
294
  if (report?.previews.some((entry) => entry.state === "ready")) {
292
295
  try {
293
- if (!readPreviewManifest(options, { verify: "cached" })) throw new Error("Preview resource manifest is missing.");
296
+ verifiedGraph = readPreviewManifest(options, { verify: "cached" });
297
+ if (!verifiedGraph) throw new Error("Preview resource manifest is missing.");
294
298
  } catch (error) {
295
299
  graphError = `Invalid preview resource graph: ${error.message}`;
296
300
  }
@@ -372,6 +376,7 @@ export async function inspectBuildStatus(root, config, { session, previewSession
372
376
  state,
373
377
  reported: Boolean(report),
374
378
  session: report?.session ?? null,
379
+ ...(verifiedGraph && !graphError && verifiedGraph.session === report?.session ? { manifestRevision: verifiedGraph.revision } : {}),
375
380
  sequence: report?.sequence ?? null,
376
381
  updatedAt: report?.updatedAt ?? null,
377
382
  ...(report?.progress ? { progress: report.progress } : {}),
@@ -1049,7 +1049,12 @@ export function createDraftController(directory, { edits, startPreview, prewarm
1049
1049
  async function syncPreviews() {
1050
1050
  const order = [...previews.keys()].sort((a, b) => (b === lastShown) - (a === lastShown));
1051
1051
  for (const id of order) {
1052
- const reason = stale(id, previews.get(id));
1052
+ // Earlier resyncs yield; acceptance, drop or shutdown can retire a later
1053
+ // session while this iteration still holds its original ID list.
1054
+ if (closed) break;
1055
+ const session = previews.get(id);
1056
+ if (!session) continue;
1057
+ const reason = stale(id, session);
1053
1058
  if (!reason) continue;
1054
1059
  if (reason === "own" || id === lastShown) {
1055
1060
  backlog.delete(id);