@reqvire-org/ads 0.3.28 → 0.3.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/atomic-composition.mjs +2 -1
  2. package/dist/behaviors.mjs +2 -2
  3. package/dist/boundaries.mjs +6 -3
  4. package/dist/check.mjs +3 -0
  5. package/dist/cli.mjs +13 -0
  6. package/dist/config.mjs +11 -4
  7. package/dist/mcp/build-status.mjs +18 -5
  8. package/dist/mcp/context.mjs +2 -1
  9. package/dist/mcp/execution-results.mjs +4 -3
  10. package/dist/mcp/mutations.mjs +53 -51
  11. package/dist/mcp/preview-watch.mjs +23 -3
  12. package/dist/mcp/preview-widget.bundle.js +16 -15
  13. package/dist/mcp/resource-loader.js +40 -12
  14. package/dist/mcp/server.mjs +88 -46
  15. package/dist/oxlint.mjs +6 -1
  16. package/dist/preview-builder.mjs +10 -4
  17. package/dist/preview-files.mjs +19 -12
  18. package/dist/preview-inputs.mjs +6 -17
  19. package/dist/preview-resources.mjs +36 -7
  20. package/dist/preview-scope.mjs +6 -0
  21. package/dist/preview-workers.mjs +184 -0
  22. package/dist/project-documents.mjs +4 -0
  23. package/dist/scenario-inspector.mjs +34 -0
  24. package/dist/scenario-trace.mjs +5 -3
  25. package/dist/scenarios-compiler.mjs +200 -25
  26. package/dist/showcase/client.bundle.js +23 -22
  27. package/dist/showcase/index.html +2 -2
  28. package/dist/showcase/style.css +5 -1
  29. package/dist/skills/ads-break-ui/SKILL.md +3 -0
  30. package/dist/skills/ads-break-ui/references/behaviors.md +2 -0
  31. package/dist/skills/ads-break-ui/references/layers.md +6 -0
  32. package/dist/skills/ads-break-ui/references/runtimes.md +31 -0
  33. package/dist/skills/ads-break-ui/references/validation.md +69 -0
  34. package/dist/skills/ads-designer/SKILL.md +3 -0
  35. package/dist/skills/ads-designer/references/behaviors.md +2 -0
  36. package/dist/skills/ads-designer/references/layers.md +6 -0
  37. package/dist/skills/ads-designer/references/runtimes.md +31 -0
  38. package/dist/skills/ads-designer/references/validation.md +69 -0
  39. package/dist/skills/ads-import/SKILL.md +3 -0
  40. package/dist/skills/ads-import/references/behaviors.md +2 -0
  41. package/dist/skills/ads-import/references/layers.md +6 -0
  42. package/dist/skills/ads-import/references/runtimes.md +31 -0
  43. package/dist/skills/ads-import/references/validation.md +69 -0
  44. package/dist/skills/ads-motion/SKILL.md +3 -0
  45. package/dist/skills/ads-motion/references/behaviors.md +2 -0
  46. package/dist/skills/ads-motion/references/layers.md +6 -0
  47. package/dist/skills/ads-motion/references/runtimes.md +31 -0
  48. package/dist/skills/ads-motion/references/validation.md +69 -0
  49. package/dist/skills/ads-port/SKILL.md +3 -0
  50. package/dist/skills/ads-port/references/behaviors.md +2 -0
  51. package/dist/skills/ads-port/references/layers.md +6 -0
  52. package/dist/skills/ads-port/references/runtimes.md +31 -0
  53. package/dist/skills/ads-port/references/validation.md +69 -0
  54. package/dist/source-symbols.mjs +11 -0
  55. package/dist/source-values.mjs +10 -3
  56. package/dist/test-boundaries.mjs +96 -0
  57. package/dist/ui-framework.mjs +2 -1
  58. package/dist/units.mjs +12 -1
  59. package/dist/validation-checks.mjs +50 -0
  60. package/dist/validation-inputs.mjs +132 -0
  61. package/dist/validation.mjs +158 -0
  62. package/dist/verification/browser.mjs +3 -1
  63. package/dist/verification.mjs +1 -0
  64. package/docs/ARCHITECTURE.md +96 -20
  65. package/docs/BEHAVIORS.md +2 -0
  66. package/docs/CHANGELOG.md +74 -0
  67. package/docs/MCP.md +105 -12
  68. package/package.json +1 -1
@@ -4,12 +4,17 @@ import path from "node:path";
4
4
  import ts from "typescript";
5
5
  import valueParser from "postcss-value-parser";
6
6
  import { isInside, loadConfig } from "./config.mjs";
7
- import { previewArtifactPath, previewManifestPath } from "./preview-scope.mjs";
7
+ import { livePreviewOptions, previewArtifactPath, previewManifestPath } from "./preview-scope.mjs";
8
8
 
9
9
  export const PREVIEW_APP_URI = "ui://ads/preview";
10
10
  export const PREVIEW_MANIFEST_URI = "ads://preview/manifest";
11
+ export const LIVE_PREVIEW_MANIFEST_URI = "ads://preview/live";
11
12
  export const assetUriPattern = /^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/;
12
13
  const hash = value => createHash("sha256").update(value).digest("hex");
14
+ // Cache verification metadata only. Resource reads still hash the returned bytes;
15
+ // status polling can reuse a check until the file identity or timestamps change.
16
+ const verifiedAssetFiles = new Map();
17
+ const assetStamp = stat => [stat.dev, stat.ino, stat.mode, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
13
18
  const unknownResource = message => Object.assign(new Error(message), { code: "ADS_PREVIEW_NOT_FOUND" });
14
19
  const mime = file => ({ js: "text/javascript", css: "text/css", json: "application/json", svg: "image/svg+xml", woff2: "font/woff2", woff: "font/woff", ttf: "font/ttf", otf: "font/otf", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif", wasm: "application/wasm" })[file.split(".").pop()] ?? "application/octet-stream";
15
20
  function atomic(file, bytes) {
@@ -142,7 +147,7 @@ function cacheOptions(options, revision) {
142
147
  }
143
148
 
144
149
  /** A cache hit still verifies every compiled byte before republishing it. */
145
- export function cachedPreviewPublication(options, entries, revision) {
150
+ export function cachedPreviewPublication(options, entries, revision, target = options) {
146
151
  if (!/^[a-f0-9]{64}$/.test(revision ?? "")) return null;
147
152
  try {
148
153
  const cached = cacheOptions(options, revision), manifest = readPreviewManifest(cached, { verify: true });
@@ -152,8 +157,12 @@ export function cachedPreviewPublication(options, entries, revision) {
152
157
  const value = readPreviewAsset(cached, uri, manifest);
153
158
  return [uri, "text" in value ? Buffer.from(value.text) : Buffer.from(value.blob, "base64")];
154
159
  }));
160
+ // A compiler may intentionally embed its working directory. Such output
161
+ // cannot be reused from a temporary candidate in the real project.
162
+ const roots=[options.root,options.root.replaceAll("\\","/"),JSON.stringify(options.root).slice(1,-1),encodeURI(options.root)];
163
+ if (target.root !== options.root && [...contents.values()].some(bytes => roots.some(root=>bytes.includes(root)))) return null;
155
164
  const { session: _session, ...graph } = manifest;
156
- return publication(options, entries, graph, contents);
165
+ return publication(target, entries, graph, contents);
157
166
  } catch { return null; } // Missing, pruned or corrupt cache means a real build.
158
167
  }
159
168
 
@@ -162,7 +171,9 @@ function publication(options, entries, manifest, contents, saveCache = true) {
162
171
  const target = previewManifestPath(options);
163
172
  const assetsRoot = path.join(path.dirname(target), "assets");
164
173
  const assetFiles = [...contents.keys()].map(uri => path.join(assetsRoot, uri.slice("ads://assets/".length)));
165
- return { assetFiles, revision, publish(session) {
174
+ return { assetFiles, revision,
175
+ publishLive(session) { publication(livePreviewOptions(options), [], manifest, contents, false).publish(session); },
176
+ publish(session) {
166
177
  const encoded = JSON.stringify({ ...manifest, session });
167
178
  if (Buffer.byteLength(encoded) > 2 * 1024 * 1024) throw new Error("Preview manifest exceeds the 2 MiB resource limit.");
168
179
  const history = path.join(path.dirname(target), "history");
@@ -201,7 +212,9 @@ export function readPreviewManifest(options, { verify = false } = {}) {
201
212
  const file = previewManifestPath(options);
202
213
  if (!existsSync(file)) return null;
203
214
  const manifest = readManifestFile(file);
204
- if (verify) for (const uri of Object.keys(manifest.assets)) readPreviewAsset(options, uri, manifest);
215
+ if (verify) for (const [uri, record] of Object.entries(manifest.assets)) {
216
+ verifiedAssetBytes(options, uri, record, verify === "cached");
217
+ }
205
218
  return manifest;
206
219
  }
207
220
 
@@ -236,10 +249,26 @@ export function readPreviewAsset(options, uri, manifest = readPreviewManifest(op
236
249
  }
237
250
  }
238
251
  if (!record) throw unknownResource("Unknown or expired preview asset resource. Refresh the manifest.");
252
+ const bytes = verifiedAssetBytes(options, uri, record);
253
+ return { uri, mimeType: record.mimeType, ...(/^(?:text\/|application\/json|image\/svg)/.test(record.mimeType) ? { text: bytes.toString() } : { blob: bytes.toString("base64") }) };
254
+ }
255
+
256
+ function verifiedAssetBytes(options, uri, record, cached = false) {
239
257
  const directory = path.join(path.dirname(previewManifestPath(options)), "assets");
240
258
  const file = path.join(directory, uri.slice("ads://assets/".length));
241
- if (!isInside(directory, file) || realpathSync(file) !== file || statSync(file).size > 16 * 1024 * 1024) throw new Error("Invalid preview asset file.");
259
+ if (!isInside(directory, file) || realpathSync(file) !== file) throw new Error("Invalid preview asset file.");
260
+ const stat = statSync(file, { bigint: true });
261
+ if (!stat.isFile() || stat.size > 16n * 1024n * 1024n) throw new Error("Invalid preview asset file.");
262
+ const key = `${file}:${record.digest}:${record.size}`;
263
+ const stamp = assetStamp(stat);
264
+ if (cached && verifiedAssetFiles.get(key) === stamp) return;
242
265
  const bytes = readFileSync(file);
243
266
  if (bytes.length !== record.size || `sha256:${hash(bytes)}` !== record.digest) throw new Error("Preview resource does not match its successful build. Rebuild before reviewing.");
244
- return { uri, mimeType: record.mimeType, ...(/^(?:text\/|application\/json|image\/svg)/.test(record.mimeType) ? { text: bytes.toString() } : { blob: bytes.toString("base64") }) };
267
+ // A write racing the read must not seed a cache entry for different bytes.
268
+ if (assetStamp(statSync(file, { bigint: true })) === stamp) {
269
+ verifiedAssetFiles.delete(key);
270
+ verifiedAssetFiles.set(key, stamp);
271
+ if (verifiedAssetFiles.size > 4096) verifiedAssetFiles.delete(verifiedAssetFiles.keys().next().value);
272
+ }
273
+ return bytes;
245
274
  }
@@ -14,6 +14,12 @@ export function previewManifestPath(options) {
14
14
  return options.previewSession ? path.join(path.dirname(configured), "sessions", options.previewSession, "manifest.json") : configured;
15
15
  }
16
16
 
17
+ /** Unverified live feedback has its own graph/assets; never accepted artifacts. */
18
+ export function livePreviewOptions(options) {
19
+ const file = path.join(path.dirname(previewManifestPath(options)), "live", "manifest.json");
20
+ return { ...options, previewSession: undefined, config: { ...options.config, mcp: { ...options.config.mcp, previewManifest: path.relative(options.root, file) } } };
21
+ }
22
+
17
23
  export function previewArtifactPath(options, file) {
18
24
  if (!options.previewSession || !file.replaceAll("\\", "/").startsWith(".ds/scenarios/")) return file;
19
25
  return path.join(".ds/preview-sessions", options.previewSession, path.relative(".ds", file)).replaceAll("\\", "/");
@@ -0,0 +1,184 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
3
+ import path from "node:path";
4
+ import ts from "typescript";
5
+ import { isInside } from "./config.mjs";
6
+
7
+ const metadata = "ads:preview-workers";
8
+ const virtual = "\0ads-preview-worker:";
9
+ const digest = value => createHash("sha256").update(value).digest("hex");
10
+ function fileHash(file) { try { return digest(readFileSync(file)); } catch { return null; } }
11
+ function directoryHash(directory) {
12
+ try { return digest(JSON.stringify(readdirSync(directory, { withFileTypes: true }).map(entry => [entry.name, entry.isDirectory(), entry.isSymbolicLink()]).sort())); }
13
+ catch { return null; }
14
+ }
15
+ const filePath = id => typeof id === "string" && path.isAbsolute(id.split("?")[0]) ? id.split("?")[0] : null;
16
+
17
+ /** Cache Vite's own completed IIFE workers through public plugin hooks. No
18
+ * project-specific worker compiler, dependency list or Vite internals involved.
19
+ * Cached constructors refer to emitted assets; resource conversion still owns
20
+ * immutable URIs, byte verification and opaque-origin worker adaptation. */
21
+ export function createPreviewWorkerCache(options, isCurrent) {
22
+ const bundles = new Map(), staged = new Map(), pending = new Map();
23
+ let memo = new Map(), configuration = [], format, cycle = 0;
24
+ function valid(entry, fresh = false) {
25
+ if (!entry) return false;
26
+ if (fresh) memo.delete(entry);
27
+ if (!memo.has(entry)) memo.set(entry, [...entry.files].every(([file, hash]) => fileHash(file) === hash)
28
+ && [...entry.directories].every(([directory, hash]) => directoryHash(directory) === hash));
29
+ return memo.get(entry);
30
+ }
31
+ function directories(files) {
32
+ const result = new Map();
33
+ for (const file of files.keys()) {
34
+ let directory = path.dirname(file);
35
+ while (!result.has(directory)) {
36
+ result.set(directory, directoryHash(directory));
37
+ if (directory === options.root || path.basename(directory) === "node_modules"
38
+ || !isInside(options.root, directory) && existsSync(path.join(directory, "package.json"))) break;
39
+ const parent = path.dirname(directory);
40
+ if (parent === directory) break;
41
+ directory = parent;
42
+ }
43
+ }
44
+ return result;
45
+ }
46
+ function tracker() {
47
+ const observed = new Map();
48
+ const generation = cycle;
49
+ let nested = false;
50
+ return { name: "ads-preview-worker-inputs", enforce: "post",
51
+ buildStart() { for (const file of configuration) observed.set(file, fileHash(file)); },
52
+ load: { order: "pre", handler(id) { const file = filePath(id); if (file && !observed.has(file)) observed.set(file, fileHash(file)); } },
53
+ moduleParsed(info) {
54
+ if (/\bnew\s+(?:Worker|SharedWorker)\s*\(\s*new\s+URL\s*\(/.test(info.code ?? "")
55
+ || info.importedIds.some(id => /[?&](?:shared)?worker(?:[&=]|$)/.test(id))) nested = true;
56
+ },
57
+ generateBundle: { order: "post", handler(output, bundle) {
58
+ // Inline, nested and split ES workers retain Vite's normal path. Their
59
+ // extra parent-owned assets cannot be inferred from one worker bundle.
60
+ const chunks = Object.values(bundle).filter(item => item.type === "chunk");
61
+ if (generation !== cycle || format !== "iife" || nested || chunks.length !== 1 || chunks[0].imports.length || chunks[0].dynamicImports.length) return;
62
+ const entry = chunks[0].facadeModuleId;
63
+ if (!entry || !path.isAbsolute(entry)) return;
64
+ const files = new Map();
65
+ for (const id of [...this.getWatchFiles(), ...this.getModuleIds(), ...configuration]) {
66
+ const file = filePath(id);
67
+ if (!file) continue;
68
+ // Unobserved plugin inputs cannot establish a reusable snapshot.
69
+ const hash = observed.get(file);
70
+ if (!hash || fileHash(file) !== hash) return;
71
+ files.set(file, hash);
72
+ }
73
+ if (!files.has(entry)) return;
74
+ staged.set(entry, { entry, files, directories: directories(files), fileName: chunks[0].fileName,
75
+ assets: Object.values(bundle).map(item => ({ type: "asset", fileName: item.fileName,
76
+ source: item.type === "chunk" ? item.code : typeof item.source === "string" ? item.source : Buffer.from(item.source) })) });
77
+ } },
78
+ };
79
+ }
80
+ async function worker(context, file, query = "worker&url") {
81
+ let entry = staged.get(file) ?? bundles.get(file);
82
+ if (!valid(entry)) {
83
+ // Vite remains the compiler, including its configured worker plugins.
84
+ if (!pending.has(file)) pending.set(file, context.load({ id: file + "?" + query }));
85
+ await pending.get(file);
86
+ entry = staged.get(file);
87
+ }
88
+ if (!valid(entry)) return null;
89
+ for (const dependency of entry.files.keys()) context.addWatchFile(dependency);
90
+ return entry;
91
+ }
92
+ const plugin = { name: "ads-preview-worker-cache", enforce: "pre",
93
+ config(config) {
94
+ const original = config.worker?.plugins;
95
+ // Mutate this option: Vite merges returned worker plugin factories by
96
+ // concatenation, which would execute the project's plugins twice.
97
+ config.worker ??= {};
98
+ config.worker.plugins = (...args) => [typeof original === "function" ? original(...args) : original ?? [], tracker()];
99
+ },
100
+ configResolved(config) {
101
+ configuration = [...new Set([...(config.configFileDependencies ?? []), path.join(options.root, "package.json"), path.join(options.root, "tsconfig.json")])].filter(existsSync);
102
+ format = config.worker.format;
103
+ },
104
+ buildStart() { ++cycle; staged.clear(); pending.clear(); memo = new Map(); },
105
+ shouldTransformCachedModule({ meta }) {
106
+ // Preserve Vite's worker-importer transform lifecycle. Other plugins can
107
+ // have evaluated dependencies which no longer appear in emitted JS (for
108
+ // example extracted CSS); only the expensive worker sub-build is cached.
109
+ if (meta[metadata]?.length) return true;
110
+ return null;
111
+ },
112
+ async resolveId(source, importer) {
113
+ if (format !== "iife" || importer?.startsWith(virtual)) return null;
114
+ const index = source.indexOf("?");
115
+ if (index < 0) return null;
116
+ const query = new URLSearchParams(source.slice(index + 1));
117
+ if (!query.has("worker") || [...query].some(([key, value]) => !["worker", "url"].includes(key) || value)) return null;
118
+ const resolved = await this.resolve(source.slice(0, index), importer, { skipSelf: true });
119
+ const file = filePath(resolved?.id);
120
+ if (!file) return null;
121
+ const suffix = query.has("url") ? "worker&url" : "worker";
122
+ if (!await worker(this, file, suffix)) return { id: file + "?" + suffix };
123
+ return virtual + JSON.stringify([file, suffix]);
124
+ },
125
+ load(id) { if (id.startsWith(virtual)) return "export {};"; },
126
+ async transform(code, id) {
127
+ if (id.startsWith(virtual)) {
128
+ const [file, query] = JSON.parse(id.slice(virtual.length));
129
+ const entry = await worker(this, file, query);
130
+ if (!entry) return { code: `export {default} from ${JSON.stringify(file + "?" + query)};`, meta: { [metadata]: [] } };
131
+ const url = JSON.stringify("/" + entry.fileName);
132
+ return { code: query === "worker&url" ? `export default ${url};`
133
+ : `export default function WorkerWrapper(options){return new Worker(${url},{name:options?.name});}`,
134
+ meta: { [metadata]: [file] } };
135
+ }
136
+ const previous = this.getModuleInfo(id)?.meta[metadata];
137
+ if (format !== "iife" || !code.includes("Worker") || !code.includes("new URL")) return previous?.length ? { meta: { [metadata]: [] } } : null;
138
+ const source = ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, /\.[jt]sx(?:\?|$)/.test(id) ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
139
+ const calls = [];
140
+ function visit(node) {
141
+ if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "Worker") {
142
+ const url = node.arguments?.[0];
143
+ if (url && ts.isNewExpression(url) && ts.isIdentifier(url.expression) && url.expression.text === "URL"
144
+ && url.arguments?.length === 2 && ts.isStringLiteralLike(url.arguments[0]) && url.arguments[1].getText(source) === "import.meta.url") calls.push(url);
145
+ }
146
+ ts.forEachChild(node, visit);
147
+ }
148
+ visit(source);
149
+ const replacements = [], used = new Set();
150
+ for (const url of calls) {
151
+ const value = url.arguments[0].text;
152
+ if (!value.startsWith(".") || /[?#]/.test(value)) continue;
153
+ const resolved = await this.resolve(value, id, { skipSelf: true });
154
+ const file = filePath(resolved?.id);
155
+ const entry = file && await worker(this, file);
156
+ if (!entry) continue;
157
+ used.add(entry.entry);
158
+ replacements.push([url.getStart(source), url.end, JSON.stringify("/" + entry.fileName)]);
159
+ }
160
+ for (const [start, end, value] of replacements.sort((a, b) => b[0] - a[0])) code = code.slice(0, start) + value + code.slice(end);
161
+ return replacements.length || previous?.length ? { code, map: null, meta: { [metadata]: [...used] } } : null;
162
+ },
163
+ generateBundle: { order: "post", handler(_output, bundle) {
164
+ const used = new Set();
165
+ for (const id of this.getModuleIds()) for (const file of this.getModuleInfo(id)?.meta[metadata] ?? []) used.add(file);
166
+ for (const file of used) {
167
+ const entry = staged.get(file) ?? bundles.get(file);
168
+ if (!valid(entry, true)) this.error("Worker inputs changed during preview compilation. Rebuild the current source.");
169
+ for (const asset of entry.assets) {
170
+ const existing = bundle[asset.fileName];
171
+ if (existing) {
172
+ if (existing.type !== "asset" || !Buffer.from(existing.source).equals(Buffer.from(asset.source))) this.error(`Worker asset path collision: ${asset.fileName}`);
173
+ continue;
174
+ }
175
+ this.emitFile(asset);
176
+ }
177
+ }
178
+ for (const file of bundles.keys()) if (!used.has(file) && !staged.has(file)) bundles.delete(file);
179
+ } },
180
+ writeBundle: { order: "post", handler() { if (isCurrent()) for (const [file, entry] of staged) if (valid(entry, true)) bundles.set(file, entry); staged.clear(); } },
181
+ closeWatcher() { ++cycle; bundles.clear(); staged.clear(); pending.clear(); memo.clear(); },
182
+ };
183
+ return plugin;
184
+ }
@@ -48,3 +48,7 @@ export function projectDocumentFiles(root) {
48
48
  export function projectGuideFiles(root) {
49
49
  return projectDocumentFiles(root).filter(file => !isProjectNotice(file));
50
50
  }
51
+
52
+ export function projectNoticeFiles(root) {
53
+ return projectDocumentFiles(root).filter(isProjectNotice);
54
+ }
@@ -0,0 +1,34 @@
1
+ import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
2
+ import { loadConfig } from "./config.mjs";
3
+ import { inspectScenarios } from "./scenarios.mjs";
4
+
5
+ // Discovery is semantic source analysis. Keep it off the live compiler's event
6
+ // loop; the caller fences each result against the exact project input digest.
7
+ if (!isMainThread && workerData?.adsScenarioInspector) {
8
+ parentPort.on("message", ({ id }) => {
9
+ try { parentPort.postMessage({ id, result: inspectScenarios(loadConfig(workerData.root)) }); }
10
+ catch (error) { parentPort.postMessage({ id, error: error.message }); }
11
+ });
12
+ }
13
+
14
+ export function createScenarioInspector(root) {
15
+ let worker, sequence = 0;
16
+ const pending = new Map();
17
+ function fail(error) { for (const task of pending.values()) task.reject(error); pending.clear(); }
18
+ return {
19
+ inspect() {
20
+ if (!worker) {
21
+ worker = new Worker(new URL(import.meta.url), { workerData: { adsScenarioInspector: true, root } });
22
+ worker.on("message", ({ id, result, error }) => {
23
+ const task = pending.get(id); pending.delete(id);
24
+ if (task) { if (error) task.reject(new Error(error)); else task.resolve(result); }
25
+ });
26
+ worker.on("error", fail);
27
+ worker.on("exit", () => { fail(new Error("Scenario inspector closed.")); worker = undefined; });
28
+ }
29
+ const id = ++sequence;
30
+ return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id }); });
31
+ },
32
+ async close() { const previous = worker; worker = undefined; fail(new Error("Scenario inspector closed.")); await previous?.terminate(); },
33
+ };
34
+ }
@@ -5,6 +5,7 @@ import { isDevelopmentFile, isInside, isReviewFile } from "./config.mjs";
5
5
  import { scenarioApi } from "./public-api.mjs";
6
6
  import { uiOperation } from "./ui-framework.mjs";
7
7
  import { inspectUnits } from "./units.mjs";
8
+ import { sourceSymbol } from "./source-symbols.mjs";
8
9
  import { createSourceValues, reference, union, isFunction } from "./source-values.mjs";
9
10
  import { inspectRuntimeContracts } from "./runtime-contracts.mjs";
10
11
  import { implementationNode } from "./unit-contracts.mjs";
@@ -18,7 +19,7 @@ export function createScenarioTrace(program, options) {
18
19
  if (!expression || seen.has(expression)) return false;
19
20
  seen.add(expression);
20
21
  const base = ts.isPropertyAccessExpression(expression) ? expression.expression : expression;
21
- const symbol = checker.getSymbolAtLocation(base);
22
+ const symbol = sourceSymbol(checker, base);
22
23
  for (const declaration of symbol?.declarations ?? []) {
23
24
  if (ts.isImportSpecifier(declaration) && (declaration.propertyName ?? declaration.name).text === name && ["@linaria/atomic", "@linaria/core"].includes(declaration.parent.parent.parent.moduleSpecifier.text)) return true;
24
25
  if (ts.isNamespaceImport(declaration) && ts.isPropertyAccessExpression(expression) && expression.name.text === name && ["@linaria/atomic", "@linaria/core"].includes(declaration.parent.parent.moduleSpecifier.text)) return true;
@@ -190,14 +191,15 @@ export function createScenarioTrace(program, options) {
190
191
  const context = state();
191
192
  const input = property ? get(reference(expression), "className", next(context)) : reference(expression);
192
193
  const value = resolve(input, next(context));
193
- if (property && value.kind === "literal" && value.value === undefined) return { present: false, ok: true, reasons: [] };
194
+ const absent = value => value.kind === "literal" && value.value === undefined || value.kind === "union" && value.values.every(absent);
195
+ if (property && absent(value)) return { present: false, ok: true, reasons: [] };
194
196
  const proof = verify(input, context);
195
197
  const ok = proof.ok && proof.branches.some(branch => branch.atoms) && proof.branches.every(branch => !branch.hooks || branch.atoms);
196
198
  if (!ok && !reasons.size) reasons.add("Each nonempty return path needs owned Linaria styles; stable hooks alone are not styling evidence.");
197
199
  return { present: !property || value.kind !== "unknown", ok, reasons: [...reasons].slice(0, 3) };
198
200
  }
199
201
  function traceEntry(source, {exercise=false}={}) {
200
- const module=checker.getSymbolAtLocation(source),symbol=module&&checker.getExportsOfModule(module).find(symbol=>symbol.name==="default");
202
+ const module=sourceSymbol(checker, source),symbol=module&&checker.getExportsOfModule(module).find(symbol=>symbol.name==="default");
201
203
  const resolved=symbol?.flags&ts.SymbolFlags.Alias?checker.getAliasedSymbol(symbol):symbol;
202
204
  const declaration=resolved?.valueDeclaration;
203
205
  return traceRenders(declaration&&(ts.isExportAssignment(declaration)?declaration.expression:declaration.name??declaration),{entry:true,exercise});