@reqvire-org/ads 0.3.36 → 0.3.37

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 (83) hide show
  1. package/README.md +10 -8
  2. package/dist/bootstrap-ds/README.md +8 -9
  3. package/dist/bootstrap-ds/ds.config.json +1 -8
  4. package/dist/bootstrap-ds/package.json +4 -3
  5. package/dist/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
  6. package/dist/bun-compiler.mjs +13 -0
  7. package/dist/bun-worker.mjs +9 -0
  8. package/dist/check.mjs +7 -4
  9. package/dist/cli.mjs +11 -7
  10. package/dist/config.mjs +22 -4
  11. package/dist/development-runtime.mjs +3 -1
  12. package/dist/init.mjs +16 -18
  13. package/dist/mcp/build-status.mjs +6 -4
  14. package/dist/mcp/context.mjs +9 -4
  15. package/dist/mcp/drafts.mjs +4 -2
  16. package/dist/mcp/mutations.mjs +4 -14
  17. package/dist/mcp/preview-watch.mjs +21 -9
  18. package/dist/mcp/preview-widget.bundle.js +58 -63
  19. package/dist/mcp/preview-work.mjs +1 -15
  20. package/dist/mcp/project-widget.bundle.js +57 -62
  21. package/dist/mcp/prompts.mjs +2 -2
  22. package/dist/mcp/resource-loader.js +32 -10
  23. package/dist/mcp/server.mjs +89 -34
  24. package/dist/mcp/widget.bundle.js +59 -64
  25. package/dist/preview-builder.mjs +17 -5
  26. package/dist/preview-bun.mjs +266 -0
  27. package/dist/preview-imports.mjs +73 -0
  28. package/dist/preview-resources.mjs +26 -14
  29. package/dist/scenario-inspector.mjs +11 -4
  30. package/dist/scenarios-compiler.mjs +47 -6
  31. package/dist/showcase/client.bundle.js +68 -72
  32. package/dist/showcase/index.html +2 -2
  33. package/dist/showcase/sandbox.bundle.js +1 -1
  34. package/dist/showcase/style.css +4 -0
  35. package/dist/skills/ads-break-ui/SKILL.md +39 -40
  36. package/dist/skills/ads-break-ui/references/drafts.md +6 -3
  37. package/dist/skills/ads-break-ui/references/guarded-editing.md +4 -3
  38. package/dist/skills/ads-break-ui/references/runtimes.md +91 -140
  39. package/dist/skills/ads-break-ui/references/validation.md +13 -3
  40. package/dist/skills/ads-break-ui/references/workflows.md +82 -0
  41. package/dist/skills/ads-designer/SKILL.md +38 -39
  42. package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +8 -9
  43. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -8
  44. package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +4 -3
  45. package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
  46. package/dist/skills/ads-designer/references/cli.md +24 -20
  47. package/dist/skills/ads-designer/references/drafts.md +6 -3
  48. package/dist/skills/ads-designer/references/guarded-editing.md +4 -3
  49. package/dist/skills/ads-designer/references/runtimes.md +91 -140
  50. package/dist/skills/ads-designer/references/validation.md +13 -3
  51. package/dist/skills/ads-designer/references/workflows.md +82 -0
  52. package/dist/skills/ads-import/SKILL.md +40 -42
  53. package/dist/skills/ads-import/references/cli.md +24 -20
  54. package/dist/skills/ads-import/references/drafts.md +6 -3
  55. package/dist/skills/ads-import/references/guarded-editing.md +4 -3
  56. package/dist/skills/ads-import/references/runtimes.md +91 -140
  57. package/dist/skills/ads-import/references/validation.md +13 -3
  58. package/dist/skills/ads-import/references/workflows.md +82 -0
  59. package/dist/skills/ads-motion/SKILL.md +37 -38
  60. package/dist/skills/ads-motion/references/drafts.md +6 -3
  61. package/dist/skills/ads-motion/references/guarded-editing.md +4 -3
  62. package/dist/skills/ads-motion/references/runtimes.md +91 -140
  63. package/dist/skills/ads-motion/references/validation.md +13 -3
  64. package/dist/skills/ads-motion/references/workflows.md +82 -0
  65. package/dist/skills/ads-port/SKILL.md +37 -38
  66. package/dist/skills/ads-port/references/cli.md +24 -20
  67. package/dist/skills/ads-port/references/drafts.md +6 -3
  68. package/dist/skills/ads-port/references/guarded-editing.md +4 -3
  69. package/dist/skills/ads-port/references/runtimes.md +91 -140
  70. package/dist/skills/ads-port/references/validation.md +13 -3
  71. package/dist/skills/ads-port/references/workflows.md +82 -0
  72. package/dist/usage.mjs +84 -0
  73. package/dist/validation.mjs +0 -12
  74. package/dist/verification/browser.mjs +77 -48
  75. package/docs/ADS.md +17 -11
  76. package/docs/ARCHITECTURE.md +43 -29
  77. package/docs/BEHAVIORS.md +3 -3
  78. package/docs/CHANGELOG.md +60 -12
  79. package/docs/GUIDE.md +96 -53
  80. package/docs/MCP.md +96 -122
  81. package/docs/benchmarks/bun-previews.md +91 -0
  82. package/docs/benchmarks/gidi-preview-memory.md +4 -0
  83. package/package.json +15 -13
package/README.md CHANGED
@@ -33,6 +33,8 @@ uses Preact. See [implementation support](docs/GUIDE.md#implementation-support).
33
33
  through focused MCP tools.
34
34
  - **Preview** real UI through MCP Apps and the local showcase, using the same
35
35
  project-owned scenarios and fixtures.
36
+ - **Edit directly or through MCP**: use your editor with MCP preview/checks, or
37
+ choose MCP-only tracked proposals and acceptance. See [editing workflows](skills/ads-designer/references/workflows.md).
36
38
  - **Edit with guards** using owner patches, coupled transactions and isolated
37
39
  dry runs that validate architecture, lint and registered project checks.
38
40
  - **Compare visual changes** with on-demand screenshots of current source and
@@ -61,7 +63,8 @@ Drafts survive restart and Git clone, but cannot enter production imports.
61
63
 
62
64
  ## Set up your project
63
65
 
64
- Run **inside your project**, where `package.json` lives. Use Node 22.12+ or Bun 1.3.13+.
66
+ Run **inside your project**, where `package.json` lives. Install Bun 1.3.13+ for
67
+ ADS tooling and previews. Your application can continue using Node/npm or Bun.
65
68
 
66
69
  ```sh
67
70
  npx @reqvire-org/ads init --framework react
@@ -76,18 +79,16 @@ already declares its framework can also omit the flag.
76
79
  For a Bun project, Node is unnecessary:
77
80
 
78
81
  ```sh
79
- bunx --bun @reqvire-org/ads init --framework react
82
+ bunx @reqvire-org/ads init --framework react
80
83
  bun install
81
84
  bun --bun run build
82
85
  ```
83
86
 
84
87
  `--bun` keeps package executables on Bun even when they have a Node shebang.
85
- `init` detects npm or Bun from your project. It adds ADS and Oxlint as development
86
- dependencies, sets up an empty local ADS if needed, and adds ADS checks before your
88
+ `init` detects npm or Bun from your project. It adds ADS as a development dependency, sets up an empty local ADS if needed, and adds ADS checks before your
87
89
  existing build. The default layout is root `design-system/`, alongside `src/`.
88
- It keeps your app, token values, scripts, and lockfile. Each build
89
- refreshes lint configuration and checks tokens, styles, imports, renderer
90
- boundaries, asset ownership, and registered component rules, then generates
90
+ It keeps your app, token values, scripts, and lockfile. Each build runs native ADS gates for tokens, styles, imports, renderer
91
+ boundaries and asset ownership, then generates
91
92
  configured brand icons. Commit the updated
92
93
  lockfile; generated `.ds/` files are ignored. Init does not install or configure
93
94
  Linaria; integrate its extraction with your build as described in the
@@ -99,11 +100,12 @@ Linaria; integrate its extraction with your build as described in the
99
100
  |---------|-----|
100
101
  | `ads init --framework react` | Set up ADS in the current project; also accepts `preact`; saved choices can omit the flag |
101
102
  | `ads check` | Check tokens, styles, imports, and ADS ownership |
103
+ | `ads compile` | Compile all previews with Bun; `--watch` rebuilds on edits |
102
104
  | `ads tokens` | Inspect token values and themes |
103
105
  | `ads behaviors` | Inspect registered behavior guarantees and current evidence |
104
106
  | `ads verify --unit <id>` | Run an owner's registered behavior checks |
105
107
  | `ads assets` | Generate standard web icons from the project's SVG |
106
- | `ads lint-config` | Generate lint config; normally called by the build |
108
+ | `ads lint-config` | Optional integration with an explicitly configured project linter |
107
109
  | `ads mcp` | Start the stdio MCP server and its local showcase |
108
110
  | `ads showcase` | Start the same MCP runtime for browser-only inspection |
109
111
 
@@ -12,8 +12,8 @@ Read the local [contract](ADS.md) and the
12
12
 
13
13
  Copy the contents of `bootstrap-ds/`, including dotfiles, into a new project.
14
14
  The installed `ads-designer` skill contains the same files in
15
- `assets/bootstrap-ds/`. Set the project name in `package.json`. Use Node 22.12+
16
- or Bun 1.3.13+ with a current ADS release.
15
+ `assets/bootstrap-ds/`. Set the project name in `package.json`. Install Bun 1.3.13+ for ADS tooling and previews. The application can keep its
16
+ Node/npm build pipeline. Use a current ADS release.
17
17
 
18
18
  ```sh
19
19
  npx @reqvire-org/ads init --framework react
@@ -33,11 +33,10 @@ npm run build
33
33
 
34
34
  For a new Bun workspace, declare Bun in `packageManager`, omit the copied npm
35
35
  lockfile and translate nested npm scripts to `bun --bun run`. Initialize with
36
- `bunx --bun @reqvire-org/ads init`. Init detects existing
36
+ `bunx @reqvire-org/ads init`. Init detects existing
37
37
  Bun projects and preserves their scripts/lockfiles. Use `bun install` and
38
38
  `bun --bun run build`/`bun --bun run dev:showcase`. Node is unnecessary with Bun
39
- 1.3.13+. The supplied preview watcher's `command: "runtime"` inherits the
40
- interpreter that launched ADS and runs the project's installed checks.
39
+ 1.3.13+. ADS supplies its Bun preview compiler independently of the project build.
41
40
 
42
41
  For an existing application, merge only the ADS source and required extraction,
43
42
  aliases and preview adapter. Preserve its framework, entry points and build.
@@ -76,13 +75,13 @@ scenarios live under `composition/`. Each entry mounts independently with its
76
75
  fixture inputs and state/callback adapter. Use public ADS APIs and owned Linaria
77
76
  styles, keeping business data/services in the application.
78
77
 
79
- `ds.config.json` configures the supplied Vite watcher. It builds all discovered
80
- scenarios into one shared resource graph on first demand and watches owner code,
78
+ `ds.config.json` selects ADS's native Bun compiler. MCP prewarms discovered
79
+ views sequentially, prioritizes foreground selections, and watches owner code,
81
80
  styles, fixtures and assets. The App loads the selected dependency closure and
82
81
  reuses unchanged runtime/CSS/font resources across selections. The MCP client
83
82
  refreshes successful revisions inside that App; failures show diagnostics and
84
- stale retained output. Switching or rebuilding a scenario unmounts its previous
85
- state. `showcase/mcp/main.tsx` exports `mountScenario(Scenario, container)` and
83
+ stale retained output. Changing a selected view's dependency closure unmounts its previous state;
84
+ background warming retains unchanged mounted views. `showcase/mcp/main.tsx` exports `mountScenario(Scenario, container)` and
86
85
  returns an unmount callback; it is not the shell. Keep the saved `framework`,
87
86
  compiler and mount adapter consistent.
88
87
  Managed sessions own their graph output; standalone prebuilds cannot replace it.
@@ -2,14 +2,7 @@
2
2
  "framework": "react",
3
3
  "behaviorLibraries": [],
4
4
  "mcp": {
5
- "previewManifest": ".ds/preview/manifest.json",
6
- "previewWatch": {
7
- "command": "runtime",
8
- "args": [
9
- "scripts/build-mcp-previews.mjs",
10
- "--watch"
11
- ]
12
- }
5
+ "previewManifest": ".ds/preview/manifest.json"
13
6
  },
14
7
  "boundaries": {
15
8
  "styleWrites": [
@@ -5,7 +5,8 @@
5
5
  "type": "module",
6
6
  "description": "Private starter workspace for a project's local React design system.",
7
7
  "engines": {
8
- "node": ">=22.12.0"
8
+ "node": ">=22.12.0",
9
+ "bun": ">=1.3.13"
9
10
  },
10
11
  "sideEffects": [
11
12
  "**/*.css"
@@ -17,10 +18,10 @@
17
18
  "typecheck": "tsc --noEmit",
18
19
  "build": "npm run lint && npm run typecheck && npm run build:lib",
19
20
  "build:lib": "vite build && tsc --project tsconfig.build.json",
20
- "build:showcase": "node scripts/build-mcp-previews.mjs",
21
+ "build:showcase": "ads compile .",
21
22
  "preview": "ads showcase",
22
23
  "preview:showcase": "ads showcase",
23
- "build:mcp-previews": "node scripts/build-mcp-previews.mjs"
24
+ "build:mcp-previews": "ads compile ."
24
25
  },
25
26
  "devDependencies": {
26
27
  "@biomejs/biome": "2.5.15",
@@ -1,33 +1,3 @@
1
- import path from "node:path";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { execFile } from "node:child_process";
4
- import { promisify } from "node:util";
5
- import { build } from "vite";
6
- import wyw from "@wyw-in-js/vite";
7
- import { linariaTagResolver } from "@reqvire-org/ads/linaria";
8
- import react from "@vitejs/plugin-react";
9
- import { runScenarioCompiler } from "@reqvire-org/ads/scenarios/compiler";
10
- import { createVitePreviewBuilder, previewEntriesPlugin } from "@reqvire-org/ads/scenarios/vite";
1
+ import { compilePreviews } from "@reqvire-org/ads/scenarios/compile";
11
2
 
12
- const root = path.resolve(import.meta.dirname, "..");
13
- const runScript = promisify(execFile);
14
- const projectPackage = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8"));
15
- const manager = projectPackage.packageManager?.split("@")[0] ?? (existsSync(path.join(root, "bun.lock")) || existsSync(path.join(root, "bun.lockb")) ? "bun" : "npm");
16
- await runScenarioCompiler(root, {
17
- watched: process.argv.includes("--watch"),
18
- compilerFiles: [import.meta.filename],
19
- async validate() {
20
- try { await runScript(manager, [...(manager === "bun" ? ["--bun"] : []), "run", "lint"], { cwd: root }); }
21
- catch (error) { throw new Error([error.stdout, error.stderr].map(value => value?.toString() ?? "").join("\n") || error.message); }
22
- },
23
- buildGraph: createVitePreviewBuilder({ build, configure(entries, options) {
24
- const mount = path.join(options.dsRoot, "showcase/mcp/main.tsx");
25
- return { configFile: false, root, base: "./", publicDir: false,
26
- plugins: [previewEntriesPlugin(entries.map(entry => ({ ...entry, root })), mount), wyw({ tagResolver: linariaTagResolver, include: ["**/*.{ts,tsx}"], exclude: ["**/node_modules/**"] }), react()],
27
- resolve: { alias: { "@ds": path.join(options.dsRoot, options.config.publicEntry) } },
28
- worker: { format: "iife" },
29
- build: { write: false, cssCodeSplit: true, assetsInlineLimit: 0, modulePreload: false,
30
- rollupOptions: { preserveEntrySignatures: "strict", input: Object.fromEntries(entries.map((_entry, index) => [`scenario-${index}`, `ads-preview-entry:${index}`])) } },
31
- };
32
- } }),
33
- });
3
+ await compilePreviews(process.cwd(), {watched:process.argv.includes("--watch")});
@@ -0,0 +1,13 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { runScenarioCompiler } from "./scenarios-compiler.mjs";
4
+ import { createBunPreviewBuilder } from "./preview-bun.mjs";
5
+ import { checkCandidate } from "./validation-checks.mjs";
6
+
7
+ /** The same ADS-owned Bun compiler serves MCP, standalone builds and CI. */
8
+ export function compilePreviews(directory=process.cwd(),{watched=false}={}) {
9
+ const root=path.resolve(directory);
10
+ return runScenarioCompiler(root,{watched,compilerFiles:[import.meta.filename,...["preview-bun.mjs","preview-imports.mjs","bun-worker.mjs"].map(file=>fileURLToPath(new URL(file,import.meta.url)))],
11
+ async validate(){const result=await checkCandidate(root);if(!result.ok)throw new Error(result.diagnostics.map(item=>`${item.file}:${item.line??1}: ${item.rule}: ${item.message}`).join("\n"));},buildGraph:createBunPreviewBuilder()});
12
+ }
13
+ 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,9 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { createBunPreviewBuilder } from "./preview-bun.mjs";
3
+
4
+ const {file,options,watched,ancestors}=JSON.parse(await Bun.stdin.text());
5
+ const builder=createBunPreviewBuilder();
6
+ try {
7
+ const result=await builder([],options,{generateBundle(){}},{watched,workerEntry:file,workerAncestors:ancestors});
8
+ writeFileSync(process.argv[2],JSON.stringify(result));
9
+ } finally { await builder.close(); }
package/dist/check.mjs CHANGED
@@ -33,6 +33,7 @@ import { createLayerBoundaries, layerSourceFiles } from "./layers.mjs";
33
33
  import { createDesignValues, inspectDesignAliases, isColorKeyword } from "./design-values.mjs";
34
34
  import { inspectTestBoundaries } from "./test-boundaries.mjs";
35
35
  import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
36
+ import { inspectUsage } from "./usage.mjs";
36
37
 
37
38
  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.";
38
39
  const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve inlineStyleFiles for documented measured geometry, not demo layout.`;
@@ -57,10 +58,11 @@ export function checkProject(directory, { trackingRoot } = {}) {
57
58
  const resolveImport = importResolver(options);
58
59
  const units = inspectUnits(options);
59
60
  options.testOwner = file => units.owner(units.relative(path.relative(root,file)));
61
+ 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()));
60
62
  const rootHtml = path.join(root, "index.html");
61
- const files = [...new Set([...sourceFiles(sourceRoot), ...sourceFiles(dsRoot), ...(existsSync(rootHtml) ? [rootHtml] : [])])];
63
+ const files = [...new Set([...sourceFiles(sourceRoot), ...sourceFiles(dsRoot), ...configurationScripts, ...(existsSync(rootHtml) ? [rootHtml] : [])])];
62
64
  const boundaryFiles = [...config.inlineStyleFiles, ...config.boundaries.styleWrites.map(entry => entry.file)].map(file => path.resolve(root, file)).filter(file => existsSync(file) && statSync(file).isFile());
63
- const scriptFiles = layerSourceFiles([...new Set([...files, ...boundaryFiles])].filter((file) => /\.[cm]?[jt]sx?$/.test(file)), options);
65
+ const scriptFiles = [...new Set([...layerSourceFiles([...new Set([...files, ...boundaryFiles])].filter((file) => /\.[cm]?[jt]sx?$/.test(file)), options), ...configurationScripts])];
64
66
  const compiler = projectCompilerOptions(options);
65
67
  const program = ts.createProgram(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 });
66
68
  const checker = program.getTypeChecker();
@@ -77,6 +79,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
77
79
  diagnostics.push({ file: path.relative(root, file).replaceAll("\\", "/"), rule, message, line, column, ...detail });
78
80
  }
79
81
  const layers = createLayerBoundaries(program, options, report), layerStyles = [];
82
+ inspectUsage(options, program, report);
80
83
  layers.inspectDependencies();
81
84
  inspectTokenValueFlows(program, options, tokenInventory, units, report);
82
85
  for (const file of layers.runtimeHelpers()) if (!files.includes(file)) files.push(file);
@@ -197,7 +200,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
197
200
  for (const file of files) {
198
201
  const role = adsFileRole(file);
199
202
  const roleExtension=role==="contract"?/\.[cm]?ts$/.test(file):["fixture","fixtures"].includes(role)?/\.(?:[cm]?[jt]sx?|json)$/.test(file):/\.[cm]?[jt]sx?$/.test(file);
200
- if (role && (!["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.`);
203
+ 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.`);
201
204
  if (file.endsWith(".css") && isInside(path.join(dsRoot, config.tokenDir), file) && !isDevelopmentFile(file, options)) { checkCss(file, readFileSync(file, "utf8"), undefined, true); continue; }
202
205
  if (file.endsWith(".html")) { inspectHtml(readFileSync(file, "utf8"), (rule, message, line) => report(file, rule, message, line)); continue; }
203
206
  if (file.endsWith(".css")) {
@@ -305,7 +308,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
305
308
  let specifier;
306
309
  if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) specifier = node.moduleSpecifier.text;
307
310
  if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) specifier = node.arguments[0].text;
308
- if (specifier && importViolation(specifier, file, options, resolveImport)) nodeReport(node, "public-import", `Import through ${config.publicAlias}, not ADS implementation paths.`);
311
+ if (specifier && !(configurationScripts.has(file)&&resolveImport(specifier,file).every(target=>configurationScripts.has(target))) && importViolation(specifier, file, options, resolveImport)) nodeReport(node, "public-import", `Import through ${config.publicAlias}, not ADS implementation paths.`);
309
312
  if (specifier && resolveImport(specifier, file).some((target) => (specifier.startsWith(".") || existsSync(target)) && target.endsWith(".css") && isInside(root, target) && !isInside(dsRoot, target) && target !== path.join(sourceRoot, "app-mount.css") && !isInside(path.join(root, "node_modules"), target))) nodeReport(node, "style-ownership", "Imported project CSS belongs to ADS components, patterns, or the foundation. Only structural app-mount.css is allowed outside the ADS.");
310
313
  if (specifier && appImportViolation(specifier, file, options, resolveImport)) nodeReport(node, "no-app-import", "ADS implementations and showcase fixtures must not import app code. Use public ADS APIs with local fixture data; keep application integration harnesses in application tests.");
311
314
  if (specifier && showcaseImportViolation(specifier, file, options, resolveImport)) nodeReport(node, "showcase-import", "Showcase code and styles are development fixtures; runtime code must not import them.");
package/dist/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env bun
2
2
  import { readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { checkProject, generateBrandAssets, generateLintConfig, initProject, inspectTokens } from "./index.mjs";
@@ -11,7 +11,8 @@ Usage: ads init [options] Run inside your project
11
11
 
12
12
  init Set up ADS in the current project (requires package.json)
13
13
  check [directory] Check tokens, ownership, imports, and showcase coverage
14
- validate [dir] Audit architecture, lint, project scripts and behavior checks
14
+ compile [directory] Build ADS previews with Bun (--watch for incremental previews)
15
+ validate [dir] Audit ADS gates, project scripts and behavior checks
15
16
  behaviors [dir] Inspect behavior contracts and current verification evidence
16
17
  verify [directory] Run registered behavior checks (--unit and --check select)
17
18
  tokens [directory] Inspect local token values and theme definitions
@@ -48,11 +49,12 @@ async function main(args) {
48
49
  const selectedChecks = [];
49
50
  let showcase = true;
50
51
  let mutations = false;
51
- let changed = false;
52
+ let changed = false, watched = false;
52
53
  const positional = [];
53
54
  for (let index = 0; index < args.length; index++) {
54
55
  const argument = args[index];
55
56
  if (argument === "--json") json = true;
57
+ else if(argument === "--watch") watched = true;
56
58
  else if (argument === "--changed") changed = true;
57
59
  else if (argument === "--no-showcase") showcase = false;
58
60
  else if (argument === "--mutations") mutations = true;
@@ -81,6 +83,8 @@ async function main(args) {
81
83
  }
82
84
  if (positional.length > 2) throw new Error("Extra argument. Run ads --help.");
83
85
  const [command, directory] = positional;
86
+ if(watched&&command!=="compile")throw new Error("--watch is supported only by compile.");
87
+ if(command==="compile"){const {compilePreviews}=await import("./bun-compiler.mjs");await compilePreviews(path.resolve(directory??process.cwd()),{watched});return;}
84
88
  if (changed && command !== "validate") throw new Error("--changed is supported only by validate.");
85
89
  if ((port !== undefined || !showcase) && !["mcp", "showcase"].includes(command)) throw new Error("Website options are supported only by mcp/showcase.");
86
90
  if (!showcase && command !== "mcp") throw new Error("--no-showcase is supported only by mcp.");
@@ -94,7 +98,7 @@ async function main(args) {
94
98
  if (command === "mcp" || command === "showcase") {
95
99
  if (json) throw new Error("--json is not supported by mcp/showcase; mcp reserves stdout for JSON-RPC.");
96
100
  const { startAdsMcp } = await import("./mcp/server.mjs");
97
- await startAdsMcp(target, { stdio: command === "mcp", showcase, port, mutations });
101
+ await startAdsMcp(target, { stdio: command === "mcp", showcase, port, mutations, prewarm:true });
98
102
  return;
99
103
  }
100
104
  let result;
@@ -114,9 +118,9 @@ async function main(args) {
114
118
  else if (command === "lint-config") result = generateLintConfig(target);
115
119
  else throw new Error(`Unknown command: ${command}. Run ads --help.`);
116
120
  if (json) console.log(JSON.stringify(result, null, 2));
117
- else if (command === "init") console.log(`Initialized ${target}\nFramework: ${result.framework}\nAdded ${result.toolDependency.name} (${result.toolDependency.spec}) as a development dependency.\nRun ${result.packageManager} install and ${result.packageManager} run build; the build refreshes lint configuration, runs ADS checks, and generates configured brand assets automatically.`);
121
+ else if (command === "init") console.log(`Initialized ${target}\nFramework: ${result.framework}\nAdded ${result.toolDependency.name} (${result.toolDependency.spec}) as a development dependency.\nRun ${result.packageManager} install and ${result.packageManager} run build; the build runs ADS checks and generates configured brand assets automatically.`);
118
122
  else if (command === "assets") console.log(result.skipped ? "No assets.iconSource configured; brand generation skipped." : `Generated ${result.files.length} brand assets in ${result.directory}.`);
119
- else if (command === "lint-config") console.log(`Generated ${result.file}\nProjects initialized with ads init refresh this automatically during lint:ds/build.`);
123
+ else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
120
124
  else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
121
125
  else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
122
126
  else if (command === "validate") {console.log(`ADS validation ${result.ok?"passed":"failed"}: ${result.scope}${result.fallback?` (${result.fallback})`:""}`);for(const check of result.checks)console.log(`${check.name}: ${check.skipped?"skipped":check.passed?"passed":"failed"}${check.reason?` (${check.reason})`:""}`);}
@@ -126,7 +130,7 @@ async function main(args) {
126
130
  if (!json && result.diagnostics?.length) {
127
131
  for (const diagnostic of result.diagnostics) console.error(`${diagnostic.file}:${diagnostic.line}:${diagnostic.column} [${diagnostic.rule}] ${diagnostic.message}`);
128
132
  }
129
- if (!json) for (const advisory of result.advisories ?? []) console.error(`${advisory.file}:${advisory.line}:${advisory.column} [${advisory.severity ?? "advisory"}:${advisory.rule}] ${advisory.message}`);
133
+ if (!json) for (const advisory of result.advisories ?? []) if(advisory.severity!=="info") console.error(`${advisory.file}:${advisory.line}:${advisory.column} [${advisory.severity ?? "advisory"}:${advisory.rule}] ${advisory.message}`);
130
134
  if (result.ok === false || result.diagnostics?.length) process.exitCode = 1;
131
135
  }
132
136
 
package/dist/config.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync, readdirSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
3
4
  import { isDraftFile, draftImportViolation } from "./draft-boundary.mjs";
4
5
  import { isSharedToken } from "./token-policy.mjs";
5
6
 
@@ -9,6 +10,7 @@ export const defaultConfig = {
9
10
  schemaVersion: 1,
10
11
  framework: null,
11
12
  behaviorLibraries: [],
13
+ usage: { notifications: [], restrictedImports: [] },
12
14
  sourceDir: "src",
13
15
  dsDir: "design-system",
14
16
  publicAlias: "@ds",
@@ -47,11 +49,24 @@ export function loadConfig(directory = process.cwd()) {
47
49
  if (!(field in defaultConfig)) throw new Error(`Unknown ADS configuration field: ${field}`);
48
50
  }
49
51
  if (user.oxlint !== undefined && (!user.oxlint || typeof user.oxlint !== "object" || Array.isArray(user.oxlint))) throw new Error("oxlint must be an object.");
50
- for (const field of ["boundaries", "assets", "oxlint", "mcp", "validation"]) {
52
+ for (const field of ["boundaries", "assets", "oxlint", "mcp", "validation", "usage"]) {
51
53
  if (user[field] !== undefined && (!user[field] || typeof user[field] !== "object" || Array.isArray(user[field]))) throw new Error(`${field} must be an object.`);
52
54
  for (const key of Object.keys(user[field] ?? {})) if (!(key in defaultConfig[field])) throw new Error(`Unknown ${field} configuration field: ${key}`);
53
55
  }
54
- const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp } };
56
+ const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp }, usage: { ...defaultConfig.usage, ...user.usage } };
57
+ if (!Array.isArray(config.usage.notifications) || config.usage.notifications.length > 100) throw new Error("usage.notifications must be an array of notification API registrations.");
58
+ const notificationNames = new Set();
59
+ for (const entry of config.usage.notifications) {
60
+ if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some(key => !["api", "host", "rootFiles"].includes(key)) || ![entry.api, entry.host].every(name => typeof name === "string" && /^[A-Za-z_$][\w$]*$/.test(name))) throw new Error("Each usage.notifications entry requires public api and host export names and rootFiles.");
61
+ if (notificationNames.has(entry.api) || notificationNames.has(entry.host) || entry.api === entry.host) throw new Error("Notification API and host registrations must be distinct.");
62
+ notificationNames.add(entry.api); notificationNames.add(entry.host);
63
+ if (!Array.isArray(entry.rootFiles) || !entry.rootFiles.length || entry.rootFiles.length > 100 || new Set(entry.rootFiles).size !== entry.rootFiles.length) throw new Error("Notification rootFiles must contain distinct project-relative source files.");
64
+ for (const file of entry.rootFiles) {
65
+ projectPath(root, file, "usage.notifications.rootFiles");
66
+ if (!/\.[cm]?[jt]sx?$/.test(file) || file.includes("\\") || file.split("/").some(part => !part || [".", "..", "node_modules", ".git", ".ds"].includes(part))) throw new Error("Notification rootFiles must name canonical project-relative source files.");
67
+ }
68
+ }
69
+ if (!Array.isArray(config.usage.restrictedImports) || config.usage.restrictedImports.length > 100 || new Set(config.usage.restrictedImports).size !== config.usage.restrictedImports.length || config.usage.restrictedImports.some(name => typeof name !== "string" || !/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/.test(name))) throw new Error("usage.restrictedImports must contain distinct npm package names.");
55
70
  if (config.validation.checks !== null && (!Array.isArray(config.validation.checks) || config.validation.checks.length > 20 || new Set(config.validation.checks).size !== config.validation.checks.length || config.validation.checks.some(name=>typeof name !== "string" || !/^[\w:.-]+$/.test(name)))) throw new Error("validation.checks must be null or up to 20 unique package script names.");
56
71
  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.");
57
72
  for (const file of config.validation.inputs) {
@@ -137,9 +152,12 @@ export function loadConfig(directory = process.cwd()) {
137
152
  const manifest = projectPath(root, config.mcp.previewManifest, "mcp.previewManifest");
138
153
  if (!isInside(path.join(root, ".ds"), manifest) || path.extname(manifest) !== ".json") throw new Error("mcp.previewManifest must name a generated JSON manifest inside .ds/.");
139
154
  }
140
- if (config.mcp.previewWatch !== null) {
155
+ if (config.mcp.previewWatch !== null && config.mcp.previewWatch !== false) {
141
156
  const watch = config.mcp.previewWatch;
142
- if (!watch || typeof watch !== "object" || Array.isArray(watch) || Object.keys(watch).some((key) => !["command", "args"].includes(key)) || typeof watch.command !== "string" || !watch.command.trim() || watch.command.includes("\0") || !Array.isArray(watch.args) || watch.args.some((arg) => typeof arg !== "string" || arg.includes("\0"))) throw new Error("mcp.previewWatch requires command (executable) and args (string array), or null.");
157
+ if (!watch || typeof watch !== "object" || Array.isArray(watch) || Object.keys(watch).some((key) => !["command", "args"].includes(key)) || typeof watch.command !== "string" || !watch.command.trim() || watch.command.includes("\0") || !Array.isArray(watch.args) || watch.args.some((arg) => typeof arg !== "string" || arg.includes("\0"))) throw new Error("mcp.previewWatch requires command (executable) and args (string array), null (native compiler), or false (externally prebuilt previews).");
158
+ }
159
+ if(config.framework&&config.mcp.previewManifest&&config.mcp.previewWatch===null){
160
+ config.mcp.previewWatch={command:"bun",args:[fileURLToPath(new URL("./bun-compiler.mjs",import.meta.url)),"--watch"]};
143
161
  }
144
162
  const appIds = new Set();
145
163
  for (const app of config.mcp.apps) {
@@ -13,5 +13,7 @@ export function developmentExecutable(command) {
13
13
  }
14
14
 
15
15
  export function packageScriptCommand(manager, script) {
16
- return { command: manager, args: [...(manager === "bun" ? ["--bun"] : []), "run", script] };
16
+ // The package manager dispatches the script. Its explicit interpreter is a
17
+ // project choice; --bun would replace even a deliberately bounded Node CLI.
18
+ return { command: manager, args: ["run", script] };
17
19
  }
package/dist/init.mjs CHANGED
@@ -3,13 +3,11 @@ import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import ts from "typescript";
5
5
  import { isInside, loadConfig, sourceFiles, supportedFrameworks } from "./config.mjs";
6
- import { createLintConfig } from "./lint-config.mjs";
7
6
  import { foundationFiles } from "./token-policy.mjs";
8
7
  import { assertFrameworkCompiler } from "./ui-framework.mjs";
9
8
 
10
9
  const tool = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
11
10
  const starter = fileURLToPath(new URL("./bootstrap-ds/", import.meta.url));
12
- const starterPackage = JSON.parse(readFileSync(path.join(starter, "package.json"), "utf8"));
13
11
 
14
12
  function dependencySpec(value) {
15
13
  if (typeof value !== "string" || !value.trim()) throw new Error("toolPackage must be a version or local tool tarball path.");
@@ -32,6 +30,7 @@ function detectManager(root, pkg, requested) {
32
30
  if (bun) return "bun";
33
31
  if (npm) return "npm";
34
32
  if (["pnpm-lock.yaml", "yarn.lock"].some((name) => existsSync(path.join(root, name)))) throw new Error("This version supports npm and Bun projects.");
33
+ if(process.env.npm_config_user_agent?.startsWith("npm/"))return "npm";
35
34
  return process.versions.bun || process.env.npm_config_user_agent?.startsWith("bun/") ? "bun" : "npm";
36
35
  }
37
36
 
@@ -105,28 +104,27 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
105
104
  }
106
105
  const manager = detectManager(root, pkg, packageManager);
107
106
  if (!["npm", "bun"].includes(manager)) throw new Error("packageManager must be npm or bun.");
108
- const run = manager === "bun" ? "bun --bun run" : "npm run";
109
- const ads = manager === "bun" ? "bun --bun run ads" : "ads";
110
- const oxlint = manager === "bun" ? "bun --bun run oxlint" : "oxlint";
107
+ const run = manager === "bun" ? "bun run" : "npm run";
108
+ const ads = manager === "bun" ? "bun run ads" : "ads";
111
109
  const spec = dependencySpec(toolPackage ?? pkg.devDependencies?.[tool.name] ?? pkg.dependencies?.[tool.name] ?? tool.version);
112
110
  const { config, dsRoot } = loadConfig(root);
111
+ const initialConfigFile=path.join(root,"ds.config.json"),initialConfig=existsSync(initialConfigFile)?JSON.parse(readFileSync(initialConfigFile,"utf8")):{};
112
+ const nativePreviewMissing=initialConfig.mcp?.previewManifest===undefined;
113
+ if(nativePreviewMissing)config.mcp.previewManifest=".ds/preview/manifest.json";
113
114
  if (framework !== undefined && !supportedFrameworks.includes(framework)) throw new Error("framework must be react or preact.");
114
115
  if (framework !== undefined && config.framework !== null && framework !== config.framework) throw new Error(`ADS is configured for ${config.framework}; --framework ${framework} would change it. Migrate the project and update ds.config.json explicitly before running init.`);
115
116
  const selectedFramework = framework ?? config.framework;
116
117
  if (selectedFramework === null) throw new Error("Specify --framework react or --framework preact on first init, including when adopting an existing ADS config without a framework.");
117
118
  assertFrameworkCompiler(root, selectedFramework);
118
119
  config.framework = selectedFramework;
119
- const lintRoots = [config.sourceDir];
120
- if (!isInside(path.resolve(root, config.sourceDir), dsRoot)) lintRoots.push(config.dsDir);
121
- const sourceArguments = lintRoots.map((directory) => `'${directory.replaceAll("'", "'\"'\"'")}'`).join(" ");
122
- const lint = `${ads} lint-config . && ${ads} check . && ${oxlint} --deny-warnings --config .ds/oxlintrc.json ${sourceArguments}`;
120
+ const lint = `${ads} check .`;
123
121
  const scripts = { ...pkg.scripts };
124
- if (scripts["lint:ds"] && scripts["lint:ds"] !== lint && !["ads lint-config . && ads check .", "ds lint-config . && ds check .", "bun --bun run ads lint-config . && bun --bun run ads check ."].some(prefix => scripts["lint:ds"].startsWith(prefix))) throw new Error("An existing custom lint:ds script would conflict. Rename it or integrate ADS checks before running init.");
122
+ if (scripts["lint:ds"] && scripts["lint:ds"] !== lint && !["ads check .", "bun run ads check .", "bun --bun run ads check .", "ds check .", "bun --bun run ds check .", "ads lint-config . && ads check .", "ds lint-config . && ds check .", "bun --bun run ads lint-config . && bun --bun run ads check ."].some(prefix => scripts["lint:ds"].startsWith(prefix))) throw new Error("An existing custom lint:ds script would conflict. Rename it or integrate ADS checks before running init.");
125
123
  scripts["lint:ds"] = lint;
126
- if (scripts["assets:ds"] && !["ads assets", "ds assets", "bun --bun run ads assets"].includes(scripts["assets:ds"])) throw new Error("An existing custom assets:ds script would conflict. Rename it or integrate ADS asset generation before running init.");
124
+ if (scripts["assets:ds"] && !["ads assets", "ds assets", "bun run ads assets", "bun --bun run ads assets"].includes(scripts["assets:ds"])) throw new Error("An existing custom assets:ds script would conflict. Rename it or integrate ADS asset generation before running init.");
127
125
  scripts["assets:ds"] = `${ads} assets`;
128
126
  for (const [name, command] of [["dev:showcase", "showcase"], ["ads-mcp", "mcp --mutations"], ["ads-read-mcp", "mcp"]]) {
129
- if (!scripts[name] || [`ds ${command}`, `ads ${command}`, `bun --bun run ads ${command}`].includes(scripts[name])) scripts[name] = `${ads} ${command}`;
127
+ if (!scripts[name] || [`ds ${command}`, `ads ${command}`, `bun run ads ${command}`, `bun --bun run ads ${command}`].includes(scripts[name])) scripts[name] = `${ads} ${command}`;
130
128
  }
131
129
  const managedBuild = /^(?:npm|bun(?: --bun)?) run lint:ds(?: && (?:npm|bun(?: --bun)?) run assets:ds)?$/.test(scripts.build ?? "");
132
130
  if (scripts.build && !managedBuild) {
@@ -141,7 +139,6 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
141
139
  }
142
140
  pkg.scripts = scripts;
143
141
  pkg.devDependencies = { ...pkg.devDependencies, [tool.name]: spec };
144
- if (!pkg.devDependencies.oxlint && !pkg.dependencies?.oxlint) pkg.devDependencies.oxlint = starterPackage.devDependencies.oxlint;
145
142
  if (pkg.dependencies?.[tool.name]) delete pkg.dependencies[tool.name];
146
143
 
147
144
  const updates = new Map();
@@ -197,13 +194,14 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
197
194
  else {
198
195
  const original = readFileSync(configFile, "utf8");
199
196
  const saved = JSON.parse(original);
200
- if (saved.framework === undefined || !existingTokens.length) {
197
+ if (saved.framework === undefined || !existingTokens.length || nativePreviewMissing) {
201
198
  const indent = original.match(/\n([\t ]+)"/)?.[1] ?? " ";
202
- updates.set(configFile, `${JSON.stringify({ ...saved, framework: selectedFramework, ...(!existingTokens.length ? { boundaries: config.boundaries } : {}) }, null, indent)}\n`);
199
+ updates.set(configFile, `${JSON.stringify({ ...saved, framework: selectedFramework, ...(nativePreviewMissing?{mcp:{...saved.mcp,previewManifest:config.mcp.previewManifest}}:{}), ...(!existingTokens.length ? { boundaries: config.boundaries } : {}) }, null, indent)}\n`);
203
200
  }
204
201
  }
205
- const lintConfigFile = path.join(root, ".ds/oxlintrc.json");
206
- updates.set(lintConfigFile, `${JSON.stringify(createLintConfig({ root, config }), null, 2)}\n`);
202
+ const mount=selectedFramework==="preact"?'import {render} from "preact";':'import {createRoot} from "react-dom/client";';
203
+ const render=selectedFramework==="preact"?'render(<Scenario/>,container);return()=>render(null,container);':'const root=createRoot(container);root.render(<Scenario/>);return()=>root.unmount();';
204
+ addMissing(path.join(dsRoot,"showcase/mcp/main.tsx"),`import ${JSON.stringify(config.publicAlias)};\n${mount}\nexport function mountScenario(Scenario,container){${render}}\n`);
207
205
  const ignoreFile = path.join(root, ".gitignore");
208
206
  assertLocalFile(root, ignoreFile);
209
207
  const ignore = existsSync(ignoreFile) ? readFileSync(ignoreFile, "utf8") : "";
@@ -212,5 +210,5 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
212
210
  const nextPackage = `${JSON.stringify(pkg, null, indent)}\n`;
213
211
  if (nextPackage !== originalPackage) updates.set(packageFile, nextPackage);
214
212
  commit(root, updates);
215
- return { directory: root, framework: selectedFramework, packageManager: manager, lintConfig: lintConfigFile, toolDependency: { name: tool.name, spec }, updatedFiles: [...updates.keys()] };
213
+ return { directory: root, framework: selectedFramework, packageManager: manager, toolDependency: { name: tool.name, spec }, updatedFiles: [...updates.keys()] };
216
214
  }
@@ -14,7 +14,8 @@ const diagnostic = z.object({ message: z.string().max(4000), file: z.string().ma
14
14
  const preview = z.object({ id: z.string().max(256), state: z.enum(["idle", "building", "ready", "error"]), revision: z.number().int().nonnegative(), lastSuccessfulRevision: z.number().int().positive().nullable(), artifactDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).nullable(), sourceRevision:z.string().regex(/^[a-f0-9]{64}$/).optional(), diagnostics: z.array(diagnostic).max(20), diagnosticSet: z.number().int().nonnegative().optional() }).strict();
15
15
  const progressSchema = z.object({ phase: z.enum(["queued", "validation", "compilation", "validation-and-compilation", "publication", "idle"]), startedAt: z.string().datetime(), updatedAt: z.string().datetime() }).strict();
16
16
  const liveSchema = z.object({ revision: z.string().regex(/^[a-f0-9]{64}$/), sourceRevision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
17
- const snapshot = z.object({ schemaVersion: z.literal(1), session: z.string().regex(/^[\w-]{1,100}$/), sequence: z.number().int().nonnegative(), updatedAt: z.string().datetime(), progress: progressSchema.optional(), live: liveSchema.optional(), previews: z.array(preview), diagnostics: z.array(diagnostic).max(20).optional(), diagnosticSets: z.array(z.array(diagnostic).max(20)).optional() }).strict().refine(value => value.previews.every(entry => entry.diagnosticSet === undefined || value.diagnosticSets?.[entry.diagnosticSet]), "Invalid shared diagnostic reference.");
17
+ const warmupSchema=z.object({state:z.enum(["warming","ready","error"]),completed:z.number().int().nonnegative(),total:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),active:z.string().max(256).optional()}).strict();
18
+ const snapshot = z.object({ schemaVersion: z.literal(1), session: z.string().regex(/^[\w-]{1,100}$/), sequence: z.number().int().nonnegative(), updatedAt: z.string().datetime(), progress: progressSchema.optional(), warmup:warmupSchema.optional(), live: liveSchema.optional(), previews: z.array(preview), diagnostics: z.array(diagnostic).max(20).optional(), diagnosticSets: z.array(z.array(diagnostic).max(20)).optional() }).strict().refine(value => value.previews.every(entry => entry.diagnosticSet === undefined || value.diagnosticSets?.[entry.diagnosticSet]), "Invalid shared diagnostic reference.");
18
19
  export const artifactDigest = (file) => {
19
20
  if (realpathSync(file) !== file) throw new Error("Preview output cannot resolve through a symlink.");
20
21
  if (statSync(file).size > 2 * 1024 * 1024) throw new Error("Preview exceeds 2 MiB.");
@@ -41,11 +42,11 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
41
42
  const entries = new Map(apps.map((app) => [app.id, { id: app.id, state: "idle", revision: 0, lastSuccessfulRevision: null, artifactDigest: null, diagnostics: [] }]));
42
43
  let sequence = 0;
43
44
  let diagnostics = [];
44
- let progress;
45
+ let progress, warmup;
45
46
  let live, batching = 0;
46
47
  function save() {
47
48
  if (batching) return;
48
- const value = { schemaVersion: 1, session, sequence: ++sequence, updatedAt: new Date().toISOString(), previews: [...entries.values()], ...(progress ? { progress } : {}), ...(live ? { live } : {}), ...(diagnostics.length ? { diagnostics } : {}) };
49
+ const value = { schemaVersion: 1, session, sequence: ++sequence, updatedAt: new Date().toISOString(), previews: [...entries.values()], ...(progress ? { progress } : {}), ...(warmup?{warmup}:{}), ...(live ? { live } : {}), ...(diagnostics.length ? { diagnostics } : {}) };
49
50
  let text = JSON.stringify(snapshot.parse(value));
50
51
  // A shared graph failure applies to every scenario. Store repeated details
51
52
  // once only when necessary; ordinary reports retain inline diagnostics.
@@ -73,6 +74,7 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
73
74
  }
74
75
  save();
75
76
  return {
77
+ warmup(value){warmup=warmupSchema.parse(value);save();},
76
78
  session,
77
79
  batch(run) { ++batching; try { return run(); } finally { --batching; save(); } },
78
80
  live(value) { live = value; save(); },
@@ -186,7 +188,7 @@ export function inspectBuildStatus(root, config, { session, previewSession, proc
186
188
  current, stale: state === "unreported" ? null : !current, available, ...(value?.sourceRevision ? {sourceRevision:value.sourceRevision} : {}), diagnostics };
187
189
  });
188
190
  const state = reportError || report?.diagnostics?.length || previews.some((entry) => entry.state === "error") ? "error" : previews.some((entry) => entry.state === "building") ? "building" : previews.some((entry) => entry.state === "unreported") ? "unreported" : previews.some(entry => entry.current) ? "ready" : previews.length ? "idle" : "disabled";
189
- return { state, reported: Boolean(report), session: report?.session ?? null, sequence: report?.sequence ?? null, updatedAt: report?.updatedAt ?? null, ...(report?.progress ? { progress: report.progress } : {}), previews, ...(report?.diagnostics?.length ? { diagnostics: report.diagnostics } : {}), resourceUri: BUILD_URI };
191
+ return { state, reported: Boolean(report), session: report?.session ?? null, sequence: report?.sequence ?? null, updatedAt: report?.updatedAt ?? null, ...(report?.progress ? { progress: report.progress } : {}), ...(report?.warmup?{warmup:report.warmup}:{}), previews, ...(report?.diagnostics?.length ? { diagnostics: report.diagnostics } : {}), resourceUri: BUILD_URI };
190
192
  }
191
193
 
192
194
  export class PreviewBuildError extends Error {