@reqvire-org/ads 0.4.3 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/bun-compiler.mjs +6 -5
- package/dist/check.mjs +3 -43
- package/dist/contrast-composition.mjs +6 -60
- package/dist/contrast-styles.mjs +88 -0
- package/dist/mcp/build-status.mjs +8 -3
- package/dist/mcp/drafts.mjs +6 -1
- package/dist/mcp/preview-widget.bundle.js +47 -47
- package/dist/mcp/resource-loader.js +1 -201
- package/dist/mcp/server.mjs +10 -3
- package/dist/preview-bun.mjs +75 -60
- package/dist/preview-incremental.mjs +358 -0
- package/dist/preview-manifest-update.mjs +70 -0
- package/dist/preview-resources.mjs +33 -1
- package/dist/render-composition.mjs +27 -5
- package/dist/skills/README.md +1 -1
- package/dist/skills/ads-designer/SKILL.md +5 -1
- package/dist/skills/ads-designer/references/accessibility.md +6 -2
- package/dist/skills/ads-designer/references/runtimes.md +15 -0
- package/dist/skills/ads-import/references/runtimes.md +15 -0
- package/dist/skills/ads-migrate/SKILL.md +2 -1
- package/dist/skills/ads-migrate/references/0.4.1-to-0.4.2.md +2 -3
- package/dist/skills/ads-migrate/references/0.4.3-to-0.4.4.md +80 -0
- package/dist/skills/ads-port/references/runtimes.md +15 -0
- package/dist/style-token-rules.mjs +51 -0
- package/docs/ARCHITECTURE.md +69 -14
- package/docs/CACHING.md +40 -1
- package/docs/CHANGELOG.md +35 -22
- package/docs/GUIDE.md +23 -3
- package/docs/MCP.md +41 -16
- package/docs/benchmarks/README.md +1 -1
- package/package.json +6 -4
|
@@ -1,201 +1 @@
|
|
|
1
|
-
function closure(records, uri) {
|
|
2
|
-
const ordered = [], seen = new Set();
|
|
3
|
-
function visit(id) {
|
|
4
|
-
if (seen.has(id)) return;
|
|
5
|
-
seen.add(id);
|
|
6
|
-
const record=records.get(id);
|
|
7
|
-
if (!record) throw new Error(`Missing preview dependency metadata: ${id}`);
|
|
8
|
-
for (const dependency of [...record.imports,...record.styles,...record.references]) visit(dependency);
|
|
9
|
-
ordered.push(id);
|
|
10
|
-
}
|
|
11
|
-
visit(uri);return ordered;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function changedPreviewScenarios(previous, next) {
|
|
15
|
-
if (!previous || previous.revision===next.revision) return [];
|
|
16
|
-
const signature=(graph,entry)=>{const records=new Map(Object.entries(graph.assets));return JSON.stringify(closure(records,entry.module).map(uri=>[uri,records.get(uri)]));};
|
|
17
|
-
return next.scenarios.filter(entry=>{const before=previous.scenarios.find(item=>item.id===entry.id);return !before || signature(previous,before)!==signature(next,entry);}).map(entry=>entry.id);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** Native ES modules keep framework semantics, cycles, and live bindings intact. */
|
|
21
|
-
export class PreviewResourceLoader {
|
|
22
|
-
constructor(read) {
|
|
23
|
-
this.read = read;
|
|
24
|
-
this.records = new Map();
|
|
25
|
-
this.bytes = new Map();
|
|
26
|
-
this.urls = new Map();
|
|
27
|
-
this.styles = new Map();
|
|
28
|
-
this.styleReady = new Map();
|
|
29
|
-
this.revisions = new Set();
|
|
30
|
-
this.loadedModules = new Set();
|
|
31
|
-
this.importing = Promise.resolve();
|
|
32
|
-
this.generation = 0;
|
|
33
|
-
this.prefetchGeneration = 0;
|
|
34
|
-
this.closed = false;
|
|
35
|
-
globalThis.__dsPreviewImport = uri => this.importModule(uri);
|
|
36
|
-
}
|
|
37
|
-
register(manifest) {
|
|
38
|
-
if (manifest.schemaVersion !== 1 || !Array.isArray(manifest.scenarios) || !manifest.assets || typeof manifest.revision !== "string") throw new Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");
|
|
39
|
-
for (const [uri, record] of Object.entries(manifest.assets)) {
|
|
40
|
-
if (!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(uri) || !/^sha256:[a-f0-9]{64}$/.test(record.digest)
|
|
41
|
-
|| !["imports", "dynamicImports", "styles", "references"].every(key => Array.isArray(record[key]) && record[key].every(ref => Object.hasOwn(manifest.assets, ref)))) throw new Error("Invalid preview dependency graph.");
|
|
42
|
-
if (this.records.has(uri) && this.records.get(uri).digest !== record.digest) throw Object.assign(new Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."), {code:"ADS_RESOURCE_IDENTITY", category:"build", resourceUri:uri});
|
|
43
|
-
}
|
|
44
|
-
// A rejected graph must not leave a partially registered revision behind.
|
|
45
|
-
for (const [uri, record] of Object.entries(manifest.assets)) this.records.set(uri, record);
|
|
46
|
-
}
|
|
47
|
-
async resource(uri) {
|
|
48
|
-
if (!this.bytes.has(uri)) {
|
|
49
|
-
const task = (async () => {
|
|
50
|
-
const record = this.records.get(uri);
|
|
51
|
-
if (!record) throw new Error(`Unknown preview dependency: ${uri}`);
|
|
52
|
-
let response;
|
|
53
|
-
try { response = await this.read(uri); }
|
|
54
|
-
catch (error) { throw Object.assign(new Error(`Preview resource read failed for ${uri}: ${error.message}`, { cause: error }), { code: "ADS_RESOURCE_READ", category: "transport", resourceUri: uri }); }
|
|
55
|
-
if (this.closed) throw new Error("The preview App was closed.");
|
|
56
|
-
const content = response.contents.find(item => item.uri === uri);
|
|
57
|
-
if (!content) throw Object.assign(new Error(`Missing preview dependency: ${uri}`), { code: "ADS_RESOURCE_CONTENT", category: "build", resourceUri: uri });
|
|
58
|
-
const bytes = typeof content.text === "string" ? new TextEncoder().encode(content.text) : Uint8Array.from(atob(content.blob), letter => letter.charCodeAt(0));
|
|
59
|
-
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
60
|
-
const actual = "sha256:" + [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, "0")).join("");
|
|
61
|
-
if (bytes.length !== record.size || actual !== record.digest) throw Object.assign(new Error("Preview resource integrity check failed. Rebuild and reopen the preview."), { code: "ADS_RESOURCE_INTEGRITY", category: "build", resourceUri: uri });
|
|
62
|
-
return bytes;
|
|
63
|
-
})();
|
|
64
|
-
this.bytes.set(uri, task);
|
|
65
|
-
task.catch(() => this.bytes.delete(uri));
|
|
66
|
-
}
|
|
67
|
-
return this.bytes.get(uri);
|
|
68
|
-
}
|
|
69
|
-
closure(uri) {
|
|
70
|
-
return closure(this.records,uri);
|
|
71
|
-
}
|
|
72
|
-
async prefetch(manifest, ids) {
|
|
73
|
-
if (this.closed) return;
|
|
74
|
-
this.register(manifest);
|
|
75
|
-
const generation=++this.prefetchGeneration, pending=new Set(), scenarios=[];
|
|
76
|
-
let bytes=0;
|
|
77
|
-
for (const id of ids) {
|
|
78
|
-
const entry=manifest.scenarios.find(entry=>entry.id===id);
|
|
79
|
-
if (!entry) continue;
|
|
80
|
-
const missing=this.closure(entry.module).filter(uri=>!this.bytes.has(uri)&&!pending.has(uri));
|
|
81
|
-
const size=missing.reduce((sum,uri)=>sum+this.records.get(uri).size,0);
|
|
82
|
-
if (bytes+size>16*1024*1024 || pending.size+missing.length>256) continue;
|
|
83
|
-
bytes+=size;scenarios.push(id);for(const uri of missing)pending.add(uri);
|
|
84
|
-
}
|
|
85
|
-
const queue=[...pending];let index=0;
|
|
86
|
-
const next=async()=>{while(!this.closed&&generation===this.prefetchGeneration&&index<queue.length)await this.resource(queue[index++]);};
|
|
87
|
-
await Promise.all(Array.from({length:Math.min(3,queue.length)},next));
|
|
88
|
-
return {scenarios,resources:queue.length};
|
|
89
|
-
}
|
|
90
|
-
async materialize(uri) {
|
|
91
|
-
const ordered = this.closure(uri);
|
|
92
|
-
await Promise.all(ordered.map(id => this.resource(id)));
|
|
93
|
-
const imports = {};
|
|
94
|
-
for (const id of ordered) {
|
|
95
|
-
if (this.closed) throw new Error("The preview App was closed.");
|
|
96
|
-
if (this.urls.has(id)) continue;
|
|
97
|
-
const record = this.records.get(id);
|
|
98
|
-
let bytes = await this.resource(id);
|
|
99
|
-
if (record.kind === "module" || record.mimeType === "text/css" || record.mimeType === "text/javascript") {
|
|
100
|
-
let text = new TextDecoder().decode(bytes);
|
|
101
|
-
for (const reference of record.references) {
|
|
102
|
-
const url = this.urls.get(reference);
|
|
103
|
-
if (!url) throw new Error("Unsupported cyclic asset reference.");
|
|
104
|
-
text = text.replaceAll(reference, url);
|
|
105
|
-
}
|
|
106
|
-
bytes = text;
|
|
107
|
-
}
|
|
108
|
-
const url = URL.createObjectURL(new Blob([bytes], { type: record.mimeType }));
|
|
109
|
-
this.urls.set(id, url);
|
|
110
|
-
if (record.kind === "module") imports[id] = url;
|
|
111
|
-
}
|
|
112
|
-
if (Object.keys(imports).length) {
|
|
113
|
-
const script = document.createElement("script");
|
|
114
|
-
script.type = "importmap";
|
|
115
|
-
script.textContent = JSON.stringify({ imports });
|
|
116
|
-
document.head.append(script);
|
|
117
|
-
}
|
|
118
|
-
return ordered;
|
|
119
|
-
}
|
|
120
|
-
async importModule(uri) {
|
|
121
|
-
const prepare = this.importing.then(() => this.materialize(uri));
|
|
122
|
-
this.importing = prepare.catch(() => {});
|
|
123
|
-
const dependencies = await prepare;
|
|
124
|
-
await this.attachStyles(dependencies);
|
|
125
|
-
try { const module = await import(/* @vite-ignore */ uri); this.loadedModules.add(uri); return module; }
|
|
126
|
-
catch (error) { throw new Error(`Preview module import failed for ${uri}: ${error.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`, { cause: error }); }
|
|
127
|
-
}
|
|
128
|
-
async attachStyles(dependencies) {
|
|
129
|
-
for (const id of dependencies) {
|
|
130
|
-
const record = this.records.get(id);
|
|
131
|
-
if (record.mimeType !== "text/css") continue;
|
|
132
|
-
if (this.styles.has(id)) { await this.styleReady.get(id); continue; }
|
|
133
|
-
const style = document.createElement("link");
|
|
134
|
-
style.rel = "stylesheet";
|
|
135
|
-
style.href = this.urls.get(id);
|
|
136
|
-
this.styles.set(id, style);
|
|
137
|
-
const ready = new Promise((resolve, reject) => { style.onload = resolve; style.onerror = () => reject(new Error("The host CSP blocked a preview stylesheet.")); });
|
|
138
|
-
this.styleReady.set(id, ready);
|
|
139
|
-
document.head.append(style);
|
|
140
|
-
try { await ready; } catch (error) { style.remove(); this.styles.delete(id); this.styleReady.delete(id); throw error; }
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
async refreshStyles(uri, generation) {
|
|
144
|
-
const roots = [uri], seen = new Set(), keep = new Set();
|
|
145
|
-
// A lazy module can keep identical JS bytes while its CSS metadata changes.
|
|
146
|
-
// Refresh only lazy branches already opened by this App, leaving unopened
|
|
147
|
-
// pages unfetched and retaining the currently mounted component state.
|
|
148
|
-
for (let index = 0; index < roots.length; index++) {
|
|
149
|
-
const root = roots[index]; if (seen.has(root)) continue; seen.add(root);
|
|
150
|
-
for (const id of await this.materialize(root)) {
|
|
151
|
-
keep.add(id);
|
|
152
|
-
for (const dynamic of this.records.get(id).dynamicImports) if (this.loadedModules.has(dynamic)) roots.push(dynamic);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
await this.attachStyles([...keep]);
|
|
156
|
-
if (generation !== this.generation || this.closed) return false;
|
|
157
|
-
for (const [id, style] of this.styles) if (!keep.has(id)) { style.remove(); this.styles.delete(id); this.styleReady.delete(id); }
|
|
158
|
-
for (const id of keep) if (this.styles.has(id)) document.head.append(this.styles.get(id));
|
|
159
|
-
return true;
|
|
160
|
-
}
|
|
161
|
-
async mount(manifest, id, container) {
|
|
162
|
-
const generation = ++this.generation;
|
|
163
|
-
this.register(manifest);
|
|
164
|
-
const scenario = manifest.scenarios.find(entry => entry.id === id);
|
|
165
|
-
if (!scenario) throw new Error("The selected scenario is no longer registered.");
|
|
166
|
-
const signature = JSON.stringify(this.closure(scenario.module).map(uri => [uri, this.records.get(uri)]));
|
|
167
|
-
// A successful global graph revision may only affect another scenario.
|
|
168
|
-
// Retain this view's form/scroll state, then let the caller rerun its audits.
|
|
169
|
-
if (this.mounted?.id === id && this.mounted.container === container && this.mounted.signature === signature) return this.refreshStyles(scenario.module, generation);
|
|
170
|
-
// Background warming changes the global manifest without loading another
|
|
171
|
-
// module into this App. Only actual selected module revisions need a reset.
|
|
172
|
-
this.revisions.add(scenario.module);
|
|
173
|
-
if (this.revisions.size > 20) throw Object.assign(new Error("Reopen the preview to release modules retained across 20 build revisions."), { code: "ADS_PREVIEW_REOPEN" });
|
|
174
|
-
const module = await this.importModule(scenario.module);
|
|
175
|
-
if (generation !== this.generation) return false;
|
|
176
|
-
const unmount = this.unmount;
|
|
177
|
-
this.unmount = undefined;
|
|
178
|
-
this.mounted = undefined;
|
|
179
|
-
await unmount?.();
|
|
180
|
-
if (generation !== this.generation || this.closed) return false;
|
|
181
|
-
container.replaceChildren();
|
|
182
|
-
if (!await this.refreshStyles(scenario.module, generation)) return false;
|
|
183
|
-
if (typeof module.mount !== "function") throw new Error("The compiled scenario has no mount adapter.");
|
|
184
|
-
this.unmount = module.mount(container);
|
|
185
|
-
if (typeof this.unmount !== "function") throw new Error("The scenario mount adapter must return an unmount callback.");
|
|
186
|
-
this.mounted = { id, container, signature };
|
|
187
|
-
return true;
|
|
188
|
-
}
|
|
189
|
-
async dispose() {
|
|
190
|
-
if (this.closed) return;
|
|
191
|
-
this.closed = true;
|
|
192
|
-
++this.generation;
|
|
193
|
-
++this.prefetchGeneration;
|
|
194
|
-
await this.unmount?.();
|
|
195
|
-
this.mounted = undefined;
|
|
196
|
-
for (const style of this.styles.values()) style.remove();
|
|
197
|
-
for (const url of this.urls.values()) URL.revokeObjectURL(url);
|
|
198
|
-
this.styles.clear(); this.styleReady.clear(); this.urls.clear(); this.bytes.clear(); this.records.clear();this.revisions.clear();this.loadedModules.clear();
|
|
199
|
-
delete globalThis.__dsPreviewImport;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
1
|
+
function S(){let t=new Map,o=new Set,n=!1,e;function s(i){let c={data:t.get(i)?.data??{},callbacks:[],listeners:new Map};return t.set(i,c),{data:c.data,accept(d,f){if(!d||typeof d==="function")c.callbacks.push({deps:[i],callback:(h)=>d?.(h[0])});else c.callbacks.push({deps:typeof d==="string"?[d]:d,callback:(h)=>f?.(typeof d==="string"?h[0]:h)})},acceptExports(d,f){c.callbacks.push({deps:[i],callback:(h)=>f?.(h[0])})},dispose(d){c.dispose=d},prune(d){c.prune=d},invalidate(){n=!0},decline(){n=!0},on(d,f){let h=c.listeners.get(d)??new Set;h.add(f),c.listeners.set(d,h)},off(d,f){c.listeners.get(d)?.delete(f)},send(){throw Error("Preview hot-update custom messages are not a public transport.")}}}async function r(i){for(let u of t.values())for(let c of u.listeners.get(i)??[])await c()}return{context:s,observe(i,u,c){let d=t.get(i);if(!d)return;let f=import(u).then((h)=>{d.exports=h,d.isComponent=c});o.add(f),f.then(()=>o.delete(f),(h)=>{o.delete(f),e=h})},async update(i,u,c,d){if(await Promise.all(o),e)throw e;let f=new Map([...i].filter(([,a])=>a.hot).map(([a,l])=>[l.hot.id,{uri:a,record:l}])),h=new Map([...u].filter(([,a])=>a.hot).map(([a,l])=>[l.hot.id,{uri:a,record:l}])),v=new Map,m=new Map;for(let[a,{record:l}]of f)for(let y of[...l.imports,...l.dynamicImports]){let g=i.get(y)?.hot?.id;if(!g)continue;let w=v.get(g)??new Set;w.add(a),v.set(g,w)}function b(a,l=new Set){if(l.has(a))return!1;let y=t.get(a);if(y?.callbacks.some((E)=>E.deps.includes(a))&&h.has(a))return m.set(a,y),!0;let g=v.get(a);if(!g?.size)return!1;let w=new Set([...l,a]);for(let E of g)if(!b(E,w))return!1;return!0}for(let[a,{record:l}]of f){let y=h.get(a)?.record;if(!y||l.hot.source!==y.hot.source){if(!b(a))return!1}}if(!m.size)return!0;n=!1,await r("vite:beforeUpdate");let p=[];for(let[a,l]of m){if(!d())return!1;await l.dispose?.(l.data),p.push([a,l,await c(h.get(a).uri)])}if(!d())return!1;for(let[,a,l]of p)if(a.isComponent){let y=a.exports,g=Object.keys(l).filter((w)=>w!=="__esModule");if(!y||g.length!==Object.keys(y).filter((w)=>w!=="__esModule").length||g.some((w)=>!Object.hasOwn(y,w)||!a.isComponent(l[w])&&y[w]!==l[w]))return!1}for(let[a,l,y]of p)for(let g of l.callbacks)if(g.deps.includes(a))await g.callback(g.deps.map((w)=>w===a?y:void 0));return await r("vite:afterUpdate"),await new Promise((a)=>setTimeout(a,20)),d()&&!n},async dispose(){for(let i of t.values())await i.dispose?.(i.data),await i.prune?.(i.data);t.clear(),o.clear(),e=void 0}}}function R(t,o){let n=[],e=new Set;function s(r){if(e.has(r))return;e.add(r);let i=t.get(r);if(!i)throw Error(`Missing preview dependency metadata: ${r}`);for(let u of[...i.imports,...i.styles,...i.references])s(u);n.push(r)}return s(o),n}function O(t,o){if(!t||t.revision===o.revision)return[];let n=(e,s)=>{let r=new Map(Object.entries(e.assets));return JSON.stringify(R(r,s.module).map((i)=>[i,r.get(i)]))};return o.scenarios.filter((e)=>{let s=t.scenarios.find((r)=>r.id===e.id);return!s||n(t,s)!==n(o,e)}).map((e)=>e.id)}class x{constructor(t){this.read=t,this.records=new Map,this.bytes=new Map,this.urls=new Map,this.styles=new Map,this.styleReady=new Map,this.revisions=new Set,this.loadedModules=new Set,this.executed=new Map,this.moduleHistory=new Set,this.importing=Promise.resolve(),this.mounting=Promise.resolve(),this.refreshDirty=!1,this.generation=0,this.prefetchGeneration=0,this.closed=!1,this.hot=S(),globalThis.__adsPreviewHot=this.hot,globalThis.__dsPreviewImport=(o)=>this.importModule(o)}register(t){if(t.schemaVersion!==1||!Array.isArray(t.scenarios)||!t.assets||typeof t.revision!=="string")throw Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");if(t.refresh&&(t.refresh.version!==1||typeof t.refresh.epoch!=="string"||!t.refresh.epoch||t.refresh.epoch.length>100))throw Error("Unsupported preview refresh protocol. Reopen with the current ADS version.");let o=new Set;for(let[n,e]of Object.entries(t.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(n)||!/^sha256:[a-f0-9]{64}$/.test(e.digest)||e.hot&&(!t.refresh||e.kind!=="module"||typeof e.hot.id!=="string"||!e.hot.id||e.hot.id.length>4096||o.has(e.hot.id)||!/^[a-f0-9]{64}$/.test(e.hot.source))||!["imports","dynamicImports","styles","references"].every((s)=>Array.isArray(e[s])&&e[s].every((r)=>Object.hasOwn(t.assets,r))))throw Error("Invalid preview dependency graph.");if(e.hot)o.add(e.hot.id);if(this.records.has(n)&&this.records.get(n).digest!==e.digest)throw Object.assign(Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."),{code:"ADS_RESOURCE_IDENTITY",category:"build",resourceUri:n})}for(let[n,e]of Object.entries(t.assets))this.records.set(n,e)}async resource(t){if(!this.bytes.has(t)){let o=(async()=>{let n=this.records.get(t);if(!n)throw Error(`Unknown preview dependency: ${t}`);let e;try{e=await this.read(t)}catch(c){throw Object.assign(Error(`Preview resource read failed for ${t}: ${c.message}`,{cause:c}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:t})}if(this.closed)throw Error("The preview App was closed.");let s=e.contents.find((c)=>c.uri===t);if(!s)throw Object.assign(Error(`Missing preview dependency: ${t}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:t});let r=typeof s.text==="string"?new TextEncoder().encode(s.text):Uint8Array.from(atob(s.blob),(c)=>c.charCodeAt(0)),i=await crypto.subtle.digest("SHA-256",r),u="sha256:"+[...new Uint8Array(i)].map((c)=>c.toString(16).padStart(2,"0")).join("");if(r.length!==n.size||u!==n.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build",resourceUri:t});return r})();this.bytes.set(t,o),o.catch(()=>this.bytes.delete(t))}return this.bytes.get(t)}closure(t){return R(this.records,t)}async prefetch(t,o){if(this.closed)return;this.register(t);let n=++this.prefetchGeneration,e=new Set,s=[],r=0;for(let d of o){let f=t.scenarios.find((m)=>m.id===d);if(!f)continue;let h=this.closure(f.module).filter((m)=>!this.bytes.has(m)&&!e.has(m)),v=h.reduce((m,b)=>m+this.records.get(b).size,0);if(r+v>16777216||e.size+h.length>256)continue;r+=v,s.push(d);for(let m of h)e.add(m)}let i=[...e],u=0,c=async()=>{while(!this.closed&&n===this.prefetchGeneration&&u<i.length)await this.resource(i[u++])};return await Promise.all(Array.from({length:Math.min(3,i.length)},c)),{scenarios:s,resources:i.length}}async materialize(t){let o=this.closure(t);await Promise.all(o.map((e)=>this.resource(e)));let n={};for(let e of o){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(e))continue;let s=this.records.get(e),r=await this.resource(e);if(s.kind==="module"||s.mimeType==="text/css"||s.mimeType==="text/javascript"){let u=new TextDecoder().decode(r);for(let c of s.references){let d=this.urls.get(c);if(!d)throw Error("Unsupported cyclic asset reference.");u=u.replaceAll(c,d)}r=u}let i=URL.createObjectURL(new Blob([r],{type:s.mimeType}));if(this.urls.set(e,i),s.kind==="module")n[e]=i}if(Object.keys(n).length){let e=document.createElement("script");e.type="importmap",e.textContent=JSON.stringify({imports:n}),document.head.append(e)}return o}async importModule(t){let o=this.importing.then(()=>this.materialize(t));this.importing=o.catch(()=>{});let n=await o;await this.attachStyles(n);try{let e=await import(t);this.loadedModules.add(t);for(let s of n){let r=this.records.get(s);if(r.hot)this.executed.set(r.hot.id,{uri:s,record:r}),this.moduleHistory.add(s)}return e}catch(e){throw Error(`Preview module import failed for ${t}: ${e.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:e})}}async attachStyles(t){for(let o of t){if(this.records.get(o).mimeType!=="text/css")continue;if(this.styles.has(o)){await this.styleReady.get(o);continue}let e=document.createElement("link");e.rel="stylesheet",e.href=this.urls.get(o),this.styles.set(o,e);let s=new Promise((r,i)=>{e.onload=r,e.onerror=()=>i(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(o,s),document.head.append(e);try{await s}catch(r){throw e.remove(),this.styles.delete(o),this.styleReady.delete(o),r}}}async refreshStyles(t,o){let n=[t],e=new Set,s=new Set;for(let r=0;r<n.length;r++){let i=n[r];if(e.has(i))continue;e.add(i);for(let u of await this.materialize(i)){s.add(u);for(let c of this.records.get(u).dynamicImports)if(this.loadedModules.has(c)||this.executed.has(this.records.get(c)?.hot?.id))n.push(c)}}if(await this.attachStyles([...s]),o!==this.generation||this.closed)return!1;for(let[r,i]of this.styles)if(!s.has(r))i.remove(),this.styles.delete(r),this.styleReady.delete(r);for(let r of s)if(this.styles.has(r))document.head.append(this.styles.get(r));return!0}async mount(t,o,n){let e=++this.generation,s=this.mounting.then(()=>e!==this.generation||this.closed?!1:this.mountRevision(t,o,n,e));return this.mounting=s.catch(()=>{}),s}async mountRevision(t,o,n,e){this.register(t);let s=t.scenarios.find((h)=>h.id===o);if(!s)throw Error("The selected scenario is no longer registered.");let r=JSON.stringify(this.closure(s.module).map((h)=>[h,this.records.get(h)])),i=new Map(this.closure(s.module).map((h)=>[h,this.records.get(h)])),u=(h)=>{throw Object.assign(Error(h),{code:"ADS_PREVIEW_REOPEN"})};if(this.refreshDirty)u("An interrupted module update requires a clean preview frame.");let c=[...this.urls.keys()].reduce((h,v)=>h+this.records.get(v).size,0);if(this.records.size>4096||c>67108864)u("Reopen the preview to release retained module revisions.");if(this.mounted&&this.mounted.refresh?.epoch!==t.refresh?.epoch)u("The preview compiler changed. Reopening an isolated frame for its new runtime.");if(t.refresh&&this.mounted){let h=new Map(Object.entries(t.assets)),v=new Map([...h].filter(([,p])=>p.hot).map(([p,a])=>[a.hot.id,{uri:p,record:a}]));for(let[p,{record:a}]of this.executed){let l=v.get(p);if(l&&l.record.hot.source!==a.hot.source&&this.moduleHistory.has(l.uri))u("Restoring a previous module revision requires a clean preview frame.")}let m=new Map([...this.executed.values()].map(({uri:p,record:a})=>[p,a]));this.refreshDirty=!0;let b=await this.hot.update(m,h,(p)=>this.importModule(p),()=>e===this.generation&&!this.closed);if(e!==this.generation||this.closed)return!1;if(!b)u("This edit changes a refresh boundary. Reopening the preview with fresh component state.");this.refreshDirty=!1;for(let p of this.executed.keys())if(v.has(p))this.executed.set(p,v.get(p));if(this.mounted.id===o){if(!await this.refreshStyles(s.module,e))return!1;return this.revisions.add(s.module),this.mounted={...this.mounted,signature:r,records:i,module:s.module},!0}}if(this.mounted?.id===o&&this.mounted.container===n&&this.mounted.signature===r)return this.refreshStyles(s.module,e);if(this.revisions.add(s.module),!t.refresh&&this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release retained module revisions."),{code:"ADS_PREVIEW_REOPEN"});let d=await this.importModule(s.module);if(e!==this.generation)return!1;let f=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await f?.(),e!==this.generation||this.closed)return!1;if(n.replaceChildren(),!await this.refreshStyles(s.module,e))return!1;if(typeof d.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=d.mount(n),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:o,container:n,signature:r,records:i,module:s.module,refresh:t.refresh},!0}async dispose(){if(this.closed)return;this.closed=!0,++this.generation,++this.prefetchGeneration,await this.mounting,await this.unmount?.(),await this.hot.dispose(),this.mounted=void 0;for(let t of this.styles.values())t.remove();for(let t of this.urls.values())URL.revokeObjectURL(t);if(this.styles.clear(),this.styleReady.clear(),this.urls.clear(),this.bytes.clear(),this.records.clear(),this.revisions.clear(),this.loadedModules.clear(),this.executed.clear(),this.moduleHistory.clear(),delete globalThis.__dsPreviewImport,globalThis.__adsPreviewHot===this.hot)delete globalThis.__adsPreviewHot}}export{x as PreviewResourceLoader,O as changedPreviewScenarios};
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -24,7 +24,7 @@ import { startShowcaseHost } from "./showcase-host.mjs";
|
|
|
24
24
|
import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
|
|
25
25
|
import { projectDocuments, PROJECT_URI, readProjectDocument } from "./catalog.mjs";
|
|
26
26
|
import { APP_MIME, appMetadata, appUri, tokenWidgetData, previewApp, PREVIEW_APP_URI } from "./apps.mjs";
|
|
27
|
-
import { LIVE_PREVIEW_MANIFEST_URI, PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewAsset } from "../preview-resources.mjs";
|
|
27
|
+
import { LIVE_PREVIEW_MANIFEST_URI, PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewManifestUpdate, readPreviewAsset } from "../preview-resources.mjs";
|
|
28
28
|
import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
|
|
29
29
|
import { getWorkflowPrompt, promptDefinitions } from "./prompts.mjs";
|
|
30
30
|
import { createReconfigurablePreviewWatch } from "./preview-watch.mjs";
|
|
@@ -1050,15 +1050,17 @@ export async function createAdsMcp(
|
|
|
1050
1050
|
contents: [executionResults.readResource(uri)],
|
|
1051
1051
|
};
|
|
1052
1052
|
else if (uri === CAPTURES_URI) value = await captureIndex();
|
|
1053
|
-
else if (uri === PREVIEW_MANIFEST_URI) {
|
|
1053
|
+
else if (uri === PREVIEW_MANIFEST_URI || uri.startsWith(PREVIEW_MANIFEST_URI + "?")) {
|
|
1054
1054
|
value = readPreviewManifest(previewOptions());
|
|
1055
1055
|
if (!value) throw new Error("Preview resources are not built yet. Invoke ads_show_scenario to start the managed compiler.");
|
|
1056
|
-
|
|
1056
|
+
if (uri !== PREVIEW_MANIFEST_URI) value = readPreviewManifestUpdate(previewOptions(), value, resourceQuery(uri, ["from"]).from);
|
|
1057
|
+
} else if (uri === LIVE_PREVIEW_MANIFEST_URI || uri.startsWith(LIVE_PREVIEW_MANIFEST_URI + "?")) {
|
|
1057
1058
|
const report = await builds(),
|
|
1058
1059
|
live = report.previews.find((entry) => entry.live)?.live;
|
|
1059
1060
|
value = readPreviewManifest(livePreviewOptions(previewOptions()));
|
|
1060
1061
|
if (!live || value?.revision !== live.revision || value.session !== report.session)
|
|
1061
1062
|
throw new Error("No live feedback for the current source. Use the verified preview after checks pass.");
|
|
1063
|
+
if (uri !== LIVE_PREVIEW_MANIFEST_URI) value = readPreviewManifestUpdate(livePreviewOptions(previewOptions()), value, resourceQuery(uri, ["from"]).from);
|
|
1062
1064
|
}
|
|
1063
1065
|
if (value !== undefined)
|
|
1064
1066
|
return {
|
|
@@ -1953,6 +1955,11 @@ export async function createAdsMcp(
|
|
|
1953
1955
|
});
|
|
1954
1956
|
server.setRequestHandler("resources/templates/list", () => ({
|
|
1955
1957
|
resourceTemplates: [
|
|
1958
|
+
...[PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI].map(uri => ({
|
|
1959
|
+
uriTemplate: uri + "{?from}", name: "Internal preview manifest update",
|
|
1960
|
+
description: "Preview UI delta from a known SHA-256 revision; falls back to a full manifest when history expired. Live-source and draft-scope restrictions are unchanged.",
|
|
1961
|
+
mimeType: "application/json",
|
|
1962
|
+
})),
|
|
1956
1963
|
{
|
|
1957
1964
|
uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fscenarios",
|
|
1958
1965
|
name: "Draft scenario diagnostics",
|
package/dist/preview-bun.mjs
CHANGED
|
@@ -62,7 +62,7 @@ function buildFailure(logs) {
|
|
|
62
62
|
// Linaria's class merger is pure, but its published implementation does not
|
|
63
63
|
// annotate calls. Mark only direct module-level calls to that imported binding;
|
|
64
64
|
// a project function named cx (or a shadowed parameter) gets no exemption.
|
|
65
|
-
async function pureClassComposition(code, file) {
|
|
65
|
+
export async function pureClassComposition(code, file) {
|
|
66
66
|
const tree = await ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX),
|
|
67
67
|
names = new Set(),
|
|
68
68
|
offsets = [];
|
|
@@ -85,7 +85,7 @@ async function pureClassComposition(code, file) {
|
|
|
85
85
|
|
|
86
86
|
// Preview-only identity survives atom sharing: identical generated classes can
|
|
87
87
|
// belong to different owners. Production builds never receive these markers.
|
|
88
|
-
async function previewIdentities(code, file, options) {
|
|
88
|
+
export async function previewIdentities(code, file, options) {
|
|
89
89
|
const relative = slash(path.relative(options.dsRoot, file));
|
|
90
90
|
if (!/^(?:components|patterns|review)\//.test(relative)) return code;
|
|
91
91
|
const source = slash(path.relative(options.root, file));
|
|
@@ -101,14 +101,80 @@ async function previewIdentities(code, file, options) {
|
|
|
101
101
|
return code;
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
/** Shared source extraction for full Bun builds and watched incremental graphs.
|
|
105
|
+
* One result per file; input/dependency bytes and spatial membership govern reuse.
|
|
106
|
+
* Callers supply their input adapter and own publication/revision fencing. */
|
|
107
|
+
export function createPreviewTransforms() {
|
|
108
|
+
const cache = new TransformCacheCollection(), transformed = new Map();
|
|
109
|
+
return {
|
|
110
|
+
values: transformed,
|
|
111
|
+
async transform(file, original, { options, resolve, sourceRevision, readSpatial }) {
|
|
112
|
+
const previous = transformed.get(file);
|
|
113
|
+
let value = previous;
|
|
114
|
+
const spatialChanged = previous?.spatialRevision !== undefined && previous.spatialRevision !== (readSpatial()?.revision ?? null);
|
|
115
|
+
if (!value || value.source !== hash(original) || spatialChanged || value.dependencies.some(([dependency, digest]) => fileHash(dependency) !== digest)) {
|
|
116
|
+
// Membership changes (a new token sheet) are not in the previous file
|
|
117
|
+
// dependency list. Invalidate this extraction, even with identical TS.
|
|
118
|
+
if (spatialChanged) cache.invalidateForFile(file);
|
|
119
|
+
if (previous) for (const [dependency, digest, imported] of previous.dependencies) if (fileHash(dependency) !== digest) {
|
|
120
|
+
cache.invalidateForFile(dependency);
|
|
121
|
+
if (imported) cache.invalidateForFile(imported);
|
|
122
|
+
if (existsSync(dependency)) cache.invalidateIfChanged(dependency, readFileSync(dependency, "utf8"));
|
|
123
|
+
}
|
|
124
|
+
cache.invalidateIfChanged(file, original);
|
|
125
|
+
let usedSpatial = false;
|
|
126
|
+
const result = await timing.timeStage("linaria-transform", () => spatialInputs.withSpatialInputs(() => {
|
|
127
|
+
usedSpatial = true;
|
|
128
|
+
return readSpatial();
|
|
129
|
+
}, () => transform(
|
|
130
|
+
{ cache, asyncResolveKey: sourceRevision, options: { filename: file, root: options.root, pluginOptions: { configFile: false, tagResolver: linariaTagResolver } } },
|
|
131
|
+
original,
|
|
132
|
+
async (specifier, importer) => resolve(specifier, importer),
|
|
133
|
+
)));
|
|
134
|
+
const classes = new Set(
|
|
135
|
+
Object.values(result.rules ?? {})
|
|
136
|
+
.map((rule) => rule.className)
|
|
137
|
+
.filter(Boolean),
|
|
138
|
+
);
|
|
139
|
+
if (result.cssText)
|
|
140
|
+
postcss.parse(result.cssText).walkRules((rule) => {
|
|
141
|
+
if (!keyframeRule(rule)) for (const name of selectorClasses(rule.selector)) classes.add(name);
|
|
142
|
+
});
|
|
143
|
+
// A computed interpolation can introduce a layout without @ads- in
|
|
144
|
+
// this source. Record the processor's actual use, not a source regex.
|
|
145
|
+
const spatial = usedSpatial || previous?.spatialRevision !== undefined ? readSpatial() : undefined;
|
|
146
|
+
value = {
|
|
147
|
+
source: hash(original),
|
|
148
|
+
code: await pureClassComposition(result.code, file),
|
|
149
|
+
css: result.cssText,
|
|
150
|
+
classes: [...classes],
|
|
151
|
+
...(spatial !== undefined ? { spatialRevision: spatial?.revision ?? null } : {}),
|
|
152
|
+
// The shared spatial revision already checks every sheet once per
|
|
153
|
+
// build. Keep watcher membership without rehashing them per owner.
|
|
154
|
+
spatialInputs: spatial?.inputs ?? [],
|
|
155
|
+
dependencies: [...new Set([file, ...(result.dependencies ?? [])])].map((dependency) => {
|
|
156
|
+
const imported = path.isAbsolute(dependency) ? dependency : path.resolve(path.dirname(file), dependency);
|
|
157
|
+
const absolute = existsSync(imported) ? imported : resolve(dependency, file);
|
|
158
|
+
return [absolute, fileHash(absolute), imported];
|
|
159
|
+
}),
|
|
160
|
+
};
|
|
161
|
+
transformed.set(file, value);
|
|
162
|
+
}
|
|
163
|
+
return value;
|
|
164
|
+
},
|
|
165
|
+
reset() { transformed.clear(); disposeEvalBroker(cache); cache.clear("all"); },
|
|
166
|
+
async close() { transformed.clear(); cache.clear("all"); await disposeEvalBroker(cache); },
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
104
170
|
/** ADS owns compilation; consuming applications keep their own build pipeline.
|
|
105
171
|
* Only the current transform for each source file is retained between builds.
|
|
106
172
|
* Publication, source fencing and verification remain the shared scheduler's job. */
|
|
107
173
|
export function createBunPreviewBuilder() {
|
|
108
174
|
assertBunRuntime();
|
|
109
175
|
process.env.WYW_NODE_BINARY = process.execPath;
|
|
110
|
-
const
|
|
111
|
-
transformed =
|
|
176
|
+
const transforms = createPreviewTransforms(),
|
|
177
|
+
transformed = transforms.values,
|
|
112
178
|
workerResults = new Map();
|
|
113
179
|
let directory,
|
|
114
180
|
context,
|
|
@@ -120,10 +186,8 @@ export function createBunPreviewBuilder() {
|
|
|
120
186
|
if (closed) throw new Error("Preview compiler is closed.");
|
|
121
187
|
const signature = JSON.stringify([options.root, options.config, watched]);
|
|
122
188
|
if (context !== signature) {
|
|
123
|
-
|
|
189
|
+
transforms.reset();
|
|
124
190
|
workerResults.clear();
|
|
125
|
-
disposeEvalBroker(cache);
|
|
126
|
-
cache.clear("all");
|
|
127
191
|
previous = undefined;
|
|
128
192
|
context = signature;
|
|
129
193
|
}
|
|
@@ -219,57 +283,7 @@ export function createBunPreviewBuilder() {
|
|
|
219
283
|
inputs.add(file);
|
|
220
284
|
let code = original;
|
|
221
285
|
if (!file.includes(`${path.sep}node_modules${path.sep}`) && /@linaria\//.test(original)) {
|
|
222
|
-
const
|
|
223
|
-
let value = previous;
|
|
224
|
-
const spatialChanged = previous?.spatialRevision !== undefined && previous.spatialRevision !== (readSpatial()?.revision ?? null);
|
|
225
|
-
if (!value || value.source !== hash(original) || spatialChanged || value.dependencies.some(([dependency, digest]) => fileHash(dependency) !== digest)) {
|
|
226
|
-
// Membership changes (a new token sheet) are not in the previous file
|
|
227
|
-
// dependency list. Invalidate this extraction, even with identical TS.
|
|
228
|
-
if (spatialChanged) cache.invalidateForFile(file);
|
|
229
|
-
if (previous) for (const [dependency, digest, imported] of previous.dependencies) if (fileHash(dependency) !== digest) {
|
|
230
|
-
cache.invalidateForFile(dependency);
|
|
231
|
-
if (imported) cache.invalidateForFile(imported);
|
|
232
|
-
if (existsSync(dependency)) cache.invalidateIfChanged(dependency, readFileSync(dependency, "utf8"));
|
|
233
|
-
}
|
|
234
|
-
cache.invalidateIfChanged(file, original);
|
|
235
|
-
let usedSpatial = false;
|
|
236
|
-
const result = await timing.timeStage("linaria-transform", () => spatialInputs.withSpatialInputs(() => {
|
|
237
|
-
usedSpatial = true;
|
|
238
|
-
return readSpatial();
|
|
239
|
-
}, () => transform(
|
|
240
|
-
{ cache, asyncResolveKey: sourceRevision, options: { filename: file, root: options.root, pluginOptions: { configFile: false, tagResolver: linariaTagResolver } } },
|
|
241
|
-
original,
|
|
242
|
-
async (specifier, importer) => resolve(specifier, importer),
|
|
243
|
-
)));
|
|
244
|
-
const classes = new Set(
|
|
245
|
-
Object.values(result.rules ?? {})
|
|
246
|
-
.map((rule) => rule.className)
|
|
247
|
-
.filter(Boolean),
|
|
248
|
-
);
|
|
249
|
-
if (result.cssText)
|
|
250
|
-
postcss.parse(result.cssText).walkRules((rule) => {
|
|
251
|
-
if (!keyframeRule(rule)) for (const name of selectorClasses(rule.selector)) classes.add(name);
|
|
252
|
-
});
|
|
253
|
-
// A computed interpolation can introduce a layout without @ads- in
|
|
254
|
-
// this source. Record the processor's actual use, not a source regex.
|
|
255
|
-
const spatial = usedSpatial || previous?.spatialRevision !== undefined ? readSpatial() : undefined;
|
|
256
|
-
value = {
|
|
257
|
-
source: hash(original),
|
|
258
|
-
code: await pureClassComposition(result.code, file),
|
|
259
|
-
css: result.cssText,
|
|
260
|
-
classes: [...classes],
|
|
261
|
-
...(spatial !== undefined ? { spatialRevision: spatial?.revision ?? null } : {}),
|
|
262
|
-
// The shared spatial revision already checks every sheet once per
|
|
263
|
-
// build. Keep watcher membership without rehashing them per owner.
|
|
264
|
-
spatialInputs: spatial?.inputs ?? [],
|
|
265
|
-
dependencies: [...new Set([file, ...(result.dependencies ?? [])])].map((dependency) => {
|
|
266
|
-
const imported = path.isAbsolute(dependency) ? dependency : path.resolve(path.dirname(file), dependency);
|
|
267
|
-
const absolute = existsSync(imported) ? imported : resolve(dependency, file);
|
|
268
|
-
return [absolute, fileHash(absolute), imported];
|
|
269
|
-
}),
|
|
270
|
-
};
|
|
271
|
-
transformed.set(file, value);
|
|
272
|
-
}
|
|
286
|
+
const value = await transforms.transform(file, original, { options, resolve, sourceRevision, readSpatial });
|
|
273
287
|
code = value.code;
|
|
274
288
|
for (const [dependency] of value.dependencies) inputs.add(dependency);
|
|
275
289
|
for (const dependency of value.spatialInputs) inputs.add(dependency);
|
|
@@ -567,12 +581,13 @@ export function createBunPreviewBuilder() {
|
|
|
567
581
|
previous = undefined;
|
|
568
582
|
transformed.clear();
|
|
569
583
|
workerResults.clear();
|
|
570
|
-
|
|
571
|
-
await disposeEvalBroker(cache);
|
|
584
|
+
await transforms.close();
|
|
572
585
|
if (directory) rmSync(directory, { recursive: true, force: true });
|
|
573
586
|
};
|
|
574
587
|
const measured = (...args) => timing.timeStage("preview-build", () => builder(...args));
|
|
575
588
|
measured.warmBatch = builder.warmBatch;
|
|
576
589
|
measured.close = builder.close;
|
|
590
|
+
// Benchmark inspection: before preview-only provenance and import pruning.
|
|
591
|
+
measured.transformedModules = () => new Map(transformed);
|
|
577
592
|
return measured;
|
|
578
593
|
}
|