@reqvire-org/ads 0.4.2 → 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 +11 -2
- package/dist/a11y.mjs +71 -65
- package/dist/analysis/helpers.mjs +5 -3
- package/dist/analysis/inputs.mjs +13 -6
- package/dist/analysis/module-resolvers.mjs +46 -0
- package/dist/analysis/service.mjs +7 -0
- package/dist/analysis/syntax.mjs +20 -5
- package/dist/assets.mjs +1 -1
- package/dist/boundaries.mjs +6 -4
- package/dist/bun-compiler.mjs +6 -5
- package/dist/check-service.mjs +8 -5
- package/dist/check.mjs +11 -46
- package/dist/component-contrast.mjs +126 -8
- package/dist/contrast-composition.mjs +80 -0
- package/dist/contrast-styles.mjs +88 -0
- package/dist/finding-rules.mjs +2 -0
- package/dist/font-rules.mjs +20 -15
- package/dist/fonts-generated.mjs +21 -14
- package/dist/foundation-views.mjs +6 -2
- package/dist/image-attributes.mjs +96 -92
- package/dist/mcp/build-status.mjs +8 -3
- package/dist/mcp/drafts.mjs +12 -5
- package/dist/mcp/mutations.mjs +11 -8
- package/dist/mcp/preview-widget.bundle.js +45 -45
- package/dist/mcp/resource-loader.js +1 -201
- package/dist/mcp/server.mjs +19 -5
- package/dist/pictogram-model.mjs +59 -0
- package/dist/pictograms.mjs +52 -0
- package/dist/preview-bun.mjs +76 -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-audit/image-shape.mjs +13 -3
- package/dist/render-audit/pictograms.mjs +88 -0
- package/dist/render-audit/worker.mjs +12 -0
- package/dist/render-audit.mjs +11 -1
- package/dist/render-composition.mjs +186 -0
- package/dist/scenario-registry.mjs +2 -2
- package/dist/scenarios-compiler.mjs +1 -1
- package/dist/showcase/client.bundle.js +23 -23
- package/dist/showcase/draft-navigation.js +5 -5
- package/dist/showcase/foundation-view.css +3 -0
- package/dist/showcase/foundation-view.mjs +3 -0
- package/dist/showcase/pictogram-view.mjs +53 -0
- package/dist/showcase/ui/ui.js +2 -0
- package/dist/skills/README.md +1 -1
- package/dist/skills/ads-designer/SKILL.md +18 -2
- package/dist/skills/ads-designer/references/accessibility.md +70 -2
- package/dist/skills/ads-designer/references/branding.md +5 -16
- package/dist/skills/ads-designer/references/performance.md +3 -2
- package/dist/skills/ads-designer/references/pictograms.md +131 -0
- 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/SKILL.md +4 -1
- package/dist/skills/ads-port/references/runtimes.md +15 -0
- package/dist/source-values.mjs +4 -1
- package/dist/starters/react/design-system/assets/pictograms/catalog.ads.json +13 -0
- package/dist/starters/react/design-system/assets/pictograms/journey.dark.svg +7 -0
- package/dist/starters/react/design-system/assets/pictograms/journey.svg +7 -0
- package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.fixture.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.ads.scenario.tsx +7 -0
- package/dist/starters/react/design-system/components/Content/Pictogram/Pictogram.tsx +26 -0
- package/dist/style-token-rules.mjs +51 -0
- package/dist/task-cache.mjs +2 -2
- package/dist/units.mjs +4 -4
- package/dist/validation-inputs.mjs +7 -3
- package/docs/ADS.md +6 -1
- package/docs/ARCHITECTURE.md +144 -16
- package/docs/CACHING.md +65 -1
- package/docs/CHANGELOG.md +86 -50
- package/docs/GUIDE.md +52 -7
- package/docs/MCP.md +47 -16
- package/docs/benchmarks/README.md +1 -1
- package/package.json +7 -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";
|
|
@@ -668,6 +668,11 @@ export async function createAdsMcp(
|
|
|
668
668
|
name: "Brand artwork, icons, committed targets and glyph sets",
|
|
669
669
|
mimeType: "text/markdown",
|
|
670
670
|
},
|
|
671
|
+
{
|
|
672
|
+
uri: "ads://guides/pictograms",
|
|
673
|
+
name: "Pictogram artwork, theme variants and usage guards",
|
|
674
|
+
mimeType: "text/markdown",
|
|
675
|
+
},
|
|
671
676
|
{
|
|
672
677
|
uri: "ads://guides/accessibility",
|
|
673
678
|
name: "WCAG 2.2 AA guards and accessibility practice",
|
|
@@ -938,6 +943,8 @@ export async function createAdsMcp(
|
|
|
938
943
|
},
|
|
939
944
|
],
|
|
940
945
|
};
|
|
946
|
+
if (uri === "ads://guides/pictograms")
|
|
947
|
+
return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/pictograms.md", import.meta.url), "utf8") }] };
|
|
941
948
|
if (uri === "ads://guides/tokens")
|
|
942
949
|
return {
|
|
943
950
|
contents: [
|
|
@@ -1043,15 +1050,17 @@ export async function createAdsMcp(
|
|
|
1043
1050
|
contents: [executionResults.readResource(uri)],
|
|
1044
1051
|
};
|
|
1045
1052
|
else if (uri === CAPTURES_URI) value = await captureIndex();
|
|
1046
|
-
else if (uri === PREVIEW_MANIFEST_URI) {
|
|
1053
|
+
else if (uri === PREVIEW_MANIFEST_URI || uri.startsWith(PREVIEW_MANIFEST_URI + "?")) {
|
|
1047
1054
|
value = readPreviewManifest(previewOptions());
|
|
1048
1055
|
if (!value) throw new Error("Preview resources are not built yet. Invoke ads_show_scenario to start the managed compiler.");
|
|
1049
|
-
|
|
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 + "?")) {
|
|
1050
1058
|
const report = await builds(),
|
|
1051
1059
|
live = report.previews.find((entry) => entry.live)?.live;
|
|
1052
1060
|
value = readPreviewManifest(livePreviewOptions(previewOptions()));
|
|
1053
1061
|
if (!live || value?.revision !== live.revision || value.session !== report.session)
|
|
1054
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);
|
|
1055
1064
|
}
|
|
1056
1065
|
if (value !== undefined)
|
|
1057
1066
|
return {
|
|
@@ -1523,9 +1532,9 @@ export async function createAdsMcp(
|
|
|
1523
1532
|
{
|
|
1524
1533
|
name: "ads_scenarios",
|
|
1525
1534
|
description:
|
|
1526
|
-
"Find an independently mountable brand, token, component, pattern or composition preview. IDs derive from source filenames. Optional group labels are derived from folder names and searchable; group is discovery output, never scenario metadata. covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.",
|
|
1535
|
+
"Find an independently mountable brand, pictogram, token, component, pattern or composition preview. Authored IDs derive from source filenames; pictogram IDs come from their catalogue. Optional group labels are derived from folder names and searchable; group is discovery output, never scenario metadata. covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.",
|
|
1527
1536
|
schema: query.extend({
|
|
1528
|
-
kind: z.enum(["brand", "tokens", "components", "patterns", "composition"]).optional(),
|
|
1537
|
+
kind: z.enum(["brand", "pictograms", "tokens", "components", "patterns", "composition"]).optional(),
|
|
1529
1538
|
offset: z.number().int().min(0).default(0),
|
|
1530
1539
|
}),
|
|
1531
1540
|
call: async ({ query: search = "", limit, kind, offset }) => {
|
|
@@ -1946,6 +1955,11 @@ export async function createAdsMcp(
|
|
|
1946
1955
|
});
|
|
1947
1956
|
server.setRequestHandler("resources/templates/list", () => ({
|
|
1948
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
|
+
})),
|
|
1949
1963
|
{
|
|
1950
1964
|
uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fscenarios",
|
|
1951
1965
|
name: "Draft scenario diagnostics",
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { SaxesParser } from "saxes";
|
|
2
|
+
|
|
3
|
+
const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4
|
+
const fail = message => { throw new Error(message); };
|
|
5
|
+
const text = value => typeof value === "string" && value.trim().length > 0;
|
|
6
|
+
const keys = (value, allowed, label) => {
|
|
7
|
+
if (!object(value) || Object.keys(value).some(key => !allowed.includes(key))) fail(`${label} has unsupported fields.`);
|
|
8
|
+
};
|
|
9
|
+
const source = value => {
|
|
10
|
+
if (!text(value) || !/^[\w./-]+\.svg$/.test(value) || value.startsWith("/") || value.split("/").some(part => !part || part === "." || part === ".."))
|
|
11
|
+
fail("Pictogram sources must be relative .svg paths inside assets/pictograms/, without parent traversal.");
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/** Pure catalogue contract. Theme names and schemes are separate from brands. */
|
|
15
|
+
export function parsePictogramCatalog(contents, themes) {
|
|
16
|
+
const data = JSON.parse(contents);
|
|
17
|
+
keys(data, ["schemaVersion", "pictograms"], "Pictogram catalogue");
|
|
18
|
+
if (data.schemaVersion !== 1 || !Array.isArray(data.pictograms) || data.pictograms.length > 512)
|
|
19
|
+
fail("Expected schemaVersion: 1 and pictograms (at most 512 entries).");
|
|
20
|
+
const ids = new Set(), names = themes.map(theme => theme.name);
|
|
21
|
+
return data.pictograms.map(item => {
|
|
22
|
+
keys(item, ["id", "title", "description", "license", "source", "themes", "schemes", "minHeight"], "Pictogram");
|
|
23
|
+
if (typeof item.id !== "string" || !/^[\w-]+$/.test(item.id) || ids.has(item.id)) fail("Each pictogram needs a unique id containing letters, digits, underscores or hyphens.");
|
|
24
|
+
ids.add(item.id);
|
|
25
|
+
for (const field of ["title", "description", "license"]) if (!text(item[field])) fail(`${item.id}: supply ${field}.`);
|
|
26
|
+
if (item.source !== undefined) source(item.source);
|
|
27
|
+
for (const [field, allowed] of [["themes", names], ["schemes", ["light", "dark"]]]) if (item[field] !== undefined) {
|
|
28
|
+
keys(item[field], allowed, `${item.id}.${field}`);
|
|
29
|
+
for (const file of Object.values(item[field])) source(file);
|
|
30
|
+
}
|
|
31
|
+
const minHeight = item.minHeight === undefined ? 48 : item.minHeight;
|
|
32
|
+
if (!Number.isFinite(minHeight) || minHeight <= 0 || minHeight > 1024) fail(`${item.id}: minHeight must be greater than zero and at most 1024 CSS pixels.`);
|
|
33
|
+
const variants = Object.fromEntries(themes.map(theme => {
|
|
34
|
+
const exact = item.themes && Object.hasOwn(item.themes, theme.name) ? item.themes[theme.name] : undefined;
|
|
35
|
+
const file = exact ?? item.schemes?.[theme.scheme] ?? item.source;
|
|
36
|
+
if (!file) fail(`${item.id}: no artwork for theme ${theme.name}. Declare a theme, scheme or shared source.`);
|
|
37
|
+
return [theme.name, file];
|
|
38
|
+
}));
|
|
39
|
+
const files = [...new Set([item.source, ...Object.values(item.themes ?? {}), ...Object.values(item.schemes ?? {})].filter(Boolean))];
|
|
40
|
+
if (!files.length) fail(`${item.id}: declare at least one artwork source.`);
|
|
41
|
+
return { id: item.id, title: item.title, description: item.description, license: item.license, minHeight, variants, files };
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Parse XML once; geometry is constrained, the artist's palette and shapes are not. */
|
|
46
|
+
export function pictogramGeometry(contents) {
|
|
47
|
+
const parser = new SaxesParser({ xmlns: true });
|
|
48
|
+
let root;
|
|
49
|
+
parser.on("opentag", node => { root ??= node; });
|
|
50
|
+
parser.write(contents).close();
|
|
51
|
+
if (root?.local !== "svg" || root.uri !== "http://www.w3.org/2000/svg") fail("Expected an SVG document with the SVG namespace.");
|
|
52
|
+
const viewBox = root.attributes.viewBox?.value?.trim().split(/[\s,]+/).map(Number);
|
|
53
|
+
if (viewBox?.length !== 4 || !viewBox.every(Number.isFinite) || viewBox[2] <= 0 || viewBox[3] <= 0)
|
|
54
|
+
fail("Supply a finite viewBox with positive width and height; non-square artwork is welcome.");
|
|
55
|
+
const preserveAspectRatio = root.attributes.preserveAspectRatio?.value ?? "xMidYMid meet";
|
|
56
|
+
if (!/^(?:defer\s+)?x(?:Min|Mid|Max)Y(?:Min|Mid|Max)(?:\s+meet)?$/.test(preserveAspectRatio.trim()))
|
|
57
|
+
fail("Preserve the artwork's proportions with a meet alignment; none stretches it and slice crops it.");
|
|
58
|
+
return { x: viewBox[0], y: viewBox[1], width: viewBox[2], height: viewBox[3], preserveAspectRatio };
|
|
59
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { currentAnalysis } from "./analysis/context.mjs";
|
|
4
|
+
import { memoFact, memoProgram, optionalSourceText } from "./analysis/helpers.mjs";
|
|
5
|
+
import { parsePictogramCatalog, pictogramGeometry } from "./pictogram-model.mjs";
|
|
6
|
+
|
|
7
|
+
export const pictogramCatalog = "assets/pictograms/catalog.ads.json";
|
|
8
|
+
const freeze = value => {
|
|
9
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) { Object.values(value).forEach(freeze); Object.freeze(value); }
|
|
10
|
+
return value;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/** Shared check/discovery adapter. Only captured inputs, with weak revision ownership. */
|
|
14
|
+
export function inspectPictograms(options) {
|
|
15
|
+
const directory = path.join(options.dsRoot, "assets/pictograms"), catalog = path.join(options.dsRoot, pictogramCatalog);
|
|
16
|
+
const relative = file => path.relative(options.root, file).replaceAll("\\", "/");
|
|
17
|
+
const capture = () => {
|
|
18
|
+
const contents = optionalSourceText(catalog), diagnostics = [], pictograms = [];
|
|
19
|
+
const report = (rule, file, message) => diagnostics.push({ rule, file: relative(file), line: 1, column: 1, message, guidanceUri: "ads://guides/pictograms" });
|
|
20
|
+
if (contents === null) return freeze({ pictograms, diagnostics });
|
|
21
|
+
let entries;
|
|
22
|
+
try { entries = parsePictogramCatalog(contents, options.config.themes); }
|
|
23
|
+
catch (error) { report("pictogram-catalog", catalog, error.message); return freeze({ pictograms, diagnostics }); }
|
|
24
|
+
const assets = new Map();
|
|
25
|
+
for (const entry of entries) {
|
|
26
|
+
for (const name of entry.files) if (!assets.has(name)) {
|
|
27
|
+
const file = path.join(directory, name), svg = optionalSourceText(file);
|
|
28
|
+
assets.set(name, null);
|
|
29
|
+
if (svg === null) { report("pictogram-source", catalog, `${entry.id}: missing ${name}.`); continue; }
|
|
30
|
+
if (Buffer.byteLength(svg) > 1024 * 1024) { report("pictogram-source", file, "A pictogram must fit within 1 MiB; simplify or optimize the SVG."); continue; }
|
|
31
|
+
try {
|
|
32
|
+
const geometry = pictogramGeometry(svg);
|
|
33
|
+
assets.set(name, { file: relative(file), geometry, digest: createHash("sha256").update(svg).digest("hex"), src: `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}` });
|
|
34
|
+
} catch (error) { report("pictogram-source", file, error.message); }
|
|
35
|
+
}
|
|
36
|
+
if (entry.files.some(name => !assets.get(name))) continue;
|
|
37
|
+
pictograms.push({ ...entry, file: relative(catalog), assets: Object.fromEntries(entry.files.map(name => [name, assets.get(name)])) });
|
|
38
|
+
}
|
|
39
|
+
return freeze({ pictograms, diagnostics });
|
|
40
|
+
};
|
|
41
|
+
const context = currentAnalysis(), key = `pictograms:${directory}:${JSON.stringify(options.config.themes)}`;
|
|
42
|
+
return context ? memoFact(context, key, () => context.revision ? memoProgram(context.revision, key, capture) : capture()) : capture();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function pictogramViews(options) {
|
|
46
|
+
const { pictograms, diagnostics } = inspectPictograms(options);
|
|
47
|
+
return { diagnostics, views: pictograms.map(item => ({
|
|
48
|
+
id: `pictograms/${item.id}`, kind: "pictograms", unit: "assets/pictograms", title: item.title,
|
|
49
|
+
covers: [], tokens: [], file: item.file,
|
|
50
|
+
foundation: { schemaVersion: 1, kind: "pictograms", title: item.title, pictogram: item },
|
|
51
|
+
})) };
|
|
52
|
+
}
|
package/dist/preview-bun.mjs
CHANGED
|
@@ -23,6 +23,7 @@ export const previewFrameFiles = [
|
|
|
23
23
|
...["mjs", "css", "d.mts"].map((extension) => `preview-frame.ads.review.${extension}`),
|
|
24
24
|
"foundation-view.mjs",
|
|
25
25
|
"foundation-view.css",
|
|
26
|
+
"pictogram-view.mjs",
|
|
26
27
|
"ui/ui.js",
|
|
27
28
|
"ui/ui.css",
|
|
28
29
|
].map((file) => fileURLToPath(new URL(`${previewFrameDirectory}${file}`, import.meta.url)));
|
|
@@ -61,7 +62,7 @@ function buildFailure(logs) {
|
|
|
61
62
|
// Linaria's class merger is pure, but its published implementation does not
|
|
62
63
|
// annotate calls. Mark only direct module-level calls to that imported binding;
|
|
63
64
|
// a project function named cx (or a shadowed parameter) gets no exemption.
|
|
64
|
-
async function pureClassComposition(code, file) {
|
|
65
|
+
export async function pureClassComposition(code, file) {
|
|
65
66
|
const tree = await ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX),
|
|
66
67
|
names = new Set(),
|
|
67
68
|
offsets = [];
|
|
@@ -84,7 +85,7 @@ async function pureClassComposition(code, file) {
|
|
|
84
85
|
|
|
85
86
|
// Preview-only identity survives atom sharing: identical generated classes can
|
|
86
87
|
// belong to different owners. Production builds never receive these markers.
|
|
87
|
-
async function previewIdentities(code, file, options) {
|
|
88
|
+
export async function previewIdentities(code, file, options) {
|
|
88
89
|
const relative = slash(path.relative(options.dsRoot, file));
|
|
89
90
|
if (!/^(?:components|patterns|review)\//.test(relative)) return code;
|
|
90
91
|
const source = slash(path.relative(options.root, file));
|
|
@@ -100,14 +101,80 @@ async function previewIdentities(code, file, options) {
|
|
|
100
101
|
return code;
|
|
101
102
|
}
|
|
102
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
|
+
|
|
103
170
|
/** ADS owns compilation; consuming applications keep their own build pipeline.
|
|
104
171
|
* Only the current transform for each source file is retained between builds.
|
|
105
172
|
* Publication, source fencing and verification remain the shared scheduler's job. */
|
|
106
173
|
export function createBunPreviewBuilder() {
|
|
107
174
|
assertBunRuntime();
|
|
108
175
|
process.env.WYW_NODE_BINARY = process.execPath;
|
|
109
|
-
const
|
|
110
|
-
transformed =
|
|
176
|
+
const transforms = createPreviewTransforms(),
|
|
177
|
+
transformed = transforms.values,
|
|
111
178
|
workerResults = new Map();
|
|
112
179
|
let directory,
|
|
113
180
|
context,
|
|
@@ -119,10 +186,8 @@ export function createBunPreviewBuilder() {
|
|
|
119
186
|
if (closed) throw new Error("Preview compiler is closed.");
|
|
120
187
|
const signature = JSON.stringify([options.root, options.config, watched]);
|
|
121
188
|
if (context !== signature) {
|
|
122
|
-
|
|
189
|
+
transforms.reset();
|
|
123
190
|
workerResults.clear();
|
|
124
|
-
disposeEvalBroker(cache);
|
|
125
|
-
cache.clear("all");
|
|
126
191
|
previous = undefined;
|
|
127
192
|
context = signature;
|
|
128
193
|
}
|
|
@@ -218,57 +283,7 @@ export function createBunPreviewBuilder() {
|
|
|
218
283
|
inputs.add(file);
|
|
219
284
|
let code = original;
|
|
220
285
|
if (!file.includes(`${path.sep}node_modules${path.sep}`) && /@linaria\//.test(original)) {
|
|
221
|
-
const
|
|
222
|
-
let value = previous;
|
|
223
|
-
const spatialChanged = previous?.spatialRevision !== undefined && previous.spatialRevision !== (readSpatial()?.revision ?? null);
|
|
224
|
-
if (!value || value.source !== hash(original) || spatialChanged || value.dependencies.some(([dependency, digest]) => fileHash(dependency) !== digest)) {
|
|
225
|
-
// Membership changes (a new token sheet) are not in the previous file
|
|
226
|
-
// dependency list. Invalidate this extraction, even with identical TS.
|
|
227
|
-
if (spatialChanged) cache.invalidateForFile(file);
|
|
228
|
-
if (previous) for (const [dependency, digest, imported] of previous.dependencies) if (fileHash(dependency) !== digest) {
|
|
229
|
-
cache.invalidateForFile(dependency);
|
|
230
|
-
if (imported) cache.invalidateForFile(imported);
|
|
231
|
-
if (existsSync(dependency)) cache.invalidateIfChanged(dependency, readFileSync(dependency, "utf8"));
|
|
232
|
-
}
|
|
233
|
-
cache.invalidateIfChanged(file, original);
|
|
234
|
-
let usedSpatial = false;
|
|
235
|
-
const result = await timing.timeStage("linaria-transform", () => spatialInputs.withSpatialInputs(() => {
|
|
236
|
-
usedSpatial = true;
|
|
237
|
-
return readSpatial();
|
|
238
|
-
}, () => transform(
|
|
239
|
-
{ cache, asyncResolveKey: sourceRevision, options: { filename: file, root: options.root, pluginOptions: { configFile: false, tagResolver: linariaTagResolver } } },
|
|
240
|
-
original,
|
|
241
|
-
async (specifier, importer) => resolve(specifier, importer),
|
|
242
|
-
)));
|
|
243
|
-
const classes = new Set(
|
|
244
|
-
Object.values(result.rules ?? {})
|
|
245
|
-
.map((rule) => rule.className)
|
|
246
|
-
.filter(Boolean),
|
|
247
|
-
);
|
|
248
|
-
if (result.cssText)
|
|
249
|
-
postcss.parse(result.cssText).walkRules((rule) => {
|
|
250
|
-
if (!keyframeRule(rule)) for (const name of selectorClasses(rule.selector)) classes.add(name);
|
|
251
|
-
});
|
|
252
|
-
// A computed interpolation can introduce a layout without @ads- in
|
|
253
|
-
// this source. Record the processor's actual use, not a source regex.
|
|
254
|
-
const spatial = usedSpatial || previous?.spatialRevision !== undefined ? readSpatial() : undefined;
|
|
255
|
-
value = {
|
|
256
|
-
source: hash(original),
|
|
257
|
-
code: await pureClassComposition(result.code, file),
|
|
258
|
-
css: result.cssText,
|
|
259
|
-
classes: [...classes],
|
|
260
|
-
...(spatial !== undefined ? { spatialRevision: spatial?.revision ?? null } : {}),
|
|
261
|
-
// The shared spatial revision already checks every sheet once per
|
|
262
|
-
// build. Keep watcher membership without rehashing them per owner.
|
|
263
|
-
spatialInputs: spatial?.inputs ?? [],
|
|
264
|
-
dependencies: [...new Set([file, ...(result.dependencies ?? [])])].map((dependency) => {
|
|
265
|
-
const imported = path.isAbsolute(dependency) ? dependency : path.resolve(path.dirname(file), dependency);
|
|
266
|
-
const absolute = existsSync(imported) ? imported : resolve(dependency, file);
|
|
267
|
-
return [absolute, fileHash(absolute), imported];
|
|
268
|
-
}),
|
|
269
|
-
};
|
|
270
|
-
transformed.set(file, value);
|
|
271
|
-
}
|
|
286
|
+
const value = await transforms.transform(file, original, { options, resolve, sourceRevision, readSpatial });
|
|
272
287
|
code = value.code;
|
|
273
288
|
for (const [dependency] of value.dependencies) inputs.add(dependency);
|
|
274
289
|
for (const dependency of value.spatialInputs) inputs.add(dependency);
|
|
@@ -566,12 +581,13 @@ export function createBunPreviewBuilder() {
|
|
|
566
581
|
previous = undefined;
|
|
567
582
|
transformed.clear();
|
|
568
583
|
workerResults.clear();
|
|
569
|
-
|
|
570
|
-
await disposeEvalBroker(cache);
|
|
584
|
+
await transforms.close();
|
|
571
585
|
if (directory) rmSync(directory, { recursive: true, force: true });
|
|
572
586
|
};
|
|
573
587
|
const measured = (...args) => timing.timeStage("preview-build", () => builder(...args));
|
|
574
588
|
measured.warmBatch = builder.warmBatch;
|
|
575
589
|
measured.close = builder.close;
|
|
590
|
+
// Benchmark inspection: before preview-only provenance and import pruning.
|
|
591
|
+
measured.transformedModules = () => new Map(transformed);
|
|
576
592
|
return measured;
|
|
577
593
|
}
|