@reqvire-org/ads 0.3.26 → 0.3.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -10
- package/dist/bootstrap-ds/README.md +7 -5
- package/dist/bootstrap-ds/ds.config.json +1 -1
- package/dist/bootstrap-ds/scripts/build-mcp-previews.mjs +1 -1
- package/dist/capture.mjs +1 -1
- package/dist/development-runtime.mjs +17 -0
- package/dist/index.mjs +1 -1
- package/dist/init.mjs +14 -12
- package/dist/mcp/apps.mjs +1 -1
- package/dist/mcp/context.mjs +5 -4
- package/dist/mcp/mutations.mjs +3 -2
- package/dist/mcp/preview-watch.mjs +2 -1
- package/dist/mcp/server.mjs +4 -1
- package/dist/mcp/widget.bundle.js +1 -1
- package/dist/preview-files.mjs +33 -0
- package/dist/preview-inputs.mjs +6 -5
- package/dist/scenarios-compiler.mjs +7 -7
- package/dist/showcase/sandbox.bundle.js +1 -1
- package/dist/skills/README.md +7 -1
- package/dist/skills/ads-break-ui/SKILL.md +6 -2
- package/dist/skills/ads-break-ui/references/behaviors.md +6 -3
- package/dist/skills/ads-break-ui/references/layers.md +16 -0
- package/dist/skills/ads-break-ui/references/runtimes.md +110 -0
- package/dist/skills/ads-designer/README.md +6 -0
- package/dist/skills/ads-designer/SKILL.md +10 -5
- package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +7 -5
- package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -1
- package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +1 -1
- package/dist/skills/ads-designer/references/behaviors.md +6 -3
- package/dist/skills/ads-designer/references/cli.md +10 -7
- package/dist/skills/ads-designer/references/design-craft.md +31 -0
- package/dist/skills/ads-designer/references/layers.md +16 -0
- package/dist/skills/ads-designer/references/runtimes.md +110 -0
- package/dist/skills/ads-import/SKILL.md +23 -3
- package/dist/skills/ads-import/agents/openai.yaml +2 -2
- package/dist/skills/ads-import/references/behaviors.md +6 -3
- package/dist/skills/ads-import/references/cli.md +10 -7
- package/dist/skills/ads-import/references/compatibility.md +113 -0
- package/dist/skills/ads-import/references/implementation.md +6 -0
- package/dist/skills/ads-import/references/layers.md +16 -0
- package/dist/skills/ads-import/references/runtimes.md +110 -0
- package/dist/skills/ads-motion/SKILL.md +6 -2
- package/dist/skills/ads-motion/references/behaviors.md +6 -3
- package/dist/skills/ads-motion/references/layers.md +16 -0
- package/dist/skills/ads-motion/references/runtimes.md +110 -0
- package/dist/skills/ads-port/SKILL.md +6 -2
- package/dist/skills/ads-port/references/behaviors.md +6 -3
- package/dist/skills/ads-port/references/cli.md +10 -7
- package/dist/skills/ads-port/references/layers.md +16 -0
- package/dist/skills/ads-port/references/runtimes.md +110 -0
- package/dist/verification.mjs +4 -3
- package/docs/ADS.md +17 -0
- package/docs/ARCHITECTURE.md +19 -0
- package/docs/BEHAVIORS.md +6 -3
- package/docs/CHANGELOG.md +21 -1
- package/docs/COMPARISON.md +63 -0
- package/docs/GUIDE.md +20 -10
- package/docs/MCP.md +44 -6
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -3,14 +3,22 @@
|
|
|
3
3
|
**A design system your agent can see and shape. Your components. Your look. Your code.**
|
|
4
4
|
|
|
5
5
|
ADS gives coding agents MCP tools and skills to build and maintain a design system
|
|
6
|
-
inside your project.
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
6
|
+
inside your project.
|
|
7
|
+
|
|
8
|
+
- **One UI for websites and MCP Apps.** Reuse the same project-owned components,
|
|
9
|
+
behavior, tokens and styles across both.
|
|
10
|
+
- **Real UI. Guarded changes.** Humans and agents review the actual implementation;
|
|
11
|
+
agent patches pass architecture and configured project checks before they land.
|
|
12
|
+
- **Colocated code, clearer ownership.** Related implementation, styles, scenarios
|
|
13
|
+
and checks stay near their owner, reducing the search for change context.
|
|
14
|
+
- **Compiled styles, efficient delivery.** Linaria extracts CSS ahead of time.
|
|
15
|
+
Modular source and extracted styles support tree shaking, code splitting and
|
|
16
|
+
independent asset caching.
|
|
11
17
|
|
|
12
18
|
**Inspired by any library. Bound to none. Owned by your project.**
|
|
13
19
|
|
|
20
|
+
[Compare ADS with traditional component libraries and shadcn/ui](docs/COMPARISON.md).
|
|
21
|
+
|
|
14
22
|
ADS requires Linaria for component and pattern styling; your project chooses its
|
|
15
23
|
UI framework and visual design. The [architecture](docs/ARCHITECTURE.md) explains
|
|
16
24
|
Data, UX, Skin, and the performance reasons behind that choice.
|
|
@@ -44,7 +52,7 @@ setup and comparison.
|
|
|
44
52
|
|
|
45
53
|
## Set up your project
|
|
46
54
|
|
|
47
|
-
Run **inside your project**, where `package.json` lives.
|
|
55
|
+
Run **inside your project**, where `package.json` lives. Use Node 22.12+ or Bun 1.3.13+.
|
|
48
56
|
|
|
49
57
|
```sh
|
|
50
58
|
npx @reqvire-org/ads init --framework react
|
|
@@ -56,13 +64,15 @@ Use `--framework preact` for native Preact. Init saves the choice in
|
|
|
56
64
|
`ds.config.json`; later runs can use plain `ads init`. A copied starter that
|
|
57
65
|
already declares its framework can also omit the flag.
|
|
58
66
|
|
|
59
|
-
For a Bun project,
|
|
67
|
+
For a Bun project, Node is unnecessary:
|
|
60
68
|
|
|
61
69
|
```sh
|
|
70
|
+
bunx --bun @reqvire-org/ads init --framework react
|
|
62
71
|
bun install
|
|
63
|
-
bun run build
|
|
72
|
+
bun --bun run build
|
|
64
73
|
```
|
|
65
74
|
|
|
75
|
+
`--bun` keeps package executables on Bun even when they have a Node shebang.
|
|
66
76
|
`init` detects npm or Bun from your project. It adds ADS and Oxlint as development
|
|
67
77
|
dependencies, sets up an empty local ADS if needed, and adds ADS checks before your
|
|
68
78
|
existing build. The default layout is root `design-system/`, alongside `src/`.
|
|
@@ -298,8 +308,9 @@ npm test # Tool guards and packed npm install/build tests
|
|
|
298
308
|
npm run build:project # ADS guards, type checking, example build and showcase
|
|
299
309
|
```
|
|
300
310
|
|
|
301
|
-
Set `ADS_TEST_BUN=1` when running `npm test` to
|
|
302
|
-
|
|
311
|
+
Set `ADS_TEST_BUN=1` when running `npm test` to test the installed package with
|
|
312
|
+
Node/npm/npx unavailable, including Bun builds, MCP previews and guarded checks.
|
|
313
|
+
Browser behavior/capture checks also run when a supported browser is installed.
|
|
303
314
|
|
|
304
315
|
Tool source lives in `src/`; tests and the dummy project live in `tests/`.
|
|
305
316
|
|
|
@@ -12,8 +12,8 @@ Read the local [contract](ADS.md) and the
|
|
|
12
12
|
|
|
13
13
|
Copy the contents of `bootstrap-ds/`, including dotfiles, into a new project.
|
|
14
14
|
The installed `ads-designer` skill contains the same files in
|
|
15
|
-
`assets/bootstrap-ds/`. Set the project name in `package.json`. Use Node 22.12
|
|
16
|
-
|
|
15
|
+
`assets/bootstrap-ds/`. Set the project name in `package.json`. Use Node 22.12+
|
|
16
|
+
or Bun 1.3.13+ with a current ADS release.
|
|
17
17
|
|
|
18
18
|
```sh
|
|
19
19
|
npx @reqvire-org/ads init --framework react
|
|
@@ -32,10 +32,12 @@ npm run build
|
|
|
32
32
|
```
|
|
33
33
|
|
|
34
34
|
For a new Bun workspace, declare Bun in `packageManager`, omit the copied npm
|
|
35
|
-
lockfile and translate nested npm scripts to `bun run`.
|
|
35
|
+
lockfile and translate nested npm scripts to `bun --bun run`. Initialize with
|
|
36
|
+
`bunx --bun @reqvire-org/ads init`. Init detects existing
|
|
36
37
|
Bun projects and preserves their scripts/lockfiles. Use `bun install` and
|
|
37
|
-
`bun run build`/`bun run dev:showcase`.
|
|
38
|
-
|
|
38
|
+
`bun --bun run build`/`bun --bun run dev:showcase`. Node is unnecessary with Bun
|
|
39
|
+
1.3.13+. The supplied preview watcher's `command: "runtime"` inherits the
|
|
40
|
+
interpreter that launched ADS and runs the project's installed checks.
|
|
39
41
|
|
|
40
42
|
For an existing application, merge only the ADS source and required extraction,
|
|
41
43
|
aliases and preview adapter. Preserve its framework, entry points and build.
|
|
@@ -17,7 +17,7 @@ await runScenarioCompiler(root, {
|
|
|
17
17
|
watched: process.argv.includes("--watch"),
|
|
18
18
|
compilerFiles: [import.meta.filename],
|
|
19
19
|
async validate() {
|
|
20
|
-
try { await runScript(manager, ["run", "lint"], { cwd: root }); }
|
|
20
|
+
try { await runScript(manager, [...(manager === "bun" ? ["--bun"] : []), "run", "lint"], { cwd: root }); }
|
|
21
21
|
catch (error) { throw new Error([error.stdout, error.stderr].map(value => value?.toString() ?? "").join("\n") || error.message); }
|
|
22
22
|
},
|
|
23
23
|
async buildGraph(entries, options, track) {
|
package/dist/capture.mjs
CHANGED
|
@@ -87,7 +87,7 @@ export function createCaptureController(root) {
|
|
|
87
87
|
const settings = { browser: "chromium", timeoutMs: 60000, ...options.config.mcp.capture };
|
|
88
88
|
writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, settings, apps, output: temporary }));
|
|
89
89
|
update("rendering", 0, apps.length);
|
|
90
|
-
const run = await executeDevelopmentCommand({ command: "
|
|
90
|
+
const run = await executeDevelopmentCommand({ command: "runtime", timeoutMs: settings.timeoutMs, label: "Screenshot capture" }, [fileURLToPath(new URL("./capture/worker.mjs", import.meta.url)), request], root, {}, signal);
|
|
91
91
|
if (run.code !== 0) throw new Error(`Screenshot browser failed (${run.code}): ${run.output.slice(-3000)}`);
|
|
92
92
|
if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > 128 * 1024) throw new Error("Screenshot runner produced no bounded report.");
|
|
93
93
|
const value = JSON.parse(readFileSync(report, "utf8"));
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
/** The launcher selects the runtime; Node-compatible imports work on both. */
|
|
4
|
+
export function developmentRuntime() {
|
|
5
|
+
return { name: process.versions.bun ? "bun" : "node", version: process.versions.bun ?? process.versions.node,
|
|
6
|
+
executable: process.execPath, binDir: path.dirname(process.execPath) };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** `runtime` is portable. Explicit interpreter names keep their meaning. */
|
|
10
|
+
export function developmentExecutable(command) {
|
|
11
|
+
const runtime = developmentRuntime();
|
|
12
|
+
return command === "runtime" || command === runtime.name ? runtime.executable : command;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function packageScriptCommand(manager, script) {
|
|
16
|
+
return { command: manager, args: [...(manager === "bun" ? ["--bun"] : []), "run", script] };
|
|
17
|
+
}
|
package/dist/index.mjs
CHANGED
|
@@ -4,7 +4,7 @@ export { inspectTokens, tokenContract } from "./tokens.mjs";
|
|
|
4
4
|
export { inspectTokenOrigins } from "./token-origins.mjs";
|
|
5
5
|
export { generateLintConfig } from "./lint-config.mjs";
|
|
6
6
|
export { generateBrandAssets } from "./brand-assets.mjs";
|
|
7
|
-
//
|
|
7
|
+
// Development-only helpers for registered project lint extensions. They reuse the
|
|
8
8
|
// same validated configuration and property boundary as the core checker.
|
|
9
9
|
export { loadConfig } from "./config.mjs";
|
|
10
10
|
export { importResolver, styleWriteViolation } from "./boundaries.mjs";
|
package/dist/init.mjs
CHANGED
|
@@ -32,7 +32,7 @@ function detectManager(root, pkg, requested) {
|
|
|
32
32
|
if (bun) return "bun";
|
|
33
33
|
if (npm) return "npm";
|
|
34
34
|
if (["pnpm-lock.yaml", "yarn.lock"].some((name) => existsSync(path.join(root, name)))) throw new Error("This version supports npm and Bun projects.");
|
|
35
|
-
return process.env.npm_config_user_agent?.startsWith("bun/") ? "bun" : "npm";
|
|
35
|
+
return process.versions.bun || process.env.npm_config_user_agent?.startsWith("bun/") ? "bun" : "npm";
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
function assertLocalFile(root, file) {
|
|
@@ -105,7 +105,9 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
|
|
|
105
105
|
}
|
|
106
106
|
const manager = detectManager(root, pkg, packageManager);
|
|
107
107
|
if (!["npm", "bun"].includes(manager)) throw new Error("packageManager must be npm or bun.");
|
|
108
|
-
const run =
|
|
108
|
+
const run = manager === "bun" ? "bun --bun run" : "npm run";
|
|
109
|
+
const ads = manager === "bun" ? "bun --bun run ads" : "ads";
|
|
110
|
+
const oxlint = manager === "bun" ? "bun --bun run oxlint" : "oxlint";
|
|
109
111
|
const spec = dependencySpec(toolPackage ?? pkg.devDependencies?.[tool.name] ?? pkg.dependencies?.[tool.name] ?? tool.version);
|
|
110
112
|
const { config, dsRoot } = loadConfig(root);
|
|
111
113
|
if (framework !== undefined && !supportedFrameworks.includes(framework)) throw new Error("framework must be react or preact.");
|
|
@@ -117,24 +119,24 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
|
|
|
117
119
|
const lintRoots = [config.sourceDir];
|
|
118
120
|
if (!isInside(path.resolve(root, config.sourceDir), dsRoot)) lintRoots.push(config.dsDir);
|
|
119
121
|
const sourceArguments = lintRoots.map((directory) => `'${directory.replaceAll("'", "'\"'\"'")}'`).join(" ");
|
|
120
|
-
const lint =
|
|
122
|
+
const lint = `${ads} lint-config . && ${ads} check . && ${oxlint} --deny-warnings --config .ds/oxlintrc.json ${sourceArguments}`;
|
|
121
123
|
const scripts = { ...pkg.scripts };
|
|
122
|
-
if (scripts["lint:ds"] && scripts["lint:ds"] !== lint && !["ads lint-config . && ads check .", "ds lint-config . && ds check ."].some(prefix => scripts["lint:ds"].startsWith(prefix))) throw new Error("An existing custom lint:ds script would conflict. Rename it or integrate ADS checks before running init.");
|
|
124
|
+
if (scripts["lint:ds"] && scripts["lint:ds"] !== lint && !["ads lint-config . && ads check .", "ds lint-config . && ds check .", "bun --bun run ads lint-config . && bun --bun run ads check ."].some(prefix => scripts["lint:ds"].startsWith(prefix))) throw new Error("An existing custom lint:ds script would conflict. Rename it or integrate ADS checks before running init.");
|
|
123
125
|
scripts["lint:ds"] = lint;
|
|
124
|
-
if (scripts["assets:ds"] && !["ads assets", "ds assets"].includes(scripts["assets:ds"])) throw new Error("An existing custom assets:ds script would conflict. Rename it or integrate ADS asset generation before running init.");
|
|
125
|
-
scripts["assets:ds"] =
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
const managedBuild =
|
|
126
|
+
if (scripts["assets:ds"] && !["ads assets", "ds assets", "bun --bun run ads assets"].includes(scripts["assets:ds"])) throw new Error("An existing custom assets:ds script would conflict. Rename it or integrate ADS asset generation before running init.");
|
|
127
|
+
scripts["assets:ds"] = `${ads} assets`;
|
|
128
|
+
for (const [name, command] of [["dev:showcase", "showcase"], ["ads-mcp", "mcp --mutations"], ["ads-read-mcp", "mcp"]]) {
|
|
129
|
+
if (!scripts[name] || [`ds ${command}`, `ads ${command}`, `bun --bun run ads ${command}`].includes(scripts[name])) scripts[name] = `${ads} ${command}`;
|
|
130
|
+
}
|
|
131
|
+
const managedBuild = /^(?:npm|bun(?: --bun)?) run lint:ds(?: && (?:npm|bun(?: --bun)?) run assets:ds)?$/.test(scripts.build ?? "");
|
|
130
132
|
if (scripts.build && !managedBuild) {
|
|
131
133
|
const previous = scripts.prebuild ?? "";
|
|
132
|
-
const remaining = previous.replace(/^(?:npm|bun) run lint:ds(?:\s*&&\s*(?:npm|bun) run assets:ds)?(?:\s*&&\s*|$)/, "");
|
|
134
|
+
const remaining = previous.replace(/^(?:npm|bun(?: --bun)?) run lint:ds(?:\s*&&\s*(?:npm|bun(?: --bun)?) run assets:ds)?(?:\s*&&\s*|$)/, "");
|
|
133
135
|
scripts.prebuild = `${run} lint:ds && ${run} assets:ds${remaining ? ` && ${remaining}` : ""}`;
|
|
134
136
|
} else scripts.build = `${run} lint:ds && ${run} assets:ds`;
|
|
135
137
|
if (scripts["build:showcase"]) {
|
|
136
138
|
const previous = scripts["prebuild:showcase"] ?? "";
|
|
137
|
-
const remaining = previous.replace(/^(?:npm|bun) run lint:ds(?:\s*&&\s*(?:npm|bun) run assets:ds)?(?:\s*&&\s*|$)/, "");
|
|
139
|
+
const remaining = previous.replace(/^(?:npm|bun(?: --bun)?) run lint:ds(?:\s*&&\s*(?:npm|bun(?: --bun)?) run assets:ds)?(?:\s*&&\s*|$)/, "");
|
|
138
140
|
scripts["prebuild:showcase"] = `${run} lint:ds && ${run} assets:ds${remaining ? ` && ${remaining}` : ""}`;
|
|
139
141
|
}
|
|
140
142
|
pkg.scripts = scripts;
|
package/dist/mcp/apps.mjs
CHANGED
|
@@ -49,5 +49,5 @@ export function projectApp(options, app, build) {
|
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
export function appMetadata({ nested = false } = {}) {
|
|
52
|
-
return { ui: { csp: { connectDomains: [], resourceDomains: ["data:", "blob:"], ...(nested ? { frameDomains: ["about:"] } : {}) } } };
|
|
52
|
+
return { ui: { csp: { connectDomains: ["blob:"], resourceDomains: ["data:", "blob:"], ...(nested ? { frameDomains: ["about:"] } : {}) } } };
|
|
53
53
|
}
|
package/dist/mcp/context.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { sourceUri } from "./catalog.mjs";
|
|
4
4
|
import { projectGuideFiles } from "../project-documents.mjs";
|
|
5
|
+
import { developmentRuntime, packageScriptCommand } from "../development-runtime.mjs";
|
|
5
6
|
|
|
6
7
|
export const GUIDE_URI = "ads://project/guide";
|
|
7
8
|
// Put the task triggers and entry path first: some hosts shorten server guidance.
|
|
@@ -20,15 +21,15 @@ export function projectContext(options) {
|
|
|
20
21
|
try { pkg = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); } catch { /* A partial ADS can still be inspected. */ }
|
|
21
22
|
const packageManager = manager(root, pkg);
|
|
22
23
|
const scripts = pkg.scripts ?? {};
|
|
23
|
-
const commands = ["ads-mcp", "ads-read-mcp", "dev:showcase", "build:showcase", "build:mcp-previews", "lint:ds", "lint", "lint:style", "typecheck", "test", "build"].filter((name) => typeof scripts[name] === "string").map((script) => ({ script, cwd: root, args:
|
|
24
|
+
const commands = ["ads-mcp", "ads-read-mcp", "dev:showcase", "build:showcase", "build:mcp-previews", "lint:ds", "lint", "lint:style", "typecheck", "test", "build"].filter((name) => typeof scripts[name] === "string").map((script) => { const launch = packageManager && packageScriptCommand(packageManager, script); return { script, cwd: root, args: launch ? [launch.command, ...launch.args] : null }; });
|
|
24
25
|
const guides = [...projectGuideFiles(root), path.join(config.dsDir, "README.md"), path.join(config.dsDir, "readme.md"), path.join(config.dsDir, "SKILL.md")].filter((file) => existsSync(path.join(root, file))).map((file) => ({ file: file.replaceAll("\\", "/"), uri: sourceUri(file.replaceAll("\\", "/")) }));
|
|
25
26
|
return { name: pkg.name ?? path.basename(root), projectRoot: root, dsRoot, sourceRoot, framework: config.framework,
|
|
26
27
|
publicEntry: path.join(dsRoot, config.publicEntry), publicEntryUri: existsSync(path.join(dsRoot, config.publicEntry)) ? sourceUri(path.relative(root, path.join(dsRoot, config.publicEntry)).replaceAll("\\", "/")) : null,
|
|
27
28
|
review: { importFrom: `${config.publicAlias}/review`, entry: path.join(dsRoot, config.reviewEntry), sourceUri: existsSync(path.join(dsRoot, config.reviewEntry)) ? sourceUri(path.relative(root, path.join(dsRoot, config.reviewEntry)).replaceAll("\\", "/")) : null, developmentOnly: true },
|
|
28
29
|
stylesEntry: path.join(dsRoot, config.stylesEntry), packageManager, commands, guides,
|
|
29
30
|
showcase: { client: "tool-owned-mcp", url: config.mcp.showcaseUrl, title: config.mcp.showcaseTitle ?? `${pkg.name ?? path.basename(root)} · Design System` },
|
|
30
|
-
runtime: {
|
|
31
|
-
shellHint: "The agent shell may have a different PATH from MCP.
|
|
31
|
+
runtime: { ...developmentRuntime(),
|
|
32
|
+
shellHint: "The agent shell may have a different PATH from MCP. Use this runtime executable/bin directory and the returned project commands; do not search the whole machine or assume another runtime must be installed." } };
|
|
32
33
|
}
|
|
33
34
|
|
|
34
35
|
export function workflow(previews) {
|
|
@@ -65,7 +66,7 @@ Execution replies from ads_verify and guarded edits contain counts, acceptance a
|
|
|
65
66
|
|
|
66
67
|
Project guide resources: ${context.guides.map((guide) => `${guide.file}: ${guide.uri}`).join("; ") || "none discovered"}.
|
|
67
68
|
|
|
68
|
-
|
|
69
|
+
Development runtime: ${context.runtime.name} ${context.runtime.version}. Executable: ${context.runtime.executable}. Bin directory: ${context.runtime.binDir}. ${context.runtime.shellHint}
|
|
69
70
|
|
|
70
71
|
If the client exposes resources but no ADS tools, this guide and the project status/public-barrel/guide resources provide the entry path. Use the returned local paths for scoped source inspection and project commands. Do not claim a resource-only connection offers ADS tool calls, native Skills activation or a rendered App. Configure/enable the tools in the client when required; project edits still use local editor/filesystem tools.
|
|
71
72
|
`;
|
package/dist/mcp/mutations.mjs
CHANGED
|
@@ -16,6 +16,7 @@ import { previewSourceRevision } from "../preview-inputs.mjs";
|
|
|
16
16
|
import { inspectScenarios } from "../scenarios.mjs";
|
|
17
17
|
import { checkUnitCandidate, checkUnitFiles, inspectUnits, validateUnitId } from "../units.mjs";
|
|
18
18
|
import { acceptance, failure as evidenceFailure } from "../evidence.mjs";
|
|
19
|
+
import { packageScriptCommand } from "../development-runtime.mjs";
|
|
19
20
|
|
|
20
21
|
export const mutationLimits = { units: 8, files: 32, patchBytes: 256 * 1024, patchFileBytes: 16 * 1024 * 1024, fileBytes: 16 * 1024 * 1024, readChars: 12000, snapshotFiles: 20000, snapshotBytes: 128 * 1024 * 1024 };
|
|
21
22
|
const digest = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
|
|
@@ -155,7 +156,7 @@ function checks(options) {
|
|
|
155
156
|
const scripts = options.config.mcp.mutationChecks ?? [pkg.scripts?.["lint:project"] ? "lint:project" : "lint", "typecheck", "build:mcp-previews"].filter(name => typeof pkg.scripts?.[name] === "string");
|
|
156
157
|
if (scripts.some(name => typeof pkg.scripts?.[name] !== "string")) throw fail("mutation-check", "Every configured mcp.mutationChecks script must exist in package.json.");
|
|
157
158
|
if (scripts.length && !["npm", "bun"].includes(context.packageManager)) throw fail("mutation-check", "Declare packageManager as npm or bun to run mutation checks.");
|
|
158
|
-
return scripts.map(script => (
|
|
159
|
+
return scripts.map(script => packageScriptCommand(context.packageManager, script));
|
|
159
160
|
}
|
|
160
161
|
|
|
161
162
|
export function createMutationController(directory, { captures = createCaptureController(directory) } = {}) {
|
|
@@ -297,7 +298,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
297
298
|
const brand = await generateBrandAssets(candidate);
|
|
298
299
|
verified.push({ name: "brand assets", passed: true, skipped: !!brand.skipped });
|
|
299
300
|
}
|
|
300
|
-
for (const check of extraChecks) verified.push(await checkCommand(check.command, check.args, candidate, signal, undefined, {category:"build",phase:`project-check:${check.args
|
|
301
|
+
for (const check of extraChecks) verified.push(await checkCommand(check.command, check.args, candidate, signal, undefined, {category:"build",phase:`project-check:${check.args.at(-1)}`}, candidateOptions.config.mcp.mutationCheckTimeoutMs));
|
|
301
302
|
boundary=evidenceFailure("runner","behavior-verification","ADS_BEHAVIOR_SETUP");
|
|
302
303
|
const behaviorUnits = affectedBehaviorUnits(candidateOptions, changes.map(change => change.path));
|
|
303
304
|
if (behaviorUnits.length) {
|
|
@@ -5,6 +5,7 @@ import path from "node:path";
|
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { buildFailure, inspectBuildStatus } from "./build-status.mjs";
|
|
7
7
|
import { previewSessionDirectories, withPreviewSession } from "../preview-scope.mjs";
|
|
8
|
+
import { developmentExecutable } from "../development-runtime.mjs";
|
|
8
9
|
|
|
9
10
|
function stamp(file) {
|
|
10
11
|
try { const stat = statSync(file); return `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`; }
|
|
@@ -64,7 +65,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
64
65
|
state = "running";
|
|
65
66
|
// No shell: configured arguments remain literal. Child stdin cannot consume
|
|
66
67
|
// the MCP channel, and both output streams go exclusively to diagnostics.
|
|
67
|
-
const executable = command.command
|
|
68
|
+
const executable = developmentExecutable(command.command);
|
|
68
69
|
const env = { ...process.env, ADS_MCP_BUILD_SESSION: session, ADS_MCP_BUILD_STATUS: reportFile, ADS_MCP_REQUEST_FILE: requestFile, PATH: [path.join(root, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) };
|
|
69
70
|
try {
|
|
70
71
|
child = spawn(executable, command.args, { cwd: root, env, shell: false, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -31,6 +31,7 @@ import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
|
|
|
31
31
|
import { compactProgress, resultBudgets } from "./result-pages.mjs";
|
|
32
32
|
import { createReportStore, bugReportSchema, featureRequestSchema } from "./reports.mjs";
|
|
33
33
|
import { createHash } from "node:crypto";
|
|
34
|
+
import { developmentRuntime } from "../development-runtime.mjs";
|
|
34
35
|
|
|
35
36
|
const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
|
|
36
37
|
class InvalidParamsError extends ProtocolError {
|
|
@@ -119,7 +120,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
119
120
|
|
|
120
121
|
function reportContext(submission) {
|
|
121
122
|
const captured = { ads: { package: pkg.name, version: pkg.version }, capturedAt: new Date().toISOString(), framework: null,
|
|
122
|
-
runtime: {
|
|
123
|
+
runtime: { ...developmentRuntime(), platform: process.platform, arch: process.arch }, warnings: [] };
|
|
123
124
|
try { const current=loadConfig(root);captured.framework=current.config.framework;captured.configurationRevision=createHash("sha256").update(JSON.stringify(current.config)).digest("hex");captured.sourceRevision=previewSourceRevision(current); }
|
|
124
125
|
catch { captured.warnings.push("Current configuration/source revision could not be captured."); }
|
|
125
126
|
try{const projectPackage=JSON.parse(readFileSync(path.join(root,"package.json"),"utf8"));if(typeof projectPackage.name==="string")captured.project={name:projectPackage.name.slice(0,160)};}catch{captured.warnings.push("Project package name could not be captured.");}
|
|
@@ -150,6 +151,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
150
151
|
return [
|
|
151
152
|
{ 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" },
|
|
152
153
|
{ uri: "ads://guides/behaviors", name: "Controller and behavioral verification guide", mimeType: "text/markdown" },
|
|
154
|
+
{ uri: "ads://guides/runtimes", name: "Node and Bun setup, compiler and verification runtime", mimeType: "text/markdown" },
|
|
153
155
|
{ uri: "ads://guides/evidence", name: "Failure boundaries and compact investigations", mimeType: "text/markdown" },
|
|
154
156
|
{ uri: "ads://guides/atomic-styles", name: "Atomic styles: composition conflicts and custom-property extraction", mimeType: "text/markdown" },
|
|
155
157
|
{ uri: "ads://guides/scenarios", name: "Scenario coverage and public class-helper contracts", mimeType: "text/markdown" },
|
|
@@ -201,6 +203,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
201
203
|
async function read(uri, signal) {
|
|
202
204
|
if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
|
|
203
205
|
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") }] };
|
|
206
|
+
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") }] };
|
|
204
207
|
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") }] };
|
|
205
208
|
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") }] };
|
|
206
209
|
if (uri === "ads://guides/reporting") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/reporting.md", import.meta.url), "utf8") }] };
|
|
@@ -138,7 +138,7 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
138
138
|
- omitted: host decides border`)}),q_=i.object({method:i.literal("ui/request-display-mode"),params:i.object({mode:Sa.describe("The display mode being requested.")})}),N_=i.object({mode:Sa.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),wR=i.union([i.literal("model"),i.literal("app")]).describe("Tool visibility scope - who can access the tool."),KT=i.object({resourceUri:i.string().optional(),visibility:i.array(wR).optional().describe(`Who can access this tool. Default: ["model", "app"]
|
|
139
139
|
- "model": Tool visible to and callable by the agent
|
|
140
140
|
- "app": Tool callable by the app from this server only`),csp:i.never().optional(),permissions:i.never().optional()}),GT=i.object({mimeTypes:i.array(i.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),xR=i.object({method:i.literal("ui/download-file"),params:i.object({contents:i.array(i.union([ht,mt])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),TR=i.object({method:i.literal("ui/message"),params:i.object({role:i.literal("user").describe('Message role, currently only "user" is supported.'),content:i.array(Ee).describe("Message content blocks (text, image, etc.).")})}),YT=i.object({method:i.literal("ui/notifications/sandbox-resource-ready"),params:i.object({html:i.string().describe("HTML content to load into the inner iframe."),sandbox:i.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Ef.optional().describe("CSP configuration from resource metadata."),permissions:kf.optional().describe("Sandbox permissions from resource metadata.")})}),QT=i.object({method:i.literal("ui/notifications/tool-result"),params:Ye.describe("Standard MCP tool execution result.")}),j_=i.object({toolInfo:i.object({id:Te.optional().describe("JSON-RPC id of the tools/call request."),tool:Ge.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:cR.optional().describe("Current color theme preference."),styles:_R.optional().describe("Style configuration for theming the app."),displayMode:Sa.optional().describe("How the UI is currently displayed."),availableDisplayModes:i.array(Sa).optional().describe("Display modes the host supports."),containerDimensions:i.union([i.object({height:i.number().describe("Fixed container height in pixels.")}),i.object({maxHeight:i.union([i.number(),i.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(i.union([i.object({width:i.number().describe("Fixed container width in pixels.")}),i.object({maxWidth:i.union([i.number(),i.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
141
|
-
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:i.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:i.string().optional().describe("User's timezone in IANA format."),userAgent:i.string().optional().describe("Host application identifier."),platform:i.union([i.literal("web"),i.literal("desktop"),i.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:i.object({touch:i.boolean().optional().describe("Whether the device supports touch input."),hover:i.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:i.object({top:i.number().describe("Top safe area inset in pixels."),right:i.number().describe("Right safe area inset in pixels."),bottom:i.number().describe("Bottom safe area inset in pixels."),left:i.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),XT=i.object({method:i.literal("ui/notifications/host-context-changed"),params:j_.describe("Partial context update containing only changed fields.")}),PR=i.object({method:i.literal("ui/update-model-context"),params:i.object({content:i.array(Ee).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:i.record(i.string(),i.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),ER=i.object({method:i.literal("ui/initialize"),params:i.object({appInfo:Pe.describe("App identification (name and version)."),appCapabilities:zR.describe("Features and capabilities this app provides."),protocolVersion:i.string().describe("Protocol version this app supports.")})}),kR=i.object({protocolVersion:i.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Pe.describe("Host application identification and version."),hostCapabilities:vR.describe("Features and capabilities provided by the host."),hostContext:j_.describe("Rich context about the host environment.")}).passthrough();var Ql=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,o){this.eventTarget=t,this.eventSource=o,this.messageListener=r=>{if(o&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let n=ct.safeParse(r.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,r):(console.error("Failed to parse message",n.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,o){t.method!==aR&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var $R=[A_],Xl=class extends ma{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Tf;_methods=new Pf;setRequestHandler=(...t)=>{let[o,...r]=O_("request",t)??t;this._methods.claim(o,"setRequestHandler"),super.setRequestHandler.call(this,o,...r)};setNotificationHandler=(...t)=>{let[o,...r]=O_("notification",t)??t;this._methods.claim(o,"setNotificationHandler"),super.setNotificationHandler.call(this,o,...r)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...o)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...o)};_wrapHandler(t,o){let r=super._wrapHandler(t,o);return t==="ui/initialize"||t==="ping"?r:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),r(n,s))}eventSchemas={sizechange:gR,sandboxready:fR,initialized:RR,requestteardown:yR,loggingmessage:bo};setEventHandler(t,o){this._ensureEventSlot(t),this._events.setHandler(t,o)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,o){this._ensureEventSlot(t),this._events.addEventListener(t,o)}removeEventListener(t,o){this._events.removeEventListener(t,o)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let o=this.eventSchemas[t];if(!o)throw Error(`Unknown event: ${String(t)}`);let r=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{r(n.params)}):this.setNotificationHandler(o.shape.method.value,{params:o.shape.params},n=>r(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,o,r){o&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,o,r,n){super(n),this._client=t,this._hostInfo=o,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:ER.shape.params,result:kR},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,a)=>(this.onping?.(s.params,a),{})),this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:TR.shape.params,result:mR},async(o,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(o,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:dR.shape.params,result:pR},async(o,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(o,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:xR.shape.params,result:hR},async(o,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(o,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},async(o,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(o,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:PR.shape.params,result:We},async(o,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(o,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(o,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(o,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(o.params,r)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(o,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(o.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(o,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(o.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(o,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(o.params,r)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(o,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(o.params,r)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let o=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:$R.includes(o)?o:A_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let o={},r=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],a=t[n];CR(s,a)||(o[n]=a,r=!0)}r&&(this._hostContext=t,this.sendHostContextChange(o))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,o){return this.request({method:"ui/resource-teardown",params:t},bR,o)}sendResourceTeardown=this.teardownResource;callTool(t,o){return this.request({method:"tools/call",params:t},o)}listTools(t,o){return this.request({method:"tools/list",params:t},o)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let o=this._client.getServerCapabilities();if(!o)throw Error("Client server capabilities not available");o.tools&&(this.oncalltool=async(r,n)=>this._client.request({method:"tools/call",params:r},{signal:n.mcpReq.signal}),o.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",r=>this.sendToolListChanged(r.params))),o.resources&&(this.onlistresources=async(r,n)=>this._client.request({method:"resources/list",params:r},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(r,n)=>this._client.request({method:"resources/templates/list",params:r},{signal:n.mcpReq.signal}),this.onreadresource=async(r,n)=>this._client.request({method:"resources/read",params:r},{signal:n.mcpReq.signal}),o.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",r=>this.sendResourceListChanged(r.params))),o.prompts&&(this.onlistprompts=async(r,n)=>this._client.request({method:"prompts/list",params:r},{signal:n.mcpReq.signal}),o.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",r=>this.sendPromptListChanged(r.params)))}return super.connect(t)}};function CR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function L_(e,t){let o=new DOMParser().parseFromString(e,"text/html"),r=o.createElement("meta");if(r.httpEquiv="Content-Security-Policy",r.content=t,o.head.prepend(r),!o.querySelector("base[href]")){let n=o.querySelector("base")??o.createElement("base");n.setAttribute("href","about:srcdoc"),r.after(n)}return"<!doctype html>"+o.documentElement.outerHTML}var $e=new Yl({name:"ADS preview",version:"1.0.0"},{},{autoResize:!0}),Wr=document.getElementById("ads-token-root"),Lt=document.getElementById("ads-widget-status"),tu=document.getElementById("ads-token-theme"),eu=document.getElementById("ads-scenario-root"),To,Me=0,U_="",Br=30,Z_=document.createElement("style");Wr&&document.head.append(Z_);function ou(e){e!=="light"&&e!=="dark"||(document.documentElement.dataset.theme=e,tu&&(tu.value=e),Wr&&To&&wo())}function Oe(e,t){let o=document.createElement(e);return o.textContent=t,o}function IR(e){let t=Oe("li","");t.dataset.token=e.name;let o=getComputedStyle(document.documentElement).getPropertyValue(e.name).trim(),r=Oe("details","");r.className="token-source";let n=Oe("summary","");n.title=`${e.name}: ${o||"Conditional or unset"}. Click to inspect source definitions.`;let s=Oe("code",e.name);s.className="token-name";let a=Oe("span",o||"Conditional or unset");n.append(s,a);let l=Oe("dl","");l.append(Oe("dt","Computed in preview"),Oe("dd",o||"Conditional or unset")),e.meaning&&l.append(Oe("dt","Meaning"),Oe("dd",e.meaning));for(let u of e.definitions)l.append(Oe("dt",u.scope),Oe("dd",`${u.value} \xB7 ${u.file}:${u.line}`));return r.append(n,l),t.append(r),t}function wo(){Z_.textContent=To.css;let e=To.tokens.filter(t=>`${t.name} ${t.type??""}`.toLowerCase().includes(U_.toLowerCase()));document.getElementById("ads-token-list").replaceChildren(...e.slice(Me,Me+Br).map(IR)),document.querySelector("footer").hidden=e.length<=Br,document.getElementById("ads-token-count").textContent=e.length?`${Me+1}\u2013${Math.min(Me+Br,e.length)} of ${e.length}`:"No matching tokens",document.getElementById("ads-token-prev").disabled=Me===0,document.getElementById("ads-token-next").disabled=Me+Br>=e.length,Lt.textContent=`${e.length} matching definitions \xB7 ${To.diagnostics.length} diagnostics`}Wr&&($e.ontoolinput=()=>{Me=0,To&&wo()},To=JSON.parse(document.getElementById("ads-token-seed").textContent),ou("light"),document.getElementById("ads-token-search").addEventListener("input",e=>{U_=e.target.value,Me=0,wo()}),tu.addEventListener("change",()=>ou(tu.value)),document.getElementById("ads-token-prev").addEventListener("click",()=>{Me=Math.max(0,Me-Br),wo()}),document.getElementById("ads-token-next").addEventListener("click",()=>{Me+=Br,wo()}),document.getElementById("ads-token-refresh").addEventListener("click",async()=>{try{let e=await $e.readServerResource({uri:"ads://project/tokens"});To=JSON.parse(e.contents.find(t=>"text"in t).text),Me=0,wo()}catch(e){Lt.textContent=`Refresh failed: ${e.message}`}}));var xo,$f,D_=!1,_a=0;async function H_(e){if($f=e,!D_||!eu)return;let t=e?.structuredContent?.scenario?.resourceUri;if(!t||!t.startsWith("ui://ads/previews/"))return;let o=++_a;Wr&&(Wr.hidden=!0,Lt=document.getElementById("ads-scenario-status")),eu.hidden=!1;try{if(!$e.getHostCapabilities()?.serverResources)throw new Error("This Apps host does not forward server resources. Use the project showcase URL from the tool result.");let n=(await $e.readServerResource({uri:t})).contents.find(u=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text=="string");if(!n)throw new Error("Scenario HTML is unavailable.");if(o!==_a)return;xo&&(await xo.close(),xo=void 0);let s=document.createElement("iframe");s.title=e.structuredContent.scenario.title,s.setAttribute("sandbox","allow-scripts allow-forms"),eu.replaceChildren(s);let a=new Xl(null,{name:"ADS scenario host",version:"1.0.0"},{serverResources:{},serverTools:{}},{hostContext:$e.getHostContext()});xo=a,a.onreadresource=u=>$e.readServerResource(u),a.oncalltool=u=>$e.callServerTool(u),a.onsizechange=({height:u})=>{u&&(s.height=String(Math.min(1e4,Math.max(120,u))))},a.oninitialized=async()=>{await a.sendToolInput({arguments:{}}),await a.sendToolResult(e),o===_a&&window.parent.postMessage({type:"ads-preview-ready"},"*")},await a.connect(new Ql(s.contentWindow,s.contentWindow));let l="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; worker-src blob: data:; connect-src 'none'; base-uri about:; object-src 'none'; form-action 'none'";s.srcdoc=L_(n.text,l),Lt.hidden=!0}catch(r){o===_a&&(Lt.hidden=!1,Lt.textContent=r.message,window.parent.postMessage({type:"ads-preview-ready"},"*"))}}eu&&($e.ontoolresult=e=>{H_(e)},$e.onteardown=async()=>{++_a;let e=xo;xo=void 0;try{await e?.teardownResource({},{timeout:500})}catch{}return await e?.close(),{}});$e.onhostcontextchanged=e=>{ou(e.theme),xo?.setHostContext(e)};try{await $e.connect(),D_=!0,$f&&H_($f),ou($e.getHostContext()?.theme),Wr&&(document.getElementById("ads-token-refresh").disabled=!$e.getHostCapabilities()?.serverResources,wo())}catch{Lt&&(Lt.textContent="Apps bridge unavailable. Samples remain usable; inspect project data through ADS tools/resources.")}
|
|
141
|
+
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:i.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:i.string().optional().describe("User's timezone in IANA format."),userAgent:i.string().optional().describe("Host application identifier."),platform:i.union([i.literal("web"),i.literal("desktop"),i.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:i.object({touch:i.boolean().optional().describe("Whether the device supports touch input."),hover:i.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:i.object({top:i.number().describe("Top safe area inset in pixels."),right:i.number().describe("Right safe area inset in pixels."),bottom:i.number().describe("Bottom safe area inset in pixels."),left:i.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),XT=i.object({method:i.literal("ui/notifications/host-context-changed"),params:j_.describe("Partial context update containing only changed fields.")}),PR=i.object({method:i.literal("ui/update-model-context"),params:i.object({content:i.array(Ee).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:i.record(i.string(),i.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),ER=i.object({method:i.literal("ui/initialize"),params:i.object({appInfo:Pe.describe("App identification (name and version)."),appCapabilities:zR.describe("Features and capabilities this app provides."),protocolVersion:i.string().describe("Protocol version this app supports.")})}),kR=i.object({protocolVersion:i.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Pe.describe("Host application identification and version."),hostCapabilities:vR.describe("Features and capabilities provided by the host."),hostContext:j_.describe("Rich context about the host environment.")}).passthrough();var Ql=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,o){this.eventTarget=t,this.eventSource=o,this.messageListener=r=>{if(o&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let n=ct.safeParse(r.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,r):(console.error("Failed to parse message",n.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,o){t.method!==aR&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var $R=[A_],Xl=class extends ma{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Tf;_methods=new Pf;setRequestHandler=(...t)=>{let[o,...r]=O_("request",t)??t;this._methods.claim(o,"setRequestHandler"),super.setRequestHandler.call(this,o,...r)};setNotificationHandler=(...t)=>{let[o,...r]=O_("notification",t)??t;this._methods.claim(o,"setNotificationHandler"),super.setNotificationHandler.call(this,o,...r)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...o)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...o)};_wrapHandler(t,o){let r=super._wrapHandler(t,o);return t==="ui/initialize"||t==="ping"?r:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),r(n,s))}eventSchemas={sizechange:gR,sandboxready:fR,initialized:RR,requestteardown:yR,loggingmessage:bo};setEventHandler(t,o){this._ensureEventSlot(t),this._events.setHandler(t,o)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,o){this._ensureEventSlot(t),this._events.addEventListener(t,o)}removeEventListener(t,o){this._events.removeEventListener(t,o)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let o=this.eventSchemas[t];if(!o)throw Error(`Unknown event: ${String(t)}`);let r=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{r(n.params)}):this.setNotificationHandler(o.shape.method.value,{params:o.shape.params},n=>r(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,o,r){o&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,o,r,n){super(n),this._client=t,this._hostInfo=o,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:ER.shape.params,result:kR},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,a)=>(this.onping?.(s.params,a),{})),this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:TR.shape.params,result:mR},async(o,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(o,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:dR.shape.params,result:pR},async(o,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(o,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:xR.shape.params,result:hR},async(o,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(o,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},async(o,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(o,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:PR.shape.params,result:We},async(o,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(o,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(o,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(o,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(o.params,r)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(o,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(o.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(o,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(o.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(o,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(o.params,r)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(o,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(o.params,r)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let o=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:$R.includes(o)?o:A_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let o={},r=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],a=t[n];CR(s,a)||(o[n]=a,r=!0)}r&&(this._hostContext=t,this.sendHostContextChange(o))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,o){return this.request({method:"ui/resource-teardown",params:t},bR,o)}sendResourceTeardown=this.teardownResource;callTool(t,o){return this.request({method:"tools/call",params:t},o)}listTools(t,o){return this.request({method:"tools/list",params:t},o)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let o=this._client.getServerCapabilities();if(!o)throw Error("Client server capabilities not available");o.tools&&(this.oncalltool=async(r,n)=>this._client.request({method:"tools/call",params:r},{signal:n.mcpReq.signal}),o.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",r=>this.sendToolListChanged(r.params))),o.resources&&(this.onlistresources=async(r,n)=>this._client.request({method:"resources/list",params:r},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(r,n)=>this._client.request({method:"resources/templates/list",params:r},{signal:n.mcpReq.signal}),this.onreadresource=async(r,n)=>this._client.request({method:"resources/read",params:r},{signal:n.mcpReq.signal}),o.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",r=>this.sendResourceListChanged(r.params))),o.prompts&&(this.onlistprompts=async(r,n)=>this._client.request({method:"prompts/list",params:r},{signal:n.mcpReq.signal}),o.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",r=>this.sendPromptListChanged(r.params)))}return super.connect(t)}};function CR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function L_(e,t){let o=new DOMParser().parseFromString(e,"text/html"),r=o.createElement("meta");if(r.httpEquiv="Content-Security-Policy",r.content=t,o.head.prepend(r),!o.querySelector("base[href]")){let n=o.querySelector("base")??o.createElement("base");n.setAttribute("href","about:srcdoc"),r.after(n)}return"<!doctype html>"+o.documentElement.outerHTML}var $e=new Yl({name:"ADS preview",version:"1.0.0"},{},{autoResize:!0}),Wr=document.getElementById("ads-token-root"),Lt=document.getElementById("ads-widget-status"),tu=document.getElementById("ads-token-theme"),eu=document.getElementById("ads-scenario-root"),To,Me=0,U_="",Br=30,Z_=document.createElement("style");Wr&&document.head.append(Z_);function ou(e){e!=="light"&&e!=="dark"||(document.documentElement.dataset.theme=e,tu&&(tu.value=e),Wr&&To&&wo())}function Oe(e,t){let o=document.createElement(e);return o.textContent=t,o}function IR(e){let t=Oe("li","");t.dataset.token=e.name;let o=getComputedStyle(document.documentElement).getPropertyValue(e.name).trim(),r=Oe("details","");r.className="token-source";let n=Oe("summary","");n.title=`${e.name}: ${o||"Conditional or unset"}. Click to inspect source definitions.`;let s=Oe("code",e.name);s.className="token-name";let a=Oe("span",o||"Conditional or unset");n.append(s,a);let l=Oe("dl","");l.append(Oe("dt","Computed in preview"),Oe("dd",o||"Conditional or unset")),e.meaning&&l.append(Oe("dt","Meaning"),Oe("dd",e.meaning));for(let u of e.definitions)l.append(Oe("dt",u.scope),Oe("dd",`${u.value} \xB7 ${u.file}:${u.line}`));return r.append(n,l),t.append(r),t}function wo(){Z_.textContent=To.css;let e=To.tokens.filter(t=>`${t.name} ${t.type??""}`.toLowerCase().includes(U_.toLowerCase()));document.getElementById("ads-token-list").replaceChildren(...e.slice(Me,Me+Br).map(IR)),document.querySelector("footer").hidden=e.length<=Br,document.getElementById("ads-token-count").textContent=e.length?`${Me+1}\u2013${Math.min(Me+Br,e.length)} of ${e.length}`:"No matching tokens",document.getElementById("ads-token-prev").disabled=Me===0,document.getElementById("ads-token-next").disabled=Me+Br>=e.length,Lt.textContent=`${e.length} matching definitions \xB7 ${To.diagnostics.length} diagnostics`}Wr&&($e.ontoolinput=()=>{Me=0,To&&wo()},To=JSON.parse(document.getElementById("ads-token-seed").textContent),ou("light"),document.getElementById("ads-token-search").addEventListener("input",e=>{U_=e.target.value,Me=0,wo()}),tu.addEventListener("change",()=>ou(tu.value)),document.getElementById("ads-token-prev").addEventListener("click",()=>{Me=Math.max(0,Me-Br),wo()}),document.getElementById("ads-token-next").addEventListener("click",()=>{Me+=Br,wo()}),document.getElementById("ads-token-refresh").addEventListener("click",async()=>{try{let e=await $e.readServerResource({uri:"ads://project/tokens"});To=JSON.parse(e.contents.find(t=>"text"in t).text),Me=0,wo()}catch(e){Lt.textContent=`Refresh failed: ${e.message}`}}));var xo,$f,D_=!1,_a=0;async function H_(e){if($f=e,!D_||!eu)return;let t=e?.structuredContent?.scenario?.resourceUri;if(!t||!t.startsWith("ui://ads/previews/"))return;let o=++_a;Wr&&(Wr.hidden=!0,Lt=document.getElementById("ads-scenario-status")),eu.hidden=!1;try{if(!$e.getHostCapabilities()?.serverResources)throw new Error("This Apps host does not forward server resources. Use the project showcase URL from the tool result.");let n=(await $e.readServerResource({uri:t})).contents.find(u=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text=="string");if(!n)throw new Error("Scenario HTML is unavailable.");if(o!==_a)return;xo&&(await xo.close(),xo=void 0);let s=document.createElement("iframe");s.title=e.structuredContent.scenario.title,s.setAttribute("sandbox","allow-scripts allow-forms"),eu.replaceChildren(s);let a=new Xl(null,{name:"ADS scenario host",version:"1.0.0"},{serverResources:{},serverTools:{}},{hostContext:$e.getHostContext()});xo=a,a.onreadresource=u=>$e.readServerResource(u),a.oncalltool=u=>$e.callServerTool(u),a.onsizechange=({height:u})=>{u&&(s.height=String(Math.min(1e4,Math.max(120,u))))},a.oninitialized=async()=>{await a.sendToolInput({arguments:{}}),await a.sendToolResult(e),o===_a&&window.parent.postMessage({type:"ads-preview-ready"},"*")},await a.connect(new Ql(s.contentWindow,s.contentWindow));let l="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; worker-src blob: data:; connect-src blob:; base-uri about:; object-src 'none'; form-action 'none'";s.srcdoc=L_(n.text,l),Lt.hidden=!0}catch(r){o===_a&&(Lt.hidden=!1,Lt.textContent=r.message,window.parent.postMessage({type:"ads-preview-ready"},"*"))}}eu&&($e.ontoolresult=e=>{H_(e)},$e.onteardown=async()=>{++_a;let e=xo;xo=void 0;try{await e?.teardownResource({},{timeout:500})}catch{}return await e?.close(),{}});$e.onhostcontextchanged=e=>{ou(e.theme),xo?.setHostContext(e)};try{await $e.connect(),D_=!0,$f&&H_($f),ou($e.getHostContext()?.theme),Wr&&(document.getElementById("ads-token-refresh").disabled=!$e.getHostCapabilities()?.serverResources,wo())}catch{Lt&&(Lt.textContent="Apps bridge unavailable. Samples remain usable; inspect project data through ADS tools/resources.")}
|
|
142
142
|
/*! Bundled license information:
|
|
143
143
|
|
|
144
144
|
@modelcontextprotocol/client/dist/src-WCy6ifGf.mjs:
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { readdirSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { isInside } from "./config.mjs";
|
|
4
|
+
|
|
5
|
+
const metadata = new Set(["node_modules", ".git", ".ds", ".vite", "coverage"]);
|
|
6
|
+
const generated = new Set(["dist", "build", "target", "out", ".next", ".nuxt", ".svelte-kit", ".turbo"]);
|
|
7
|
+
|
|
8
|
+
/** Shared watch/fingerprint policy. Explicit source roots take priority over default outputs. */
|
|
9
|
+
export function previewFileIgnored({root, config}, file) {
|
|
10
|
+
const absolute = path.resolve(file), relative = path.relative(root, absolute);
|
|
11
|
+
if (relative.split(path.sep).some(name => metadata.has(name))) return true;
|
|
12
|
+
if (config.assets.generatedPaths.some(base => isInside(path.resolve(root, base), absolute))) return true;
|
|
13
|
+
const sources = [config.dsDir, config.sourceDir].map(base => path.resolve(root, base));
|
|
14
|
+
for (const name of relative.split(path.sep)) {
|
|
15
|
+
if (!generated.has(name)) continue;
|
|
16
|
+
if (!sources.some(source => isInside(source, absolute) || isInside(absolute, source))) return true;
|
|
17
|
+
}
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Allocate individual watches so excluded descendants never consume OS watches. */
|
|
22
|
+
export function previewWatchDirectories(options) {
|
|
23
|
+
const directories = [];
|
|
24
|
+
function visit(directory) {
|
|
25
|
+
directories.push(directory);
|
|
26
|
+
for (const entry of readdirSync(directory, {withFileTypes:true})) {
|
|
27
|
+
const child = path.join(directory, entry.name);
|
|
28
|
+
if (entry.isDirectory() && !entry.isSymbolicLink() && !previewFileIgnored(options, child)) visit(child);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
visit(options.root);
|
|
32
|
+
return directories;
|
|
33
|
+
}
|
package/dist/preview-inputs.mjs
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { previewFileIgnored } from "./preview-files.mjs";
|
|
5
5
|
|
|
6
6
|
/** Shared source evidence for compilation, watch recovery and status reads. */
|
|
7
|
-
export function previewSourceRevision(
|
|
8
|
-
const
|
|
7
|
+
export function previewSourceRevision(options, apps = options.config.mcp.apps ?? []) {
|
|
8
|
+
const {root} = options;
|
|
9
|
+
const rows = [];
|
|
9
10
|
const outputs = new Set(apps.map(app => path.resolve(root,app.file)));
|
|
10
11
|
function digest(file) { return createHash("sha256").update(readFileSync(file)).digest("hex"); }
|
|
11
12
|
function visit(directory) {
|
|
12
13
|
for (const entry of readdirSync(directory,{withFileTypes:true})) {
|
|
13
|
-
if (entry.isSymbolicLink()
|
|
14
|
+
if (entry.isSymbolicLink()) continue;
|
|
14
15
|
const file = path.join(directory,entry.name);
|
|
15
|
-
if (outputs.has(file) ||
|
|
16
|
+
if (outputs.has(file) || previewFileIgnored(options,file)) continue;
|
|
16
17
|
if (entry.isDirectory()) visit(file);
|
|
17
18
|
else if (entry.isFile() && /\.(?:[cm]?[jt]sx?|css|html|json|md|svg|png|jpe?g|webp|gif|woff2?|ttf|otf|lock|lockb)$/.test(file)) rows.push([path.relative(root,file),digest(file)]);
|
|
18
19
|
}
|
|
@@ -7,6 +7,7 @@ import { artifactDigest, createBuildReporter } from "./mcp/build-status.mjs";
|
|
|
7
7
|
import { cachedPreviewPublication, previewArtifactHtml, readPreviewManifest } from "./preview-resources.mjs";
|
|
8
8
|
import { previewArtifactPath, withPreviewSession } from "./preview-scope.mjs";
|
|
9
9
|
import { previewSourceRevision } from "./preview-inputs.mjs";
|
|
10
|
+
import { previewFileIgnored, previewWatchDirectories } from "./preview-files.mjs";
|
|
10
11
|
|
|
11
12
|
const digest = value => createHash("sha256").update(value).digest("hex");
|
|
12
13
|
const fileDigest = file => { try { return digest(readFileSync(file)); } catch { return null; } };
|
|
@@ -15,7 +16,7 @@ const fileDigest = file => { try { return digest(readFileSync(file)); } catch {
|
|
|
15
16
|
* Cache state is development output, never proof that a failed build is current. */
|
|
16
17
|
export function createPreviewCache(options, compilerFiles = []) {
|
|
17
18
|
const { root } = options;
|
|
18
|
-
const adapterFiles = [import.meta.filename, ...["preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
|
|
19
|
+
const adapterFiles = [import.meta.filename, ...["preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
|
|
19
20
|
...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "node_modules/.package-lock.json"].map(file => path.join(root, file))];
|
|
20
21
|
const adapterDigest = () => digest(JSON.stringify(adapterFiles.map(file => [file, fileDigest(file)])));
|
|
21
22
|
const loadedAdapter = adapterDigest();
|
|
@@ -273,7 +274,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
273
274
|
function sourceChanged(_event, file, topology = false) {
|
|
274
275
|
if (!file || !topology && !/\.(?:[cm]?[jt]sx?|css|html|json|md|svg|png|jpe?g|webp|gif|woff2?|ttf|otf|lock|lockb)$/.test(file)) return;
|
|
275
276
|
const absolute = path.join(root, file);
|
|
276
|
-
if (
|
|
277
|
+
if (previewFileIgnored(options, absolute)) return;
|
|
277
278
|
changed.add(absolute);
|
|
278
279
|
clearTimeout(timer);
|
|
279
280
|
timer = setTimeout(() => {
|
|
@@ -324,12 +325,11 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
324
325
|
try {
|
|
325
326
|
addWatch(root, sourceChanged);
|
|
326
327
|
const wanted = new Set([root, path.join(root, ".ds")]);
|
|
327
|
-
for (const
|
|
328
|
-
|
|
329
|
-
if (!entry.isDirectory() || entry.isSymbolicLink() || ["node_modules", ".git", ".ds", ".vite", "coverage"].includes(entry.name)
|
|
330
|
-
|| options.config.assets.generatedPaths.some(base => isInside(path.resolve(root, base), directory))) continue;
|
|
328
|
+
for (const directory of previewWatchDirectories(options)) {
|
|
329
|
+
if (directory === root) continue;
|
|
331
330
|
wanted.add(directory);
|
|
332
|
-
|
|
331
|
+
const relative = path.relative(root, directory);
|
|
332
|
+
if (addWatch(directory, (event, file) => sourceChanged(event, file && path.join(relative, file))) && !initial) sourceChanged("rename", relative, true);
|
|
333
333
|
}
|
|
334
334
|
mkdirSync(path.join(root, ".ds"), { recursive: true });
|
|
335
335
|
addWatch(path.join(root, ".ds"), (_event, file) => { if (file === path.basename(process.env.ADS_MCP_REQUEST_FILE ?? "")) request(); });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function c(e,t){let
|
|
1
|
+
function c(e,t){let n=new DOMParser().parseFromString(e,"text/html"),s=n.createElement("meta");if(s.httpEquiv="Content-Security-Policy",s.content=t,n.head.prepend(s),!n.querySelector("base[href]")){let i=n.querySelector("base")??n.createElement("base");i.setAttribute("href","about:srcdoc"),s.after(i)}return"<!doctype html>"+n.documentElement.outerHTML}var a=new URL(location.href).searchParams.get("parent"),o;function r(e=[]){return e.filter(t=>/^(?:https?:\/\/[a-z0-9.*:[\]-]+(?::\d+)?|data:|blob:|about:)$/i.test(t)).join(" ")}function d(e={}){let t=r(e.resourceDomains);return`default-src 'none';script-src 'unsafe-inline' 'wasm-unsafe-eval' ${t};style-src 'unsafe-inline' ${t};img-src data: ${t};font-src ${t||"'none'"};media-src ${t||"'none'"};worker-src ${t||"'none'"};connect-src ${r(e.connectDomains)||"'none'"};frame-src ${r(e.frameDomains)||"'none'"};base-uri about: ${r(e.baseUriDomains)};object-src 'none';form-action 'none'`}window.addEventListener("message",e=>{if(e.source===parent&&e.origin===a){let t=e.data;if(t?.method==="ui/notifications/sandbox-resource-ready"){let{html:n,csp:s}=t.params??{};if(typeof n!="string")return;o?.remove(),o=window.document.createElement("iframe"),o.title="Design-system App",o.setAttribute("sandbox","allow-scripts allow-forms"),window.document.body.append(o),o.srcdoc=c(n,d(s))}else t?.jsonrpc==="2.0"&&!t.method?.startsWith("ui/notifications/sandbox-")&&o?.contentWindow.postMessage(t,"*")}else e.source===o?.contentWindow&&e.data?.jsonrpc==="2.0"&&!e.data.method?.startsWith("ui/notifications/sandbox-")&&parent.postMessage(e.data,a)});parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-ready",params:{}},a);
|