@reqvire-org/ads 0.3.53 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -8
- package/dist/assets.mjs +1 -1
- package/dist/behaviors.mjs +6 -5
- package/dist/boundaries.mjs +5 -5
- package/dist/browser-audit.mjs +10 -5
- package/dist/bun-compiler.mjs +14 -7
- package/dist/check-service.mjs +83 -0
- package/dist/check.mjs +16 -17
- package/dist/cli.mjs +4 -2
- package/dist/config.mjs +17 -40
- package/dist/contracts.d.mts +9 -0
- package/dist/fonts-generated.mjs +2 -0
- package/dist/generated-entries.mjs +131 -0
- package/dist/icons.mjs +1 -1
- package/dist/init.mjs +11 -32
- package/dist/layers.mjs +7 -3
- package/dist/lint-config.mjs +4 -2
- package/dist/mcp/catalog.mjs +2 -1
- package/dist/mcp/context.mjs +3 -3
- package/dist/mcp/drafts.mjs +136 -121
- package/dist/mcp/mutations.mjs +65 -19
- package/dist/mcp/preview-watch.mjs +31 -5
- package/dist/mcp/prompts.mjs +1 -1
- package/dist/mcp/server.mjs +79 -38
- package/dist/mcp/showcase-host.mjs +20 -7
- package/dist/oxlint.mjs +3 -2
- package/dist/program-cache.mjs +36 -0
- package/dist/public-api.mjs +2 -1
- package/dist/scenarios-compiler.mjs +82 -14
- package/dist/scenarios-vite.mjs +1 -1
- package/dist/scenarios.mjs +4 -3
- package/dist/showcase/client.bundle.js +1 -1
- package/dist/showcase/index.html +2 -2
- package/dist/skills/ads-break-ui/SKILL.md +25 -28
- package/dist/skills/ads-break-ui/references/behaviors.md +7 -6
- package/dist/skills/ads-break-ui/references/captures.md +7 -32
- package/dist/skills/ads-break-ui/references/contracts.md +58 -25
- package/dist/skills/ads-break-ui/references/drafts.md +59 -43
- package/dist/skills/ads-break-ui/references/evidence.md +1 -1
- package/dist/skills/ads-break-ui/references/guarded-editing.md +58 -47
- package/dist/skills/ads-break-ui/references/review.md +9 -8
- package/dist/skills/ads-break-ui/references/scenarios.md +1 -1
- package/dist/skills/ads-break-ui/references/validation.md +8 -4
- package/dist/skills/ads-break-ui/references/workflows.md +15 -8
- package/dist/skills/ads-designer/SKILL.md +25 -28
- package/dist/skills/ads-designer/references/accessibility.md +9 -5
- package/dist/skills/ads-designer/references/behaviors.md +7 -6
- package/dist/skills/ads-designer/references/captures.md +7 -32
- package/dist/skills/ads-designer/references/cli.md +5 -1
- package/dist/skills/ads-designer/references/contracts.md +58 -25
- package/dist/skills/ads-designer/references/drafts.md +59 -43
- package/dist/skills/ads-designer/references/evidence.md +1 -1
- package/dist/skills/ads-designer/references/guarded-editing.md +58 -47
- package/dist/skills/ads-designer/references/performance.md +3 -2
- package/dist/skills/ads-designer/references/review.md +9 -8
- package/dist/skills/ads-designer/references/scenarios.md +1 -1
- package/dist/skills/ads-designer/references/validation.md +8 -4
- package/dist/skills/ads-designer/references/workflows.md +15 -8
- package/dist/skills/ads-import/SKILL.md +25 -28
- package/dist/skills/ads-import/references/behaviors.md +7 -6
- package/dist/skills/ads-import/references/captures.md +7 -32
- package/dist/skills/ads-import/references/cli.md +5 -1
- package/dist/skills/ads-import/references/contracts.md +58 -25
- package/dist/skills/ads-import/references/drafts.md +59 -43
- package/dist/skills/ads-import/references/evidence.md +1 -1
- package/dist/skills/ads-import/references/guarded-editing.md +58 -47
- package/dist/skills/ads-import/references/review.md +9 -8
- package/dist/skills/ads-import/references/scenarios.md +1 -1
- package/dist/skills/ads-import/references/validation.md +8 -4
- package/dist/skills/ads-import/references/workflows.md +15 -8
- package/dist/skills/ads-motion/SKILL.md +25 -28
- package/dist/skills/ads-motion/references/behaviors.md +7 -6
- package/dist/skills/ads-motion/references/captures.md +7 -32
- package/dist/skills/ads-motion/references/contracts.md +58 -25
- package/dist/skills/ads-motion/references/drafts.md +59 -43
- package/dist/skills/ads-motion/references/evidence.md +1 -1
- package/dist/skills/ads-motion/references/guarded-editing.md +58 -47
- package/dist/skills/ads-motion/references/review.md +9 -8
- package/dist/skills/ads-motion/references/scenarios.md +1 -1
- package/dist/skills/ads-motion/references/validation.md +8 -4
- package/dist/skills/ads-motion/references/workflows.md +15 -8
- package/dist/skills/ads-port/SKILL.md +25 -28
- package/dist/skills/ads-port/references/behaviors.md +7 -6
- package/dist/skills/ads-port/references/captures.md +7 -32
- package/dist/skills/ads-port/references/cli.md +5 -1
- package/dist/skills/ads-port/references/contracts.md +58 -25
- package/dist/skills/ads-port/references/drafts.md +59 -43
- package/dist/skills/ads-port/references/evidence.md +1 -1
- package/dist/skills/ads-port/references/guarded-editing.md +58 -47
- package/dist/skills/ads-port/references/native-implementation.md +6 -6
- package/dist/skills/ads-port/references/review.md +9 -8
- package/dist/skills/ads-port/references/scenarios.md +1 -1
- package/dist/skills/ads-port/references/validation.md +8 -4
- package/dist/skills/ads-port/references/workflows.md +15 -8
- package/dist/starters/preact/design-system/components/Layout/Grid/Grid.ads.contract.ts +6 -0
- package/dist/starters/preact/design-system/review/token-preview/TokenPreview.ads.contract.ts +6 -0
- package/dist/starters/preact/ds.config.json +0 -14
- package/dist/starters/react/README.md +9 -5
- package/dist/starters/react/design-system/components/Actions/Button/Button.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Image/Image.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Logo/Logo.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Forms/TextField/TextField.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.contract.ts +6 -0
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/controllers/Palette/Palette.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/index.ts +3 -7
- package/dist/starters/react/design-system/patterns/Search/SearchBar/SearchBar.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/brand-preview/BrandPreview.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/demo-frame/DemoFrame.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/grid-cell/GridCell.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/index.ts +4 -3
- package/dist/starters/react/design-system/review/screen-frame/ScreenFrame.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/token-preview/TokenPreview.ads.contract.ts +6 -0
- package/dist/starters/react/design-system/review/token-preview/TokenPreview.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/styles.css +1 -0
- package/dist/starters/react/ds.config.json +0 -14
- package/dist/style-boundaries.mjs +7 -6
- package/dist/test-boundaries.mjs +2 -2
- package/dist/themes-watch.mjs +9 -3
- package/dist/token-fixtures.mjs +1 -1
- package/dist/unit-contracts.mjs +38 -4
- package/dist/units.mjs +16 -91
- package/dist/validation-checks.mjs +7 -1
- package/docs/ADS.md +10 -10
- package/docs/ARCHITECTURE.md +79 -43
- package/docs/BEHAVIORS.md +8 -7
- package/docs/CACHING.md +15 -6
- package/docs/CHANGELOG.md +61 -12
- package/docs/COMPARISON.md +1 -1
- package/docs/CONTRACTS.md +10 -25
- package/docs/GUIDE.md +64 -55
- package/docs/MCP.md +116 -151
- package/package.json +1 -1
- package/dist/contract-migration.mjs +0 -110
- package/dist/mcp/draft-exports.mjs +0 -40
- package/dist/mcp/edit-preparation.mjs +0 -115
package/README.md
CHANGED
|
@@ -39,8 +39,9 @@ uses Preact. See [implementation support](docs/GUIDE.md#implementation-support).
|
|
|
39
39
|
project-owned scenarios and fixtures.
|
|
40
40
|
- **Edit directly or through MCP**: use your editor with MCP preview/checks, or
|
|
41
41
|
choose MCP-only tracked proposals and acceptance. See [editing access](docs/MCP.md#editing-access-and-compiler-ownership).
|
|
42
|
-
- **Edit with guards**
|
|
43
|
-
|
|
42
|
+
- **Edit with guards** through drafts: one or more owners per draft, acceptance dry
|
|
43
|
+
runs that validate architecture, lint and registered project checks, and a stage
|
|
44
|
+
check that audits everything a series of drafts reached.
|
|
44
45
|
- **Compare visual changes** with on-demand screenshots of current source and
|
|
45
46
|
proposed candidates, exposed as MCP image resources.
|
|
46
47
|
- **Iterate in tracked drafts** without rerunning acceptance checks after every
|
|
@@ -185,12 +186,12 @@ downloads the published package. See the [MCP guide](docs/MCP.md#connect-codex-o
|
|
|
185
186
|
for config files and Claude Desktop setup.
|
|
186
187
|
|
|
187
188
|
To let the agent edit the ADS through enforced checks, append `--mutations` to
|
|
188
|
-
the MCP command.
|
|
189
|
-
fixtures,
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
candidate.
|
|
193
|
-
|
|
189
|
+
the MCP command. Every change is a draft (file contents or a Git patch for its owners,
|
|
190
|
+
including their scenarios and fixtures), reviewed in the showcase and accepted after
|
|
191
|
+
the guards pass. Foundation styles, original assets, guides and project
|
|
192
|
+
configuration/guard extensions have editable units too. Coupled owners share one
|
|
193
|
+
draft, checked as one complete candidate. One runtime and one compiler serve the
|
|
194
|
+
project and all its draft previews. See
|
|
194
195
|
[guarded editing](docs/MCP.md#guarded-editing).
|
|
195
196
|
|
|
196
197
|
The server exposes public components/patterns, token values,
|
package/dist/assets.mjs
CHANGED
|
@@ -20,7 +20,7 @@ function assetFiles(directory, prefix = "") {
|
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
const sourceExtensions = /\.(?:[cm]?[jt]sx?|css|html|svg)$/;
|
|
23
|
-
const previewFile =
|
|
23
|
+
const previewFile = /\.ads\.(?:scenario\.tsx?|fixture\.ts)$/;
|
|
24
24
|
/** Text of the project's own source files, for finding which brand artwork is referenced. */
|
|
25
25
|
function sourceTexts(directories, skipped) {
|
|
26
26
|
const texts = [];
|
package/dist/behaviors.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { existsSync,
|
|
1
|
+
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import ts from "typescript";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
import {
|
|
5
|
+
import { isDevelopmentFile, isInside, sourceFiles, isReviewFile, isTestFile } from "./config.mjs";
|
|
6
6
|
import { importResolver, projectCompilerOptions } from "./boundaries.mjs";
|
|
7
7
|
import { inspectUnits } from "./units.mjs";
|
|
8
|
+
import { cachedProgram } from "./program-cache.mjs";
|
|
8
9
|
import { scenarioApi } from "./public-api.mjs";
|
|
9
10
|
import { inspectScenarios } from "./scenarios.mjs";
|
|
10
11
|
import { uiOperation } from "./ui-framework.mjs";
|
|
@@ -29,9 +30,9 @@ export function inspectBehaviors(options, suppliedProgram, suppliedRegistry) {
|
|
|
29
30
|
const inventory = inspectUnits(options);
|
|
30
31
|
const declarations = inspectUnitContracts(options);
|
|
31
32
|
const typed = declarations.contracts.filter(entry => entry.behavior);
|
|
32
|
-
const files =
|
|
33
|
+
const files = typed.map(entry => path.resolve(root, entry.file));
|
|
33
34
|
if (!files.length) return { contracts: [], diagnostics: [] };
|
|
34
|
-
const program = suppliedProgram ?? declarations.program ??
|
|
35
|
+
const program = suppliedProgram ?? declarations.program ?? cachedProgram(`behaviors:${root}`, sourceFiles(dsRoot).filter(file => /\.[cm]?[jt]sx?$/.test(file)), { ...projectCompilerOptions(options), allowJs: true });
|
|
35
36
|
const checker = program.getTypeChecker();
|
|
36
37
|
const apis = new Map(scenarioApi(program, options).map(item => [item.name, item]));
|
|
37
38
|
const scenarios = (suppliedRegistry ?? inspectScenarios(options, program)).scenarios;
|
|
@@ -42,7 +43,7 @@ export function inspectBehaviors(options, suppliedProgram, suppliedRegistry) {
|
|
|
42
43
|
let value;
|
|
43
44
|
try {
|
|
44
45
|
if (statSync(file).size > 128 * 1024 || realpathSync(file) !== file) throw new Error("Behavior contracts must be regular files of at most 128 KiB.");
|
|
45
|
-
const parsed = behaviorSchema.safeParse(typed.find(entry => path.resolve(root, entry.file) === file)
|
|
46
|
+
const parsed = behaviorSchema.safeParse(typed.find(entry => path.resolve(root, entry.file) === file).behavior);
|
|
46
47
|
if (!parsed.success) throw new Error(parsed.error.issues.slice(0, 5).map(issue => `${issue.path.join(".")}: ${issue.message}`).join("; "));
|
|
47
48
|
value = parsed.data;
|
|
48
49
|
} catch (error) { report(error.message); continue; }
|
package/dist/boundaries.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import ts from "typescript";
|
|
|
4
4
|
import { importedUiName } from "./ui-framework.mjs";
|
|
5
5
|
import { isInside, isStateVariable, isTestFile, isDevelopmentFile } from "./config.mjs";
|
|
6
6
|
import { isSharedToken } from "./token-policy.mjs";
|
|
7
|
-
import { runtimeBindingOwner } from "./unit-contracts.mjs";
|
|
7
|
+
import { ownerStylePolicy, runtimeBindingOwner } from "./unit-contracts.mjs";
|
|
8
8
|
|
|
9
9
|
export function projectCompilerOptions({ root, config, dsRoot }) {
|
|
10
10
|
const file = ts.findConfigFile(root, ts.sys.fileExists, "tsconfig.json");
|
|
@@ -77,7 +77,7 @@ export function checkComponentVariable(name, filename, options) {
|
|
|
77
77
|
if (components) return null;
|
|
78
78
|
if (isStateVariable(name)) return { rule: "primitive-state", message: "Primitive interaction variables belong to components. Add a typed primitive variant instead of overriding state policy." };
|
|
79
79
|
if (tokens) return { rule: "variable-ownership", message: "Component --ds-* variables belong to components, not shared token files." };
|
|
80
|
-
if (!
|
|
80
|
+
if (!ownerStylePolicy(options).componentVariables.includes(name)) return { rule: "component-variable", message: `Undocumented component customization ${name}. The component publishes it in its contract (customization), or use a public prop.` };
|
|
81
81
|
return null;
|
|
82
82
|
}
|
|
83
83
|
|
|
@@ -120,11 +120,11 @@ export function styleAccessProperty(node) {
|
|
|
120
120
|
}
|
|
121
121
|
|
|
122
122
|
// Aliases, computed keys, cssText and bulk writes cannot widen an exception.
|
|
123
|
-
export function styleWriteViolation(node, filename,
|
|
123
|
+
export function styleWriteViolation(node, filename, options) {
|
|
124
124
|
const property = styleAccessProperty(node);
|
|
125
125
|
if (property !== undefined && property !== false && !(property && property !== "css-text"
|
|
126
|
-
&&
|
|
127
|
-
return "Imperative styles require
|
|
126
|
+
&& ownerStylePolicy(options).styleWrites.find((boundary) => path.resolve(options.root, boundary.file) === filename)?.properties?.includes(property))) {
|
|
127
|
+
return "Imperative styles require the owner contract's styles.writes entry for this file and property. Bulk writes, computed property names, and style-object escapes are forbidden.";
|
|
128
128
|
}
|
|
129
129
|
if (ts.isCallExpression(node) && isMember(node.expression) && ["setAttribute", "setAttributeNS"].includes(memberName(node.expression))) {
|
|
130
130
|
const index = memberName(node.expression) === "setAttributeNS" ? 1 : 0;
|
package/dist/browser-audit.mjs
CHANGED
|
@@ -44,7 +44,7 @@ export const containerKinds = Object.freeze(["components", "patterns"]);
|
|
|
44
44
|
/** Attempts for one render, against a dropped preview connection or a slow preview. */
|
|
45
45
|
export const auditAttempts = 3;
|
|
46
46
|
/** overlays and controls bound what each render opens and hovers: distinct ones, in document order. */
|
|
47
|
-
const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024,
|
|
47
|
+
const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024, overlays: 3, controls: 6, contentQuietMs: 500, contentLimitMs: 5000 };
|
|
48
48
|
|
|
49
49
|
/** WCAG success criteria named by axe tags such as wcag143 or wcag1412. */
|
|
50
50
|
export function wcagCriteria(tags) {
|
|
@@ -238,10 +238,15 @@ export function layoutShiftFindings(runs, scenarios) {
|
|
|
238
238
|
* scenario; so does a failure to trace imports. Public/review entry re-exports are bookkeeping
|
|
239
239
|
* for their own units and do not widen the selection.
|
|
240
240
|
*/
|
|
241
|
-
|
|
241
|
+
/** "owners": the changed owners' own scenarios. "affected": every scenario the change reaches. */
|
|
242
|
+
export function auditScenarioSelection(options, changedFiles, { mode = "affected", owners = [] } = {}) {
|
|
242
243
|
const scenarios = inspectScenarios(options).scenarios.filter(scenario => auditedKinds.includes(scenario.kind));
|
|
243
244
|
const all = reason => ({ mode: "all", reason, scenarios: scenarios.map(scenario => scenario.id) });
|
|
244
245
|
const inventory = inspectUnits(options), entries = [inventory.publicEntry, inventory.reviewEntry];
|
|
246
|
+
if (mode === "owners") {
|
|
247
|
+
const changed = new Set([...owners, ...changedFiles.map(file => inventory.owner(inventory.relative(file))).filter(Boolean)]);
|
|
248
|
+
return { mode: "owners", reason: "Owners' own scenarios; the validation stage audits everything they affect.", scenarios: scenarios.filter(scenario => changed.has(inventory.owner(inventory.relative(scenario.file)))).map(scenario => scenario.id) };
|
|
249
|
+
}
|
|
245
250
|
const traced = changedFiles.filter(file => !entries.includes(inventory.relative(file)));
|
|
246
251
|
const shared = traced.find(file => {
|
|
247
252
|
const owner = inventory.owner(inventory.relative(file));
|
|
@@ -301,10 +306,10 @@ async function warmScenariosApart(host, ids, signal) {
|
|
|
301
306
|
|
|
302
307
|
/** One browser process over the given renders. Its report grows as they finish, so a worker that
|
|
303
308
|
* dies keeps what it finished. A browser that is not installed stops the audit. */
|
|
304
|
-
async function runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed }) {
|
|
309
|
+
async function runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed, pages }) {
|
|
305
310
|
const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
|
|
306
311
|
rmSync(report, { force: true });
|
|
307
|
-
writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, overflowWidths, smallPart: smallPartLimitPx, overlayLimit: limits.overlays, stateLimit: limits.controls, contentQuietMs: limits.contentQuietMs, contentLimitMs: limits.contentLimitMs, claimed, tags: auditTags, nodeLimit: limits.nodes, concurrency:
|
|
312
|
+
writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, overflowWidths, smallPart: smallPartLimitPx, overlayLimit: limits.overlays, stateLimit: limits.controls, contentQuietMs: limits.contentQuietMs, contentLimitMs: limits.contentLimitMs, claimed, tags: auditTags, nodeLimit: limits.nodes, concurrency: pages, apps, output: temporary }));
|
|
308
313
|
const timeoutMs = Math.min(30 * 60 * 1000, settings.timeoutMs + apps.length * Math.min(settings.timeoutMs, 15000));
|
|
309
314
|
let cause;
|
|
310
315
|
try {
|
|
@@ -394,7 +399,7 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
|
|
|
394
399
|
if (app.brand) url.searchParams.set("brand", app.brand);
|
|
395
400
|
return { ...app, url: url.href };
|
|
396
401
|
});
|
|
397
|
-
const reached = apps.length ? await runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed: [...renders.values()].flatMap(render => render.result?.coverage?.claimed ?? []) }) : { runs: [], capped: [] };
|
|
402
|
+
const reached = apps.length ? await runAuditWorker({ root, temporary, playwright, settings, apps, signal, pages: options.config.mcp.auditPages, claimed: [...renders.values()].flatMap(render => render.result?.coverage?.claimed ?? []) }) : { runs: [], capped: [] };
|
|
398
403
|
for (const item of reached.capped ?? []) capped.set(item.claim, item);
|
|
399
404
|
for (const run of reached.runs) {
|
|
400
405
|
const render = renders.get(renderKey(run));
|
package/dist/bun-compiler.mjs
CHANGED
|
@@ -7,19 +7,26 @@ import { createBunPreviewBuilder } from "./preview-bun.mjs";
|
|
|
7
7
|
import { checkCandidate } from "./validation-checks.mjs";
|
|
8
8
|
import { renderStoppingRules } from "./finding-rules.mjs";
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
async function validate(){
|
|
10
|
+
const compilerFiles=[import.meta.filename,...["preview-bun.mjs","preview-imports.mjs","bun-worker.mjs"].map(file=>fileURLToPath(new URL(file,import.meta.url)))];
|
|
11
|
+
|
|
12
|
+
function validator(root){
|
|
13
|
+
return async function validate(){
|
|
15
14
|
const result=await checkCandidate(root);
|
|
16
15
|
if(result.ok)return true;
|
|
17
16
|
// A session the audit started renders despite policy errors and reports them; it records no pass.
|
|
18
17
|
const stopping=process.env.ADS_PREVIEW_DESPITE_POLICY==="1"?result.diagnostics.filter(item=>renderStoppingRules.has(item.rule)):result.diagnostics;
|
|
19
18
|
if(stopping.length)throw Object.assign(new Error("ADS project validation failed."),{diagnostics:stopping});
|
|
20
19
|
return false;
|
|
21
|
-
}
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The same ADS-owned Bun compiler serves MCP, standalone builds and CI. */
|
|
24
|
+
export async function compilePreviews(directory=process.cwd(),{watched=false}={}) {
|
|
25
|
+
const root=path.resolve(directory);
|
|
22
26
|
if(!watched){const restored=await restoreCompiledPreviews(withPreviewSession(loadConfig(root),process.env.ADS_MCP_BUILD_SESSION),compilerFiles);if(restored)return restored;}
|
|
23
|
-
|
|
27
|
+
// Each root, the project's and every hosted draft's, gets its own validator and Bun builder.
|
|
28
|
+
const main=await runScenarioCompiler(root,projectRoot=>({watched,compilerFiles,validate:validator(projectRoot),buildGraph:createBunPreviewBuilder()}));
|
|
29
|
+
if(watched)for(const signal of ["SIGINT","SIGTERM"])process.once(signal,()=>main?.stop());
|
|
30
|
+
return main;
|
|
24
31
|
}
|
|
25
32
|
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))await compilePreviews(process.cwd(),{watched:process.argv.includes("--watch")});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { isMainThread, parentPort, Worker, workerData } from "node:worker_threads";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { architectureTaskInputs } from "./task-cache.mjs";
|
|
5
|
+
|
|
6
|
+
// Long-lived ADS processes (the MCP server and its preview compiler) run `ads check` in one warm
|
|
7
|
+
// worker thread instead of a fresh Turbo task per check. The worker keeps its TypeScript programs
|
|
8
|
+
// and parsed files (program-cache.mjs), so a check after an edit reparses only what changed. An
|
|
9
|
+
// exact repeat of the same inputs returns the remembered report. One-shot CLI and CI checks keep
|
|
10
|
+
// the Turbo task and its persistent cache.
|
|
11
|
+
|
|
12
|
+
const hash = value => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
13
|
+
|
|
14
|
+
if (!isMainThread && workerData?.adsCheckService) {
|
|
15
|
+
const { checkProject } = await import("./check.mjs");
|
|
16
|
+
parentPort.on("message", ({ id, root, trackingRoot }) => {
|
|
17
|
+
try { parentPort.postMessage({ id, result: JSON.parse(JSON.stringify(checkProject(root, { trackingRoot }))) }); }
|
|
18
|
+
catch (error) { parentPort.postMessage({ id, error: error.message }); }
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let worker, sequence = 0;
|
|
23
|
+
const pending = new Map(), remembered = new Map(), limit = 16;
|
|
24
|
+
let queue = Promise.resolve();
|
|
25
|
+
|
|
26
|
+
function start() {
|
|
27
|
+
if (worker) return worker;
|
|
28
|
+
worker = new Worker(new URL(import.meta.url), { workerData: { adsCheckService: true } });
|
|
29
|
+
worker.unref();
|
|
30
|
+
const current = worker;
|
|
31
|
+
worker.on("message", ({ id, result, error }) => {
|
|
32
|
+
const task = pending.get(id); pending.delete(id);
|
|
33
|
+
if (task) { if (error) task.reject(new Error(error)); else task.resolve(result); }
|
|
34
|
+
});
|
|
35
|
+
const fail = failure => { if (worker !== current) return; for (const task of pending.values()) task.reject(failure); pending.clear(); worker = undefined; };
|
|
36
|
+
worker.on("error", fail);
|
|
37
|
+
worker.on("exit", code => fail(new Error(`ADS check worker exited (${code}).`)));
|
|
38
|
+
return worker;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function cancelled() { return Object.assign(new Error("Mutation cancelled during validation."), { diagnostic: { rule: "mutation-cancelled", message: "Mutation cancelled during validation." } }); }
|
|
42
|
+
|
|
43
|
+
/** A synchronous check cannot be interrupted inside the thread, so cancelling ends the worker. */
|
|
44
|
+
function run(root, trackingRoot, signal) {
|
|
45
|
+
const id = ++sequence;
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
const abort = () => { if (pending.delete(id)) { reject(cancelled()); void stopWarmChecks(); } };
|
|
48
|
+
pending.set(id, { resolve: value => { signal?.removeEventListener("abort", abort); resolve(value); }, reject: error => { signal?.removeEventListener("abort", abort); reject(error); } });
|
|
49
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
50
|
+
start().postMessage({ id, root, trackingRoot });
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** End the warm worker; the next check starts a fresh one. The server calls this on shutdown. */
|
|
55
|
+
export async function stopWarmChecks() {
|
|
56
|
+
const current = worker; worker = undefined;
|
|
57
|
+
for (const task of pending.values()) task.reject(cancelled()); pending.clear();
|
|
58
|
+
await current?.terminate();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** One check at a time in the warm worker, with the same result shape as the Turbo task. */
|
|
62
|
+
export function warmCheck(root, trackingRoot = root, signal, { fresh = false } = {}) {
|
|
63
|
+
const job = queue.then(async () => {
|
|
64
|
+
if (signal?.aborted) throw cancelled();
|
|
65
|
+
const started = Date.now(), key = hash(architectureTaskInputs(root, trackingRoot));
|
|
66
|
+
if (!fresh && remembered.has(key)) return { ...remembered.get(key), cache: { backend: "warm", task: "architecture", key, status: "hit", elapsedMs: Date.now() - started } };
|
|
67
|
+
const result = await run(root, trackingRoot, signal);
|
|
68
|
+
if (hash(architectureTaskInputs(root, trackingRoot)) !== key) throw Object.assign(new Error("Source, dependencies or Git tracking changed during the ADS task; retry against the current inputs."), { code: "ADS_SOURCE_CHANGED" });
|
|
69
|
+
// Only successful reports are remembered, as with the Turbo task.
|
|
70
|
+
if (result.ok !== false) { remembered.delete(key); remembered.set(key, result); while (remembered.size > limit) remembered.delete(remembered.keys().next().value); }
|
|
71
|
+
return { ...result, cache: { backend: "warm", task: "architecture", key, status: fresh ? "fresh" : "miss", elapsedMs: Date.now() - started } };
|
|
72
|
+
});
|
|
73
|
+
queue = job.catch(() => {});
|
|
74
|
+
return job;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Projects whose checks run warm in this process: the MCP server registers its own root.
|
|
78
|
+
// A separate long-lived process (the preview compiler) opts in through ADS_WARM_CHECKS.
|
|
79
|
+
const warmRoots = new Set();
|
|
80
|
+
export function useWarmChecks(root) { warmRoots.add(path.resolve(root)); }
|
|
81
|
+
export function releaseWarmChecks(root) { warmRoots.delete(path.resolve(root)); if (!warmRoots.size) void stopWarmChecks(); }
|
|
82
|
+
/** Whether checks tracked against this project run in the warm worker. */
|
|
83
|
+
export function warmChecksFor(trackingRoot) { return process.env.ADS_WARM_CHECKS === "1" || warmRoots.has(path.resolve(trackingRoot)); }
|
package/dist/check.mjs
CHANGED
|
@@ -8,14 +8,14 @@ import { inspectTokens, references } from "./tokens.mjs";
|
|
|
8
8
|
import { displaySwitches, generatedPaletteFile, generatedThemeFiles } from "./themes-generated.mjs";
|
|
9
9
|
import { createRenderColorProbe } from "./render-color-probe.mjs";
|
|
10
10
|
import { themeAncestorSelector } from "./themes.mjs";
|
|
11
|
-
import {
|
|
11
|
+
import { isSharedToken } from "./token-policy.mjs";
|
|
12
12
|
import { inspectAssets } from "./assets.mjs";
|
|
13
13
|
import { a11ySourceAdvisories } from "./a11y.mjs";
|
|
14
14
|
import { appImportViolation, showcaseImportViolation, checkComponentVariable, importResolver, projectCompilerOptions, isUiCssProperties, styleWriteViolation } from "./boundaries.mjs";
|
|
15
15
|
import { inspectPublicProps } from "./public-props.mjs";
|
|
16
16
|
import { adsFileRole } from "./config.mjs";
|
|
17
17
|
import { inspectPaintContracts, inspectTokenValueFlows } from "./paint-contracts.mjs";
|
|
18
|
-
import { runtimeBindingOwner } from "./unit-contracts.mjs";
|
|
18
|
+
import { ownerStylePolicy, runtimeBindingOwner } from "./unit-contracts.mjs";
|
|
19
19
|
import { inspectRuntimeContracts } from "./runtime-contracts.mjs";
|
|
20
20
|
import { inspectHtml, isMountCss } from "./html.mjs";
|
|
21
21
|
import { inspectShowcasePages } from "./showcase.mjs";
|
|
@@ -27,6 +27,8 @@ import { inspectBehaviors, inspectControllers } from "./behaviors.mjs";
|
|
|
27
27
|
import { numericCssUnit, tokenLengthLiteral } from "./css-values.mjs";
|
|
28
28
|
import { foundationDeclaration, foundationSelector } from "./foundation.mjs";
|
|
29
29
|
import { inspectUnits } from "./units.mjs";
|
|
30
|
+
import { generatedEntryDiagnostics } from "./generated-entries.mjs";
|
|
31
|
+
import { cachedProgram } from "./program-cache.mjs";
|
|
30
32
|
import { createAtomicCompositionReview } from "./atomic-composition.mjs";
|
|
31
33
|
import { createScenarioTrace } from "./scenario-trace.mjs";
|
|
32
34
|
import { createScenarioSlots } from "./scenario-slots.mjs";
|
|
@@ -46,7 +48,7 @@ import { imageAttributeFindings } from "./image-attributes.mjs";
|
|
|
46
48
|
import { findingSeverity, routeFindings } from "./finding-rules.mjs";
|
|
47
49
|
|
|
48
50
|
const scenarioLayoutGuidance = "Put demo-only sizing and framing in the development-only review/ layer, imported through the separate review entry. Patterns are production UI. Keep required behavior in the runtime owner; add component props for deliberate product API needs.";
|
|
49
|
-
const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve
|
|
51
|
+
const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve the owner contract's styles.inline for documented measured geometry, not demo layout.`;
|
|
50
52
|
|
|
51
53
|
const showcaseControls = new Set(["a", "button", "input", "select", "textarea", "option", "optgroup", "table", "thead", "tbody", "tfoot", "tr", "td", "th", "dialog", "details", "summary", "progress", "meter"]);
|
|
52
54
|
const svgTags = new Set(["svg", "g", "path", "circle", "rect", "ellipse", "line", "polyline", "polygon", "text", "tspan", "use", "defs", "clipPath", "mask", "filter", "linearGradient", "radialGradient", "stop", "marker", "pattern"]);
|
|
@@ -61,6 +63,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
61
63
|
if (!existsSync(file) || (field === "dsDir" ? !statSync(file).isDirectory() : !statSync(file).isFile())) diagnostics.push({ rule: "project-structure", file: path.relative(root, file), line: 1, column: 1, message: `Missing or invalid ${field}. Bootstrap an empty ADS or configure its actual path.` });
|
|
62
64
|
}
|
|
63
65
|
if (diagnostics.length) return architectureEvidence({ ok: false, diagnostics });
|
|
66
|
+
diagnostics.push(...generatedEntryDiagnostics(options, inspectUnits(options)));
|
|
64
67
|
const tokenInventory = inspectTokens(root, options);
|
|
65
68
|
const declaredTokens = new Set(tokenInventory.tokens.map((token) => token.name));
|
|
66
69
|
// Display switches are defined by the generated themes.generated.css, not a token sheet.
|
|
@@ -75,10 +78,11 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
75
78
|
const configurationScripts=new Set((units.units.find(unit=>unit.id==="configuration")?.files??[]).filter(file=>/\.[cm]?[jt]sx?$/.test(file)).map(file=>path.resolve(root,file)).filter(file=>existsSync(file)&&statSync(file).isFile()));
|
|
76
79
|
const rootHtml = path.join(root, "index.html");
|
|
77
80
|
const files = [...new Set([...sourceFiles(sourceRoot), ...sourceFiles(dsRoot), ...configurationScripts, ...(existsSync(rootHtml) ? [rootHtml] : [])])];
|
|
78
|
-
const
|
|
81
|
+
const stylePolicy = ownerStylePolicy(options);
|
|
82
|
+
const boundaryFiles = [...stylePolicy.inlineStyleFiles, ...stylePolicy.styleWrites.map(entry => entry.file)].map(file => path.resolve(root, file)).filter(file => existsSync(file) && statSync(file).isFile());
|
|
79
83
|
const scriptFiles = [...new Set([...layerSourceFiles([...new Set([...files, ...boundaryFiles])].filter((file) => /\.[cm]?[jt]sx?$/.test(file)), options), ...configurationScripts])];
|
|
80
84
|
const compiler = projectCompilerOptions(options);
|
|
81
|
-
const program =
|
|
85
|
+
const program = cachedProgram(`check:${root}`, scriptFiles, { ...compiler, paths: { ...compiler.paths, [config.publicAlias]: [path.join(dsRoot, config.publicEntry)] }, allowJs: true, noResolve: true, noLib: true, types: [], target: ts.ScriptTarget.Latest, module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.Preserve });
|
|
82
86
|
const checker = program.getTypeChecker();
|
|
83
87
|
diagnostics.push(...inspectBehaviorLibraries(options, program).diagnostics);
|
|
84
88
|
const designValues = createDesignValues(program,options);
|
|
@@ -137,13 +141,6 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
137
141
|
}catch(error){report(file,"property-registration",`${error.message} See ads://guides/atomic-styles.`,line,rule.source?.start.column??1);diagnostics.at(-1).guidanceUri="ads://guides/atomic-styles";}
|
|
138
142
|
});
|
|
139
143
|
}
|
|
140
|
-
try {
|
|
141
|
-
const css = postcss.parse(readFileSync(foundationEntry, "utf8"), { from: foundationEntry });
|
|
142
|
-
const imports = css.nodes.filter((node) => node.type !== "comment");
|
|
143
|
-
const expected = foundationFiles.filter((name) => name !== "fonts.css" || existsSync(path.join(dsRoot, config.tokenDir, name))).map((name) => path.join(dsRoot, config.tokenDir, name));
|
|
144
|
-
const actual = imports.map(node => foundationImportTarget(node, foundationEntry));
|
|
145
|
-
if (actual.length !== expected.length || actual.some((file, index) => file !== expected[index] || !existsSync(file))) report(foundationEntry, "styles-entry", "Foundation CSS must import only fonts (when present), colors, typography, spacing, elevation, base and the generated themes.generated.css, in that order.");
|
|
146
|
-
} catch (error) { report(foundationEntry, "css-syntax", error.reason ?? error.message, error.line ?? 1); }
|
|
147
144
|
function checkCss(file, text, offset = { line: 1, column: 1 }, foundation = false) {
|
|
148
145
|
let css;
|
|
149
146
|
try { css = postcss.parse(text, { from: file }); }
|
|
@@ -237,8 +234,8 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
237
234
|
}
|
|
238
235
|
for (const file of files) {
|
|
239
236
|
const role = adsFileRole(file);
|
|
240
|
-
const roleExtension=
|
|
241
|
-
if (role && !configurationScripts.has(file) && (!["contract", "scenario", "fixture", "fixtures", "helpers", "test", "spec", "behavior.spec"].includes(role)||!roleExtension)) report(file, "development-role", `Unknown .ads. role or unsupported extension: ${role}. Use a TypeScript contract, a script scenario/fixture/helpers/test/behavior.spec, or JSON fixture; marking development code does not grant styling or mutation permissions.`);
|
|
237
|
+
const roleExtension=["contract","exports"].includes(role)?/\.[cm]?ts$/.test(file):["fixture","fixtures"].includes(role)?/\.(?:[cm]?[jt]sx?|json)$/.test(file):/\.[cm]?[jt]sx?$/.test(file);
|
|
238
|
+
if (role && !configurationScripts.has(file) && (!["contract", "exports", "scenario", "fixture", "fixtures", "helpers", "test", "spec", "behavior.spec"].includes(role)||!roleExtension)) report(file, "development-role", `Unknown .ads. role or unsupported extension: ${role}. Use a TypeScript contract, a script scenario/fixture/helpers/test/behavior.spec, or JSON fixture; marking development code does not grant styling or mutation permissions.`);
|
|
242
239
|
// The generated theme sheet and palette are checked for freshness with the tokens, not authored.
|
|
243
240
|
if (generatedThemeFiles.some(generated => file === path.join(dsRoot, config.tokenDir, generated))) continue;
|
|
244
241
|
if (file.endsWith(".css") && isInside(path.join(dsRoot, config.tokenDir), file) && !isDevelopmentFile(file, options)) { checkCss(file, readFileSync(file, "utf8"), undefined, true); continue; }
|
|
@@ -257,7 +254,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
257
254
|
const position = source.getLineAndCharacterOfPosition(diagnostic.start ?? 0);
|
|
258
255
|
report(file, "source-syntax", ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"), position.line + 1, position.character + 1);
|
|
259
256
|
}
|
|
260
|
-
const inlineAllowed =
|
|
257
|
+
const inlineAllowed = stylePolicy.inlineStyleFiles.some((allowed) => path.resolve(root, allowed) === file);
|
|
261
258
|
const showcase = isDevelopmentFile(file, options) && !isTestFile(file) && !isReviewFile(file, options);
|
|
262
259
|
function nodeReport(node, rule, message, detail) {
|
|
263
260
|
const position = source.getLineAndCharacterOfPosition(node.getStart(source));
|
|
@@ -312,6 +309,8 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
312
309
|
if (svgPresentation.has(name)) nodeReport(node, "svg-attribute", `Native Preact SVG needs ${name.replace(/[A-Z]/g, letter => "-" + letter.toLowerCase())}; React-style ${name} is not normalized by its native renderer.`);
|
|
313
310
|
}
|
|
314
311
|
const lightDarkLiterals = ["components", "patterns"].some(section => isInside(path.join(dsRoot, section), file)) && !isDevelopmentFile(file, options);
|
|
312
|
+
// Per-file facts, computed once rather than at every syntax node.
|
|
313
|
+
const fileInDs = isInside(dsRoot, file);
|
|
315
314
|
function inLinariaTemplate(node) {
|
|
316
315
|
const template = ts.isTemplateMiddle(node) || ts.isTemplateTail(node) ? node.parent.parent : node.parent;
|
|
317
316
|
const tagged = ts.isTemplateExpression(template) ? template.parent : template;
|
|
@@ -340,11 +339,11 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
340
339
|
if (showcaseControls.has(tag.text) || role && ts.isStringLiteralLike(role) && widgetRoles.has(role.text)) scenarioControl(node, showcaseControls.has(tag.text));
|
|
341
340
|
}
|
|
342
341
|
}
|
|
343
|
-
if (
|
|
342
|
+
if (fileInDs && (ts.isIdentifier(node) && ["fetch", "XMLHttpRequest", "WebSocket", "EventSource"].includes(node.text) && !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node))) {
|
|
344
343
|
const declarations = checker.getSymbolAtLocation(node)?.declarations ?? [];
|
|
345
344
|
if (!declarations.some((declaration) => !declaration.getSourceFile().isDeclarationFile)) nodeReport(node, "data-access", "ADS UI and scenarios receive business data through typed inputs or injected services. Direct network access belongs in an application adapter; fixture services remain local.");
|
|
346
345
|
}
|
|
347
|
-
if (
|
|
346
|
+
if (fileInDs && ts.isPropertyAccessExpression(node) && ["window", "globalThis", "self"].includes(node.expression.getText(source)) && ["fetch", "XMLHttpRequest", "WebSocket", "EventSource"].includes(node.name.text)) nodeReport(node, "data-access", "Inject the data service instead of using a global network API in ADS UI or scenarios.");
|
|
348
347
|
if (showcase && (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) && ts.isIdentifier(node.tagName) && /^[a-z]/.test(node.tagName.text)) {
|
|
349
348
|
const role = node.attributes.properties.find((attr) => ts.isJsxAttribute(attr) && attr.name.text === "role")?.initializer;
|
|
350
349
|
const roleValue = role && ts.isStringLiteralLike(role) ? role.text : role && ts.isJsxExpression(role) && role.expression && ts.isStringLiteralLike(role.expression) ? role.expression.text : null;
|
package/dist/cli.mjs
CHANGED
|
@@ -28,7 +28,8 @@ Usage: ads create <directory> --framework react|preact New design-system proje
|
|
|
28
28
|
--format dtcg prints them as W3C Design Tokens JSON;
|
|
29
29
|
--theme <name> exports that theme's values (default: the first)
|
|
30
30
|
--brand <name> exports that brand's values (default: the first)
|
|
31
|
-
assets [directory] Generate configured brand assets, glyphs, themes.generated.css and .ts
|
|
31
|
+
assets [directory] Generate configured brand assets, glyphs, themes.generated.css and .ts,
|
|
32
|
+
the styles entry, and the public/review barrels from .ads.exports.ts files
|
|
32
33
|
lint-config [dir] Generate .ds/oxlintrc.json with core and project plugins
|
|
33
34
|
mcp [directory] Serve stdio MCP tools/Apps and the local showcase website
|
|
34
35
|
showcase [directory] Serve the built-in MCP client website (no stdio connection)
|
|
@@ -186,7 +187,7 @@ async function main(args) {
|
|
|
186
187
|
}
|
|
187
188
|
else if (command === "tokens" && format === "dtcg") { const { exportTokensDtcg } = await import("./token-export.mjs"); console.log(JSON.stringify(exportTokensDtcg(target, { theme, brand }), null, 2)); return; }
|
|
188
189
|
else if (command === "tokens") result = inspectTokens(target);
|
|
189
|
-
else if (command === "assets") { const { refreshThemesCss } = await import("./themes-watch.mjs"); const themes = refreshThemesCss(target); result = { ...await generateBrandAssets(target), themes: { file: themes.file, written: themes.files[0]?.written ?? false, ...(themes.skipped ? { skipped: themes.skipped } : {}) }, ...(themes.files[1] ? { palette: { file: themes.files[1].file, written: themes.files[1].written }, ...(themes.files[2] ? { fontPreloads: { file: themes.files[2].file, written: themes.files[2].written } } : {}) } : {}) }; }
|
|
190
|
+
else if (command === "assets") { const { refreshThemesCss } = await import("./themes-watch.mjs"); const { writeGeneratedEntries } = await import("./generated-entries.mjs"); const themes = refreshThemesCss(target), barrels = writeGeneratedEntries(loadConfig(target)).files.map(({ file, changed }) => ({ file, written: changed })); result = { ...await generateBrandAssets(target), barrels, themes: { file: themes.file, written: themes.files[0]?.written ?? false, ...(themes.skipped ? { skipped: themes.skipped } : {}) }, ...(themes.files[1] ? { palette: { file: themes.files[1].file, written: themes.files[1].written }, ...(themes.files[2] ? { fontPreloads: { file: themes.files[2].file, written: themes.files[2].written } } : {}) } : {}) }; }
|
|
190
191
|
else if (command === "lint-config") result = generateLintConfig(target);
|
|
191
192
|
else throw new Error(`Unknown command: ${command}. Run ads --help.`);
|
|
192
193
|
// Bun ends a piped stdout at its buffer unless the write is awaited.
|
|
@@ -198,6 +199,7 @@ async function main(args) {
|
|
|
198
199
|
const themesFile = path.relative(process.cwd(), result.themes.file) || result.themes.file;
|
|
199
200
|
console.log(result.themes.skipped ? `Skipped ${themesFile}: the token sheets still use the old theme form.` : `${result.themes.written ? "Wrote" : "Unchanged"} ${themesFile}.`);
|
|
200
201
|
if (result.palette) console.log(`${result.palette.written ? "Wrote" : "Unchanged"} ${path.relative(process.cwd(), result.palette.file) || result.palette.file}.`);
|
|
202
|
+
for (const barrel of result.barrels) console.log(`${barrel.written ? "Wrote" : "Unchanged"} ${path.relative(process.cwd(), barrel.file) || barrel.file}.`);
|
|
201
203
|
if (result.fontPreloads) console.log(`${result.fontPreloads.written ? "Wrote" : "Unchanged"} ${path.relative(process.cwd(), result.fontPreloads.file) || result.fontPreloads.file}.`);
|
|
202
204
|
}
|
|
203
205
|
else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
|
package/dist/config.mjs
CHANGED
|
@@ -3,7 +3,6 @@ import path from "node:path";
|
|
|
3
3
|
import { hasProjectConfig } from "./project-boundary.mjs";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { isDraftFile, draftImportViolation } from "./draft-boundary.mjs";
|
|
6
|
-
import { isSharedToken } from "./token-policy.mjs";
|
|
7
6
|
import { defaultThemes, validateThemes } from "./themes.mjs";
|
|
8
7
|
import { validateBrands } from "./brands.mjs";
|
|
9
8
|
|
|
@@ -26,16 +25,14 @@ export const defaultConfig = {
|
|
|
26
25
|
brands: [],
|
|
27
26
|
// With no data-theme on the root, the OS color scheme picks the first theme of that scheme.
|
|
28
27
|
followSystemTheme: false,
|
|
29
|
-
inlineStyleFiles: [],
|
|
30
|
-
boundaries: { styleWrites: [], componentVariables: [] },
|
|
31
28
|
assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null, targets: [], glyphs: null, imageBudgetKb: null, fontBudgetKb: null, preloadFonts: null },
|
|
32
29
|
oxlint: { plugins: [], rules: {}, overrides: [] },
|
|
33
|
-
acceptance: { checks: [], behaviorChecks: false, browserAudit:
|
|
30
|
+
acceptance: { checks: [], behaviorChecks: false, browserAudit: "owners" },
|
|
34
31
|
validation: { checks: [], behaviorChecks: true, browserAudit: true, inputs: [] },
|
|
35
32
|
resources: { memoryLimitMb: null },
|
|
36
33
|
// Width tokens and owners allowed fixed widths; see src/layout-widths.mjs.
|
|
37
34
|
layout: { widthTokens: [], fixedWidthUnits: [] },
|
|
38
|
-
mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {}, resultRetention: {maxRuns:50,maxAgeDays:7,maxBytesMb:256} },
|
|
35
|
+
mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationCheckTimeoutMs: 60000, previewBuildTimeoutMs: 300000, auditPages: 4, behaviorProfiles: {}, capture: {}, resultRetention: {maxRuns:50,maxAgeDays:7,maxBytesMb:256} },
|
|
39
36
|
};
|
|
40
37
|
|
|
41
38
|
export function isInside(parent, file) {
|
|
@@ -115,12 +112,11 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
115
112
|
if (!(field in defaultConfig)) throw new Error(`Unknown ADS configuration field: ${field}`);
|
|
116
113
|
}
|
|
117
114
|
if (user.oxlint !== undefined && (!user.oxlint || typeof user.oxlint !== "object" || Array.isArray(user.oxlint))) throw new Error("oxlint must be an object.");
|
|
118
|
-
|
|
119
|
-
for (const field of ["boundaries", "assets", "oxlint", "mcp", "acceptance", "validation", "usage", "resources", "layout"]) {
|
|
115
|
+
for (const field of ["assets", "oxlint", "mcp", "acceptance", "validation", "usage", "resources", "layout"]) {
|
|
120
116
|
if (user[field] !== undefined && (!user[field] || typeof user[field] !== "object" || Array.isArray(user[field]))) throw new Error(`${field} must be an object.`);
|
|
121
117
|
for (const key of Object.keys(user[field] ?? {})) if (!(key in defaultConfig[field])) throw new Error(`Unknown ${field} configuration field: ${key}`);
|
|
122
118
|
}
|
|
123
|
-
const config = { ...defaultConfig, ...user,
|
|
119
|
+
const config = { ...defaultConfig, ...user, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, acceptance: { ...defaultConfig.acceptance, ...user.acceptance }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp }, usage: { ...defaultConfig.usage, ...user.usage }, resources: { ...defaultConfig.resources, ...user.resources }, layout: { ...defaultConfig.layout, ...user.layout } };
|
|
124
120
|
validateThemes(config.themes);
|
|
125
121
|
validateBrands(config.brands);
|
|
126
122
|
if (typeof config.followSystemTheme !== "boolean") throw new Error("followSystemTheme must be true or false.");
|
|
@@ -152,7 +148,8 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
152
148
|
const policy=config[name];
|
|
153
149
|
if (!Array.isArray(policy.checks) || policy.checks.length>20 || new Set(policy.checks).size!==policy.checks.length || policy.checks.some(script=>typeof script!=="string" || !/^[a-zA-Z0-9][\w:.-]*$/.test(script))) throw new Error(`${name}.checks must contain up to 20 unique package script names.`);
|
|
154
150
|
if(typeof policy.behaviorChecks!=="boolean")throw new Error(`${name}.behaviorChecks must be a boolean.`);
|
|
155
|
-
|
|
151
|
+
// Acceptance audits the draft's own owners, or everything they affect; the validation stage audits fully.
|
|
152
|
+
if(name==="acceptance"?!["owners","affected",false].includes(policy.browserAudit):typeof policy.browserAudit!=="boolean")throw new Error(name==="acceptance"?'acceptance.browserAudit must be "owners" (the draft owners\' own scenarios), "affected" (every scenario they reach) or false.':`${name}.browserAudit must be a boolean.`);
|
|
156
153
|
}
|
|
157
154
|
if (!Array.isArray(config.validation.inputs) || config.validation.inputs.length > 200 || new Set(config.validation.inputs).size !== config.validation.inputs.length) throw new Error("validation.inputs must contain at most 200 unique project-relative files or directories.");
|
|
158
155
|
for (const file of config.validation.inputs) {
|
|
@@ -165,22 +162,10 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
165
162
|
|| new Set(config.behaviorLibraries).size !== config.behaviorLibraries.length
|
|
166
163
|
|| config.behaviorLibraries.some(name => typeof name !== "string" || name.length > 214 || !/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/.test(name))) throw new Error("behaviorLibraries must contain up to 100 unique npm package names, without versions, subpaths or wildcards.");
|
|
167
164
|
if (typeof config.publicAlias !== "string" || !config.publicAlias.trim()) throw new Error("publicAlias must be a non-empty string.");
|
|
168
|
-
if (!Array.isArray(config.inlineStyleFiles)) throw new Error("inlineStyleFiles must be an array of relative paths.");
|
|
169
165
|
const sourceRoot = projectPath(root, config.sourceDir, "sourceDir");
|
|
170
166
|
const dsRoot = projectPath(root, config.dsDir, "dsDir");
|
|
171
167
|
for (const field of ["publicEntry", "reviewEntry", "stylesEntry", "tokenDir"]) projectPath(dsRoot, config[field], field);
|
|
172
168
|
if (!isInside(path.join(dsRoot, "review"), path.resolve(dsRoot, config.reviewEntry)) || path.resolve(dsRoot, config.reviewEntry) === path.join(dsRoot, "review") || !/\.[cm]?[jt]sx?$/.test(config.reviewEntry)) throw new Error("reviewEntry must name a script entry inside the ADS review/ development layer.");
|
|
173
|
-
for (const file of config.inlineStyleFiles) projectPath(root, file, "inlineStyleFiles");
|
|
174
|
-
if (!Array.isArray(config.boundaries.componentVariables) || config.boundaries.componentVariables.some((name) => typeof name !== "string" || !/^--ds-[\w-]+$/.test(name) || isStateVariable(name))) throw new Error("boundaries.componentVariables must name non-state --ds-* customization variables.");
|
|
175
|
-
if (!Array.isArray(config.boundaries.styleWrites)) throw new Error("boundaries.styleWrites must be an array.");
|
|
176
|
-
const boundaryFiles = new Set();
|
|
177
|
-
for (const boundary of config.boundaries.styleWrites) {
|
|
178
|
-
if (!boundary || typeof boundary !== "object" || Array.isArray(boundary) || Object.keys(boundary).some((key) => !["file", "properties"].includes(key))) throw new Error("Each styleWrites boundary requires file and properties.");
|
|
179
|
-
const file = projectPath(root, boundary.file, "boundaries.styleWrites.file");
|
|
180
|
-
if (boundaryFiles.has(file)) throw new Error("Duplicate styleWrites file boundary.");
|
|
181
|
-
boundaryFiles.add(file);
|
|
182
|
-
if (!Array.isArray(boundary.properties) || !boundary.properties.length || boundary.properties.some((name) => typeof name !== "string" || !/^(?:--[\w-]+|[a-z][a-z0-9-]*)$/.test(name) || name === "css-text" || isStateVariable(name) || isSharedToken(name) || name.startsWith("--") && !/^(?:--ds-|--ux-|--showcase-)/.test(name))) throw new Error("styleWrites.properties must name explicit CSS properties; bulk cssText, shared tokens, foreign prefixes, and primitive-state writes cannot be allowed.");
|
|
183
|
-
}
|
|
184
169
|
for (const field of ["publicDirs", "generatedPaths", "generatedFiles"]) {
|
|
185
170
|
if (!Array.isArray(config.assets[field])) throw new Error(`assets.${field} must be an array.`);
|
|
186
171
|
for (const entry of config.assets[field]) {
|
|
@@ -238,6 +223,8 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
238
223
|
if(!config.mcp.resultRetention || typeof config.mcp.resultRetention!=="object" || Array.isArray(config.mcp.resultRetention) || Object.keys(config.mcp.resultRetention).some(key=>!["maxRuns","maxAgeDays","maxBytesMb"].includes(key)) || !Number.isInteger(retention.maxRuns) || retention.maxRuns<1 || retention.maxRuns>1000 || !Number.isInteger(retention.maxAgeDays) || retention.maxAgeDays<1 || retention.maxAgeDays>365 || !Number.isInteger(retention.maxBytesMb) || retention.maxBytesMb<8 || retention.maxBytesMb>16384)throw new Error("mcp.resultRetention requires maxRuns (1–1000), maxAgeDays (1–365), maxBytesMb (8–16384).");
|
|
239
224
|
config.mcp.resultRetention=retention;
|
|
240
225
|
if (!Number.isInteger(config.mcp.mutationCheckTimeoutMs) || config.mcp.mutationCheckTimeoutMs < 100 || config.mcp.mutationCheckTimeoutMs > 300000) throw new Error("mcp.mutationCheckTimeoutMs must be an integer from 100 to 300000. This budget applies to each registered project script, separately from behavior profiles.");
|
|
226
|
+
if (!Number.isInteger(config.mcp.auditPages) || config.mcp.auditPages < 1 || config.mcp.auditPages > 16) throw new Error("mcp.auditPages must be an integer from 1 to 16: how many pages the browser audit renders at once.");
|
|
227
|
+
if (!Number.isInteger(config.mcp.previewBuildTimeoutMs) || config.mcp.previewBuildTimeoutMs < 1000 || config.mcp.previewBuildTimeoutMs > 3600000) throw new Error("mcp.previewBuildTimeoutMs must be an integer from 1000 to 3600000. It is how long a preview waits for its build, including the first build after the MCP server starts.");
|
|
241
228
|
if (config.mcp.previewManifest !== null) {
|
|
242
229
|
const manifest = projectPath(root, config.mcp.previewManifest, "mcp.previewManifest");
|
|
243
230
|
if (!isInside(path.join(root, ".ds"), manifest) || path.extname(manifest) !== ".json") throw new Error("mcp.previewManifest must name a generated JSON manifest inside .ds/.");
|
|
@@ -268,19 +255,11 @@ export function isTestFile(file) {
|
|
|
268
255
|
}
|
|
269
256
|
|
|
270
257
|
export function isScenarioFile(file) {
|
|
271
|
-
return
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
export function isFixtureFile(file) {
|
|
275
|
-
return /(?:^|[\\/])fixtures?\.(?:[cm]?[jt]sx?|json)$/.test(file) || /\.fixtures?\.(?:[cm]?[jt]sx?|json)$/.test(file);
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/** File role, rather than folder location, keeps colocated preview code private. */
|
|
279
|
-
export function isBehaviorFile(file) {
|
|
280
|
-
return /(?:^|[\\/])behavior\.json$|\.behavior\.json$/.test(file);
|
|
258
|
+
return /\.ads\.scenario\.[cm]?[jt]sx?$/.test(file);
|
|
281
259
|
}
|
|
282
260
|
|
|
283
|
-
/** A visible development boundary, independent of whether its role is supported.
|
|
261
|
+
/** A visible development boundary, independent of whether its role is supported.
|
|
262
|
+
* File role, rather than folder location, keeps colocated development code private. */
|
|
284
263
|
export function adsFileRole(file) {
|
|
285
264
|
const match = path.basename(file).match(/\.ads\.(.+)\.[^.]+$/);
|
|
286
265
|
return match ? match[1] : null;
|
|
@@ -290,9 +269,9 @@ export function isContractFile(file) {
|
|
|
290
269
|
return /\.ads\.contract\.[cm]?ts$/.test(file);
|
|
291
270
|
}
|
|
292
271
|
|
|
293
|
-
/**
|
|
272
|
+
/** The ADS-relative path without `.ads.scenario.*`; a canonical `<Dir>/<Dir>.ads.scenario.*` identifies the directory. */
|
|
294
273
|
export function scenarioIdentity(file, dsRoot) {
|
|
295
|
-
let id = path.relative(dsRoot, file).replaceAll("\\", "/").replace(/\.ads
|
|
274
|
+
let id = path.relative(dsRoot, file).replaceAll("\\", "/").replace(/\.ads\.scenario\.[^.]+$/, "");
|
|
296
275
|
if (adsFileRole(file) === "scenario" && path.posix.basename(id) === path.posix.basename(path.posix.dirname(id))) id = path.posix.dirname(id);
|
|
297
276
|
return id;
|
|
298
277
|
}
|
|
@@ -301,15 +280,13 @@ export function isDevelopmentFile(file, { dsRoot }) {
|
|
|
301
280
|
if (isDraftFile(file)) return true;
|
|
302
281
|
if (!isInside(dsRoot, file)) return isTestFile(file) || adsFileRole(file) !== null;
|
|
303
282
|
const relative = path.relative(dsRoot, file).replaceAll("\\", "/");
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|| /(?:^|\/)(?:scenario|fixtures)(?:\/|$)/.test(relative)
|
|
307
|
-
|| /\.scenario(?:-adapter)?\.[cm]?[jt]sx?$/.test(relative);
|
|
283
|
+
// An exports file belongs to its owner's layer: production for the public barrel, development under review/.
|
|
284
|
+
return adsFileRole(file) !== null && adsFileRole(file) !== "exports" || isTestFile(file) || /^(?:showcase|composition|review|brand)\//.test(relative);
|
|
308
285
|
}
|
|
309
286
|
|
|
310
287
|
/** Review implementations may own demo presentation; scenarios/fixtures may not. */
|
|
311
288
|
export function isReviewFile(file, { dsRoot }) {
|
|
312
|
-
return !isDraftFile(file) && isInside(path.join(dsRoot, "review"), file) && adsFileRole(file) === null && !isTestFile(file)
|
|
289
|
+
return !isDraftFile(file) && isInside(path.join(dsRoot, "review"), file) && adsFileRole(file) === null && !isTestFile(file);
|
|
313
290
|
}
|
|
314
291
|
|
|
315
292
|
const ignored = new Set(["node_modules", "dist", "dist-showcase", "dist-kit", ".git", ".vite", ".ds", "coverage"]);
|
|
@@ -321,7 +298,7 @@ export function sourceFiles(root) {
|
|
|
321
298
|
if (ignored.has(entry.name) || entry.isSymbolicLink() || isDraftFile(path.join(root, entry.name))) continue;
|
|
322
299
|
const file = path.join(root, entry.name);
|
|
323
300
|
if (entry.isDirectory()) { if (!hasProjectConfig(file)) files.push(...sourceFiles(file)); }
|
|
324
|
-
else if (entry.isFile() &&
|
|
301
|
+
else if (entry.isFile() && /\.(css|html|[cm]?[jt]sx?)$/.test(entry.name)) files.push(file);
|
|
325
302
|
}
|
|
326
303
|
return files.sort();
|
|
327
304
|
}
|
package/dist/contracts.d.mts
CHANGED
|
@@ -3,6 +3,15 @@ export type Implementation = ((...args: never[]) => unknown) | (abstract new (..
|
|
|
3
3
|
export interface BehaviorCheck { file: string; case: string; scenario?: string; profile: string; }
|
|
4
4
|
export interface UnitContract {
|
|
5
5
|
schemaVersion: 1;
|
|
6
|
+
/** The owner's own style permissions, by file path relative to this contract. */
|
|
7
|
+
styles?: {
|
|
8
|
+
/** CSS properties or owned --ds-/--ux-/--showcase- variables a file writes at runtime. */
|
|
9
|
+
writes?: Readonly<Record<string, readonly string[]>>;
|
|
10
|
+
/** Files that may use inline JSX/factory styles. */
|
|
11
|
+
inline?: readonly string[];
|
|
12
|
+
};
|
|
13
|
+
/** A component's --ds-* variables that patterns, the showcase and the application may set. */
|
|
14
|
+
customization?: readonly string[];
|
|
6
15
|
paintInputs?: readonly { api: Implementation; property: string; kind: "paint-reference"; bindings?: readonly string[] }[];
|
|
7
16
|
bindings?: Readonly<Record<string, {
|
|
8
17
|
input: { api: Implementation; property: string };
|