@reqvire-org/ads 0.3.28 → 0.3.29
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/dist/atomic-composition.mjs +2 -1
- package/dist/behaviors.mjs +2 -2
- package/dist/boundaries.mjs +6 -3
- package/dist/check.mjs +3 -0
- package/dist/cli.mjs +13 -0
- package/dist/config.mjs +5 -3
- package/dist/mcp/build-status.mjs +17 -4
- package/dist/mcp/context.mjs +2 -1
- package/dist/mcp/execution-results.mjs +4 -3
- package/dist/mcp/mutations.mjs +5 -43
- package/dist/mcp/preview-watch.mjs +23 -3
- package/dist/mcp/preview-widget.bundle.js +16 -15
- package/dist/mcp/resource-loader.js +40 -12
- package/dist/mcp/server.mjs +74 -36
- package/dist/oxlint.mjs +6 -1
- package/dist/preview-builder.mjs +10 -4
- package/dist/preview-resources.mjs +11 -4
- package/dist/preview-scope.mjs +6 -0
- package/dist/preview-workers.mjs +184 -0
- package/dist/scenario-inspector.mjs +34 -0
- package/dist/scenario-trace.mjs +3 -2
- package/dist/scenarios-compiler.mjs +200 -25
- package/dist/showcase/client.bundle.js +22 -21
- package/dist/showcase/index.html +2 -2
- package/dist/showcase/style.css +2 -1
- package/dist/skills/ads-break-ui/SKILL.md +3 -0
- package/dist/skills/ads-break-ui/references/runtimes.md +31 -0
- package/dist/skills/ads-break-ui/references/validation.md +53 -0
- package/dist/skills/ads-designer/SKILL.md +3 -0
- package/dist/skills/ads-designer/references/runtimes.md +31 -0
- package/dist/skills/ads-designer/references/validation.md +53 -0
- package/dist/skills/ads-import/SKILL.md +3 -0
- package/dist/skills/ads-import/references/runtimes.md +31 -0
- package/dist/skills/ads-import/references/validation.md +53 -0
- package/dist/skills/ads-motion/SKILL.md +3 -0
- package/dist/skills/ads-motion/references/runtimes.md +31 -0
- package/dist/skills/ads-motion/references/validation.md +53 -0
- package/dist/skills/ads-port/SKILL.md +3 -0
- package/dist/skills/ads-port/references/runtimes.md +31 -0
- package/dist/skills/ads-port/references/validation.md +53 -0
- package/dist/source-symbols.mjs +11 -0
- package/dist/source-values.mjs +10 -3
- package/dist/test-boundaries.mjs +95 -0
- package/dist/ui-framework.mjs +2 -1
- package/dist/units.mjs +12 -1
- package/dist/validation-checks.mjs +50 -0
- package/dist/validation.mjs +172 -0
- package/dist/verification/browser.mjs +3 -1
- package/dist/verification.mjs +1 -0
- package/docs/ARCHITECTURE.md +72 -17
- package/docs/CHANGELOG.md +37 -0
- package/docs/MCP.md +68 -9
- package/package.json +1 -1
|
@@ -1,3 +1,22 @@
|
|
|
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
|
+
|
|
1
20
|
/** Native ES modules keep framework semantics, cycles, and live bindings intact. */
|
|
2
21
|
export class PreviewResourceLoader {
|
|
3
22
|
constructor(read) {
|
|
@@ -10,6 +29,7 @@ export class PreviewResourceLoader {
|
|
|
10
29
|
this.revisions = new Set();
|
|
11
30
|
this.importing = Promise.resolve();
|
|
12
31
|
this.generation = 0;
|
|
32
|
+
this.prefetchGeneration = 0;
|
|
13
33
|
this.closed = false;
|
|
14
34
|
globalThis.__dsPreviewImport = uri => this.importModule(uri);
|
|
15
35
|
}
|
|
@@ -47,18 +67,25 @@ export class PreviewResourceLoader {
|
|
|
47
67
|
return this.bytes.get(uri);
|
|
48
68
|
}
|
|
49
69
|
closure(uri) {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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};
|
|
62
89
|
}
|
|
63
90
|
async materialize(uri) {
|
|
64
91
|
const ordered = this.closure(uri);
|
|
@@ -140,6 +167,7 @@ export class PreviewResourceLoader {
|
|
|
140
167
|
if (this.closed) return;
|
|
141
168
|
this.closed = true;
|
|
142
169
|
++this.generation;
|
|
170
|
+
++this.prefetchGeneration;
|
|
143
171
|
await this.unmount?.();
|
|
144
172
|
this.mounted = undefined;
|
|
145
173
|
for (const style of this.styles.values()) style.remove();
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@m
|
|
|
4
4
|
import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
import { checkProject } from "../check.mjs";
|
|
7
|
+
import { createValidationController } from "../validation.mjs";
|
|
7
8
|
import { loadConfig, sourceFiles } from "../config.mjs";
|
|
8
9
|
import { createVerificationController, BEHAVIOR_URI } from "../verification.mjs";
|
|
9
10
|
import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigationSections, readInvestigation, readInvestigationResource } from "../investigations.mjs";
|
|
@@ -15,8 +16,8 @@ import { startShowcaseHost } from "./showcase-host.mjs";
|
|
|
15
16
|
import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
|
|
16
17
|
import { inspectCatalog, projectDocuments, PROJECT_URI, readProjectDocument } from "./catalog.mjs";
|
|
17
18
|
import { APP_MIME, appMetadata, appUri, projectApp, TOKENS_APP_URI, tokensApp, tokenWidgetData, SCENARIO_APP_URI, scenarioApp, previewApp, PREVIEW_APP_URI } from "./apps.mjs";
|
|
18
|
-
import { PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewAsset } from "../preview-resources.mjs";
|
|
19
|
-
import { previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
|
|
19
|
+
import { LIVE_PREVIEW_MANIFEST_URI, PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewAsset } from "../preview-resources.mjs";
|
|
20
|
+
import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
|
|
20
21
|
import { getWorkflowPrompt, promptDefinitions } from "./prompts.mjs";
|
|
21
22
|
import { createReconfigurablePreviewWatch } from "./preview-watch.mjs";
|
|
22
23
|
import { BUILD_URI, buildFailure, inspectBuildStatus, summarizeBuild } from "./build-status.mjs";
|
|
@@ -66,6 +67,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
66
67
|
const captures = cache.captures ??= createCaptureController(root);
|
|
67
68
|
const edits = cache.edits ??= createMutationController(root, { captures });
|
|
68
69
|
const verification = cache.verification ??= createVerificationController(root);
|
|
70
|
+
const validation = cache.validation ??= createValidationController(root);
|
|
69
71
|
const executionResults = cache.executionResults ??= createExecutionResults(root);
|
|
70
72
|
const reports = cache.reports ??= createReportStore(root, { context: reportContext, resolveEvidence: reportEvidence });
|
|
71
73
|
let options = loadConfig(root);
|
|
@@ -90,32 +92,34 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
90
92
|
capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
|
|
91
93
|
extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
|
|
92
94
|
});
|
|
93
|
-
const getRegistry = () => cache.registry ??= inspectScenarios(options);
|
|
95
|
+
const getRegistry = () => { cache.registry ??= inspectScenarios(options); cache.lastRegistry = cache.registry; return cache.registry; };
|
|
96
|
+
const previewRegistry = waitFor => waitFor === "compiled" ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry();
|
|
94
97
|
function captureInventory() {
|
|
95
98
|
const current = loadConfig(root), registry = inspectScenarios(current);
|
|
96
99
|
return { ...registry, revision: previewSourceRevision(current) };
|
|
97
100
|
}
|
|
98
101
|
function captureIndex() { const inventory = captureInventory(); return captures.store.list(inventory.scenarios, inventory.revision, { prune: !inventory.diagnostics.length }); }
|
|
99
|
-
const scenarioApps = () => getRegistry().scenarios.map(item => ({ id: item.id, title: item.title, kind: item.kind, ...(item.samples ? { samples: item.samples } : {}), file: item.artifact }));
|
|
102
|
+
const scenarioApps = (quick = false) => (quick ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry()).scenarios.map(item => ({ id: item.id, title: item.title, kind: item.kind, ...(item.samples ? { samples: item.samples } : {}), file: item.artifact }));
|
|
100
103
|
const tokenScenarios = () => getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id: item.id, title: item.title, count: item.tokens.length }));
|
|
101
|
-
const allApps = () => [...options.config.mcp.apps, ...scenarioApps()];
|
|
104
|
+
const allApps = (quick = false) => [...options.config.mcp.apps, ...scenarioApps(quick)];
|
|
102
105
|
const scenarioWidget = () => options.config.mcp.previewManifest ? PREVIEW_APP_URI : SCENARIO_APP_URI;
|
|
103
106
|
const previewOptions = () => withPreviewSession(options, previewWatch?.resourceSession?.());
|
|
104
107
|
const resourceAssets = () => {
|
|
105
108
|
try { return Object.entries(readPreviewManifest(previewOptions())?.assets ?? {}).map(([uri, record]) => ({ uri, name: `Preview asset ${uri.slice("ads://assets/".length)}`, mimeType: record.mimeType, size: record.size })); }
|
|
106
109
|
catch { return []; } // Discovery and diagnostics remain usable after a failed graph.
|
|
107
110
|
};
|
|
108
|
-
function graphSelection(id) {
|
|
111
|
+
function graphSelection(id, build) {
|
|
109
112
|
if (!options.config.mcp.previewManifest) return {};
|
|
110
|
-
const
|
|
113
|
+
const live = build?.live && !build.current;
|
|
114
|
+
const manifest = readPreviewManifest(live ? livePreviewOptions(previewOptions()) : previewOptions());
|
|
111
115
|
if (!manifest?.scenarios.some(entry => entry.id === id)) throw new Error("The preview resource graph is not ready for this scenario. Rebuild previews.");
|
|
112
|
-
return { manifestUri: PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
|
|
116
|
+
return { manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
|
|
113
117
|
}
|
|
114
118
|
const getCatalog = () => cache.catalog ??= inspectCatalog(options, getRegistry().scenarios);
|
|
115
119
|
const getDocuments = () => cache.documents ??= projectDocuments(options);
|
|
116
120
|
const builds = () => {
|
|
117
|
-
previewWatch?.setApps(allApps());
|
|
118
|
-
return previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps() });
|
|
121
|
+
previewWatch?.setApps(allApps(true));
|
|
122
|
+
return previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
|
|
119
123
|
};
|
|
120
124
|
const previews = () => options.config.mcp.apps.map((app) => ({ id: app.id, title: app.title, kind: app.kind, tool: `ads_show_${app.id.replaceAll("-", "_")}`, resourceUri: appUri(app.id), available: existsSync(path.resolve(root, app.file)), file: app.file }));
|
|
121
125
|
|
|
@@ -152,6 +156,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
152
156
|
return [
|
|
153
157
|
{ uri: GUIDE_URI, name: "Start here: design-system workflow", description: "Read first for UI/ADS tasks, especially when only resource access is exposed. Explains the exact workspace, tool sequence, skill selection, previews, project commands and fallback.", mimeType: "text/markdown" },
|
|
154
158
|
{ uri: "ads://guides/behaviors", name: "Controller and behavioral verification guide", mimeType: "text/markdown" },
|
|
159
|
+
{ uri: "ads://guides/validation", name: "Full and affected validation; test boundaries", mimeType: "text/markdown" },
|
|
155
160
|
{ uri: "ads://guides/runtimes", name: "Node and Bun setup, compiler and verification runtime", mimeType: "text/markdown" },
|
|
156
161
|
{ uri: "ads://guides/evidence", name: "Failure boundaries and compact investigations", mimeType: "text/markdown" },
|
|
157
162
|
{ uri: "ads://guides/atomic-styles", name: "Atomic styles: composition conflicts and custom-property extraction", mimeType: "text/markdown" },
|
|
@@ -177,7 +182,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
177
182
|
{ uri: "ads://guides/reporting", name: "Report suspected ADS bugs and feature requests", mimeType: "text/markdown" },
|
|
178
183
|
{ uri: TOKENS_APP_URI, name: "Experimental token widget", mimeType: APP_MIME },
|
|
179
184
|
{ uri: SCENARIO_APP_URI, name: "Experimental scenario widget", mimeType: APP_MIME },
|
|
180
|
-
...(options.config.mcp.previewManifest ? [{ uri: PREVIEW_APP_URI, name: "Shared-resource preview App", mimeType: APP_MIME }, { uri: PREVIEW_MANIFEST_URI, name: "
|
|
185
|
+
...(options.config.mcp.previewManifest ? [{ uri: PREVIEW_APP_URI, name: "Shared-resource preview App", mimeType: APP_MIME }, { uri: PREVIEW_MANIFEST_URI, name: "Verified preview dependency graph", mimeType: "application/json" }, { uri: LIVE_PREVIEW_MANIFEST_URI, name: "Unverified live feedback; background checks pending", mimeType: "application/json" }] : []),
|
|
181
186
|
...(options.config.mcp.previewManifest ? resourceAssets() : []),
|
|
182
187
|
...allApps().map((app) => ({ uri: appUri(app.id), name: app.title, description: app.description, mimeType: APP_MIME })),
|
|
183
188
|
...documents.filter((document) => !promoted.has(document.uri)).map(({ file: _file, ...document }) => document),
|
|
@@ -196,6 +201,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
196
201
|
build: summarizeBuild(builds()),
|
|
197
202
|
previews: previews(), skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description })),
|
|
198
203
|
scenarios: { count: getRegistry().scenarios.length, diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
|
|
204
|
+
validation: { ...validation.status(), tool: "ads_validate", lastResult: executionResults.latest("validation") },
|
|
199
205
|
behaviors: { resourceUri: BEHAVIOR_URI, discoveryTool: "ads_behaviors", verificationTool: "ads_verify", investigationTool: "ads_investigate", investigationResourceUri: INVESTIGATIONS_URI, ...behaviorState, progress: compactProgress(behaviorState.progress), lastResult: executionResults.latest("verification"), resultsTool: "ads_results", resultsResourceUri: RESULTS_URI },
|
|
200
206
|
captures: { resourceUri: CAPTURES_URI, tool: "ads_capture", clearTool: "ads_capture_clear", ...captures.status() },
|
|
201
207
|
reports: { access:"submission-only", storageDirectory:".ds/reports", bugTool:"ads_report_bug", featureTool:"ads_request_feature", guidanceUri:"ads://guides/reporting", delivery:"local-only", retention:"until-explicit-removal" },
|
|
@@ -204,6 +210,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
204
210
|
async function read(uri, signal) {
|
|
205
211
|
if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
|
|
206
212
|
if (uri === "ads://guides/behaviors") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/behaviors.md", import.meta.url), "utf8") }] };
|
|
213
|
+
if (uri === "ads://guides/validation") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/validation.md", import.meta.url), "utf8") }] };
|
|
207
214
|
if (uri === "ads://guides/runtimes") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/runtimes.md", import.meta.url), "utf8") }] };
|
|
208
215
|
if (uri === "ads://guides/evidence") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/evidence.md", import.meta.url), "utf8") }] };
|
|
209
216
|
if (uri === "ads://guides/tokens") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/design-data.md", import.meta.url), "utf8") }] };
|
|
@@ -230,6 +237,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
230
237
|
value = readPreviewManifest(previewOptions());
|
|
231
238
|
if (!value) throw new Error("Preview resources are not built yet. Invoke ads_show_scenario to start the managed compiler.");
|
|
232
239
|
}
|
|
240
|
+
else if (uri === LIVE_PREVIEW_MANIFEST_URI && options.config.mcp.previewManifest) {
|
|
241
|
+
const report = builds(), live = report.previews.find(entry => entry.live)?.live;
|
|
242
|
+
value = readPreviewManifest(livePreviewOptions(previewOptions()));
|
|
243
|
+
if (!live || value?.revision !== live.revision || value.session !== report.session) throw new Error("No live feedback for the current source. Use the verified preview after checks pass.");
|
|
244
|
+
}
|
|
233
245
|
if (value !== undefined) return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(value) }] };
|
|
234
246
|
if (uri.startsWith("ads://investigations/") || uri.startsWith("ads://verification-artifacts/")) {
|
|
235
247
|
try { return {contents:[readInvestigationResource(root,uri)]}; }
|
|
@@ -244,7 +256,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
244
256
|
if (uri === PREVIEW_APP_URI && options.config.mcp.previewManifest) return { contents: [{ uri, mimeType: APP_MIME, text: previewApp(), _meta: appMetadata() }] };
|
|
245
257
|
if (uri.startsWith("ads://assets/") && options.config.mcp.previewManifest) {
|
|
246
258
|
try { return { contents: [readPreviewAsset(previewOptions(), uri)] }; }
|
|
247
|
-
catch (error) {
|
|
259
|
+
catch (error) {
|
|
260
|
+
if (error.code !== "ADS_PREVIEW_NOT_FOUND") throw error;
|
|
261
|
+
try { return { contents: [readPreviewAsset(livePreviewOptions(previewOptions()), uri)] }; }
|
|
262
|
+
catch (error) { if (error.code === "ADS_PREVIEW_NOT_FOUND") throw new ResourceNotFoundError(uri, error.message); throw error; }
|
|
263
|
+
}
|
|
248
264
|
}
|
|
249
265
|
const app = allApps().find((entry) => appUri(entry.id) === uri);
|
|
250
266
|
if (app) {
|
|
@@ -257,10 +273,14 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
257
273
|
if (document) return { contents: [{ uri, mimeType: document.mimeType, text: readProjectDocument(document) }] };
|
|
258
274
|
throw new ResourceNotFoundError(uri, `Unknown ADS resource: ${uri}`);
|
|
259
275
|
}
|
|
260
|
-
async function previewBuild(app, signal) {
|
|
261
|
-
previewWatch?.setApps(allApps());
|
|
262
|
-
if (previewWatch) return previewWatch.ensure(path.resolve(root, app.file), signal);
|
|
276
|
+
async function previewBuild(app, signal, waitFor = "verified") {
|
|
277
|
+
previewWatch?.setApps(allApps(waitFor === "compiled"));
|
|
278
|
+
if (previewWatch) return previewWatch.ensure(path.resolve(root, app.file), signal, { waitFor });
|
|
263
279
|
const build = builds().previews.find((entry) => entry.id === app.id);
|
|
280
|
+
if (waitFor === "compiled" && options.config.mcp.previewManifest) {
|
|
281
|
+
try { graphSelection(app.id, build); return build; }
|
|
282
|
+
catch { /* No usable graph yet: keep the normal diagnostics/wait path. */ }
|
|
283
|
+
}
|
|
264
284
|
if (build?.state === "error") throw buildFailure(build);
|
|
265
285
|
if (["building", "idle"].includes(build?.state)) throw Object.assign(new Error("Preview build is still pending. Invoke the preview again after rebuilding."), { build: { ...build, resourceUri: BUILD_URI } });
|
|
266
286
|
return build;
|
|
@@ -272,6 +292,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
272
292
|
return { ...json(summary), ...(!result.ok ? { isError: true } : {}) };
|
|
273
293
|
}
|
|
274
294
|
async function applyEdits(args,signal,progress) {
|
|
295
|
+
if (validation.status().busy) throw new Error("Wait for the active validation run before editing source.");
|
|
275
296
|
const result = await edits.apply(args,signal,progress);
|
|
276
297
|
if (result.screenshots) await refresh();
|
|
277
298
|
if (result.applied) {
|
|
@@ -279,6 +300,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
279
300
|
if (result.changes.some(change => change.path === "ds.config.json") || result.unit === "configuration" || result.units?.includes("configuration")) await previewWatch?.reconfigure?.(loadConfig(root).config.mcp,true);
|
|
280
301
|
await previewWatch?.invalidate?.();
|
|
281
302
|
await refresh(true);
|
|
303
|
+
previewWatch?.setApps(allApps());
|
|
304
|
+
if ((result.units??[result.unit]).some(unit=>unit!=="documentation")) await previewWatch?.warm?.((options.config.mcp.previewManifest?scenarioApps():allApps()).map(app=>path.resolve(root,app.file)));
|
|
282
305
|
} catch (error) {result.warnings=[...(result.warnings ?? []),{rule:"mutation-notification",message:`Changes were applied, but preview refresh failed: ${error.message.slice(0,2000)}. Recheck ads_status and reopen the scenario.`}];}
|
|
283
306
|
}
|
|
284
307
|
return finishExecution("mutation", { ...(args.patches ? {units:args.patches.map(item=>item.unit),transaction:true} : {unit:args.unit}), ...result });
|
|
@@ -300,13 +323,14 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
300
323
|
const units = edits.units();
|
|
301
324
|
return json({ total: matches.length, scenarios: matches.slice(offset, offset + limit).map(item => ({ ...item, unit: units.find(unit => unit.files.includes(item.file))?.id ?? null })), ...(offset + limit < matches.length ? { nextOffset: offset + limit } : {}), diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios` });
|
|
302
325
|
} },
|
|
303
|
-
{ name: "ads_show_scenario", title: "Scenario preview", description: "Render one real
|
|
304
|
-
const
|
|
326
|
+
{ name: "ads_show_scenario", title: "Scenario preview", description: "Render one real scenario with its fixtures. Discover its exact id first. Default waitFor: verified waits for successful current checks. Interactive browsers may request waitFor: compiled for unverified live feedback or a retained earlier view; inspect build.current and never use pending output as verification evidence. Requires MCP Apps and resource forwarding; fallback links to the same showcase scenario.", schema: z.object({ id: z.string().min(1).max(256), waitFor: z.enum(["verified", "compiled"]).default("verified") }).strict(), _meta: { ui: { resourceUri: scenarioWidget() } }, call: async ({ id, waitFor }, signal) => {
|
|
327
|
+
const registry = previewRegistry(waitFor);
|
|
328
|
+
const entry = registry.scenarios.find(item => item.id === id);
|
|
305
329
|
if (!entry) throw new Error("Unknown scenario id. Read ads_scenarios; IDs must match discovered source entries.");
|
|
306
|
-
if (
|
|
307
|
-
const app = scenarioApps().find(item => item.id === id);
|
|
308
|
-
const build = await previewBuild(app, signal);
|
|
309
|
-
const graph = graphSelection(id);
|
|
330
|
+
if (registry.diagnostics.length) throw new Error("Scenario registry has errors. Read ads://project/scenarios and fix its diagnostics.");
|
|
331
|
+
const app = scenarioApps(waitFor === "compiled").find(item => item.id === id);
|
|
332
|
+
const build = await previewBuild(app, signal, waitFor);
|
|
333
|
+
const graph = graphSelection(id, build);
|
|
310
334
|
if (!options.config.mcp.previewManifest) projectApp(options, app, build);
|
|
311
335
|
return json({ widget: { resourceUri: scenarioWidget() }, scenario: { ...entry, resourceUri: appUri(id) }, ...graph, build, showcaseUrl: scenarioUrl(id) });
|
|
312
336
|
} },
|
|
@@ -330,27 +354,33 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
330
354
|
if (!("text" in content)) return json({ ...manifest, mimeType: content.mimeType, binary: true, note: "Read binary bytes via resources/read; this tool does not embed them." });
|
|
331
355
|
return json({ ...manifest, text: content.text.slice(offset, offset + limit), offset, ...(offset + limit < content.text.length ? { nextOffset: offset + limit } : {}) });
|
|
332
356
|
} },
|
|
333
|
-
{ name: "ads_show_tokens", title: "Token previews", description: "Render
|
|
334
|
-
|
|
357
|
+
{ name: "ads_show_tokens", title: "Token previews", description: "Render a discovered token scenario with project-owned templates and fixtures. Pass its id as category, or omit for the first token scenario. Default waitFor: verified requires current checks. Interactive browsers may use waitFor: compiled for explicitly unverified feedback or a retained view. Older compilers provide a generic definition inspector.", schema: z.object({ category: z.string().max(256).optional(), waitFor: z.enum(["verified", "compiled"]).default("verified") }).strict(), _meta: { ui: { resourceUri: options.config.mcp.previewManifest ? PREVIEW_APP_URI : TOKENS_APP_URI } }, call: async ({ category, waitFor }, signal) => {
|
|
358
|
+
const registry = previewRegistry(waitFor);
|
|
359
|
+
if (!category && options.config.mcp.previewManifest) category = registry.scenarios.find(item => item.kind === "tokens")?.id;
|
|
335
360
|
if (!category && options.config.mcp.previewManifest) throw new Error("No token scenario is registered. Colocate a token scenario and fixture before opening the preview; ads_tokens still inspects definitions.");
|
|
336
361
|
if (category) {
|
|
337
|
-
const entry =
|
|
362
|
+
const entry = registry.scenarios.find(item => item.kind === "tokens" && item.id === category);
|
|
338
363
|
if (!entry) throw new Error("Unknown token scenario. Discover categories with ads_tokens or ads_scenarios(kind: tokens) first.");
|
|
339
|
-
if (
|
|
340
|
-
const app = scenarioApps().find(item => item.id === category);
|
|
341
|
-
const build = await previewBuild(app, signal);
|
|
342
|
-
const graph = graphSelection(category);
|
|
364
|
+
if (registry.diagnostics.length) throw new Error("Scenario registry has errors. Fix its diagnostics before reviewing.");
|
|
365
|
+
const app = scenarioApps(waitFor === "compiled").find(item => item.id === category);
|
|
366
|
+
const build = await previewBuild(app, signal, waitFor);
|
|
367
|
+
const graph = graphSelection(category, build);
|
|
343
368
|
if (!options.config.mcp.previewManifest) projectApp(options, app, build);
|
|
344
369
|
return json({ widget: { resourceUri: options.config.mcp.previewManifest ? PREVIEW_APP_URI : TOKENS_APP_URI }, category, scenario: { ...entry, resourceUri: appUri(category) }, ...graph, build, showcaseUrl: scenarioUrl(category) });
|
|
345
370
|
}
|
|
346
371
|
return json({ widget: { resourceUri: TOKENS_APP_URI }, category: null, tokenCount: inspectTokens(root).tokens.length, dataUri: `${PROJECT_URI}/tokens`, showcaseUrl: getShowcaseUrl() });
|
|
347
372
|
} },
|
|
348
373
|
{ name: "ads_behaviors", description: "Discover behavior owners, then page an exact unit's checks, guarantees, subjects, demonstrations or profiles. Summary listings never embed runner logs. Default 10/max 20 entries and 8 KiB JSON per page; continue with nextCursor and identical filters. Cursors expire when discovery/evidence changes. Read sourceFile with ads_read_file for a complete contract. Metadata and reachable calls do not prove execution; use ads_verify for registered checks.", schema: z.object({ query: z.string().max(200).optional(), unit: z.string().min(1).max(256).optional(), api: z.string().max(200).optional(), section: z.enum(behaviorSections).optional(), ...paged }).strict(), call: args => json(behaviorPage(options,args)) },
|
|
349
|
-
{ name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Only the latest verification and mutation snapshots are retained; replaced IDs fail explicitly. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
|
|
374
|
+
{ name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_validate/ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Only the latest validation, verification and mutation snapshots are retained; replaced IDs fail explicitly. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
|
|
350
375
|
{ name:"ads_report_bug",title:"Report a suspected ADS defect",description:"Record an unexpected ADS guard, preview, build, transport or runner behavior after targeted investigation. Provide expected/observed behavior, minimal steps and frequency; keep suspectedCause separate. Evidence optionally selects a returned resultId or exact unit/check/runId. ADS snapshots compact evidence, version, configured framework and revisions. A report is an untriaged agent claim, not proof of an ADS cause. Returns a small receipt with the report ID and local file path; submitted reports cannot be read through MCP. Stored locally under .ds/reports/ with deduplication, no automatic expiry and no upload. Read ads://guides/reporting; ordinary valid guard rejections should be fixed in their owner.",schema:bugReportSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("bug",args) },
|
|
351
376
|
{ name:"ads_request_feature",title:"Request an ADS capability",description:"Record a legitimate workflow that needs a missing ADS capability. Provide workflow, capability and impact; proposal is optional. Preserve valid design/API rather than weakening guards or inventing workaround props. Optional evidence references an existing execution/check, not pasted files/logs. ADS attaches compact context and returns a receipt with the report ID and local file path. Intake is submission-only; no report-reading tools or resources. Shared local report store: deduplicated, untriaged, no automatic expiry or upload. Read ads://guides/reporting; use ads_report_bug for suspected broken existing behavior.",schema:featureRequestSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("feature",args) },
|
|
352
377
|
{ name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Only the latest bundle per check is retained, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
|
|
378
|
+
{ name: "ads_validate", description: "Run the shared ads validate audit. Default scope all: core architecture and test ownership, registered Oxlint, configured project scripts and all registered behavior checks. scope changed uses affected behavior checks since the last successful full audit; missing/incompatible baselines or broad changes expand to all and report why. Core and opaque project scripts retain their full scope. Use changed during editing, all after test/ownership/config migrations and before releases or explicit complete audits. Reports scope, source revision, skipped stages, progress and a bounded resultId; page diagnostics/checks/outcomes with ads_results. Changed inputs, cancellation and failed/skipped registered cases cannot pass. Read ads://guides/validation. Runs trusted configured commands; installs nothing.", schema: z.object({scope:z.enum(["all","changed"]).default("all")}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
|
|
379
|
+
if (verification.status().running || edits.status().busy) throw new Error("Wait for the active verification or guarded edit before validating.");
|
|
380
|
+
return finishExecution("validation",await validation.run(args,signal,progress));
|
|
381
|
+
} },
|
|
353
382
|
{ name: "ads_verify", description: "Run one owner's registered development behavior checks using its configured runner/profile. Executes trusted project commands with bounded output, cancellation and process-tree cleanup; installs nothing. Progress and per-check timings are available through ads_status; a profile timeout bounds the whole run. Browser profiles use an isolated managed showcase/MCP App. React StrictMode requires a project development harness, not a production widget. Missing/skipped cases, stale inputs and process exit alone cannot produce passing evidence. Replies contain counts, acceptance, at most three failure summaries and a resultId (4 KiB JSON maximum). Page outcomes with ads_results; inspect one exact unit/check/runId with ads_investigate. Discover exact unit/check IDs with ads_behaviors first.", schema: z.object({ unit: z.string().min(1).max(256), checks: z.array(z.string().min(1).max(100)).min(1).max(100).optional() }).strict(), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
|
|
383
|
+
if (validation.status().busy) throw new Error("Wait for the active validation run before verifying separately.");
|
|
354
384
|
const result = await verification.run(args, signal, progress);
|
|
355
385
|
return finishExecution("verification", {unit:args.unit,...result});
|
|
356
386
|
} },
|
|
@@ -452,7 +482,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
452
482
|
const sources = sourceFiles(options.dsRoot);
|
|
453
483
|
return `${fileFingerprint([...sources, ...getDocuments().map(doc => doc.file), path.join(root, "ds.config.json"), path.join(root, "package.json"), path.join(root, ".ds/behavior-results.json")])}\n${scenarioGroupFingerprint(options, sources)}`;
|
|
454
484
|
};
|
|
455
|
-
const artifactFingerprint = () => fileFingerprint(allApps().map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
|
|
485
|
+
const artifactFingerprint = () => fileFingerprint(allApps(true).map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
|
|
456
486
|
const assetFingerprint = () => resourceAssets().map(asset => asset.uri).sort().join("\n");
|
|
457
487
|
let previous = fingerprint();
|
|
458
488
|
let previousArtifacts = artifactFingerprint();
|
|
@@ -463,6 +493,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
463
493
|
const investigationFingerprint=()=>fileFingerprint([path.join(root,".ds/investigations.json")]);
|
|
464
494
|
let previousInvestigations=investigationFingerprint();
|
|
465
495
|
let previousResults=executionResults.fingerprint();
|
|
496
|
+
let deferredDiscovery = false;
|
|
466
497
|
async function refresh(force = false) {
|
|
467
498
|
// Polling covers replaced files and new directories consistently across OSes.
|
|
468
499
|
cache.documents = undefined;
|
|
@@ -477,7 +508,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
477
508
|
const capturesChanged = captures.store.fingerprint() !== previousCaptures;
|
|
478
509
|
const investigationsChanged=investigationFingerprint()!==previousInvestigations;
|
|
479
510
|
const resultsChanged=executionResults.fingerprint()!==previousResults;
|
|
480
|
-
if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged) return false;
|
|
511
|
+
if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged && !deferredDiscovery) return false;
|
|
481
512
|
if (filesChanged) {
|
|
482
513
|
const updated = loadConfig(root);
|
|
483
514
|
await previewWatch?.reconfigure?.(updated.config.mcp);
|
|
@@ -489,15 +520,21 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
489
520
|
previous = fingerprint();
|
|
490
521
|
if (appsChanged) { if (notifications) notifications.toolsChanged(); else await server.sendToolListChanged(); }
|
|
491
522
|
}
|
|
492
|
-
|
|
523
|
+
const checking = options.config.mcp.previewManifest && previewWatch?.status().state === "running"
|
|
524
|
+
&& builds().previews.some(entry => ["idle", "building"].includes(entry.state)
|
|
525
|
+
|| entry.diagnostics.some(item => item.code === "ADS_PREVIEW_STALE_SOURCE"));
|
|
526
|
+
deferredDiscovery ||= filesChanged;
|
|
527
|
+
const discoveryChanged = deferredDiscovery && !checking;
|
|
528
|
+
if (discoveryChanged) deferredDiscovery = false;
|
|
529
|
+
if (discoveryChanged || assetsChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
|
|
493
530
|
previousArtifacts = artifactFingerprint();
|
|
494
531
|
previousAssets = assetFingerprint();
|
|
495
532
|
previousBuild = JSON.stringify(builds());
|
|
496
|
-
const targets =
|
|
497
|
-
: [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_URI, `${PROJECT_URI}/status`, ...(options.config.mcp.previewManifest ? [PREVIEW_MANIFEST_URI] : []), ...(artifactsChanged ? allApps().map(app => appUri(app.id)) : [])].filter((uri) => era === "modern" || subscribed.has(uri));
|
|
533
|
+
const targets = discoveryChanged ? era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]
|
|
534
|
+
: [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_URI, `${PROJECT_URI}/status`, ...(filesChanged ? [`${PROJECT_URI}/tokens`] : []), ...(options.config.mcp.previewManifest ? [PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI] : []), ...(artifactsChanged ? allApps(true).map(app => appUri(app.id)) : [])].filter((uri) => era === "modern" || subscribed.has(uri));
|
|
498
535
|
if(resultsChanged){targets.push(...[RESULTS_URI,...executionResults.index().results.map(entry=>entry.resourceUri),...[...subscribed].filter(uri=>uri.startsWith("ads://results/"))].filter(uri=>era==="modern"||subscribed.has(uri)));previousResults=executionResults.fingerprint();}
|
|
499
536
|
if(investigationsChanged){targets.push(...[INVESTIGATIONS_URI,...investigationIndex(root).entries.map(entry=>entry.resourceUri),...[...subscribed].filter(uri=>uri.startsWith("ads://investigations/"))].filter(uri=>era==="modern"||subscribed.has(uri)));previousInvestigations=investigationFingerprint();}
|
|
500
|
-
if (capturesChanged ||
|
|
537
|
+
if (capturesChanged || discoveryChanged) {
|
|
501
538
|
const current = (captures.store.fingerprint() ? captureIndex().captures : []).flatMap(record => [record.current?.resourceUri, record.candidate?.resourceUri].filter(Boolean));
|
|
502
539
|
targets.push(...[CAPTURES_URI, ...previousCaptureUris, ...current].filter(uri => era === "modern" || subscribed.has(uri)));
|
|
503
540
|
previousCaptureUris = current;
|
|
@@ -510,7 +547,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
510
547
|
timer?.unref();
|
|
511
548
|
server.oninitialized = () => previewWatch?.start();
|
|
512
549
|
server.onclose = () => { if (timer) clearInterval(timer); };
|
|
513
|
-
return { server, refresh, async close() { if (timer) clearInterval(timer); if (!inspection) { await verification.close(); await captures.close(); } await server.close(); } };
|
|
550
|
+
return { server, refresh, async close() { if (timer) clearInterval(timer); if (!inspection) { await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
|
|
514
551
|
}
|
|
515
552
|
|
|
516
553
|
export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false } = {}) {
|
|
@@ -535,6 +572,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
|
|
|
535
572
|
const results = await Promise.allSettled([
|
|
536
573
|
Promise.resolve().then(() => host?.close()),
|
|
537
574
|
previewWatch.stop(),
|
|
575
|
+
Promise.resolve().then(() => inspection.validation?.close()),
|
|
538
576
|
Promise.resolve().then(() => inspection.verification?.close()),
|
|
539
577
|
Promise.resolve().then(() => inspection.captures?.close()),
|
|
540
578
|
Promise.resolve().then(() => handle?.close()),
|
package/dist/oxlint.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
-
import { defaultConfig, importViolation } from "./config.mjs";
|
|
2
|
+
import { defaultConfig, importViolation, isTestFile } from "./config.mjs";
|
|
3
|
+
import { inspectUnits } from "./units.mjs";
|
|
3
4
|
import { appImportViolation, showcaseImportViolation, importResolver } from "./boundaries.mjs";
|
|
4
5
|
|
|
5
6
|
const schema = [{
|
|
@@ -59,6 +60,10 @@ export default {
|
|
|
59
60
|
const resolve = importResolver(settings);
|
|
60
61
|
const filename = path.resolve(context.getFilename());
|
|
61
62
|
const buildFiles = new Set((settings.config.configurationFiles ?? []).map(file => path.resolve(settings.root,file)));
|
|
63
|
+
if (isTestFile(filename)) {
|
|
64
|
+
const inventory = inspectUnits({...settings,sourceRoot:path.resolve(settings.root,settings.config.sourceDir)});
|
|
65
|
+
settings.testOwner = file => inventory.owner(inventory.relative(path.relative(settings.root,file)));
|
|
66
|
+
}
|
|
62
67
|
function inspect(node) {
|
|
63
68
|
if (typeof node.source?.value !== "string") return;
|
|
64
69
|
if (buildFiles.has(filename) && resolve(node.source.value,filename).every(file=>buildFiles.has(file))) return;
|
package/dist/preview-builder.mjs
CHANGED
|
@@ -3,10 +3,12 @@ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { previewSourceRevision } from "./preview-inputs.mjs";
|
|
5
5
|
import { createPreviewResources } from "./preview-resources.mjs";
|
|
6
|
+
import { createPreviewWorkerCache } from "./preview-workers.mjs";
|
|
6
7
|
|
|
7
8
|
/** Project-owned Vite plugins/configuration, with a persistent development graph.
|
|
8
9
|
* Watch output is private scratch data; only the compiler may publish it after
|
|
9
|
-
*
|
|
10
|
+
* the relevant source/generation checks; verified output also requires validation.
|
|
11
|
+
* Existing buildGraph adapters work
|
|
10
12
|
* unchanged; opt in by passing this function as buildGraph. */
|
|
11
13
|
export function createVitePreviewBuilder({ build, configure }) {
|
|
12
14
|
let graph;
|
|
@@ -51,15 +53,19 @@ export function createVitePreviewBuilder({ build, configure }) {
|
|
|
51
53
|
const capture = { name: "ads-incremental-preview", enforce: "post",
|
|
52
54
|
buildStart() { started = previewSourceRevision(options); this.addWatchFile(trigger); },
|
|
53
55
|
writeBundle(_output, bundle) {
|
|
54
|
-
|
|
56
|
+
const inputs = [...this.getModuleIds(), ...this.getWatchFiles()].filter(id => !id.startsWith("\0"))
|
|
57
|
+
.map(id => path.isAbsolute(id) ? id : path.resolve(options.root, id));
|
|
58
|
+
candidate = { source: started, output: { output: Object.values(bundle) }, modules: [...new Set(inputs)]
|
|
59
|
+
.filter(file => !file.startsWith(directory + path.sep)) };
|
|
55
60
|
},
|
|
56
61
|
};
|
|
57
62
|
try {
|
|
58
63
|
const config = await configure(entries, options);
|
|
59
64
|
const output = config.build?.rollupOptions?.output;
|
|
60
65
|
if (Array.isArray(output) || output?.file) throw new Error("Incremental preview builds require one module output without output.file.");
|
|
61
|
-
|
|
62
|
-
|
|
66
|
+
const workers = createPreviewWorkerCache(options, () => started === previewSourceRevision(options));
|
|
67
|
+
current.watcher = await build({ ...config, plugins: [...config.plugins ?? [], workers, capture],
|
|
68
|
+
build: { ...config.build, minify: false, cssMinify: false, reportCompressedSize: false, write: true, outDir: path.join(directory, "output"), emptyOutDir: true,
|
|
63
69
|
rollupOptions: { ...config.build?.rollupOptions, output: { ...output, dir: path.join(directory, "output") } },
|
|
64
70
|
watch: { ...config.build?.watch, skipWrite: false,
|
|
65
71
|
// Bun's native fs-watch reattachment can miss rapid subsequent
|
|
@@ -4,10 +4,11 @@ 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");
|
|
13
14
|
const unknownResource = message => Object.assign(new Error(message), { code: "ADS_PREVIEW_NOT_FOUND" });
|
|
@@ -142,7 +143,7 @@ function cacheOptions(options, revision) {
|
|
|
142
143
|
}
|
|
143
144
|
|
|
144
145
|
/** A cache hit still verifies every compiled byte before republishing it. */
|
|
145
|
-
export function cachedPreviewPublication(options, entries, revision) {
|
|
146
|
+
export function cachedPreviewPublication(options, entries, revision, target = options) {
|
|
146
147
|
if (!/^[a-f0-9]{64}$/.test(revision ?? "")) return null;
|
|
147
148
|
try {
|
|
148
149
|
const cached = cacheOptions(options, revision), manifest = readPreviewManifest(cached, { verify: true });
|
|
@@ -152,8 +153,12 @@ export function cachedPreviewPublication(options, entries, revision) {
|
|
|
152
153
|
const value = readPreviewAsset(cached, uri, manifest);
|
|
153
154
|
return [uri, "text" in value ? Buffer.from(value.text) : Buffer.from(value.blob, "base64")];
|
|
154
155
|
}));
|
|
156
|
+
// A compiler may intentionally embed its working directory. Such output
|
|
157
|
+
// cannot be reused from a temporary candidate in the real project.
|
|
158
|
+
const roots=[options.root,options.root.replaceAll("\\","/"),JSON.stringify(options.root).slice(1,-1),encodeURI(options.root)];
|
|
159
|
+
if (target.root !== options.root && [...contents.values()].some(bytes => roots.some(root=>bytes.includes(root)))) return null;
|
|
155
160
|
const { session: _session, ...graph } = manifest;
|
|
156
|
-
return publication(
|
|
161
|
+
return publication(target, entries, graph, contents);
|
|
157
162
|
} catch { return null; } // Missing, pruned or corrupt cache means a real build.
|
|
158
163
|
}
|
|
159
164
|
|
|
@@ -162,7 +167,9 @@ function publication(options, entries, manifest, contents, saveCache = true) {
|
|
|
162
167
|
const target = previewManifestPath(options);
|
|
163
168
|
const assetsRoot = path.join(path.dirname(target), "assets");
|
|
164
169
|
const assetFiles = [...contents.keys()].map(uri => path.join(assetsRoot, uri.slice("ads://assets/".length)));
|
|
165
|
-
return { assetFiles, revision,
|
|
170
|
+
return { assetFiles, revision,
|
|
171
|
+
publishLive(session) { publication(livePreviewOptions(options), [], manifest, contents, false).publish(session); },
|
|
172
|
+
publish(session) {
|
|
166
173
|
const encoded = JSON.stringify({ ...manifest, session });
|
|
167
174
|
if (Buffer.byteLength(encoded) > 2 * 1024 * 1024) throw new Error("Preview manifest exceeds the 2 MiB resource limit.");
|
|
168
175
|
const history = path.join(path.dirname(target), "history");
|
package/dist/preview-scope.mjs
CHANGED
|
@@ -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("\\", "/");
|