@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.
@@ -0,0 +1,358 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { createServer as createHttpServer } from "node:http";
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { createServer } from "vite";
7
+ import react from "@vitejs/plugin-react";
8
+ import prefresh from "@prefresh/vite";
9
+ import { init, parse } from "es-module-lexer";
10
+ import valueParser from "postcss-value-parser";
11
+ import { createBunPreviewBuilder, createPreviewTransforms, previewFrameFiles, previewIdentities } from "./preview-bun.mjs";
12
+ import { createPreviewImportOptimizer } from "./preview-imports.mjs";
13
+ import { createPreviewResources } from "./preview-resources.mjs";
14
+ import { spatialMetadata } from "./spatial-metadata.mjs";
15
+ import spatialInputs from "./linaria/spatial-inputs.cjs";
16
+
17
+ const hash = value => createHash("sha256").update(value).digest("hex");
18
+ const slash = value => value.replaceAll("\\", "/");
19
+ const fingerprint = file => { try { return hash(readFileSync(file)); } catch { return null; } };
20
+ const cleanUrl = value => value.replace(/([?&])(?:t|v)=[^&]+&?/g, "$1").replace(/[?&]$/, "");
21
+ const clientId = "/@vite/client";
22
+ const bootstrapId = "/@ads/refresh-bootstrap";
23
+ const clientCode = `export const createHotContext=id=>globalThis.__adsPreviewHot.context(id);
24
+ export function injectQuery(url,query){if(!url.startsWith('.')&&!url.startsWith('/'))return url;const parsed=new URL(url,'http://ads');return url.split(/[?#]/)[0]+'?'+query+(parsed.search?'&'+parsed.search.slice(1):'')+parsed.hash;}`;
25
+
26
+ /** A development module graph, never a public dev server. The shared compiler
27
+ * scheduler fences and publishes its immutable output through MCP resources.
28
+ * Complete verification builds retain the existing Bun compiler. */
29
+ export function createIncrementalPreviewBuilder() {
30
+ const complete = createBunPreviewBuilder();
31
+ let state, closed = false, running = Promise.resolve();
32
+ async function build(entries, options, track, context = {}) {
33
+ if (closed) throw new Error("Preview compiler is closed.");
34
+ if (!context.watched) return complete(entries, options, track, context);
35
+ const configuration = JSON.stringify([options.root, options.config,
36
+ ...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "tsconfig.json"].map(file => fingerprint(path.join(options.root, file)))]);
37
+ if (state?.configuration !== configuration || state?.exhausted || state?.dependenciesChanged || state?.membershipChanged) {
38
+ await state?.close();
39
+ state = await createGraph(options, configuration);
40
+ }
41
+ return state.build(entries, track, context.sourceRevision);
42
+ }
43
+ // The scheduler is serial, but own the lifetime here too: disposal must not
44
+ // close native extraction or the module graph underneath an in-flight build.
45
+ const builder = (...args) => {
46
+ const task = running.then(() => build(...args));
47
+ running = task.catch(() => {});
48
+ return task;
49
+ };
50
+ builder.close = async () => { closed = true; await running; await state?.close(); await complete.close(); };
51
+ builder.transformedModules = () => new Map(state?.transforms.values);
52
+ builder.stats = () => state?.stats;
53
+ // Preserve the scheduler's existing background batching. Publishing each
54
+ // unvisited root separately can keep the selected view pending for the whole
55
+ // warm-up catalogue, despite its own build and checks already completing.
56
+ builder.warmBatch = true;
57
+ return builder;
58
+ }
59
+
60
+ async function createGraph(options, configuration) {
61
+ await init;
62
+ process.env.WYW_NODE_BINARY = process.execPath;
63
+ const directory = path.join(options.root, ".ds/incremental", randomUUID());
64
+ mkdirSync(directory, { recursive: true });
65
+ const transforms = createPreviewTransforms(), sheets = new Map(), inputs = new Set(), digests = new Map();
66
+ const lowered = new Map(), generated = new Map(), workerCache = new Map(), preparedCache = new Map();
67
+ const optimizedInputs = new Set();
68
+ const workerBuilder = createBunPreviewBuilder();
69
+ const epoch = randomUUID(), socketHost = createHttpServer();
70
+ const refreshInclude = new RegExp("^" + slash(options.dsRoot).replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "/");
71
+ let revision, spatial, optimizer, server, membership, active = Promise.resolve(), stats;
72
+ const frame = path.dirname(previewFrameFiles[0]);
73
+ const alias = specifier => specifier === options.config.publicAlias ? path.join(options.dsRoot, options.config.publicEntry)
74
+ : specifier === options.config.publicAlias + "/review" ? path.join(options.dsRoot, options.config.reviewEntry)
75
+ : specifier === "@reqvire-org/ads/preview" ? previewFrameFiles[0] : specifier;
76
+ const resolve = (specifier, importer) => Bun.resolveSync(alias(specifier), path.dirname(importer));
77
+ const readSpatial = () => spatial ??= spatialInputs.captureSpatial(options);
78
+ function inputMembership() {
79
+ const directories = new Map();
80
+ function inspect(directory, recursive = false) {
81
+ if (directories.has(directory)) return;
82
+ let entries;
83
+ try { entries = readdirSync(directory, { withFileTypes: true }); }
84
+ catch (error) { if (error.code !== "ENOENT") throw error; directories.set(directory, null); return; }
85
+ directories.set(directory, entries.map(entry => [entry.name, entry.isDirectory(), entry.isSymbolicLink()]).sort());
86
+ if (recursive) for (const entry of entries) if (entry.isDirectory()) inspect(path.join(directory, entry.name), true);
87
+ }
88
+ // A newly added sibling can outrank a previously resolved import without
89
+ // changing any recorded file bytes. Observe membership, not only contents.
90
+ inspect(options.dsRoot, true);
91
+ for (const file of inputs) {
92
+ if (file.startsWith(options.dsRoot + path.sep) || file.startsWith(directory + path.sep)) continue;
93
+ let parent = path.dirname(file);
94
+ inspect(parent);
95
+ while (parent.startsWith(options.root + path.sep)) { parent = path.dirname(parent); inspect(parent); }
96
+ }
97
+ return hash(JSON.stringify([...directories].sort()));
98
+ }
99
+ const sourceUrl = file => file.startsWith(options.root + path.sep) ? "/" + slash(path.relative(options.root, file)) : "/@fs" + slash(file);
100
+ function sourceFile(url) {
101
+ const pathname = decodeURI(url.split("?")[0]);
102
+ return pathname.startsWith("/@fs/") ? pathname.slice(4) : path.join(options.root, pathname);
103
+ }
104
+ async function lower(code, file) {
105
+ inputs.add(file);
106
+ const previous = lowered.get(file);
107
+ if (previous && previous.revision === revision && previous.source === code) return previous.code;
108
+ const original = code;
109
+ let value;
110
+ if (/@linaria\//.test(code)) {
111
+ const before = transforms.values.get(file);
112
+ value = await transforms.transform(file, code, { options, resolve, sourceRevision: revision, readSpatial });
113
+ if (before !== value) stats.extracted.push(file);
114
+ code = value.code;
115
+ for (const [dependency] of value.dependencies) inputs.add(dependency);
116
+ for (const dependency of value.spatialInputs) inputs.add(dependency);
117
+ sheets.set(file + ".ads-incremental.css", value.css ?? "");
118
+ }
119
+ optimizer ??= createPreviewImportOptimizer(options, resolve, inputs);
120
+ code = await (await optimizer)(code, file);
121
+ code = await previewIdentities(code, file, options);
122
+ if (value?.css) code += `\nimport ${JSON.stringify(file + ".ads-incremental.css")};\n`;
123
+ lowered.set(file, { revision, source: original, code });
124
+ stats.transformed.push(file);
125
+ return code;
126
+ }
127
+ const plugin = {
128
+ name: "ads-preview-source", enforce: "pre",
129
+ resolveId(id) { if (sheets.has(id) || id === bootstrapId) return id; },
130
+ load(id) {
131
+ if (sheets.has(id)) return sheets.get(id);
132
+ if (id === bootstrapId) return options.config.framework === "react"
133
+ ? 'import {injectIntoGlobalHook} from "/@react-refresh";injectIntoGlobalHook(globalThis);globalThis.$RefreshReg$=()=>{};globalThis.$RefreshSig$=()=>type=>type;'
134
+ : "export {};";
135
+ },
136
+ async transform(code, id) {
137
+ if (!id.startsWith(options.dsRoot + path.sep) || !/\.[cm]?[jt]sx?$/.test(id)) return;
138
+ const task = active.then(() => lower(code, id));
139
+ active = task.catch(() => {});
140
+ return { code: await task, map: null };
141
+ },
142
+ };
143
+ try {
144
+ server = await createServer({
145
+ configFile: false, envFile: false, root: options.root, publicDir: false,
146
+ cacheDir: path.join(directory, "deps"), logLevel: "silent",
147
+ // Preserve original artwork bytes and the resource bridge's fetch policy.
148
+ // Vite otherwise minifies small SVGs into data URLs during development.
149
+ build: { assetsInlineLimit: 0 },
150
+ plugins: [plugin, ...(options.config.framework === "react" ? [react({ include: refreshInclude })] : [prefresh({ include: refreshInclude })])],
151
+ esbuild: { jsx: "automatic", jsxImportSource: options.config.framework },
152
+ resolve: { dedupe: ["react", "react-dom", "preact"], alias: [
153
+ { find: options.config.publicAlias + "/review", replacement: path.join(options.dsRoot, options.config.reviewEntry) },
154
+ { find: options.config.publicAlias, replacement: path.join(options.dsRoot, options.config.publicEntry) },
155
+ { find: "@reqvire-org/ads/preview", replacement: previewFrameFiles[0] },
156
+ ] },
157
+ optimizeDeps: { noDiscovery: true, esbuildOptions: { plugins: [{
158
+ name: "ads-preview-dependency-inputs",
159
+ setup(build) { build.onLoad({ filter: /./ }, args => {
160
+ if (path.isAbsolute(args.path)) { optimizedInputs.add(args.path); inputs.add(args.path); }
161
+ }); },
162
+ }] }, include: [
163
+ ...(options.config.framework === "react" ? ["react", "react-dom/client", "react/jsx-runtime", "react/jsx-dev-runtime"] : ["preact", "preact/hooks", "preact/jsx-runtime", "preact/jsx-dev-runtime"]),
164
+ "@linaria/atomic", ...options.config.behaviorLibraries,
165
+ ] },
166
+ server: { middlewareMode: true, hmr: { server: socketHost }, watch: null, preTransformRequests: false,
167
+ fs: { allow: [options.root, path.dirname(fileURLToPath(import.meta.url)), path.dirname(Bun.resolveSync(options.config.framework, options.root)),
168
+ ...["@prefresh/core", "@prefresh/utils"].map(name => path.dirname(Bun.resolveSync(name + "/package.json", import.meta.dirname)))] } },
169
+ });
170
+ } catch (error) { await transforms.close(); rmSync(directory, { recursive: true, force: true }); throw error; }
171
+
172
+ async function invalidate(nextRevision) {
173
+ revision = nextRevision; spatial = undefined; optimizer = undefined;
174
+ const changed = new Set([...digests].filter(([file, digest]) => fingerprint(file) !== digest).map(([file]) => file));
175
+ for (const [file, value] of transforms.values) {
176
+ if (value.dependencies.some(([dependency]) => changed.has(dependency)) ||
177
+ (value.spatialRevision !== undefined && value.spatialRevision !== (readSpatial()?.revision ?? null))) changed.add(file);
178
+ }
179
+ // Import optimization reads public barrels/package side-effect policy.
180
+ // Recheck those consumers when their captured resolver inputs change.
181
+ if ([...changed].some(file => !lowered.has(file))) for (const [file, value] of lowered)
182
+ if (value.source.includes(options.config.publicAlias)) changed.add(file);
183
+ for (const file of changed) {
184
+ lowered.delete(file);
185
+ if (sheets.has(file + ".ads-incremental.css")) {
186
+ // Vite's CSS node has its own transform cache.
187
+ for (const node of server.moduleGraph.getModulesByFile(file + ".ads-incremental.css") ?? []) server.moduleGraph.invalidateModule(node);
188
+ }
189
+ for (const node of server.moduleGraph.getModulesByFile(file) ?? []) server.moduleGraph.invalidateModule(node);
190
+ }
191
+ stats.changed = [...changed];
192
+ }
193
+
194
+ async function snapshot(entries) {
195
+ const output = new Map(), queued = new Map();
196
+ const moduleName = url => "module-" + hash(cleanUrl(url)) + ".js";
197
+ async function asset(url) {
198
+ const file = sourceFile(url), bytes = readFileSync(file);
199
+ inputs.add(file);
200
+ const name = "asset-" + hash(bytes) + path.extname(file);
201
+ output.set(name, { type: "asset", fileName: name, source: bytes });
202
+ return name;
203
+ }
204
+ async function worker(url) {
205
+ const file = sourceFile(url), previous = workerCache.get(file);
206
+ let value = previous;
207
+ if (!value || value.inputs.some(([input, digest]) => fingerprint(input) !== digest)) {
208
+ const result = await workerBuilder([], options, { generateBundle() {} }, { watched: true, workerEntry: file, sourceRevision: revision });
209
+ const main = result.outputs.find(item => item.kind === "entry-point"), bytes = Buffer.from(main.bytes, "base64");
210
+ value = { name: "worker-" + hash(bytes) + ".js", inputs: result.inputs.map(input => [input, fingerprint(input)]),
211
+ assets: [...result.assets.map(item => ({ ...item, source: Buffer.from(item.source, "base64") })),
212
+ ...result.outputs.filter(item => item !== main).map(item => ({ type: "asset", fileName: item.path.replace(/^\.\//, ""), source: Buffer.from(item.bytes, "base64") }))], bytes };
213
+ workerCache.set(file, value);
214
+ }
215
+ for (const [input] of value.inputs) inputs.add(input);
216
+ for (const item of value.assets) output.set(item.fileName, item);
217
+ output.set(value.name, { type: "asset", fileName: value.name, source: value.bytes });
218
+ return value.name;
219
+ }
220
+ function queue(url) {
221
+ url = cleanUrl(url);
222
+ if (!queued.has(url)) queued.set(url, undefined);
223
+ return moduleName(url);
224
+ }
225
+ async function cssAsset(code, url) {
226
+ const parsed = valueParser(code), targets = [];
227
+ parsed.walk(node => {
228
+ if (node.type !== "function" || node.value !== "url") return;
229
+ const value = valueParser.stringify(node.nodes).replace(/^["']|["']$/g, "");
230
+ if (value.startsWith("/") && !value.startsWith("//")) targets.push([node, value]);
231
+ });
232
+ for (const [node, value] of targets) {
233
+ const [target, fragment] = value.split("#");
234
+ node.nodes = [{ type: "string", quote: '"', value: "./" + await asset(target) + (fragment ? "#" + fragment : "") }];
235
+ }
236
+ const source = parsed.toString(), name = "style-" + hash(cleanUrl(url)) + ".css";
237
+ const owner = sourceFile(url).replace(/\.ads-incremental\.css$/, "");
238
+ output.set(name, { type: "asset", fileName: name, source, spatial: spatialMetadata(source, slash(path.relative(options.root, owner))) });
239
+ return name;
240
+ }
241
+ const roots = entries.map((entry, index) => {
242
+ const file = path.join(directory, hash(entry.id) + ".tsx");
243
+ const mount = entry.foundation
244
+ ? `import {mountFoundation} from ${JSON.stringify(path.join(frame, "foundation-view.mjs"))};export const mount=container=>mountFoundation(container,${JSON.stringify(entry.foundation)});`
245
+ : `import {mountScenario} from ${JSON.stringify(path.join(options.dsRoot, "showcase/mcp/main.ads.mount.tsx"))};import Scenario from ${JSON.stringify(path.join(options.root, entry.file))};export const mount=container=>mountScenario(Scenario,container);`;
246
+ // The configured design-system sheet belongs to every preview, including
247
+ // tool-generated foundations which do not import a project mount adapter.
248
+ const code = `import ${JSON.stringify(path.join(options.dsRoot, options.config.stylesEntry))};\nimport ${JSON.stringify(bootstrapId)};\n` + mount;
249
+ if (generated.get(file) !== code) {
250
+ writeFileSync(file, code); generated.set(file, code);
251
+ for (const node of server.moduleGraph.getModulesByFile(file) ?? []) server.moduleGraph.invalidateModule(node);
252
+ }
253
+ const url = sourceUrl(file); queue(url);
254
+ return [moduleName(url), index];
255
+ });
256
+ for (const [url] of queued) {
257
+ if (queued.size > 4096) throw new Error("Preview module graph exceeds 4096 modules.");
258
+ const transformed = url === clientId ? { code: clientCode } : await server.transformRequest(url);
259
+ if (!transformed) throw new Error("Missing preview module: " + url);
260
+ const node = await server.moduleGraph.getModuleByUrl(url);
261
+ if (node?.file && existsSync(node.file)) inputs.add(node.file);
262
+ let code = transformed.code.replace(/\n\/\/# sourceMappingURL=.*$/gm, "");
263
+ // Prefresh owns hook signatures/replacement. Unlike React Refresh it does
264
+ // not validate mixed exports itself; keep changed non-component exports
265
+ // from being silently accepted with stale importer bindings.
266
+ if (options.config.framework === "preact" && node?.file?.startsWith(options.dsRoot + path.sep) && code.includes("import.meta.hot")) {
267
+ const utils = sourceUrl(Bun.resolveSync("@prefresh/utils", import.meta.dirname));
268
+ code += `\nimport {isComponent as __adsIsComponent} from ${JSON.stringify(utils)};globalThis.__adsPreviewHot.observe(${JSON.stringify(node.url)},import.meta.url,__adsIsComponent);\n`;
269
+ }
270
+ const styles = [];
271
+ // Vite compiles @imports/assets/CSS modules. ADS owns stylesheet attachment
272
+ // and removal, so its snapshot carries the CSS as an ordinary graph asset.
273
+ if (/\.css(?:\?|$)/.test(url) && !/[?&](?:inline|raw)(?:&|$)/.test(url)) {
274
+ const match = code.match(/(?:const|let|var) __vite__css = ("(?:[^"\\]|\\.)*")/);
275
+ if (match) {
276
+ styles.push(await cssAsset(JSON.parse(match[1]), url));
277
+ code = code.replace(match[0], 'const __vite__css = ""').replace(/^import .*from ["']\/@vite\/client["'];?\s*$/gm, "")
278
+ .replace(/^__vite__updateStyle\([^\n]*\)\s*;?$/gm, "")
279
+ .replace(/^import\.meta\.hot\.[^\n]*$/gm, "")
280
+ .replace(/^import\.meta\.hot\s*=.*$/gm, "");
281
+ }
282
+ }
283
+ const imports = [], dynamicImports = [], edits = [];
284
+ for (const item of parse(code)[0]) {
285
+ if (item.d === -2) continue;
286
+ // React Refresh's self-import receives the already materialized module
287
+ // URL. Authored dynamic imports still need a finite registered closure.
288
+ if (!item.n && url === "/@react-refresh") continue;
289
+ if (!item.n) throw new Error("Preview dynamic imports must resolve to registered local modules: " + url);
290
+ if (/^(?:https?:|data:|blob:)/.test(item.n)) throw new Error("Preview modules must use registered local resources: " + item.n);
291
+ const resolved = new URL(item.n, "http://ads" + url);
292
+ const targetUrl = resolved.pathname + resolved.search;
293
+ const target = queue(targetUrl);
294
+ (item.d < 0 ? imports : dynamicImports).push(target);
295
+ edits.push([item.s, item.e, item.d < 0 ? "./" + target : JSON.stringify("./" + target)]);
296
+ }
297
+ // Asset wrappers and worker constructors contain compiler-generated URLs.
298
+ for (const match of code.matchAll(/"(\/(?:[^"\\\r\n]|\\.)*)"/g)) {
299
+ const value = JSON.parse(match[0]);
300
+ // Static import spans exclude their quotes, while this match includes
301
+ // them. Any overlap means the module rewrite already owns this string.
302
+ if (edits.some(([start, end]) => start < match.index + match[0].length && end > match.index)) continue;
303
+ if (/[?&]worker_file(?:&|=|$)/.test(value)) edits.push([match.index, match.index + match[0].length, JSON.stringify("./" + await worker(value))]);
304
+ else {
305
+ const file = sourceFile(value);
306
+ const urlImport = /[?&]url(?:&|$)/.test(url) && node?.file === file;
307
+ const urlConstructor = /new URL\(\s*(?:\/\* @vite-ignore \*\/\s*)?$/.test(code.slice(0, match.index));
308
+ if ((server.config.assetsInclude(file) || urlImport || urlConstructor) && existsSync(file))
309
+ edits.push([match.index, match.index + match[0].length, JSON.stringify("./" + await asset(value))]);
310
+ }
311
+ }
312
+ for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) code = code.slice(0, start) + replacement + code.slice(end);
313
+ const name = moduleName(url);
314
+ output.set(name, { type: "chunk", fileName: name, code, imports, dynamicImports,
315
+ viteMetadata: { importedCss: new Set(styles) }, hot: { id: url, source: hash(code) } });
316
+ queued.set(url, name);
317
+ }
318
+ for (const [file, index] of roots) output.get(file).facadeModuleId = "\0ads-preview-entry:" + index;
319
+ return { output: [...output.values()] };
320
+ }
321
+ return {
322
+ configuration, transforms, get stats() { return stats; },
323
+ // Optimized modules live in the private temporary directory. Their original
324
+ // inputs still belong to cache evidence, including transitive CJS requires.
325
+ // Recreate the optimizer when those bytes change; invalidating a source node
326
+ // alone cannot invalidate an already optimized dependency bundle.
327
+ get dependenciesChanged() {
328
+ return [...optimizedInputs].some(file => digests.has(file) && fingerprint(file) !== digests.get(file));
329
+ },
330
+ // Vite owns resolution caches in addition to transforms. Renew the graph
331
+ // on additions/deletions rather than reusing an old resolved module ID.
332
+ get membershipChanged() { return membership === undefined || inputMembership() !== membership; },
333
+ // Vite retains graph nodes for deleted/renamed files; extraction also owns
334
+ // reusable evaluations. Bound this session without dropping input evidence
335
+ // from a still-live cache. A new epoch gives the browser a clean renderer.
336
+ get exhausted() {
337
+ return inputs.size > 4096 || server.moduleGraph.idToModuleMap.size > 4096 ||
338
+ [...lowered.values()].reduce((size, value) => size + Buffer.byteLength(value.source) + Buffer.byteLength(value.code), 0) > 64 * 1024 * 1024;
339
+ },
340
+ async build(entries, track, nextRevision) {
341
+ stats = { transformed: [], extracted: [], changed: [] };
342
+ await invalidate(nextRevision);
343
+ const output = await snapshot(entries);
344
+ // PostCSS inlines CSS imports. Vite records these as file-only graph nodes,
345
+ // so they must join byte fingerprints even though no JS import queues them.
346
+ for (const file of server.moduleGraph.fileToModulesMap.keys()) inputs.add(file);
347
+ const sourceInputs = [...inputs].filter(file => !file.startsWith(directory + path.sep));
348
+ track.generateBundle.call({ getModuleIds: () => sourceInputs });
349
+ for (const file of sourceInputs) digests.set(file, fingerprint(file));
350
+ membership = inputMembership();
351
+ return createPreviewResources(output, options, entries, { prune: true, refresh: { version: 1, epoch }, preparedCache });
352
+ },
353
+ async close() {
354
+ await active; await server.close(); await transforms.close(); await workerBuilder.close();
355
+ socketHost.close(); rmSync(directory, { recursive: true, force: true });
356
+ },
357
+ };
358
+ }
@@ -0,0 +1,70 @@
1
+ const revisionPattern = /^[a-f0-9]{64}$/;
2
+ const assetPattern = /^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/;
3
+ const equal = (left, right) => JSON.stringify(left) === JSON.stringify(right);
4
+ const metadata = ({ assets: _assets, scenarios: _scenarios, ...header }) => header;
5
+
6
+ /** Internal UI transport only. Existing full-manifest resources stay unchanged. */
7
+ export function previewManifestUpdate(current, previous) {
8
+ const full = { version: 1, type: "full", manifest: current };
9
+ if (!previous) return full;
10
+ const header = metadata(current), baseRevision = previous.revision;
11
+ if (baseRevision === current.revision) return { version: 1, type: "unchanged", baseRevision, header };
12
+ const oldScenarios = new Map(previous.scenarios.map(item => [item.id, item]));
13
+ const order = current.scenarios.map(item => item.id);
14
+ const patch = {
15
+ version: 1, type: "delta", baseRevision, header,
16
+ assets: {
17
+ upsert: Object.fromEntries(Object.entries(current.assets).filter(([uri, record]) => !equal(record, previous.assets[uri]))),
18
+ remove: Object.keys(previous.assets).filter(uri => !Object.hasOwn(current.assets, uri)),
19
+ },
20
+ scenarios: {
21
+ upsert: current.scenarios.filter(item => !equal(item, oldScenarios.get(item.id))),
22
+ remove: previous.scenarios.filter(item => !order.includes(item.id)).map(item => item.id),
23
+ ...(!equal(order, previous.scenarios.map(item => item.id)) ? { order } : {}),
24
+ },
25
+ };
26
+ return JSON.stringify(patch).length < JSON.stringify(full).length ? patch : full;
27
+ }
28
+
29
+ function validate(graph) {
30
+ if (graph?.schemaVersion !== 1 || !["react", "preact"].includes(graph.framework) || !revisionPattern.test(graph.revision) ||
31
+ !graph.assets || typeof graph.assets !== "object" || Array.isArray(graph.assets) || !Array.isArray(graph.scenarios)) throw new Error("Invalid preview manifest update.");
32
+ const ids = new Set();
33
+ for (const scenario of graph.scenarios) {
34
+ if (!scenario || typeof scenario.id !== "string" || ids.has(scenario.id) || graph.assets[scenario.module]?.kind !== "module") throw new Error("Invalid updated preview scenarios.");
35
+ ids.add(scenario.id);
36
+ }
37
+ for (const [uri, record] of Object.entries(graph.assets)) {
38
+ if (!assetPattern.test(uri) || !record || !["imports", "dynamicImports", "styles", "references"].every(key =>
39
+ Array.isArray(record[key]) && record[key].every(target => Object.hasOwn(graph.assets, target)))) throw new Error("Invalid updated preview dependencies.");
40
+ }
41
+ return graph;
42
+ }
43
+
44
+ /** Reconstruct without mutating a cached revision or trusting a different base. */
45
+ export function applyPreviewManifestUpdate(update, previous) {
46
+ if (update?.version !== 1) throw new Error("Unsupported preview manifest update.");
47
+ if (update.type === "full") return validate(update.manifest);
48
+ if (!previous || update.baseRevision !== previous.revision) throw new Error("Preview manifest update base does not match.");
49
+ const header = update.header;
50
+ if (!header || Object.hasOwn(header, "assets") || Object.hasOwn(header, "scenarios") || !revisionPattern.test(header.revision)) throw new Error("Invalid preview manifest update header.");
51
+ if (update.type === "unchanged") {
52
+ if (header.revision !== previous.revision) throw new Error("Unchanged preview revision does not match.");
53
+ return validate({ ...header, assets: previous.assets, scenarios: previous.scenarios });
54
+ }
55
+ if (update.type !== "delta" || !update.assets?.upsert || !Array.isArray(update.assets.remove) ||
56
+ !Array.isArray(update.scenarios?.upsert) || !Array.isArray(update.scenarios.remove)) throw new Error("Invalid preview manifest delta.");
57
+ const assets = new Map(Object.entries(previous.assets)), scenarios = new Map(previous.scenarios.map(item => [item.id, item]));
58
+ for (const uri of update.assets.remove) if (!assets.delete(uri)) throw new Error("Unknown removed preview asset.");
59
+ for (const [uri, record] of Object.entries(update.assets.upsert)) assets.set(uri, record);
60
+ for (const id of update.scenarios.remove) if (!scenarios.delete(id)) throw new Error("Unknown removed preview scenario.");
61
+ const changed = new Set();
62
+ for (const item of update.scenarios.upsert) {
63
+ if (!item || changed.has(item.id)) throw new Error("Duplicate updated preview scenario.");
64
+ changed.add(item.id); scenarios.set(item.id, item);
65
+ }
66
+ const order = update.scenarios.order ?? previous.scenarios.map(item => item.id);
67
+ if (!Array.isArray(order) || order.length !== scenarios.size || new Set(order).size !== order.length || order.some(id => !scenarios.has(id)))
68
+ throw new Error("Invalid updated preview scenario order.");
69
+ return validate({ ...header, assets: Object.fromEntries(assets), scenarios: order.map(id => scenarios.get(id)) });
70
+ }
@@ -6,6 +6,7 @@ import ts from "./analysis/syntax.mjs";
6
6
  import valueParser from "postcss-value-parser";
7
7
  import { isInside } from "./config.mjs";
8
8
  import { livePreviewOptions, previewArtifactPath, previewManifestPath } from "./preview-scope.mjs";
9
+ import { previewManifestUpdate } from "./preview-manifest-update.mjs";
9
10
 
10
11
  export const PREVIEW_APP_URI = "ui://ads/preview";
11
12
  export const PREVIEW_MANIFEST_URI = "ads://preview/manifest";
@@ -102,10 +103,15 @@ function resourceUris(prepared) {
102
103
  }
103
104
 
104
105
  /** Convert compiler output to registered MCP resources without evaluating project code. */
105
- export async function createPreviewResources(output, options, entries, { retain, prune = false } = {}) {
106
+ export async function createPreviewResources(output, options, entries, { retain, prune = false, refresh, preparedCache } = {}) {
106
107
  const bundle = (Array.isArray(output) ? output : [output]).flatMap((result) => result.output);
107
108
  const files = new Map(bundle.map((item) => [item.fileName, item]));
108
109
  const original = (item) => Buffer.from(item.type === "chunk" ? item.code : item.source);
110
+ // One prepared rewrite per current output file. Membership matters because a
111
+ // formerly external string can become a graph reference. Worker bytes also
112
+ // participate: unchanged callers must recheck a changed worker's module form.
113
+ const membership = preparedCache && hash(JSON.stringify(bundle.map(item => [item.fileName, item.type,
114
+ item.type === "asset" && item.fileName.endsWith(".js") ? hash(original(item)) : null]).sort((a, b) => a[0].localeCompare(b[0]))));
109
115
  const prepared = new Map();
110
116
  const records = { ...retain?.manifest.assets };
111
117
  const contents = new Map(retain?.contents);
@@ -117,6 +123,9 @@ export async function createPreviewResources(output, options, entries, { retain,
117
123
  for (const item of bundle) {
118
124
  const references = new Set();
119
125
  const bytes = original(item);
126
+ const preparationKey = preparedCache && hash(JSON.stringify([membership, hash(bytes), item.imports, item.dynamicImports, [...(item.viteMetadata?.importedCss ?? [])]]));
127
+ const cachedPreparation = preparedCache?.get(item.fileName);
128
+ if (cachedPreparation && cachedPreparation.key === preparationKey) { prepared.set(item.fileName, cachedPreparation.value); continue; }
120
129
  let render = () => bytes;
121
130
  if (item.type === "chunk" || item.fileName.endsWith(".js")) {
122
131
  const source = await ts.createSourceFile(item.fileName, bytes.toString(), ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
@@ -201,7 +210,9 @@ export async function createPreviewResources(output, options, entries, { retain,
201
210
  const styles = item.type === "chunk" ? [...(item.viteMetadata?.importedCss ?? [])].filter((file) => files.has(file)) : [];
202
211
  const links = { imports, dynamicImports, styles, references: [...references] };
203
212
  prepared.set(item.fileName, { file: item.fileName, digest: hash(bytes), links, dependencies, render });
213
+ preparedCache?.set(item.fileName, { key: preparationKey, value: prepared.get(item.fileName) });
204
214
  }
215
+ if (preparedCache) for (const file of preparedCache.keys()) if (!files.has(file)) preparedCache.delete(file);
205
216
  // Bump the transform version in resourceUris whenever rewriting changes.
206
217
  const uris = resourceUris(prepared);
207
218
  for (const item of bundle) {
@@ -216,6 +227,7 @@ export async function createPreviewResources(output, options, entries, { retain,
216
227
  kind: item.type === "chunk" ? "module" : "asset",
217
228
  ...links,
218
229
  ...(item.spatial ? { spatial: item.spatial } : {}),
230
+ ...(item.hot ? { hot: item.hot } : {}),
219
231
  };
220
232
  contents.set(uri, bytes);
221
233
  }
@@ -248,6 +260,7 @@ export async function createPreviewResources(output, options, entries, { retain,
248
260
  const graph = {
249
261
  schemaVersion: 1,
250
262
  framework: options.config.framework,
263
+ ...(refresh ? { refresh } : {}),
251
264
  themes: options.config.themes,
252
265
  ...(options.config.brands?.length ? { brands: options.config.brands } : {}),
253
266
  assets: records,
@@ -394,6 +407,20 @@ export function readPreviewManifest(options, { verify = false } = {}) {
394
407
  return manifest;
395
408
  }
396
409
 
410
+ /** Use only retained, validated metadata in this project's preview scope. Missing
411
+ * history costs a full response; it never changes current-source authorization. */
412
+ export function readPreviewManifestUpdate(options, current, from) {
413
+ if (!/^[a-f0-9]{64}$/.test(from ?? "")) throw new Error("Preview update from must be a SHA-256 revision.");
414
+ if (from === current.revision) return previewManifestUpdate(current, current);
415
+ for (const file of [path.join(path.dirname(previewManifestPath(options)), "history", `${from}.json`), previewManifestPath(cacheOptions(options, from))]) {
416
+ try {
417
+ const previous = readManifestFile(file);
418
+ if (previous.revision === from) return previewManifestUpdate(current, previous);
419
+ } catch { /* Expired/corrupt history cannot become a delta base. */ }
420
+ }
421
+ return previewManifestUpdate(current);
422
+ }
423
+
397
424
  function readManifestFile(file) {
398
425
  if (realpathSync(file) !== file || !statSync(file).isFile() || statSync(file).size > 2 * 1024 * 1024) throw new Error("Invalid preview manifest file.");
399
426
  return validateManifest(JSON.parse(readFileSync(file, "utf8")));
@@ -410,6 +437,9 @@ function validateManifest(manifest) {
410
437
  !Array.isArray(manifest.scenarios)
411
438
  )
412
439
  throw new Error("Invalid preview resource manifest. Rebuild the project previews.");
440
+ if (manifest.refresh && (manifest.refresh.version !== 1 || typeof manifest.refresh.epoch !== "string" || !manifest.refresh.epoch || manifest.refresh.epoch.length > 100))
441
+ throw new Error("Invalid preview refresh protocol.");
442
+ const hotIds = new Set();
413
443
  for (const [uri, record] of Object.entries(manifest.assets)) {
414
444
  if (
415
445
  !record ||
@@ -420,11 +450,13 @@ function validateManifest(manifest) {
420
450
  record.size < 0 ||
421
451
  record.size > 16 * 1024 * 1024 ||
422
452
  typeof record.mimeType !== "string" ||
453
+ (record.hot && (!manifest.refresh || record.kind !== "module" || typeof record.hot.id !== "string" || !record.hot.id || record.hot.id.length > 4096 || hotIds.has(record.hot.id) || !/^[a-f0-9]{64}$/.test(record.hot.source))) ||
423
454
  !["imports", "dynamicImports", "styles", "references"].every(
424
455
  (key) => Array.isArray(record[key]) && record[key].every((ref) => Object.hasOwn(manifest.assets, ref)),
425
456
  )
426
457
  )
427
458
  throw new Error("Invalid preview asset dependency graph.");
459
+ if (record.hot) hotIds.add(record.hot.id);
428
460
  }
429
461
  if (
430
462
  manifest.scenarios.some((entry) => !entry || typeof entry.id !== "string" || manifest.assets[entry.module]?.kind !== "module") ||
@@ -50,13 +50,13 @@ async function build(program, options) {
50
50
  if (value.values.length > 64) return { templates: [], names: [], reason: "Class composition exceeds 64 alternatives." };
51
51
  for (const item of value.values) alternatives.push(await classes(item, values.next(context)));
52
52
  const first = alternatives[0];
53
- if (first && alternatives.every(item => !item.reason && item.templates.length === first.templates.length && item.templates.every((template, i) => template === first.templates[i]) && item.names.join(" ") === first.names.join(" "))) return first;
54
- return { templates: [], names: [], reason: "Class alternatives do not establish one definite style composition." };
53
+ if (first && alternatives.every(item => !item.reason && !item.choices?.length && item.templates.length === first.templates.length && item.templates.every((template, i) => template === first.templates[i]) && item.names.join(" ") === first.names.join(" "))) return first;
54
+ return { templates: [], names: [], choices: [alternatives] };
55
55
  }
56
56
  if (value.kind === "node") {
57
57
  if (ts.isTaggedTemplateExpression(value.node) && await linaria(value.node.tag) === "css") return { templates: [value.node], names: [] };
58
58
  if (ts.isCallExpression(value.node) && await isCx(value.node.expression)) {
59
- const result = { templates: [], names: [] };
59
+ const result = { templates: [], names: [], choices: [] };
60
60
  for (const argument of value.node.arguments) {
61
61
  const items = ts.isSpreadElement(argument)
62
62
  ? await values.arrays(reference(argument.expression, value.env, value.via), values.next(context))
@@ -65,6 +65,7 @@ async function build(program, options) {
65
65
  for (const item of items) {
66
66
  const part = await classes(item, values.next(context));
67
67
  result.templates.push(...part.templates); result.names.push(...part.names);
68
+ result.choices.push(...(part.choices ?? []));
68
69
  result.reason ??= part.reason;
69
70
  }
70
71
  }
@@ -74,6 +75,19 @@ async function build(program, options) {
74
75
  return { templates: [], names: [], reason: value.reason ?? "A class or later prop spread cannot be resolved." };
75
76
  }
76
77
 
78
+ const textTypes = new Map();
79
+ async function textSlot(input) {
80
+ const node = input?.node;
81
+ if (!node || !ts.isIdentifier(node) && !ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node)) return false;
82
+ if (!textTypes.has(node)) textTypes.set(node, (async () => {
83
+ const type = await checker.getTypeAtLocation(node), parts = type?.isUnion() ? type.types : [type];
84
+ const text = ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike;
85
+ const absent = ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.BooleanLike;
86
+ return parts.some(part => part?.flags & text) && parts.every(part => part?.flags & (text | absent));
87
+ })());
88
+ return textTypes.get(node);
89
+ }
90
+
77
91
  async function render(input, parent, context, sites = new Set(), uncertain = false) {
78
92
  if (nodes.length >= 20000 || context.depth > 48 || context.budget.steps > 16000) {
79
93
  limit(input.node ?? parent?.node, "Render composition reached its depth or work limit.");
@@ -95,6 +109,9 @@ async function build(program, options) {
95
109
  return;
96
110
  }
97
111
  if (value.kind !== "node") {
112
+ // A typed text slot needs readable paint for its supplied text. Arbitrary
113
+ // children, failed resolution and bounded-analysis limits remain unknown.
114
+ if (parent && value.kind === "unknown" && !value.reason && await textSlot(input)) { parent.text = true; return; }
98
115
  if (parent) parent.unknownText = value.reason ?? "Dynamic children cannot be established as text.";
99
116
  return;
100
117
  }
@@ -156,9 +173,14 @@ async function build(program, options) {
156
173
  });
157
174
  for (const node of sites) await render(reference(node), null, { ...values.state(), maxSteps: 16000 });
158
175
  }
176
+ function freezeClasses(classes) {
177
+ Object.freeze(classes.templates); Object.freeze(classes.names);
178
+ for (const choice of classes.choices ?? []) { choice.forEach(freezeClasses); Object.freeze(choice); }
179
+ if (classes.choices) Object.freeze(classes.choices);
180
+ Object.freeze(classes);
181
+ }
159
182
  for (const item of nodes) {
160
- Object.freeze(item.classes.templates); Object.freeze(item.classes.names);
161
- Object.freeze(item.classes); Object.freeze(item.children); Object.freeze(item.attributes); Object.freeze(item);
183
+ freezeClasses(item.classes); Object.freeze(item.children); Object.freeze(item.attributes); Object.freeze(item);
162
184
  }
163
185
  return Object.freeze({ roots: Object.freeze(roots), nodes: Object.freeze(nodes), limits: Object.freeze([...limits.values()]) });
164
186
  }
@@ -48,7 +48,7 @@ the browser, and provides a running URL or exact command for review. See the
48
48
  | [ads-designer](ads-designer/SKILL.md) | Bootstrap or build UI using the local ADS, with layout, motion, stress-testing and craft/mobile guidance | `$ads-designer build a settings page using this project's ADS`, `$ads-designer stress-test AppShell +fix`, `$ads-designer review Toast motion` |
49
49
  | [ads-import](ads-import/SKILL.md) | Check destination compatibility, then integrate selected ADS source, artwork or theme values | `$ads-import /path/to/source-repo component Toast` |
50
50
  | [ads-port](ads-port/SKILL.md) | Port library capabilities into a coherent ADS using shared tokens and primitives | `$ads-port https://github.com/emilkowalski/sonner` |
51
- | [ads-migrate](ads-migrate/SKILL.md) | Upgrade an existing design system between ADS versions using version-specific migration guides | `$ads-migrate upgrade this project from ADS 0.4.1 to 0.4.2` |
51
+ | [ads-migrate](ads-migrate/SKILL.md) | Upgrade an existing design system between ADS versions using version-specific migration guides | `$ads-migrate upgrade this project from ADS 0.4.3 to 0.4.4` |
52
52
 
53
53
  For token values, use `$ads-import /path/to/source-repo tokens`; for original
54
54
  artwork and its guidance, use `$ads-import /path/to/source-repo brand`. ADS token
@@ -434,7 +434,11 @@ installed `ads showcase` or the project's `dev:showcase` script. Do not launch a
434
434
  second runtime/compiler for the same connected project. ADS's managed Bun
435
435
  preview compiler publishes a shared graph on first demand and after source
436
436
  changes. The built-in client refreshes discovery and the active scenario in the
437
- same App after a successful build. Shared runtime, foundation CSS, fonts and
437
+ same App; compatible watched edits preserve state and focus. Incompatible edits
438
+ or rollback can reset the frame. Compiled feedback can appear before checks pass:
439
+ use current verified output for captures and acceptance. See
440
+ [runtime guidance](references/runtimes.md) for updates and upgrade behavior.
441
+ Shared runtime, foundation CSS, fonts and
438
442
  selected scenario modules load through MCP
439
443
  resources inside the sandboxed App. Never inject project styles/runtime into
440
444
  the outer host. Keep the declared framework and its native mount/unmount adapter