@reqvire-org/ads 0.3.36 → 0.3.38

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 (86) hide show
  1. package/README.md +12 -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 +20 -8
  10. package/dist/config.mjs +24 -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-owner-guard.mjs +7 -4
  18. package/dist/mcp/preview-watch.mjs +21 -9
  19. package/dist/mcp/preview-widget.bundle.js +57 -63
  20. package/dist/mcp/preview-work.mjs +1 -15
  21. package/dist/mcp/project-widget.bundle.js +55 -61
  22. package/dist/mcp/prompts.mjs +2 -2
  23. package/dist/mcp/resource-loader.js +32 -10
  24. package/dist/mcp/server.mjs +94 -34
  25. package/dist/mcp/widget.bundle.js +58 -64
  26. package/dist/preview-builder.mjs +17 -5
  27. package/dist/preview-bun.mjs +269 -0
  28. package/dist/preview-imports.mjs +73 -0
  29. package/dist/preview-resources.mjs +26 -14
  30. package/dist/resource-limits.mjs +146 -0
  31. package/dist/runtime-requirements.mjs +21 -0
  32. package/dist/scenario-inspector.mjs +11 -4
  33. package/dist/scenarios-compiler.mjs +51 -9
  34. package/dist/showcase/client.bundle.js +66 -71
  35. package/dist/showcase/index.html +2 -2
  36. package/dist/showcase/sandbox.bundle.js +1 -1
  37. package/dist/showcase/style.css +4 -0
  38. package/dist/skills/ads-break-ui/SKILL.md +42 -42
  39. package/dist/skills/ads-break-ui/references/drafts.md +6 -3
  40. package/dist/skills/ads-break-ui/references/guarded-editing.md +4 -3
  41. package/dist/skills/ads-break-ui/references/runtimes.md +175 -140
  42. package/dist/skills/ads-break-ui/references/validation.md +13 -3
  43. package/dist/skills/ads-break-ui/references/workflows.md +82 -0
  44. package/dist/skills/ads-designer/SKILL.md +41 -41
  45. package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +8 -9
  46. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -8
  47. package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +4 -3
  48. package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
  49. package/dist/skills/ads-designer/references/cli.md +25 -21
  50. package/dist/skills/ads-designer/references/drafts.md +6 -3
  51. package/dist/skills/ads-designer/references/guarded-editing.md +4 -3
  52. package/dist/skills/ads-designer/references/runtimes.md +175 -140
  53. package/dist/skills/ads-designer/references/validation.md +13 -3
  54. package/dist/skills/ads-designer/references/workflows.md +82 -0
  55. package/dist/skills/ads-import/SKILL.md +43 -44
  56. package/dist/skills/ads-import/references/cli.md +25 -21
  57. package/dist/skills/ads-import/references/drafts.md +6 -3
  58. package/dist/skills/ads-import/references/guarded-editing.md +4 -3
  59. package/dist/skills/ads-import/references/runtimes.md +175 -140
  60. package/dist/skills/ads-import/references/validation.md +13 -3
  61. package/dist/skills/ads-import/references/workflows.md +82 -0
  62. package/dist/skills/ads-motion/SKILL.md +40 -40
  63. package/dist/skills/ads-motion/references/drafts.md +6 -3
  64. package/dist/skills/ads-motion/references/guarded-editing.md +4 -3
  65. package/dist/skills/ads-motion/references/runtimes.md +175 -140
  66. package/dist/skills/ads-motion/references/validation.md +13 -3
  67. package/dist/skills/ads-motion/references/workflows.md +82 -0
  68. package/dist/skills/ads-port/SKILL.md +40 -40
  69. package/dist/skills/ads-port/references/cli.md +25 -21
  70. package/dist/skills/ads-port/references/drafts.md +6 -3
  71. package/dist/skills/ads-port/references/guarded-editing.md +4 -3
  72. package/dist/skills/ads-port/references/runtimes.md +175 -140
  73. package/dist/skills/ads-port/references/validation.md +13 -3
  74. package/dist/skills/ads-port/references/workflows.md +82 -0
  75. package/dist/usage.mjs +84 -0
  76. package/dist/validation.mjs +0 -12
  77. package/dist/verification/browser.mjs +77 -48
  78. package/docs/ADS.md +17 -11
  79. package/docs/ARCHITECTURE.md +43 -29
  80. package/docs/BEHAVIORS.md +3 -3
  81. package/docs/CHANGELOG.md +81 -13
  82. package/docs/GUIDE.md +96 -53
  83. package/docs/MCP.md +117 -123
  84. package/docs/benchmarks/bun-previews.md +91 -0
  85. package/docs/benchmarks/gidi-preview-memory.md +4 -0
  86. package/package.json +16 -14
@@ -30,15 +30,19 @@ export function createVitePreviewBuilder({ build, configure }) {
30
30
  }
31
31
  // Metadata changes do not change virtual module identities. A changed entry
32
32
  // list or project configuration does require a fresh configured graph.
33
- const key = JSON.stringify([options.root, options.config, entries.map(entry => [entry.id, entry.file])]);
33
+ const context = JSON.stringify([options.root, options.config]);
34
+ const key = JSON.stringify([context, entries.map(entry => [entry.id, entry.file])]);
34
35
  if (graph?.key !== key) {
36
+ // Growing the entry set must retain transformed modules, not rebuild the
37
+ // entire visited prefix from scratch. Keep only the latest graph cache.
38
+ const moduleCache = graph?.context === context ? graph.cache : undefined;
35
39
  await close();
36
40
  const directory = path.join(options.root, ".ds/incremental", randomUUID());
37
41
  mkdirSync(directory, { recursive: true });
38
42
  const trigger = path.join(directory, "trigger");
39
43
  writeFileSync(trigger, "0");
40
44
  const listeners = new Set();
41
- const current = { key, directory, closed: false, building: true, serial: 0,
45
+ const current = { key, context, directory, closed: false, building: true, serial: 0,
42
46
  notify() { for (const resolve of listeners) resolve(); listeners.clear(); },
43
47
  wait(reconcile) { return new Promise(resolve => {
44
48
  const done = () => { clearTimeout(timer); listeners.delete(done); resolve(); };
@@ -49,6 +53,10 @@ export function createVitePreviewBuilder({ build, configure }) {
49
53
  }); },
50
54
  };
51
55
  graph = current;
56
+ // Rollup's watch task owns its input cache and replaces rollupOptions.cache.
57
+ // Seed the first options hook; later builds use the watcher's own cache.
58
+ let seed = moduleCache;
59
+ const seedCache = {name:"ads-preview-seed-cache",options(input){if(!seed)return;const cache=seed;seed=undefined;return{...input,cache};}};
52
60
  let started;
53
61
  let candidate;
54
62
  const capture = { name: "ads-incremental-preview", enforce: "post",
@@ -65,9 +73,9 @@ export function createVitePreviewBuilder({ build, configure }) {
65
73
  const output = config.build?.rollupOptions?.output;
66
74
  if (Array.isArray(output) || output?.file) throw new Error("Incremental preview builds require one module output without output.file.");
67
75
  const workers = createPreviewWorkerCache(options, () => started === previewSourceRevision(options));
68
- current.watcher = await build({ ...config, plugins: [...config.plugins ?? [], workers, capture],
76
+ current.watcher = await build({ ...config, plugins: [seedCache, ...config.plugins ?? [], workers, capture],
69
77
  build: { ...config.build, minify: false, cssMinify: false, reportCompressedSize: false, write: true, outDir: path.join(directory, "output"), emptyOutDir: true,
70
- rollupOptions: { ...config.build?.rollupOptions, output: { ...output, dir: path.join(directory, "output") } },
78
+ rollupOptions: { ...config.build?.rollupOptions, ...(moduleCache ? {cache:moduleCache} : {}), output: { ...output, dir: path.join(directory, "output") } },
71
79
  watch: { ...config.build?.watch, skipWrite: false,
72
80
  // Bun's native fs-watch reattachment can miss rapid subsequent
73
81
  // edits on Linux. Poll only this compiler's dependency watches.
@@ -80,7 +88,11 @@ export function createVitePreviewBuilder({ build, configure }) {
80
88
  rmSync(directory, { recursive: true, force: true });
81
89
  throw new Error("Preview builder was closed.");
82
90
  }
83
- current.watcher.on("event", event => {
91
+ current.watcher.on("event", async event => {
92
+ if (event.result) {
93
+ if (event.code === "BUNDLE_END") current.cache = event.result.cache;
94
+ await event.result.close();
95
+ }
84
96
  if (event.code === "START") { current.building = true; current.error = undefined; candidate = undefined; }
85
97
  if (event.code === "ERROR") {
86
98
  current.error = { source: started, value: event.error }; current.building = false; current.notify();
@@ -0,0 +1,269 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { spawn } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
+ import ts from "typescript";
7
+ import postcss from "postcss";
8
+ import selectorParser from "postcss-selector-parser";
9
+ import valueParser from "postcss-value-parser";
10
+ import { transform, TransformCacheCollection, disposeEvalBroker } from "@wyw-in-js/transform";
11
+ import { createPreviewResources } from "./preview-resources.mjs";
12
+ import { previewSourceRevision } from "./preview-inputs.mjs";
13
+ import { linariaTagResolver } from "./linaria.mjs";
14
+ import {createPreviewImportOptimizer} from "./preview-imports.mjs";
15
+ import { assertBunRuntime } from "./runtime-requirements.mjs";
16
+
17
+ const hash = value => createHash("sha256").update(value).digest("hex");
18
+ const fileHash = file => { try { return hash(readFileSync(file)); } catch { return null; } };
19
+ const slash = file => file.replaceAll("\\", "/");
20
+ const selectorClasses=selector=>{const names=[];selectorParser(selectors=>selectors.walkClasses(node=>names.push(node.value))).processSync(selector);return names;};
21
+ const keyframeRule=rule=>rule.parent.type==="atrule"&&/(?:^|-)keyframes$/i.test(rule.parent.name);
22
+ function buildFailure(logs) {
23
+ return new Error("ADS preview compilation failed:\n"+logs.map(log=>`${log.position?.file??""}${log.position?.line?":"+log.position.line:""}: ${log.message??String(log)}`).join("\n"));
24
+ }
25
+
26
+ // Linaria's class merger is pure, but its published implementation does not
27
+ // annotate calls. Mark only direct module-level calls to that imported binding;
28
+ // a project function named cx (or a shadowed parameter) gets no exemption.
29
+ function pureClassComposition(code,file){
30
+ const tree=ts.createSourceFile(file,code,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX),names=new Set(),offsets=[];
31
+ for(const statement of tree.statements)if(ts.isImportDeclaration(statement)&&["@linaria/core","@linaria/atomic"].includes(statement.moduleSpecifier.text)){
32
+ const bindings=statement.importClause?.namedBindings;
33
+ if(bindings&&ts.isNamedImports(bindings))for(const binding of bindings.elements)if((binding.propertyName??binding.name).text==="cx")names.add(binding.name.text);
34
+ }
35
+ if(!names.size)return code;
36
+ for(const statement of tree.statements)if(ts.isVariableStatement(statement))for(const declaration of statement.declarationList.declarations){
37
+ const call=declaration.initializer;
38
+ if(call&&ts.isCallExpression(call)&&ts.isIdentifier(call.expression)&&names.has(call.expression.text))offsets.push(call.getStart(tree));
39
+ }
40
+ for(const offset of offsets.sort((a,b)=>b-a))code=code.slice(0,offset)+"/* @__PURE__ */"+code.slice(offset);
41
+ return code;
42
+ }
43
+
44
+ /** ADS owns compilation; consuming applications keep their own build pipeline.
45
+ * Only the current transform for each source file is retained between builds.
46
+ * Publication, source fencing and verification remain the shared scheduler's job. */
47
+ export function createBunPreviewBuilder() {
48
+ assertBunRuntime();
49
+ const cache = new TransformCacheCollection(), transformed = new Map(), workerResults = new Map();
50
+ let directory, context, previous, closed = false, workerQueue=Promise.resolve();
51
+ const builder = async (entries, options, track, {watched = false, workerEntry, workerAncestors=[], sourceRevision=previewSourceRevision(options)} = {}) => {
52
+ if (closed) throw new Error("Preview compiler is closed.");
53
+ const signature = JSON.stringify([options.root, options.config, watched]);
54
+ if (context !== signature) { transformed.clear(); workerResults.clear(); disposeEvalBroker(cache); cache.clear("all"); previous=undefined; context = signature; }
55
+ directory ??= path.join(options.root, ".ds/bun-entries", randomUUID());
56
+ mkdirSync(directory, {recursive:true});
57
+ const css = new Map(), workers = new Map(), workerAssets = new Map(), inputs = new Set();
58
+ const foundation=path.resolve(options.dsRoot,options.config.stylesEntry);
59
+ const mounts = new Map(entries.map((entry,index) => {
60
+ const file=path.join(directory,hash(entry.id)+".tsx");
61
+ const code=`import {mountScenario} from ${JSON.stringify(path.join(options.dsRoot,"showcase/mcp/main.tsx"))};import Scenario from ${JSON.stringify(path.join(options.root,entry.file))};export const mount=container=>mountScenario(Scenario,container);`;
62
+ writeFileSync(file,code);return[file,index];
63
+ }));
64
+ const alias = specifier => specifier === options.config.publicAlias ? path.join(options.dsRoot,options.config.publicEntry)
65
+ : specifier === options.config.publicAlias+"/review" ? path.join(options.dsRoot,options.config.reviewEntry) : specifier;
66
+ const resolve = (specifier, importer) => Bun.resolveSync(alias(specifier),path.dirname(importer));
67
+ const optimizeImports=createPreviewImportOptimizer(options,resolve,inputs);
68
+ function metadata(result) {
69
+ for(const file of Object.keys(result.metafile.inputs)) if(path.isAbsolute(file)||!file.includes(":"))inputs.add(path.resolve(file));
70
+ }
71
+ async function worker(file, ancestors = new Set()) {
72
+ if(ancestors.has(file))throw new Error("Cyclic preview worker imports: "+file);
73
+ if(workers.has(file))return workers.get(file);
74
+ const pending=workerQueue.then(async()=>{
75
+ const saved=workerResults.get(file);
76
+ if(saved&&saved.watched===watched&&saved.dependencies.every(([input,digest])=>fileHash(input)===digest)){
77
+ for(const[input]of saved.dependencies)inputs.add(input);
78
+ for(const asset of saved.assets)workerAssets.set(asset.fileName,asset);
79
+ return saved.fileName;
80
+ }
81
+ const nested=new Set([...ancestors,file]);
82
+ const report=path.join(directory,randomUUID()+".json");
83
+ // Bun 1.3 serializes build contexts: a nested Bun.build awaited by an
84
+ // onLoad hook deadlocks. One short-lived worker compiler avoids that
85
+ // boundary and releases its heap before the next worker is compiled.
86
+ await new Promise((resolve,reject)=>{
87
+ const child=spawn(process.execPath,[fileURLToPath(new URL("./bun-worker.mjs",import.meta.url)),report],{stdio:["pipe","ignore","pipe"]});
88
+ let errors="";child.stderr.on("data",bytes=>{errors=(errors+bytes).slice(-8000);});
89
+ child.stdin.on("error",()=>{});child.stdin.end(JSON.stringify({file,options,watched,ancestors:[...nested]}));
90
+ child.once("error",reject);child.once("close",code=>code===0?resolve():reject(new Error(`Preview worker compilation failed (${code}): ${errors}`)));
91
+ });
92
+ const result=JSON.parse(readFileSync(report,"utf8"));rmSync(report,{force:true});
93
+ for(const input of result.inputs)inputs.add(input);
94
+ const script=result.outputs.find(output=>output.kind==="entry-point");
95
+ if(!script)throw new Error("Preview worker emitted no script: "+file);
96
+ // Worker dependencies are self-contained; its resource is a classic
97
+ // script so it also runs inside the opaque-origin MCP App sandbox.
98
+ const source=Buffer.from(script.bytes,"base64"),fileName="ads-worker-"+hash(source)+".js";
99
+ const childAssets=[...result.assets.map(asset=>({...asset,source:Buffer.from(asset.source,"base64")})),...result.outputs.filter(output=>output.kind!=="entry-point").map(output=>({type:"asset",fileName:slash(output.path).replace(/^\.\//,""),source:Buffer.from(output.bytes,"base64")}))];
100
+ for(const asset of childAssets)workerAssets.set(asset.fileName,asset);
101
+ const asset={type:"asset",fileName,source};workerAssets.set(fileName,asset);
102
+ workerResults.set(file,{watched,fileName,dependencies:result.inputs.map(input=>[input,fileHash(input)]),assets:[asset,...childAssets]});return fileName;
103
+ });
104
+ workerQueue=pending.catch(()=>{});
105
+ workers.set(file,pending);return pending;
106
+ }
107
+ async function source(file, ancestors, defer) {
108
+ const original=readFileSync(file,"utf8");inputs.add(file);
109
+ let code=original;
110
+ if(!file.includes(`${path.sep}node_modules${path.sep}`)&&/@linaria\//.test(original)){
111
+ const previous=transformed.get(file);
112
+ let value=previous;
113
+ if(!value||value.source!==hash(original)||value.dependencies.some(([dependency,digest])=>fileHash(dependency)!==digest)){
114
+ if(previous)for(const[dependency,digest]of previous.dependencies)if(fileHash(dependency)!==digest)cache.invalidateForFile(dependency);
115
+ cache.invalidateIfChanged(file,original);
116
+ const result=await transform({cache,options:{filename:file,root:options.root,pluginOptions:{configFile:false,tagResolver:linariaTagResolver}}},original,async(specifier,importer)=>resolve(specifier,importer));
117
+ const classes=new Set(Object.values(result.rules??{}).map(rule=>rule.className).filter(Boolean));
118
+ if(result.cssText)postcss.parse(result.cssText).walkRules(rule=>{
119
+ if(!keyframeRule(rule))for(const name of selectorClasses(rule.selector))classes.add(name);
120
+ });
121
+ value={source:hash(original),code:pureClassComposition(result.code,file),css:result.cssText,classes:[...classes],dependencies:[file,...result.dependencies??[]].map(dependency=>{const absolute=path.isAbsolute(dependency)?dependency:path.resolve(path.dirname(file),dependency);return[absolute,fileHash(absolute)];})};
122
+ transformed.set(file,value);
123
+ }
124
+ code=value.code;for(const[dependency]of value.dependencies)inputs.add(dependency);
125
+ // A side-effect CSS import here defeats JS tree shaking through public
126
+ // barrels. Attach this owner's styles only after Bun retains its code.
127
+ if(value.css)css.set(file,value.css);
128
+ }
129
+ code=optimizeImports(code,file);
130
+ // Bun does not interpret Vite's worker query or new Worker(new URL()).
131
+ // Compile these through Bun too, then register the resulting immutable
132
+ // script with the same MCP resource graph as all other emitted assets.
133
+ if(/\bnew\s+(?:Worker|SharedWorker|URL)\s*\(/.test(code)){
134
+ await defer();
135
+ const tree=ts.createSourceFile(file,code,ts.ScriptTarget.Latest,true,file.endsWith("tsx")?ts.ScriptKind.TSX:ts.ScriptKind.TS),edits=[],assetImports=[],assetNames=new Map();
136
+ const jobs=[];
137
+ function visit(node){
138
+ if(ts.isNewExpression(node)&&ts.isIdentifier(node.expression)&&["Worker","SharedWorker"].includes(node.expression.text)){
139
+ const url=node.arguments?.[0];
140
+ if(url&&ts.isNewExpression(url)&&ts.isIdentifier(url.expression)&&url.expression.text==="URL"&&url.arguments?.[0]&&ts.isStringLiteralLike(url.arguments[0])){
141
+ const target=resolve(url.arguments[0].text,file);
142
+ jobs.push(worker(target,ancestors).then(name=>edits.push([url.getStart(tree),url.end,JSON.stringify("./"+name)])));
143
+ }
144
+ }
145
+ if(ts.isNewExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="URL"&&node.arguments?.length===2&&ts.isStringLiteralLike(node.arguments[0])){
146
+ const base=node.arguments[1],parent=node.parent;
147
+ const workerURL=ts.isNewExpression(parent)&&ts.isIdentifier(parent.expression)&&["Worker","SharedWorker"].includes(parent.expression.text)&&parent.arguments?.[0]===node;
148
+ if(!workerURL&&ts.isPropertyAccessExpression(base)&&ts.isMetaProperty(base.expression)&&base.name.text==="url"&&!/^(?:[a-z]+:|#|\?)/i.test(node.arguments[0].text)){
149
+ const target=resolve(node.arguments[0].text,file);let name=assetNames.get(target);
150
+ if(!name){name="__ads_asset_"+hash(target).slice(0,16);while(code.includes(name))name+="_";assetNames.set(target,name);}
151
+ assetImports.push(`import ${name} from ${JSON.stringify(target+"?ads-asset")};`);
152
+ if(workerEntry)edits.push([node.getStart(tree),node.end,`new URL(${name})`]);
153
+ else edits.push([node.arguments[0].getStart(tree),node.arguments[0].end,name]);
154
+ }
155
+ }
156
+ ts.forEachChild(node,visit);
157
+ }
158
+ visit(tree);await Promise.all(jobs);
159
+ for(const[start,end,replacement]of edits.sort((a,b)=>b[0]-a[0]))code=code.slice(0,start)+replacement+code.slice(end);
160
+ code=[...new Set(assetImports),code].join("\n");
161
+ }
162
+ return code;
163
+ }
164
+ function plugin(ancestors = new Set()) {
165
+ return{name:"ads-bun-preview",setup(build){
166
+ build.onResolve({filter:/./},args=>{
167
+ if(/[?&]worker(?:[&=]|$)/.test(args.path)){const specifier=args.path.split("?")[0];return{path:resolve(specifier,args.importer),namespace:args.path.includes("url")?"ads-worker-url":"ads-worker"};}
168
+ if(/[?&](?:url|raw|ads-asset)(?:[&=]|$)/.test(args.path))return{path:resolve(args.path.split("?")[0],args.importer),namespace:args.path.includes("raw")?"ads-raw":"ads-file"};
169
+ const mapped=alias(args.path);if(mapped!==args.path)return{path:resolve(mapped,args.importer)};
170
+ if(args.path.endsWith(".css")&&resolve(args.path,args.importer||foundation)===foundation)return{path:foundation,namespace:"ads-foundation"};
171
+ });
172
+ build.onLoad({filter:/./,namespace:"ads-foundation"},()=>({contents:"export {};",loader:"js"}));
173
+ build.onLoad({filter:/./,namespace:"ads-file"},args=>{inputs.add(args.path);return{contents:readFileSync(args.path),loader:"file"};});
174
+ build.onLoad({filter:/./,namespace:"ads-raw"},args=>{inputs.add(args.path);return{contents:readFileSync(args.path,"utf8"),loader:"text"};});
175
+ for(const namespace of ["ads-worker","ads-worker-url"])build.onLoad({filter:/./,namespace},async args=>{
176
+ await args.defer();
177
+ const name=await worker(args.path,ancestors),url=JSON.stringify("./"+name);
178
+ return{loader:"js",contents:namespace==="ads-worker-url"?`export default ${url};`:`export default function WorkerFactory(options){return new Worker(${url},{...options,type:"classic"});}`};
179
+ });
180
+ build.onLoad({filter:/\.[cm]?[jt]sx?$/},async args=>({contents:await source(args.path,ancestors,args.defer),loader:args.path.endsWith("tsx")?"tsx":args.path.endsWith("jsx")?"jsx":/\.([cm]?ts)$/.test(args.path)?"ts":"js"}));
181
+ }};
182
+ }
183
+ // The MCP resource loader owns dependency fetching and lazy imports. Bun's
184
+ // HTTP modulepreload table adds self-references that cannot become blob URLs.
185
+ const result=await Bun.build({entrypoints:workerEntry?[workerEntry]:[...mounts.keys()],root:workerEntry?path.dirname(workerEntry):directory,target:"browser",format:workerEntry?"iife":"esm",jsx:{runtime:"automatic",importSource:options.config.framework},splitting:!workerEntry,modulePreload:false,metafile:true,minify:!watched,plugins:[plugin(new Set(workerAncestors))],define:{"process.env.NODE_ENV":JSON.stringify(watched?"development":"production")}});
186
+ if(!result.success)throw buildFailure(result.logs);
187
+ metadata(result);
188
+ if(workerEntry)return{inputs:[...inputs],outputs:await Promise.all(result.outputs.map(async artifact=>({kind:artifact.kind,path:artifact.path,bytes:Buffer.from(await artifact.arrayBuffer()).toString("base64")}))),assets:[...workerAssets.values()].map(asset=>({...asset,source:Buffer.from(asset.source).toString("base64")}))};
189
+ const output=[], styleFiles=new Map(), retainedCss=new Set(), chunkStyles=new Map(), retainedClasses=new Map();
190
+ const emitted=new Map(await Promise.all(result.outputs.map(async artifact=>[artifact.path,Buffer.from(await artifact.arrayBuffer())])));
191
+ for(const [file,meta]of Object.entries(result.metafile.outputs))if(file.endsWith(".js")){
192
+ const code=emitted.get(file).toString(),owners=[];
193
+ for(const[input,info]of Object.entries(meta.inputs)){
194
+ const owner=path.resolve(input),classes=transformed.get(owner)?.classes??[];
195
+ // A discarded React component can leave only its JSX-runtime import in
196
+ // this chunk. That import has bytesInOutput, but needs no owner CSS.
197
+ const present=classes.filter(name=>code.includes(name));
198
+ if(info.bytesInOutput>0&&css.has(owner)&&(!classes.length||present.length)){
199
+ retainedCss.add(owner);owners.push(owner);
200
+ const names=retainedClasses.get(owner)??new Set();for(const name of present)names.add(name);retainedClasses.set(owner,names);
201
+ }
202
+ }
203
+ chunkStyles.set(file,owners);
204
+ }
205
+ // This is a CSS-only build, not a second JS compilation. Keeping each owner
206
+ // as an entry preserves immutable style URIs across views and JS rechunking.
207
+ // Foundation comes first in every module's style list, including shared
208
+ // chunks, so @layer declarations precede any extracted component rules.
209
+ const cssEntries=[foundation,...[...retainedCss].map(file=>file+".ads-bun.css")];
210
+ function cssSource(contents,file,names){
211
+ const root=postcss.parse(contents);
212
+ if(names)root.walkRules(rule=>{
213
+ if(keyframeRule(rule))return;
214
+ const classes=selectorClasses(rule.selector);
215
+ if(classes.length&&!classes.some(name=>names.has(name)))rule.remove();
216
+ });
217
+ root.walkDecls(decl=>{
218
+ const parsed=valueParser(decl.value);parsed.walk(node=>{
219
+ if(node.type!=="function"||node.value!=="url"||node.nodes.some(child=>child.type==="function"))return;
220
+ const specifier=valueParser.stringify(node.nodes).replace(/^["']|["']$/g,"");
221
+ if(!specifier||/^(?:[a-z]+:|#|\/\/)/i.test(specifier))return;
222
+ const [target,fragment]=specifier.split("#"),asset=resolve(decodeURI(target.split("?")[0]),file),bytes=readFileSync(asset);inputs.add(asset);
223
+ const fileName="ads-file-"+hash(bytes)+path.extname(asset);workerAssets.set(fileName,{type:"asset",fileName,source:bytes});
224
+ node.nodes=[{type:"string",quote:'"',value:"/"+fileName+(fragment?"#"+fragment:"")}];
225
+ });decl.value=parsed.toString();
226
+ });
227
+ return root.toString();
228
+ }
229
+ const cssResult=await Bun.build({entrypoints:cssEntries,root:options.root,target:"browser",metafile:true,minify:!watched,plugins:[{name:"ads-extracted-css",setup(build){
230
+ build.onResolve({filter:/./},args=>{
231
+ if(args.path.endsWith(".ads-bun.css"))return{path:args.path,namespace:"ads-css"};
232
+ if(args.path.startsWith("/ads-file-"))return{path:args.path,external:true};
233
+ if(args.namespace==="ads-css")return{path:resolve(args.path,args.importer)};
234
+ });
235
+ build.onLoad({filter:/./,namespace:"ads-css"},args=>{const file=args.path.slice(0,-".ads-bun.css".length);return{contents:cssSource(css.get(file),args.path,retainedClasses.get(file)),loader:"css",resolveDir:path.dirname(args.path)};});
236
+ build.onLoad({filter:/\.css$/},args=>{inputs.add(args.path);return{contents:cssSource(readFileSync(args.path,"utf8"),args.path),loader:"css"};});
237
+ }}]});
238
+ if(!cssResult.success)throw buildFailure(cssResult.logs);
239
+ metadata(cssResult);
240
+ for(const artifact of cssResult.outputs){
241
+ const meta=cssResult.metafile.outputs[artifact.path],bytes=Buffer.from(await artifact.arrayBuffer());
242
+ const fileName="ads-style-"+hash(bytes)+path.extname(artifact.path);
243
+ output.push({type:"asset",fileName,source:bytes});
244
+ if(meta?.entryPoint)styleFiles.set(path.resolve(meta.entryPoint.replace(/^ads-css:/,"")),fileName);
245
+ }
246
+ for(const artifact of result.outputs){
247
+ const fileName=slash(artifact.path).replace(/^\.\//,""),meta=result.metafile.outputs[artifact.path]??result.metafile.outputs["./"+fileName];
248
+ const bytes=emitted.get(artifact.path);
249
+ if(["entry-point","chunk"].includes(artifact.kind)&&fileName.endsWith(".js")){
250
+ const entry=meta?.entryPoint&&mounts.get(path.resolve(meta.entryPoint));
251
+ const styles=[styleFiles.get(foundation),...(chunkStyles.get(artifact.path)??[]).map(input=>styleFiles.get(input+".ads-bun.css")),...(meta?.cssBundle?[meta.cssBundle.replace(/^\.\//,"")]:[])].filter(Boolean);
252
+ output.push({type:"chunk",fileName,code:bytes.toString(),...(entry!==undefined?{facadeModuleId:"\0ads-preview-entry:"+entry}:{}),imports:(meta?.imports??[]).filter(item=>item.kind!=="dynamic-import").map(item=>item.path.replace(/^\.\//,"")),dynamicImports:(meta?.imports??[]).filter(item=>item.kind==="dynamic-import").map(item=>item.path.replace(/^\.\//,"")),viteMetadata:{importedCss:new Set(styles)}});
253
+ }else output.push({type:"asset",fileName,source:bytes});
254
+ }
255
+ output.push(...workerAssets.values());
256
+ // Generated entry modules disappear when this compiler closes. Recording
257
+ // them as source inputs makes every otherwise valid restart a cache miss.
258
+ track.generateBundle.call({getModuleIds:()=>[...inputs].filter(file=>file!==directory&&!file.startsWith(directory+path.sep))});
259
+ // Inactive/removed source files must not accumulate transform histories.
260
+ for(const file of transformed.keys())if(!inputs.has(file))transformed.delete(file);
261
+ for(const file of workerResults.keys())if(!inputs.has(file))workerResults.delete(file);
262
+ const publication=createPreviewResources({output},options,entries,{retain:previous?.sourceRevision===sourceRevision?previous.snapshot:undefined,prune:true});
263
+ previous={sourceRevision,snapshot:publication.snapshot()};
264
+ return publication;
265
+ };
266
+ builder.warmBatch=true;
267
+ builder.close=async()=>{closed=true;previous=undefined;transformed.clear();workerResults.clear();cache.clear("all");await disposeEvalBroker(cache);if(directory)rmSync(directory,{recursive:true,force:true});};
268
+ return builder;
269
+ }
@@ -0,0 +1,73 @@
1
+ import {existsSync,readFileSync} from "node:fs";
2
+ import path from "node:path";
3
+ import ts from "typescript";
4
+
5
+ /** Preserve each named public import as a split point. Bun otherwise groups a
6
+ * public barrel's exports into one chunk when multiple scenarios share it.
7
+ * Only projects explicitly declaring JavaScript side-effect-free and barrels
8
+ * consisting solely of re-exports and foundation imports qualify. Namespace
9
+ * imports and executable barrels retain their normal ESM semantics. */
10
+ export function createPreviewImportOptimizer(options,resolve,inputs){
11
+ let directory=options.dsRoot;
12
+ while(directory!==options.root&&!existsSync(path.join(directory,"package.json")))directory=path.dirname(directory);
13
+ const packageFile=path.join(directory,"package.json"),pkg=JSON.parse(readFileSync(packageFile,"utf8"));inputs.add(packageFile);
14
+ const safe=pkg.sideEffects===false||Array.isArray(pkg.sideEffects)&&pkg.sideEffects.every(pattern=>typeof pattern==="string"&&pattern.endsWith(".css"));
15
+ if(!safe)return code=>code;
16
+ const foundation=path.resolve(options.dsRoot,options.config.stylesEntry),maps=new Map();
17
+ function owned(file){
18
+ if(!file||path.relative(options.dsRoot,file).startsWith("..")||!path.isAbsolute(file))return false;
19
+ for(let parent=path.dirname(file);;parent=path.dirname(parent)){
20
+ const manifest=path.join(parent,"package.json");
21
+ if(existsSync(manifest)){inputs.add(manifest);return manifest===packageFile;}
22
+ if(parent===path.dirname(parent))return false;
23
+ }
24
+ }
25
+ function barrel(file,visiting=new Set()){
26
+ if(maps.has(file))return maps.get(file);
27
+ if(visiting.has(file))return null;
28
+ const next=new Set([...visiting,file]),code=readFileSync(file,"utf8"),tree=ts.createSourceFile(file,code,ts.ScriptTarget.Latest,true),exports=new Map(),effects=[];
29
+ for(const statement of tree.statements){
30
+ if(ts.isImportDeclaration(statement)&&!statement.importClause&&ts.isStringLiteralLike(statement.moduleSpecifier)&&resolve(statement.moduleSpecifier.text,file)===foundation){effects.push(foundation);continue;}
31
+ if(!ts.isExportDeclaration(statement))return null;
32
+ if(statement.isTypeOnly)continue;
33
+ if(!statement.moduleSpecifier){if(statement.exportClause&&ts.isNamedExports(statement.exportClause)&&!statement.exportClause.elements.length)continue;return null;}
34
+ if(!ts.isStringLiteralLike(statement.moduleSpecifier))return null;
35
+ const target=resolve(statement.moduleSpecifier.text,file);
36
+ // An outer package's policy cannot erase another package's side effects.
37
+ if(!owned(target))return null;
38
+ if(statement.exportClause&&ts.isNamedExports(statement.exportClause))for(const element of statement.exportClause.elements){
39
+ if(!element.isTypeOnly){if(exports.has(element.name.text))return null;exports.set(element.name.text,{file:target,name:(element.propertyName??element.name).text});}
40
+ }else if(!statement.exportClause){
41
+ const child=barrel(target,next);if(!child)return null;
42
+ for(const[name,binding]of child.exports)if(name!=="default"){
43
+ const prior=exports.get(name);if(prior&&(prior.file!==binding.file||prior.name!==binding.name))return null;
44
+ exports.set(name,binding);
45
+ }
46
+ effects.push(...child.effects);
47
+ }else return null;
48
+ }
49
+ inputs.add(file);const value={exports,effects:[...new Set(effects)]};maps.set(file,value);return value;
50
+ }
51
+ const aliases=new Map([options.config.publicAlias,options.config.publicAlias+"/review"].map(alias=>{
52
+ try{return[alias,barrel(resolve(alias,path.join(options.root,"index.ts")))];}catch{return[alias,null];}
53
+ }));
54
+ return(code,file)=>{
55
+ if(![...aliases.keys()].some(alias=>code.includes(alias)))return code;
56
+ const tree=ts.createSourceFile(file,code,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX),changes=[];
57
+ for(const statement of tree.statements){
58
+ if(!ts.isImportDeclaration(statement)||!ts.isStringLiteralLike(statement.moduleSpecifier)||statement.attributes)continue;
59
+ const map=aliases.get(statement.moduleSpecifier.text);if(!map||statement.importClause?.isTypeOnly)continue;
60
+ const clause=statement.importClause,bindings=clause?.namedBindings;
61
+ if(bindings&&!ts.isNamedImports(bindings))continue;
62
+ const imports=[];
63
+ if(clause?.name)imports.push({exported:"default",local:clause.name.text});
64
+ for(const binding of bindings?.elements??[])if(!binding.isTypeOnly)imports.push({exported:(binding.propertyName??binding.name).text,local:binding.name.text});
65
+ if(imports.some(binding=>!map.exports.has(binding.exported)))continue;
66
+ const rows=map.effects.map(effect=>`import ${JSON.stringify(effect)};`);
67
+ for(const binding of imports){const target=map.exports.get(binding.exported),name=/^[A-Za-z_$][\w$]*$/.test(target.name)?target.name:JSON.stringify(target.name);rows.push(`import {${name} as ${binding.local}} from ${JSON.stringify(target.file)};`);}
68
+ changes.push([statement.getStart(tree),statement.end,rows.join("\n")]);
69
+ }
70
+ for(const[start,end,replacement]of changes.sort((a,b)=>b[0]-a[0]))code=code.slice(0,start)+replacement+code.slice(end);
71
+ return code;
72
+ };
73
+ }
@@ -49,15 +49,15 @@ export function previewEntriesPlugin(entries, mountEntry) {
49
49
  }
50
50
 
51
51
  /** Convert Rollup output to registered MCP resources without evaluating project code. */
52
- export function createPreviewResources(output, options, entries) {
52
+ export function createPreviewResources(output, options, entries, {retain, prune = false} = {}) {
53
53
  const bundle = (Array.isArray(output) ? output : [output]).flatMap(result => result.output);
54
54
  const original = item => Buffer.from(item.type === "chunk" ? item.code : item.source);
55
55
  // Rollup's emitted import names include dependency hashes. Include original
56
56
  // content too; an immutable URI must never represent two different outputs.
57
57
  // Bump the transform version whenever emitted resource rewriting changes.
58
- const uris = new Map(bundle.map(item => [item.fileName, `ads://assets/${hash(Buffer.concat([Buffer.from("ads-preview-v1\n" + item.fileName + "\n"), original(item)]))}.${item.fileName.split(".").pop()}`]));
59
- const records = {};
60
- const contents = new Map();
58
+ const uris = new Map(bundle.map(item => [item.fileName, `ads://assets/${hash(Buffer.concat([Buffer.from("ads-preview-v2\n" + item.fileName + "\n"), original(item)]))}.${item.fileName.split(".").pop()}`]));
59
+ const records = {...retain?.manifest.assets};
60
+ const contents = new Map(retain?.contents);
61
61
  function reference(from, value) {
62
62
  if (/^(?:[a-z]+:|#|\/\/)/i.test(value)) return null;
63
63
  const file = value.startsWith("/") ? value.slice(1) : path.posix.normalize(path.posix.join(path.posix.dirname(from), value));
@@ -67,11 +67,11 @@ export function createPreviewResources(output, options, entries) {
67
67
  const uri = uris.get(item.fileName);
68
68
  const references = new Set();
69
69
  let bytes = original(item);
70
- if (item.type === "chunk") {
71
- const source = ts.createSourceFile(item.fileName, item.code, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
70
+ if (item.type === "chunk" || item.fileName.endsWith(".js")) {
71
+ const source = ts.createSourceFile(item.fileName, bytes.toString(), ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
72
72
  const replacements = [];
73
73
  function visit(node) {
74
- if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "Worker" && node.arguments?.[0]) {
74
+ if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && ["Worker","SharedWorker"].includes(node.expression.text) && node.arguments?.[0]) {
75
75
  let bundledWorker = false;
76
76
  function workerReference(child) {
77
77
  if (ts.isStringLiteralLike(child)) {
@@ -79,7 +79,7 @@ export function createPreviewResources(output, options, entries) {
79
79
  const asset = bundle.find(candidate => uris.get(candidate.fileName) === uri);
80
80
  if (asset?.type === "asset" && mime(asset.fileName) === "text/javascript") {
81
81
  const worker = ts.createSourceFile(asset.fileName, original(asset).toString(), ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
82
- if (worker.statements.some(statement => ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement) || statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword))) throw new Error("Preview workers must be self-contained IIFE output. Set Vite worker.format to iife; keep the production worker build unchanged.");
82
+ if (worker.statements.some(statement => ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement) || statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword))) throw new Error("Preview workers must be self-contained IIFE output. Use self-contained worker output in the ADS preview compiler.");
83
83
  bundledWorker = true;
84
84
  }
85
85
  }
@@ -106,7 +106,7 @@ export function createPreviewResources(output, options, entries) {
106
106
  ts.forEachChild(node, visit);
107
107
  }
108
108
  visit(source);
109
- let code = item.code;
109
+ let code = bytes.toString();
110
110
  for (const [start, end, replacement] of replacements.sort((a, b) => b[0] - a[0])) code = code.slice(0, start) + replacement + code.slice(end);
111
111
  bytes = Buffer.from(code);
112
112
  } else if (item.fileName.endsWith(".css")) {
@@ -114,8 +114,9 @@ export function createPreviewResources(output, options, entries) {
114
114
  parsed.walk(node => {
115
115
  if (node.type !== "function" || node.value !== "url") return;
116
116
  const value = valueParser.stringify(node.nodes).replace(/^["']|["']$/g, "");
117
- const target = reference(item.fileName, value);
118
- if (target) { references.add(target); node.nodes = [{ type: "string", quote: '"', value: target }]; }
117
+ const marker=value.indexOf("#"),fragment=marker<0?"":value.slice(marker);
118
+ const target = reference(item.fileName, marker<0?value:value.slice(0,marker));
119
+ if (target) { references.add(target); node.nodes = [{ type: "string", quote: '"', value: target+fragment }]; }
119
120
  });
120
121
  bytes = Buffer.from(parsed.toString());
121
122
  }
@@ -129,8 +130,15 @@ export function createPreviewResources(output, options, entries) {
129
130
  const scenarios = entries.map((entry, index) => {
130
131
  const chunk = bundle.find(item => item.type === "chunk" && item.facadeModuleId === `\0ads-preview-entry:${index}`);
131
132
  if (!chunk) throw new Error(`Missing compiled scenario entry: ${entry.id}`);
132
- return { id: entry.id, title: entry.title, kind: entry.kind, ...(entry.samples ? { samples: entry.samples } : {}), ...(entry.paintBindings?.length ? {paintBindings:entry.paintBindings} : {}), ...(entry.paintAudit?{paintAudit:true}:{}), module: uris.get(chunk.fileName) };
133
+ return retain?.manifest.scenarios.find(previous=>previous.id===entry.id) ?? { id: entry.id, title: entry.title, kind: entry.kind, ...(entry.samples ? { samples: entry.samples } : {}), ...(entry.paintBindings?.length ? {paintBindings:entry.paintBindings} : {}), ...(entry.paintAudit?{paintAudit:true}:{}), module: uris.get(chunk.fileName) };
133
134
  });
135
+ // Rechunking a growing warm graph must not replace already compiled views.
136
+ // Retain their exact closures for identical source/compiler modes, then prune
137
+ // unused output so there is one current graph rather than revision histories.
138
+ const used=new Set();
139
+ function visit(uri){if(used.has(uri))return;const record=records[uri];if(!record)throw new Error("Missing retained preview dependency: "+uri);used.add(uri);for(const target of [...record.imports,...record.dynamicImports,...record.styles,...record.references])visit(target);}
140
+ if(retain||prune){for(const scenario of scenarios)visit(scenario.module);
141
+ for(const uri of Object.keys(records))if(!used.has(uri)){delete records[uri];contents.delete(uri);}}
134
142
  const graph = { schemaVersion: 1, framework: options.config.framework, assets: records, scenarios };
135
143
  const revision = hash(JSON.stringify(graph));
136
144
  validateManifest({ ...graph, revision });
@@ -171,7 +179,7 @@ function publication(options, entries, manifest, contents, saveCache = true) {
171
179
  const target = previewManifestPath(options);
172
180
  const assetsRoot = path.join(path.dirname(target), "assets");
173
181
  const assetFiles = [...contents.keys()].map(uri => path.join(assetsRoot, uri.slice("ads://assets/".length)));
174
- return { assetFiles, revision,
182
+ return { assetFiles, revision, snapshot:()=>({manifest,contents}),
175
183
  publishLive(session) { publication(livePreviewOptions(options), [], manifest, contents, false).publish(session); },
176
184
  publish(session) {
177
185
  const encoded = JSON.stringify({ ...manifest, session });
@@ -183,7 +191,11 @@ function publication(options, entries, manifest, contents, saveCache = true) {
183
191
  if (previous && previous.revision !== revision) atomic(path.join(history, `${previous.revision}.json`), JSON.stringify(previous));
184
192
  } catch { /* A successful rebuild replaces corrupt generated metadata. */ }
185
193
  }
186
- for (const [uri, bytes] of contents) atomic(path.join(assetsRoot, uri.slice("ads://assets/".length)), bytes);
194
+ for (const [uri, bytes] of contents) {
195
+ try{verifiedAssetBytes(options,uri,manifest.assets[uri],true);continue;}catch{/* Missing/corrupt output is repaired by this publication. */}
196
+ atomic(path.join(assetsRoot, uri.slice("ads://assets/".length)), bytes);
197
+ verifiedAssetBytes(options,uri,manifest.assets[uri],true);
198
+ }
187
199
  for (const entry of entries) {
188
200
  atomic(path.join(options.root, previewArtifactPath(options, entry.artifact)), previewArtifactHtml(entry.id, revision));
189
201
  }