@reqvire-org/ads 0.3.47 → 0.3.49
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/browser-audit/worker.mjs +8 -2
- package/dist/browser-audit.mjs +33 -3
- package/dist/finding-rules.mjs +2 -0
- package/dist/mcp/context.mjs +1 -1
- package/dist/mcp/mutations.mjs +23 -0
- package/dist/mcp/server.mjs +4 -4
- package/dist/palette-generated.mjs +6 -3
- package/dist/showcase/client.bundle.js +1 -1
- package/dist/showcase/icons.js +1 -1
- package/dist/showcase/style.css +1 -1
- package/dist/skills/ads-break-ui/references/design-data.md +8 -1
- package/dist/skills/ads-break-ui/references/drafts.md +3 -1
- package/dist/skills/ads-break-ui/references/guarded-editing.md +3 -2
- package/dist/skills/ads-break-ui/references/validation.md +6 -1
- package/dist/skills/ads-designer/references/accessibility.md +4 -2
- package/dist/skills/ads-designer/references/design-data.md +8 -1
- package/dist/skills/ads-designer/references/drafts.md +3 -1
- package/dist/skills/ads-designer/references/guarded-editing.md +3 -2
- package/dist/skills/ads-designer/references/validation.md +6 -1
- package/dist/skills/ads-import/references/design-data.md +8 -1
- package/dist/skills/ads-import/references/drafts.md +3 -1
- package/dist/skills/ads-import/references/guarded-editing.md +3 -2
- package/dist/skills/ads-import/references/validation.md +6 -1
- package/dist/skills/ads-motion/references/design-data.md +8 -1
- package/dist/skills/ads-motion/references/drafts.md +3 -1
- package/dist/skills/ads-motion/references/guarded-editing.md +3 -2
- package/dist/skills/ads-motion/references/validation.md +6 -1
- package/dist/skills/ads-port/references/design-data.md +8 -1
- package/dist/skills/ads-port/references/drafts.md +3 -1
- package/dist/skills/ads-port/references/guarded-editing.md +3 -2
- package/dist/skills/ads-port/references/validation.md +6 -1
- package/dist/token-quality.mjs +49 -22
- package/dist/validation.mjs +3 -4
- package/dist/verification.mjs +25 -4
- package/docs/CHANGELOG.md +51 -12
- package/docs/GUIDE.md +6 -2
- package/docs/MCP.md +15 -5
- package/package.json +1 -1
|
@@ -16,7 +16,13 @@ try {
|
|
|
16
16
|
// The audit injects its own script; bypassCSP keeps project CSP from blocking it.
|
|
17
17
|
const context = await browser.newContext({ viewport: request.viewport, deviceScaleFactor: 1, colorScheme: apps[0].scheme, bypassCSP: true, reducedMotion: "reduce" });
|
|
18
18
|
try {
|
|
19
|
-
|
|
19
|
+
// A bounded number of pages render at once; results keep request order.
|
|
20
|
+
const results = [];
|
|
21
|
+
let next = 0;
|
|
22
|
+
async function lane() { while (next < apps.length) { const index = next++; results[index] = await audit(apps[index]); } }
|
|
23
|
+
await Promise.all(Array.from({ length: Math.min(apps.length, request.concurrency ?? 1) }, lane));
|
|
24
|
+
runs.push(...results);
|
|
25
|
+
async function audit(app) {
|
|
20
26
|
const page = await context.newPage();
|
|
21
27
|
try {
|
|
22
28
|
const frame = await openPreviewScenario(page, app.url, app.scenario, { timeout });
|
|
@@ -36,7 +42,7 @@ try {
|
|
|
36
42
|
nodes: violation.nodes.slice(0, nodeLimit).map(node => ({ selector: clip(node.target.flat().join(" "), 300), html: clip(node.html, 200), summary: clip(node.failureSummary, 500) })) })), incomplete: outcome.incomplete.length };
|
|
37
43
|
}, { tags: request.tags, nodeLimit: request.nodeLimit });
|
|
38
44
|
if (await frame.locator("html").getAttribute("data-ads-preview-state") !== "ready") throw new Error(`Scenario ${app.scenario} stopped being ready during the audit.`);
|
|
39
|
-
|
|
45
|
+
return { scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), ...result };
|
|
40
46
|
} finally { await page.close(); }
|
|
41
47
|
}
|
|
42
48
|
} finally { await context.close(); }
|
package/dist/browser-audit.mjs
CHANGED
|
@@ -6,7 +6,10 @@ import { fileURLToPath } from "node:url";
|
|
|
6
6
|
import { loadConfig } from "./config.mjs";
|
|
7
7
|
import { discoverScenarioRegistry } from "./scenario-registry.mjs";
|
|
8
8
|
import { executeDevelopmentCommand } from "./verification.mjs";
|
|
9
|
-
import { findingSeverity } from "./finding-rules.mjs";
|
|
9
|
+
import { findingSeverity, routeFindings } from "./finding-rules.mjs";
|
|
10
|
+
import { inspectScenarios } from "./scenarios.mjs";
|
|
11
|
+
import { inspectUnits } from "./units.mjs";
|
|
12
|
+
import { affectedScenarios } from "./verification.mjs";
|
|
10
13
|
|
|
11
14
|
// Browser accessibility audit: axe-core (Deque, MPL-2.0, an unmodified ADS dependency
|
|
12
15
|
// injected at run time, never bundled) runs inside each rendered scenario document, once per
|
|
@@ -19,7 +22,7 @@ export const AUDIT_RULE = "a11y-axe";
|
|
|
19
22
|
export const auditTags = Object.freeze(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]);
|
|
20
23
|
const viewport = { width: 1280, height: 800 };
|
|
21
24
|
export const auditedKinds = Object.freeze(["components", "patterns", "composition"]);
|
|
22
|
-
const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024 };
|
|
25
|
+
const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024, pages: 4 };
|
|
23
26
|
|
|
24
27
|
/** WCAG success criteria named by axe tags such as wcag143 or wcag1412. */
|
|
25
28
|
export function wcagCriteria(tags) {
|
|
@@ -49,6 +52,33 @@ export function auditFindings(runs, scenarios) {
|
|
|
49
52
|
});
|
|
50
53
|
}
|
|
51
54
|
|
|
55
|
+
/**
|
|
56
|
+
* UI scenarios a candidate change can affect, for acceptance audits. Changes to configuration,
|
|
57
|
+
* foundation, tokens, assets or files outside every unit affect all rendering and select every UI
|
|
58
|
+
* scenario; so does a failure to trace imports. Public/review entry re-exports are bookkeeping
|
|
59
|
+
* for their own units and do not widen the selection.
|
|
60
|
+
*/
|
|
61
|
+
export function auditScenarioSelection(options, changedFiles) {
|
|
62
|
+
const scenarios = inspectScenarios(options).scenarios.filter(scenario => auditedKinds.includes(scenario.kind));
|
|
63
|
+
const all = reason => ({ mode: "all", reason, scenarios: scenarios.map(scenario => scenario.id) });
|
|
64
|
+
const inventory = inspectUnits(options), entries = [inventory.publicEntry, inventory.reviewEntry];
|
|
65
|
+
const traced = changedFiles.filter(file => !entries.includes(inventory.relative(file)));
|
|
66
|
+
const shared = traced.find(file => {
|
|
67
|
+
const owner = inventory.owner(inventory.relative(file));
|
|
68
|
+
return [null, "configuration", "foundation", "tokens"].includes(owner) || owner.startsWith("assets") || !inventory.units.some(unit => unit.id === owner);
|
|
69
|
+
});
|
|
70
|
+
if (shared) return all(`${shared} is shared configuration, foundation, token, asset or unowned input.`);
|
|
71
|
+
try { return { mode: "affected", scenarios: affectedScenarios(options, traced, scenarios) }; }
|
|
72
|
+
catch (error) { return all(`Affected scenario selection failed: ${error.message}`); }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Policy check entry and routed findings for one audit result. */
|
|
76
|
+
export function auditCheck(audit, extra = {}) {
|
|
77
|
+
const routed = routeFindings([], audit.findings);
|
|
78
|
+
return { routed, check: { name: "browser-accessibility-audit", passed: !routed.diagnostics.length, engine: audit.engine, scenarios: audit.scenarios, themes: audit.themes, ...(audit.brands ? { brands: audit.brands } : {}),
|
|
79
|
+
renders: audit.runs, errors: routed.diagnostics.length, reviews: routed.advisories.length, elapsedMs: audit.elapsedMs, ...extra } };
|
|
80
|
+
}
|
|
81
|
+
|
|
52
82
|
function projectPlaywright(root) {
|
|
53
83
|
const require = createRequire(path.join(root, "package.json"));
|
|
54
84
|
for (const name of ["@playwright/test", "playwright"]) { try { return require.resolve(name); } catch { /* Try the other supported project-installed entry. */ } }
|
|
@@ -99,7 +129,7 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
|
|
|
99
129
|
})));
|
|
100
130
|
const settings = { browser: "chromium", timeoutMs: 60000, ...options.config.mcp.capture };
|
|
101
131
|
const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
|
|
102
|
-
writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, tags: auditTags, nodeLimit: limits.nodes, apps, output: temporary }));
|
|
132
|
+
writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, tags: auditTags, nodeLimit: limits.nodes, concurrency: limits.pages, apps, output: temporary }));
|
|
103
133
|
onProgress?.({ stage: "browser-audit", message: `Accessibility audit: ${apps.length} renders (${scenarios.length} scenarios × ${themes.length} themes${brands.length ? ` × ${brands.length} brands` : ""}).`, elapsedMs: Date.now() - startedAt });
|
|
104
134
|
const timeoutMs = Math.min(30 * 60 * 1000, settings.timeoutMs + apps.length * Math.min(settings.timeoutMs, 15000));
|
|
105
135
|
const run = await executeDevelopmentCommand({ command: "runtime", timeoutMs, label: "Accessibility audit" }, [fileURLToPath(new URL("./browser-audit/worker.mjs", import.meta.url)), request], root, {}, signal);
|
package/dist/finding-rules.mjs
CHANGED
|
@@ -27,6 +27,8 @@ export const findingRules = Object.freeze({
|
|
|
27
27
|
// light-dark() picks by color scheme, so it cannot tell two themes of one scheme apart.
|
|
28
28
|
"theme-light-dark": "error",
|
|
29
29
|
"token-contrast": "error", "token-rhythm": "error",
|
|
30
|
+
// A contrast pair color ADS cannot resolve statically (currentColor, relative color syntax).
|
|
31
|
+
"token-contrast-unresolved": "info",
|
|
30
32
|
// Equal values do not prove equal purpose.
|
|
31
33
|
"token-overlap-review": "review",
|
|
32
34
|
});
|
package/dist/mcp/context.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { developmentRuntime, packageScriptCommand } from "../development-runtime
|
|
|
6
6
|
|
|
7
7
|
export const GUIDE_URI = "ads://project/guide";
|
|
8
8
|
// Put the task triggers and entry path first: some hosts shorten server guidance.
|
|
9
|
-
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. Choose direct source editing or MCP-only editing using ads://guides/workflows, based on actual editor access and user preference, not mutations.enabled. With direct code access, edit owned files normally and use MCP for preview/checks; ordinary direct edits do not require drafts or ads_accept. MCP-only iterative design uses enabled draft tools, rendered review and exact-revision ads_accept; read ads://guides/drafts. Complete tracked proposals by accepting required drafts; accept dependencies first and review dependents again. Without a source editor or enabled mutation tools, inspection is available but editing is not. Low-level MCP repairs can use ads_units and guarded ads_apply_patch for one owner or ads_apply_transaction for coupled owners. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. For direct edits, use ads_validate with policy acceptance to enforce the project acceptance policy without applying source. Draft acceptance
|
|
9
|
+
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. Choose direct source editing or MCP-only editing using ads://guides/workflows, based on actual editor access and user preference, not mutations.enabled. With direct code access, edit owned files normally and use MCP for preview/checks; ordinary direct edits do not require drafts or ads_accept. MCP-only iterative design uses enabled draft tools, rendered review and exact-revision ads_accept; read ads://guides/drafts. Complete tracked proposals by accepting required drafts; accept dependencies first and review dependents again. Without a source editor or enabled mutation tools, inspection is available but editing is not. Low-level MCP repairs can use ads_units and guarded ads_apply_patch for one owner or ads_apply_transaction for coupled owners. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. For direct edits, use ads_validate with policy acceptance to enforce the project acceptance policy without applying source. Draft acceptance and guarded patches use the same configured policy on their candidate, including the axe-core audit of affected UI scenarios when acceptance.browserAudit is true; draft edit/show runs neither policy. Test registration alone does not gate acceptance. Use ads_validate with scope changed during editing, and the default full validation policy/scope after test/ownership/config migrations, before releases, or for explicit complete audits. Read ads://guides/validation; report actual scope/revision and inspect failures through ads_results. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. After targeted investigation, record suspected ADS defects with ads_report_bug or missing capabilities with ads_request_feature; read ads://guides/reporting. These are local untriaged reports, not established causes or upstream issues. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
|
|
10
10
|
|
|
11
11
|
function manager(root, pkg) {
|
|
12
12
|
if (typeof pkg.packageManager === "string") return pkg.packageManager.split("@")[0];
|
package/dist/mcp/mutations.mjs
CHANGED
|
@@ -309,6 +309,11 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
309
309
|
verified.push(await checkCommand(check.command, check.args, candidate, signal, undefined, {category:"build",phase:`project-check:${check.args.at(-1)}`}, candidateOptions.config.mcp.mutationCheckTimeoutMs));
|
|
310
310
|
}
|
|
311
311
|
const behaviorUnits = candidateOptions.config.acceptance.behaviorChecks ? affectedBehaviorUnits(candidateOptions, changes.map(change => change.path)) : [];
|
|
312
|
+
// acceptance.browserAudit: axe-core audits the candidate's affected UI scenarios before any source is written.
|
|
313
|
+
// It reuses the candidate preview host built for behavior checks/captures; on its own it starts a
|
|
314
|
+
// candidate host that compiles only the selected scenarios.
|
|
315
|
+
const audit = candidateOptions.config.acceptance.browserAudit ? await import("../browser-audit.mjs") : null;
|
|
316
|
+
const auditSelection = audit?.auditScenarioSelection(candidateOptions, changes.map(change => change.path));
|
|
312
317
|
if ((behaviorUnits.length || screenshot) && candidateOptions.config.mcp.previewManifest && candidateOptions.config.mcp.previewWatch) {
|
|
313
318
|
boundary=evidenceFailure("build","preview-build","ADS_PREVIEW_BUILD");
|
|
314
319
|
progress={stage:"preview-build",message:"Building all candidate previews"};notifyProgress?.(progress);
|
|
@@ -330,6 +335,24 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
330
335
|
verified.push({ name: "registered behavior checks", passed: true, results: evidence.results });
|
|
331
336
|
}
|
|
332
337
|
else verified.push({name:"registered behavior checks",skipped:true,reason:candidateOptions.config.acceptance.behaviorChecks ? "No affected behavior contracts." : "Not required by acceptance policy."});
|
|
338
|
+
if (auditSelection) {
|
|
339
|
+
boundary=evidenceFailure("runner","browser-audit","ADS_AUDIT_FAILED");
|
|
340
|
+
const selection = {selection:auditSelection.mode,...(auditSelection.reason?{selectionReason:auditSelection.reason}:{}),auditedScenarios:auditSelection.scenarios};
|
|
341
|
+
if (!auditSelection.scenarios.length) verified.push({name:"browser-accessibility-audit",skipped:true,reason:"No affected UI scenarios.",scenarios:0,...selection});
|
|
342
|
+
else {
|
|
343
|
+
progress={stage:"browser-audit",message:`Accessibility audit of ${auditSelection.scenarios.length} candidate scenarios`};notifyProgress?.(progress);
|
|
344
|
+
let result;
|
|
345
|
+
try { result = await audit.runBrowserAudit(candidate, {scenarios:auditSelection.scenarios,previewHost,signal,onProgress:value=>{progress=value;notifyProgress?.(value);}}); }
|
|
346
|
+
catch (error) {
|
|
347
|
+
if (signal.aborted) throw error;
|
|
348
|
+
verified.push({name:"browser-accessibility-audit",passed:false,...selection});
|
|
349
|
+
return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: [{ rule: "browser-audit", message: error.message, failure: evidenceFailure("runner","browser-audit",error.code ?? "ADS_AUDIT_FAILED") }], checks: verified },candidateRevision);
|
|
350
|
+
}
|
|
351
|
+
const {routed,check} = audit.auditCheck(result,selection);
|
|
352
|
+
verified.push(check);
|
|
353
|
+
if (!check.passed) return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: routed.diagnostics.map(item => ({...item,failure:evidenceFailure("assertion","browser-audit",item.rule)})), total: routed.diagnostics.length, checks: verified, ...(routed.advisories.length ? {advisories:routed.advisories,advisoryCount:routed.advisories.length} : {}) },candidateRevision);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
333
356
|
let screenshots;
|
|
334
357
|
if (screenshot) {
|
|
335
358
|
boundary=evidenceFailure("runner","capture","ADS_CAPTURE_FAILED");
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -442,7 +442,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
442
442
|
{ name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–64 coupled ADS owners, copying only their source/companions into non-importable .ads files. New owners are allowed. Optional dependencies name separate unaccepted drafts used by pattern/composition previews. Creation does not change accepted source. Edit the returned files normally; use ads_update_draft to register additions/deletions.", schema:z.object({units:z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units),title:z.string().min(1).max(160).optional(),id:draftIdSchema.optional(),dependencies:z.array(draftIdSchema).max(8).default([]),tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.create(args);if(observeChanges)await refresh();return json(result);} },
|
|
443
443
|
{ name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. refresh:true rebases onto current accepted source using stored baselines; non-overlapping edits merge and overlapping edits leave the draft unchanged with diagnostics. Use changes with refresh only for explicit resolved contents of existing draft files; refresh separately from dependency changes. Optional dependencies replaces the draft dependency list. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema,refresh:z.boolean().default(false),dependencies:z.array(draftIdSchema).max(8).optional(),changes:z.array(z.object({unit:z.string().max(256),path:z.string().min(1).max(500),content:z.string().max(256*1024).nullable(),encoding:z.enum(["utf8","base64"]).optional()}).strict()).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
|
|
444
444
|
{ name:"ads_drop_draft",description:"Delete an exact tracked draft and its generated preview. This is Drop, not a separate refusal workflow. Accepted source is unchanged. Dependents report a missing dependency until corrected.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async args=>{const result=await drafts.drop(args);if(observeChanges)await refresh();return json(result);} },
|
|
445
|
-
{ name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({fresh:z.boolean().default(false),id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
|
|
445
|
+
{ name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. When acceptance.browserAudit is true, axe-core audits the candidate's affected UI scenarios in every declared brand and theme; any a11y-axe error (or an audit that cannot run) rejects acceptance. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({fresh:z.boolean().default(false),id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
|
|
446
446
|
const result=await drafts.accept(args,signal,progress);
|
|
447
447
|
if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
|
|
448
448
|
return finishExecution("mutation",result);
|
|
@@ -526,7 +526,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
526
526
|
{ 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) },
|
|
527
527
|
{ 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) },
|
|
528
528
|
{ 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. Lists latest checks; an exact runId reads retained historical evidence, 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)) },
|
|
529
|
-
{ name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness, optional registered behavior checks and, when <policy>.browserAudit is true, an axe-core audit of every rendered UI scenario in every declared brand and theme (a11y-axe findings are blocking errors in the diagnostics section). policy acceptance runs acceptance.checks and acceptance.
|
|
529
|
+
{ name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness, optional registered behavior checks and, when <policy>.browserAudit is true, an axe-core audit of every rendered UI scenario in every declared brand and theme (a11y-axe findings are blocking errors in the diagnostics section). policy acceptance runs acceptance.checks, acceptance.behaviorChecks and acceptance.browserAudit without applying source, for direct editing; draft acceptance and guarded patches run the same acceptance policy, auditing only the candidate's affected UI scenarios. No script names are inferred. scope changed selects affected registered checks from this policy's own successful full baseline; broad changes expand to all. Project scripts keep full scope. Draft edit/show never triggers policies. Reports skipped stages honestly and a bounded resultId; use ads_results for details. Read ads://guides/validation. Trusted configured commands run; nothing is installed.", schema: z.object({scope:z.enum(["all","changed"]).default("all"),policy:z.enum(["acceptance","validation"]).default("validation"),fresh:z.boolean().default(false)}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
|
|
530
530
|
return finishExecution("validation",await validation.run(args,signal,progress));
|
|
531
531
|
} },
|
|
532
532
|
{ 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) => {
|
|
@@ -543,11 +543,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
543
543
|
const {patch,...result}=reconcileTokenSamples(options,args);
|
|
544
544
|
return json({...result,removed:result.removed.slice(0,50),unresolved:result.unresolved.slice(0,50),unresolvedCount:result.unresolved.length,...storePreparedPatch(options,patch)});
|
|
545
545
|
}},
|
|
546
|
-
{ name: "ads_apply_patch", description: "Apply one Git diff to one ADS unit from ads_units. Pass exactly one of patch (inline) or patchFile (a regular .patch/.diff under .ds/patches/, for large/binary diffs without model-context bytes). Text uses --- a/path, +++ b/path and exact @@ hunks; /dev/null creates/deletes. Git binary patches require git diff --binary --full-index and installed Git. A unit owns its implementation, previews and fixtures; imported peers are separate. Foundation, documentation, assets and configuration are editable too. Configuration changes may register/edit project guards and builders; the proposed schema, mandatory ADS and candidate project checks must pass. Only selected-unit public re-exports may change; preserve unrelated statements. A real selected-unit re-export may remove a redundant export {}; placeholder. A tokens patch may include its companionFiles foundation entry only to add/remove canonical imports required by token files created/deleted in this patch, preserving other imports/comments and canonical order. A runtime owner patch may also include its ds.config.json companion solely for that owner's inlineStyleFiles/styleWrites entries alongside its source. Unused permissions fail validation. Set dryRun true to validate without writing. Optional screenshot:true plus captures:[{scenario,target?,theme?,brand?,viewport?}] captures current/candidate only after gates pass. For genuinely coupled owner changes use ads_apply_transaction with one patch per owner. Fix rejected patches and inspect current previews after acceptance. Reply is a 4 KiB summary; read diagnostics, outcomes and requested captures through ads_results using its resultId.",
|
|
546
|
+
{ name: "ads_apply_patch", description: "Apply one Git diff to one ADS unit from ads_units. Pass exactly one of patch (inline) or patchFile (a regular .patch/.diff under .ds/patches/, for large/binary diffs without model-context bytes). Text uses --- a/path, +++ b/path and exact @@ hunks; /dev/null creates/deletes. Git binary patches require git diff --binary --full-index and installed Git. A unit owns its implementation, previews and fixtures; imported peers are separate. Foundation, documentation, assets and configuration are editable too. Configuration changes may register/edit project guards and builders; the proposed schema, mandatory ADS and candidate project checks must pass. Only selected-unit public re-exports may change; preserve unrelated statements. A real selected-unit re-export may remove a redundant export {}; placeholder. A tokens patch may include its companionFiles foundation entry only to add/remove canonical imports required by token files created/deleted in this patch, preserving other imports/comments and canonical order. A runtime owner patch may also include its ds.config.json companion solely for that owner's inlineStyleFiles/styleWrites entries alongside its source. Unused permissions fail validation. When acceptance.browserAudit is true, axe-core audits the candidate's affected UI scenarios in every brand and theme; a11y-axe errors reject the patch. Set dryRun true to validate without writing. Optional screenshot:true plus captures:[{scenario,target?,theme?,brand?,viewport?}] captures current/candidate only after gates pass. For genuinely coupled owner changes use ads_apply_transaction with one patch per owner. Fix rejected patches and inspect current previews after acceptance. Reply is a 4 KiB summary; read diagnostics, outcomes and requested captures through ads_results using its resultId.",
|
|
547
547
|
schema: z.object({ unit: z.string().min(1).max(256), dryRun: z.boolean(), patch: z.string().min(1).max(mutationLimits.patchBytes).optional(), patchFile: z.string().min(1).max(500).optional(), ...screenshotFields }).strict().refine(args => (args.patch !== undefined) !== (args.patchFile !== undefined), "Provide exactly one of patch or patchFile."),
|
|
548
548
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, _meta: { ui: { visibility: ["model"] } },
|
|
549
549
|
call: applyEdits,
|
|
550
|
-
}, {name:"ads_apply_transaction",description:"Apply genuinely coupled ADS changes as 2–64 distinct owner Git patches. Each patch must obey its unit and narrow companion rules. Patches run in order; later patches use the earlier candidate's shared-entry content. Core guards, configured project checks
|
|
550
|
+
}, {name:"ads_apply_transaction",description:"Apply genuinely coupled ADS changes as 2–64 distinct owner Git patches. Each patch must obey its unit and narrow companion rules. Patches run in order; later patches use the earlier candidate's shared-entry content. Core guards, configured project checks, affected behavior checks and, when acceptance.browserAudit is true, the axe-core audit of affected UI scenarios validate the complete final candidate before any live source is written. Maximum 256 distinct files/16 MiB combined. Dry runs, failures and cancellation publish nothing; publication rolls back on write failure. Optional screenshot:true with dryRun:true and explicit captures selects current/candidate images. Prefer ads_apply_patch for independent edits. Reply is a bounded summary; page diagnostics, outcomes and captures with ads_results using the returned resultId.",schema:z.object({patches:z.array(ownerPatch).min(2).max(mutationLimits.units),dryRun:z.boolean(),...screenshotFields}).strict(),annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:false},_meta:{ui:{visibility:["model"]}},call:applyEdits}] : []),
|
|
551
551
|
...options.config.mcp.apps.map((app) => ({ name: `ads_show_${app.id.replaceAll("-", "_")}`, title: app.title, description: `${app.description ?? app.title}. Renders the project's built ${app.kind} examples through MCP Apps; text fallback provides the showcase URL.`, schema: empty, _meta: { ui: { resourceUri: appUri(app.id) } }, call: async (_args, signal) => {
|
|
552
552
|
// Validate readiness without embedding executable HTML in model results.
|
|
553
553
|
const build = await previewBuild(app, signal);
|
|
@@ -48,8 +48,11 @@ function substitute(values, text, seen) {
|
|
|
48
48
|
return parsed.toString();
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
/** One token in one context
|
|
52
|
-
|
|
51
|
+
/** One token in one context (contextValues() of that theme and brand, and the theme's color
|
|
52
|
+
* scheme): { color: [r, g, b, a] } in sRGB 0–255 clipped as a canvas draws it,
|
|
53
|
+
* { unresolved: reason, value, invalid? }, { other: true, value } for a value that is not a
|
|
54
|
+
* color, or null when the token is not set. token-contrast resolves its pairs through this. */
|
|
55
|
+
export function resolveColorToken(values, name, scheme) {
|
|
53
56
|
const own = values.get(name);
|
|
54
57
|
if (!own) return null;
|
|
55
58
|
let text;
|
|
@@ -84,7 +87,7 @@ export function resolvePalette(tokens, config) {
|
|
|
84
87
|
const results = new Map(names.map(name => [name, []]));
|
|
85
88
|
for (const context of contexts) {
|
|
86
89
|
const values = contextValues(tokens, { theme: context.theme.name, brand: context.brand, themes });
|
|
87
|
-
for (const name of names) results.get(name).push(
|
|
90
|
+
for (const name of names) results.get(name).push(resolveColorToken(values, name, context.theme.scheme));
|
|
88
91
|
}
|
|
89
92
|
const palette = Object.fromEntries(contexts.map(context => [context.key, {}])), unresolved = [], included = [];
|
|
90
93
|
for (const name of names) {
|
|
@@ -116,7 +116,7 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
116
116
|
- omitted: host decides border`)}),fS=p({method:h("ui/request-display-mode"),params:p({mode:Vi.describe("The display mode being requested.")})}),gS=p({mode:Vi.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),Sw=T([h("model"),h("app")]).describe("Tool visibility scope - who can access the tool."),mT=p({resourceUri:c().optional(),visibility:S(Sw).optional().describe(`Who can access this tool. Default: ["model", "app"]
|
|
117
117
|
- "model": Tool visible to and callable by the agent
|
|
118
118
|
- "app": Tool callable by the app from this server only`),csp:nu().optional(),permissions:nu().optional()}),fT=p({mimeTypes:S(c()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),_w=p({method:h("ui/download-file"),params:p({contents:S(T([Zr,Dr])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),bw=p({method:h("ui/message"),params:p({role:h("user").describe('Message role, currently only "user" is supported.'),content:S(Pt).describe("Message content blocks (text, image, etc.).")})}),gT=p({method:h("ui/notifications/sandbox-resource-ready"),params:p({html:c().describe("HTML content to load into the inner iframe."),sandbox:c().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Bu.optional().describe("CSP configuration from resource metadata."),permissions:Wu.optional().describe("Sandbox permissions from resource metadata.")})}),ST=p({method:h("ui/notifications/tool-result"),params:dr.describe("Standard MCP tool execution result.")}),yS=p({toolInfo:p({id:lt.optional().describe("JSON-RPC id of the tools/call request."),tool:ur.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:tw.optional().describe("Current color theme preference."),styles:dw.optional().describe("Style configuration for theming the app."),displayMode:Vi.optional().describe("How the UI is currently displayed."),availableDisplayModes:S(Vi).optional().describe("Display modes the host supports."),containerDimensions:T([p({height:z().describe("Fixed container height in pixels.")}),p({maxHeight:T([z(),ou()]).optional().describe("Maximum container height in pixels.")})]).and(T([p({width:z().describe("Fixed container width in pixels.")}),p({maxWidth:T([z(),ou()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
119
|
-
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:c().optional().describe("User's language and region preference in BCP 47 format."),timeZone:c().optional().describe("User's timezone in IANA format."),userAgent:c().optional().describe("Host application identifier."),platform:T([h("web"),h("desktop"),h("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:E().optional().describe("Whether the device supports touch input."),hover:E().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:z().describe("Top safe area inset in pixels."),right:z().describe("Right safe area inset in pixels."),bottom:z().describe("Bottom safe area inset in pixels."),left:z().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),_T=p({method:h("ui/notifications/host-context-changed"),params:yS.describe("Partial context update containing only changed fields.")}),yw=p({method:h("ui/update-model-context"),params:p({content:S(Pt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),M().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),vw=p({method:h("ui/initialize"),params:p({appInfo:Rt.describe("App identification (name and version)."),appCapabilities:fw.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),zw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Rt.describe("Host application identification and version."),hostCapabilities:mw.describe("Features and capabilities provided by the host."),hostContext:yS.describe("Rich context about the host environment.")}).passthrough();class Ji{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(r)=>{if(t&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=ut.safeParse(r.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(r.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,r);else console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==ew)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var ww=[bS];class Bi extends Ec{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new SS;_methods=new _S;setRequestHandler=(...e)=>{let[t,...r]=hS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=hS("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);if(e==="ui/initialize"||e==="ping")return r;return async(o,n)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return r(o,n)}}eventSchemas={sizechange:lw,sandboxready:cw,initialized:gw,requestteardown:hw,loggingmessage:Fr};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=(o)=>{if(e==="initialized")this._initializedReceived=!0;this._events.dispatch(e,o)};if(e==="loggingmessage")this.setNotificationHandler("notifications/message",(o)=>{r(o.params)});else this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>r(o));this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,r,o){super(o);this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=o?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:vw.shape.params,result:zw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,i)=>(this.onping?.(n.params,i),{})),this.replaceRequestHandler("ui/request-display-mode",{params:fS.shape.params,result:gS},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:bw.shape.params,result:aw},async(t,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:nw.shape.params,result:sw},async(t,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:_w.shape.params,result:iw},async(t,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:fS.shape.params,result:gS},async(t,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:yw.shape.params,result:cr},async(t,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(t,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(t.params,r)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(t,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(t,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(t,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,r)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(t,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,r)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;if(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.");return this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:ww.includes(t)?t:bS,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){let n=this._hostContext[o],i=e[o];if(Rw(n,i))continue;t[o]=i,r=!0}if(r)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},pw,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},{signal:o.mcpReq.signal}),t.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(r)=>this.sendToolListChanged(r.params))}if(t.resources){if(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},{signal:o.mcpReq.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},{signal:o.mcpReq.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},{signal:o.mcpReq.signal}),t.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(r)=>this.sendResourceListChanged(r.params))}if(t.prompts){if(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},{signal:o.mcpReq.signal}),t.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(r)=>this.sendPromptListChanged(r.params))}}return super.connect(e)}}function Rw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var vS=[200,800],xw=(e)=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function Pw(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let i=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(i),t.removeEventListener("abort",s),o(t.reason)};t?.addEventListener("abort",s,{once:!0})})}function zS(e,{signal:t,onDiagnostic:r,wait:o=Pw}={}){return async(n)=>{for(let i=1;;i++){t?.throwIfAborted();try{let s=await e(n);if(t?.throwIfAborted(),i>1)r?.({state:"recovered",uri:n.uri,attempt:i});return s}catch(s){if(t?.throwIfAborted(),!xw(s))throw s;if(i>vS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:i,message:s.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${i} attempts: ${s.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:s}),{code:"ADS_RESOURCE_TRANSPORT"});let a=vS[i-1];r?.({state:"retry",uri:n.uri,attempt:i,nextAttempt:i+1,delayMs:a,message:s.message}),await o(a,t)}}}}function wS(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}if(!r.has(o.group))r.set(o.group,[]);r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function xS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:i,callTool:s,context:a,onError:l,onState:u},m=n,f,g,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await g,await f?.close(),y)return;g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=void 0}}).catch((L)=>{if(!y)l(L)}).finally(()=>{b=void 0})}g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=void 0}return{async updateResult(L){if(m=L,await b,!y)await f.updateResult(m)},refreshContext(){if(!y&&!b)f.refreshContext()},async close(){y=!0,await b,await f?.close()}}}async function RS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u,onReopen:d}){let m=!1,g=(await i({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!g)throw Error("Comparison preview App is unavailable.");let b=document.createElement("iframe");b.title=t,b.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),b.src=r,e.append(b);let y=new Bi(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=i,y.oncalltool=s,y.onerror=(x)=>{if(!m)l(x)},y.onloggingmessage=(x)=>{if(m||x.logger!=="ads-preview")return;if(x.data?.code==="ADS_PREVIEW_REOPEN"){d();return}if(u?.(x.data),x.data?.state==="error")l(Error(x.data.message))};let v,L=new Promise((x,Z)=>{v=setTimeout(()=>Z(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:g.text,csp:g._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Ji(b.contentWindow,b.contentWindow)),L]),H.observe(b),await y.sendToolInput({arguments:{}}),await y.sendToolResult(n)}catch(x){throw H.disconnect(),b.remove(),await y.close(),x}finally{clearTimeout(v)}return{updateResult:(x)=>y.sendToolResult(x),refreshContext:()=>y.setHostContext(a(b)),async close(){m=!0,H.disconnect();try{await y.teardownResource({},{timeout:500})}catch{}await y.close(),b.remove()}}}function Ku(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function PS(e,t,r,o=new Map){let n=new Map(r.map(({id:l,title:u,revision:d,state:m,preview:f})=>[l,{id:l,title:u,revision:d,state:m,...f?{preview:f}:{}}])),i=new Map(e.map((l)=>[l.id,{...l,drafts:(l.drafts??[]).flatMap((u)=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let l of t){let u=i.get(l.id);i.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let s=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:Ku(l,u.id)),a=(l,u)=>{if(!l.drafts.some((d)=>d.id===u.id))l.drafts.push(n.get(u.id))};for(let l of r){let u=o.get(l.id);for(let d of u?.scenarios??[]){if(!l.units.some((f)=>s(f,d)))continue;let m=i.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},i.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["brand","tokens","components","patterns","composition"].includes(d))continue;let m=[...i.values()].filter((f)=>s(u,f));if(m.length)for(let f of m)a(f,l);else i.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...i.values()],categories:[...i.values()].filter((l)=>l.kind==="tokens")}}function TS(e,t,r){let o=e.drafts?.find((l)=>l.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find((l)=>l.id===o.id)??o.preview),i=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,s=i?.state==="error"?"error":i?.state==="checking"||i?.live?"checking":i?.building||["queued","building"].includes(i?.state)?"building":i?.current?"ready":i?.stale?"stale":"unreported",a={error:ya(i),checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"};return{state:s,label:`${o?"Draft · ":""}${a[s]}${o&&s==="ready"?" · unaccepted":""}`}}var ES={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var Nc="ads://project/icons";function Q(e,t={},...r){let o=Object.assign(document.createElement(e),t);return o.append(...r.filter((n)=>n!==null&&n!==void 0&&n!==!1)),o}var Tw={fill:"black",stroke:"none","stroke-width":"1","stroke-linecap":"butt","stroke-linejoin":"miter","stroke-miterlimit":"4","stroke-dasharray":"none","fill-opacity":"1","stroke-opacity":"1","fill-rule":"nonzero"};function Ew(e){let t=new DOMParser().parseFromString(e,"image/svg+xml").documentElement;if(t.namespaceURI!=="http://www.w3.org/2000/svg"||t.localName!=="svg")return null;for(let o of t.querySelectorAll("*"))if(["script","foreignObject","iframe","image","a","animate","set","animateTransform","animateMotion"].includes(o.localName)||o.namespaceURI!=="http://www.w3.org/2000/svg")o.remove();for(let o of[t,...t.querySelectorAll("*")])for(let n of Array.from(o.attributes))if(/^on/i.test(n.name)||/href$/i.test(n.name)&&!n.value.trim().startsWith("#"))o.removeAttribute(n.name);let r=document.importNode(t,!0);for(let o of["width","height","class"])r.removeAttribute(o);for(let[o,n]of Object.entries(Tw))if(!r.style.getPropertyValue(o))r.style.setProperty(o,r.getAttribute(o)??n);return r.setAttribute("aria-hidden","true"),r.setAttribute("focusable","false"),r}function Gu(e,t,r){let o=Q("span",{className:"icons-glyph"});o.style.width=o.style.height=`${t}px`;let n=Ew(e.svg);if(n)o.append(n);if(r)o.setAttribute("role","img"),o.setAttribute("aria-label",r),o.title=r;else o.setAttribute("aria-hidden","true");return o}function kw(e){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("class","icons-grid"),t.setAttribute("aria-hidden","true"),t.setAttribute("viewBox",`${e.x} ${e.y} ${e.width} ${e.height}`),t.setAttribute("preserveAspectRatio","xMidYMid meet");let r=Math.max(1,Math.ceil(Math.max(e.width,e.height)/48)),o=(n,i,s,a,l)=>{let u=document.createElementNS("http://www.w3.org/2000/svg","line");for(let[d,m]of Object.entries({x1:n,y1:i,x2:s,y2:a}))u.setAttribute(d,m);if(l)u.setAttribute("class","mid");t.append(u)};for(let n=0;n<=e.width;n+=r)o(e.x+n,e.y,e.x+n,e.y+e.height,n*2===e.width);for(let n=0;n<=e.height;n+=r)o(e.x,e.y+n,e.x+e.width,e.y+n,n*2===e.height);if(e.width%2&&r===1)o(e.x+e.width/2,e.y,e.x+e.width/2,e.y+e.height,!0);if(e.height%2&&r===1)o(e.x,e.y+e.height/2,e.x+e.width,e.y+e.height/2,!0);return t}var Yu=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function $w(e){let t=e.filter((r)=>r.severity==="error").length;return t===e.length?Yu(t,"error"):Yu(e.length,"issue")}function kS(e){return Q("p",{className:"icons-finding",title:e.file??""},Q("strong",{textContent:e.rule})," ",e.message)}function Cw(e,t){let r=Q("article",{className:"icons-card"});if(r.dataset.glyph=e.name,e.findings.length)r.dataset.findings=String(e.findings.length);let o=Q("div",{className:"icons-card-head"},Q("h3",{textContent:e.name}),e.findings.length?Q("span",{className:"icons-badge",textContent:$w(e.findings)}):null),n=Q("div",{className:"icons-mag"});if(e.grid)n.append(kw(e.grid));n.append(Gu(e,96));let i=Q("div",{className:"icons-sizes"},...t.map((s)=>Q("span",{className:"icons-size"},Gu(e,s.px),Q("small",{textContent:String(s.px),title:s.token}))));return r.append(...[o,e.aliases.length?Q("p",{className:"icons-alias",textContent:`alias: ${e.aliases.join(", ")}`}):null,n,i,...e.findings.map(kS)].filter(Boolean)),r.setAttribute("aria-label",e.name),r}function Iw(e){let t=Q("figure",{className:"icons-logo"});if(t.dataset.logo=e.name,e.tooLarge)return t.append(Q("figcaption",{textContent:`${e.name} (over 1 MB; not shown)`})),t;let r=Q("span",{className:"icons-logo-muted",title:`${e.name}, muted`});return r.setAttribute("aria-hidden","true"),r.style.maskImage=r.style.webkitMaskImage=`url("${e.src}")`,t.append(Q("img",{src:e.src,alt:e.name,title:e.file}),r,Q("figcaption",{textContent:e.name})),t}var Ow=(e,t)=>!t||[e.name,...e.aliases].some((r)=>r.toLowerCase().includes(t));function $S(e,t){let r=e.querySelector(":scope > .icons-view"),o=r?.querySelector("input[type=search]")?.value??"",n=r?.scrollTop??0;if(r=Q("div",{className:"icons-view"}),r.setAttribute("role","region"),r.setAttribute("aria-label","Icons"),!t?.configured)return r.append(Q("h1",{textContent:"Icons"}),Q("p",{className:"icons-summary",textContent:"The project configures no glyph set (assets.glyphs)."})),e.replaceChildren(r),r;let i=t.mixed?"mixed grids":t.grid?`${/^(?:8|11|18)(?!\d)|^8/.test(String(t.grid.width))?"an":"a"} ${t.grid.width}×${t.grid.height} grid`:"no viewBox",s=`${t.source} · ${Yu(t.glyphs.length,"glyph")} on ${i} · ${t.aliasCount} ${t.aliasCount===1?"alias":"aliases"}`,a=Q("input",{type:"search",placeholder:"Search name or alias",value:o});a.setAttribute("aria-label","Search glyphs by name or alias");let l=Q("div",{className:"icons-set"});l.setAttribute("role","list"),l.setAttribute("aria-label","The set");let u=Q("div",{className:"icons-cards"}),d=Q("p",{className:"icons-empty",hidden:!0}),m=t.textSize;r.append(Q("div",{className:"icons-head"},Q("div",{},Q("h1",{textContent:"Icons"}),Q("p",{className:"icons-summary",textContent:s})),a),...t.findings.map(kS),Q("h2",{},"The set ",Q("small",{textContent:m?`every glyph at ${m.px} px, the size used beside text`:"every glyph"})),l,Q("h2",{},"Glyphs ",Q("small",{textContent:t.sizes.length?"each on its grid, at every icon size":"each on its grid"})),d,u);for(let g of t.glyphs){let b=Q("span",{className:"icons-set-item"},Gu(g,m?.px??18,g.name));b.dataset.glyph=g.name,b.setAttribute("role","listitem"),l.append(b),u.append(Cw(g,t.sizes))}if(t.logos)r.append(Q("h2",{},"Other products' logos ",Q("small",{textContent:`${t.logos.source} · in color and muted`})),t.logos.files.length?Q("div",{className:"icons-logos"},...t.logos.files.map(Iw)):Q("p",{className:"icons-summary",textContent:"No images yet."}));let f=()=>{let g=a.value.trim().toLowerCase(),b=0;t.glyphs.forEach((y,v)=>{let L=Ow(y,g);l.children[v].hidden=u.children[v].hidden=!L,b+=L}),d.hidden=b>0,d.textContent=`No glyph matches “${a.value.trim()}”.`};if(a.addEventListener("input",f),f(),e.replaceChildren(r),r.scrollTop=n,o&&document.activeElement===document.body)a.focus();return r}var k=(e)=>document.getElementById(e),De=new URLSearchParams(location.search),CS=De.get("scenario")??De.get("category"),Nw=["brand","tokens","icons","components","patterns","composition"],Mc=!1,sn=[],be,jc=De.get("draft"),nd=[],NS=[],sd=new Map,ln=De.get("split")==="1",ed,fr=[],$t=0,Fc;async function Qi(){let e=fr;fr=[],await Promise.allSettled(e.map((t)=>t.close()))}var nt=document.createElement("button");nt.id="split-view";nt.setAttribute("aria-label","Split view");nt.setAttribute("aria-pressed","false");nt.disabled=!0;nt.title="Select a draft with an accepted version to compare";nt.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';k("viewport").before(nt);var te="brand",Ze={},IS=new Map,Wi=!0,id=[],Hc=[],Vc=[],rt,ea,fe,ye,rn,Gi,an,Lc,on,Ge=0,cn=De.get("capture")!=="1"&&De.get("viewport")==="phone",ot=[{name:"light",scheme:"light"},{name:"dark",scheme:"dark"}],Kt=De.get("capture")==="1"&&De.get("theme")||"light";if(De.get("capture")==="1")document.documentElement.dataset.capture="true";var td=()=>ot.find((e)=>e.name===Kt)?.scheme??"light";function AS(){document.documentElement.dataset.theme=td();let e=ot[(ot.findIndex((r)=>r.name===Kt)+1)%ot.length],t=ot.length>1?`Use ${e.name} theme`:`Theme: ${Kt}`;k("theme").setAttribute("aria-label",t),k("theme").title=t,k("theme").disabled=ot.length<2,k("theme").querySelector("svg").innerHTML=td()==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>'}document.documentElement.dataset.theme="light";var Qr=[],pt=De.get("capture")==="1"&&De.get("brand")||null;function qS(){let e=k("brand-select");if(e.hidden=!Qr.length,e.options.length!==Qr.length||Qr.some((t,r)=>e.options[r].value!==t.name))e.replaceChildren(...Qr.map((t)=>Object.assign(document.createElement("option"),{value:t.name,textContent:t.name})));if(pt)e.value=pt,e.title=`Brand: ${pt}`}var Xu,MS=!0,Ac=!1,Uc,rd,Jc=!1,Yi=!1,hr,Bt,Qu=0,Ki,eo=new AbortController,Ct=new uS({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),jS=(e,t={},r={})=>Ct.callTool({name:e,arguments:t},{signal:eo.signal,...r}),Zc=zS((e)=>Ct.readResource(e,{signal:eo.signal}),{signal:eo.signal,onDiagnostic:(e)=>{if(e.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",e)}}),ad=async(e)=>JSON.parse((await Zc({uri:e})).contents.find((t)=>typeof t.text==="string").text);function LS(e){let t=Vc.find((r)=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return Ct.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(k("preview-error").hidden=!t,k("preview-error-message").textContent=t?o.split(`
|
|
119
|
+
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:c().optional().describe("User's language and region preference in BCP 47 format."),timeZone:c().optional().describe("User's timezone in IANA format."),userAgent:c().optional().describe("Host application identifier."),platform:T([h("web"),h("desktop"),h("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:E().optional().describe("Whether the device supports touch input."),hover:E().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:z().describe("Top safe area inset in pixels."),right:z().describe("Right safe area inset in pixels."),bottom:z().describe("Bottom safe area inset in pixels."),left:z().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),_T=p({method:h("ui/notifications/host-context-changed"),params:yS.describe("Partial context update containing only changed fields.")}),yw=p({method:h("ui/update-model-context"),params:p({content:S(Pt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),M().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),vw=p({method:h("ui/initialize"),params:p({appInfo:Rt.describe("App identification (name and version)."),appCapabilities:fw.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),zw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Rt.describe("Host application identification and version."),hostCapabilities:mw.describe("Features and capabilities provided by the host."),hostContext:yS.describe("Rich context about the host environment.")}).passthrough();class Ji{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(r)=>{if(t&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=ut.safeParse(r.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(r.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,r);else console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==ew)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var ww=[bS];class Bi extends Ec{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new SS;_methods=new _S;setRequestHandler=(...e)=>{let[t,...r]=hS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=hS("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);if(e==="ui/initialize"||e==="ping")return r;return async(o,n)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return r(o,n)}}eventSchemas={sizechange:lw,sandboxready:cw,initialized:gw,requestteardown:hw,loggingmessage:Fr};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=(o)=>{if(e==="initialized")this._initializedReceived=!0;this._events.dispatch(e,o)};if(e==="loggingmessage")this.setNotificationHandler("notifications/message",(o)=>{r(o.params)});else this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>r(o));this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,r,o){super(o);this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=o?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:vw.shape.params,result:zw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,i)=>(this.onping?.(n.params,i),{})),this.replaceRequestHandler("ui/request-display-mode",{params:fS.shape.params,result:gS},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:bw.shape.params,result:aw},async(t,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:nw.shape.params,result:sw},async(t,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:_w.shape.params,result:iw},async(t,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:fS.shape.params,result:gS},async(t,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:yw.shape.params,result:cr},async(t,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(t,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(t.params,r)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(t,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(t,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(t,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,r)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(t,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,r)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;if(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.");return this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:ww.includes(t)?t:bS,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){let n=this._hostContext[o],i=e[o];if(Rw(n,i))continue;t[o]=i,r=!0}if(r)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},pw,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},{signal:o.mcpReq.signal}),t.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(r)=>this.sendToolListChanged(r.params))}if(t.resources){if(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},{signal:o.mcpReq.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},{signal:o.mcpReq.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},{signal:o.mcpReq.signal}),t.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(r)=>this.sendResourceListChanged(r.params))}if(t.prompts){if(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},{signal:o.mcpReq.signal}),t.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(r)=>this.sendPromptListChanged(r.params))}}return super.connect(e)}}function Rw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var vS=[200,800],xw=(e)=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function Pw(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let i=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(i),t.removeEventListener("abort",s),o(t.reason)};t?.addEventListener("abort",s,{once:!0})})}function zS(e,{signal:t,onDiagnostic:r,wait:o=Pw}={}){return async(n)=>{for(let i=1;;i++){t?.throwIfAborted();try{let s=await e(n);if(t?.throwIfAborted(),i>1)r?.({state:"recovered",uri:n.uri,attempt:i});return s}catch(s){if(t?.throwIfAborted(),!xw(s))throw s;if(i>vS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:i,message:s.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${i} attempts: ${s.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:s}),{code:"ADS_RESOURCE_TRANSPORT"});let a=vS[i-1];r?.({state:"retry",uri:n.uri,attempt:i,nextAttempt:i+1,delayMs:a,message:s.message}),await o(a,t)}}}}function wS(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}if(!r.has(o.group))r.set(o.group,[]);r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function xS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:i,callTool:s,context:a,onError:l,onState:u},m=n,f,g,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await g,await f?.close(),y)return;g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=void 0}}).catch((L)=>{if(!y)l(L)}).finally(()=>{b=void 0})}g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=void 0}return{async updateResult(L){if(m=L,await b,!y)await f.updateResult(m)},refreshContext(){if(!y&&!b)f.refreshContext()},async close(){y=!0,await b,await f?.close()}}}async function RS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u,onReopen:d}){let m=!1,g=(await i({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!g)throw Error("Comparison preview App is unavailable.");let b=document.createElement("iframe");b.title=t,b.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),b.src=r,e.append(b);let y=new Bi(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=i,y.oncalltool=s,y.onerror=(x)=>{if(!m)l(x)},y.onloggingmessage=(x)=>{if(m||x.logger!=="ads-preview")return;if(x.data?.code==="ADS_PREVIEW_REOPEN"){d();return}if(u?.(x.data),x.data?.state==="error")l(Error(x.data.message))};let v,L=new Promise((x,Z)=>{v=setTimeout(()=>Z(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:g.text,csp:g._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Ji(b.contentWindow,b.contentWindow)),L]),H.observe(b),await y.sendToolInput({arguments:{}}),await y.sendToolResult(n)}catch(x){throw H.disconnect(),b.remove(),await y.close(),x}finally{clearTimeout(v)}return{updateResult:(x)=>y.sendToolResult(x),refreshContext:()=>y.setHostContext(a(b)),async close(){m=!0,H.disconnect();try{await y.teardownResource({},{timeout:500})}catch{}await y.close(),b.remove()}}}function Ku(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function PS(e,t,r,o=new Map){let n=new Map(r.map(({id:l,title:u,revision:d,state:m,preview:f})=>[l,{id:l,title:u,revision:d,state:m,...f?{preview:f}:{}}])),i=new Map(e.map((l)=>[l.id,{...l,drafts:(l.drafts??[]).flatMap((u)=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let l of t){let u=i.get(l.id);i.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let s=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:Ku(l,u.id)),a=(l,u)=>{if(!l.drafts.some((d)=>d.id===u.id))l.drafts.push(n.get(u.id))};for(let l of r){let u=o.get(l.id);for(let d of u?.scenarios??[]){if(!l.units.some((f)=>s(f,d)))continue;let m=i.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},i.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["brand","tokens","components","patterns","composition"].includes(d))continue;let m=[...i.values()].filter((f)=>s(u,f));if(m.length)for(let f of m)a(f,l);else i.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...i.values()],categories:[...i.values()].filter((l)=>l.kind==="tokens")}}function TS(e,t,r){let o=e.drafts?.find((l)=>l.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find((l)=>l.id===o.id)??o.preview),i=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,s=i?.state==="error"?"error":i?.state==="checking"||i?.live?"checking":i?.building||["queued","building"].includes(i?.state)?"building":i?.current?"ready":i?.stale?"stale":"unreported",a={error:ya(i),checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"};return{state:s,label:`${o?"Draft · ":""}${a[s]}${o&&s==="ready"?" · unaccepted":""}`}}var ES={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var Nc="ads://project/icons";function Q(e,t={},...r){let o=Object.assign(document.createElement(e),t);return o.append(...r.filter((n)=>n!==null&&n!==void 0&&n!==!1)),o}var Tw={fill:"black",stroke:"none","stroke-width":"1","stroke-linecap":"butt","stroke-linejoin":"miter","stroke-miterlimit":"4","stroke-dasharray":"none","fill-opacity":"1","stroke-opacity":"1","fill-rule":"nonzero"};function Ew(e){let t=new DOMParser().parseFromString(e,"image/svg+xml").documentElement;if(t.namespaceURI!=="http://www.w3.org/2000/svg"||t.localName!=="svg")return null;for(let o of t.querySelectorAll("*"))if(["script","foreignObject","iframe","image","a","animate","set","animateTransform","animateMotion"].includes(o.localName)||o.namespaceURI!=="http://www.w3.org/2000/svg")o.remove();for(let o of[t,...t.querySelectorAll("*")])for(let n of Array.from(o.attributes))if(/^on/i.test(n.name)||/href$/i.test(n.name)&&!n.value.trim().startsWith("#"))o.removeAttribute(n.name);let r=document.importNode(t,!0);for(let o of["width","height","class"])r.removeAttribute(o);for(let[o,n]of Object.entries(Tw))if(!r.style.getPropertyValue(o))r.style.setProperty(o,r.getAttribute(o)??n);return r.setAttribute("aria-hidden","true"),r.setAttribute("focusable","false"),r}function Gu(e,t,r){let o=Q("span",{className:"icons-glyph"});o.style.width=o.style.height=`${t}px`;let n=Ew(e.svg);if(n)o.append(n);if(r)o.setAttribute("role","img"),o.setAttribute("aria-label",r),o.title=r;else o.setAttribute("aria-hidden","true");return o}function kw(e){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("class","icons-grid"),t.setAttribute("aria-hidden","true"),t.setAttribute("viewBox",`${e.x} ${e.y} ${e.width} ${e.height}`),t.setAttribute("preserveAspectRatio","xMidYMid meet");let r=Math.max(1,Math.ceil(Math.max(e.width,e.height)/48)),o=(n,i,s,a,l)=>{let u=document.createElementNS("http://www.w3.org/2000/svg","line");for(let[d,m]of Object.entries({x1:n,y1:i,x2:s,y2:a}))u.setAttribute(d,m);if(l)u.setAttribute("class","mid");t.append(u)};for(let n=0;n<=e.width;n+=r)o(e.x+n,e.y,e.x+n,e.y+e.height,n*2===e.width);for(let n=0;n<=e.height;n+=r)o(e.x,e.y+n,e.x+e.width,e.y+n,n*2===e.height);if(e.width%2&&r===1)o(e.x+e.width/2,e.y,e.x+e.width/2,e.y+e.height,!0);if(e.height%2&&r===1)o(e.x,e.y+e.height/2,e.x+e.width,e.y+e.height/2,!0);return t}var Yu=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function $w(e){let t=e.filter((r)=>r.severity==="error").length;return t===e.length?Yu(t,"error"):Yu(e.length,"issue")}function kS(e){return Q("p",{className:"icons-finding",title:e.file??""},Q("strong",{textContent:e.rule})," ",e.message)}function Cw(e,t){let r=Q("article",{className:"icons-card"});if(r.dataset.glyph=e.name,e.findings.length)r.dataset.findings=String(e.findings.length);let o=Q("div",{className:"icons-card-head"},Q("h3",{textContent:e.name}),e.findings.length?Q("span",{className:"icons-badge",textContent:$w(e.findings)}):null),n=Q("div",{className:"icons-mag"});if(e.grid)n.append(kw(e.grid));n.append(Gu(e,96));let i=Q("div",{className:"icons-sizes"},...t.map((s)=>Q("span",{className:"icons-size"},Gu(e,s.px),Q("small",{textContent:String(s.px),title:s.token}))));return r.append(...[o,Q("p",{className:"icons-alias",textContent:e.aliases.length?`alias: ${e.aliases.join(", ")}`:"",title:e.aliases.join(", ")}),n,i,...e.findings.map(kS)].filter(Boolean)),r.setAttribute("aria-label",e.name),r}function Iw(e){let t=Q("figure",{className:"icons-logo"});if(t.dataset.logo=e.name,e.tooLarge)return t.append(Q("figcaption",{textContent:`${e.name} (over 1 MB; not shown)`})),t;let r=Q("span",{className:"icons-logo-muted",title:`${e.name}, muted`});return r.setAttribute("aria-hidden","true"),r.style.maskImage=r.style.webkitMaskImage=`url("${e.src}")`,t.append(Q("img",{src:e.src,alt:e.name,title:e.file}),r,Q("figcaption",{textContent:e.name})),t}var Ow=(e,t)=>!t||[e.name,...e.aliases].some((r)=>r.toLowerCase().includes(t));function $S(e,t){let r=e.querySelector(":scope > .icons-view"),o=r?.querySelector("input[type=search]")?.value??"",n=r?.scrollTop??0;if(r=Q("div",{className:"icons-view"}),r.setAttribute("role","region"),r.setAttribute("aria-label","Icons"),!t?.configured)return r.append(Q("h1",{textContent:"Icons"}),Q("p",{className:"icons-summary",textContent:"The project configures no glyph set (assets.glyphs)."})),e.replaceChildren(r),r;let i=t.mixed?"mixed grids":t.grid?`${/^(?:8|11|18)(?!\d)|^8/.test(String(t.grid.width))?"an":"a"} ${t.grid.width}×${t.grid.height} grid`:"no viewBox",s=`${t.source} · ${Yu(t.glyphs.length,"glyph")} on ${i} · ${t.aliasCount} ${t.aliasCount===1?"alias":"aliases"}`,a=Q("input",{type:"search",placeholder:"Search name or alias",value:o});a.setAttribute("aria-label","Search glyphs by name or alias");let l=Q("div",{className:"icons-set"});l.setAttribute("role","list"),l.setAttribute("aria-label","The set");let u=Q("div",{className:"icons-cards"}),d=Q("p",{className:"icons-empty",hidden:!0}),m=t.textSize;r.append(Q("div",{className:"icons-head"},Q("div",{},Q("h1",{textContent:"Icons"}),Q("p",{className:"icons-summary",textContent:s})),a),...t.findings.map(kS),Q("h2",{},"The set ",Q("small",{textContent:m?`every glyph at ${m.px} px, the size used beside text`:"every glyph"})),l,Q("h2",{},"Glyphs ",Q("small",{textContent:t.sizes.length?"each on its grid, at every icon size":"each on its grid"})),d,u);for(let g of t.glyphs){let b=Q("span",{className:"icons-set-item"},Gu(g,m?.px??18,g.name));b.dataset.glyph=g.name,b.setAttribute("role","listitem"),l.append(b),u.append(Cw(g,t.sizes))}if(t.logos)r.append(Q("h2",{},"Other products' logos ",Q("small",{textContent:`${t.logos.source} · in color and muted`})),t.logos.files.length?Q("div",{className:"icons-logos"},...t.logos.files.map(Iw)):Q("p",{className:"icons-summary",textContent:"No images yet."}));let f=()=>{let g=a.value.trim().toLowerCase(),b=0;t.glyphs.forEach((y,v)=>{let L=Ow(y,g);l.children[v].hidden=u.children[v].hidden=!L,b+=L}),d.hidden=b>0,d.textContent=`No glyph matches “${a.value.trim()}”.`};if(a.addEventListener("input",f),f(),e.replaceChildren(r),r.scrollTop=n,o&&document.activeElement===document.body)a.focus();return r}var k=(e)=>document.getElementById(e),De=new URLSearchParams(location.search),CS=De.get("scenario")??De.get("category"),Nw=["brand","tokens","icons","components","patterns","composition"],Mc=!1,sn=[],be,jc=De.get("draft"),nd=[],NS=[],sd=new Map,ln=De.get("split")==="1",ed,fr=[],$t=0,Fc;async function Qi(){let e=fr;fr=[],await Promise.allSettled(e.map((t)=>t.close()))}var nt=document.createElement("button");nt.id="split-view";nt.setAttribute("aria-label","Split view");nt.setAttribute("aria-pressed","false");nt.disabled=!0;nt.title="Select a draft with an accepted version to compare";nt.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';k("viewport").before(nt);var te="brand",Ze={},IS=new Map,Wi=!0,id=[],Hc=[],Vc=[],rt,ea,fe,ye,rn,Gi,an,Lc,on,Ge=0,cn=De.get("capture")!=="1"&&De.get("viewport")==="phone",ot=[{name:"light",scheme:"light"},{name:"dark",scheme:"dark"}],Kt=De.get("capture")==="1"&&De.get("theme")||"light";if(De.get("capture")==="1")document.documentElement.dataset.capture="true";var td=()=>ot.find((e)=>e.name===Kt)?.scheme??"light";function AS(){document.documentElement.dataset.theme=td();let e=ot[(ot.findIndex((r)=>r.name===Kt)+1)%ot.length],t=ot.length>1?`Use ${e.name} theme`:`Theme: ${Kt}`;k("theme").setAttribute("aria-label",t),k("theme").title=t,k("theme").disabled=ot.length<2,k("theme").querySelector("svg").innerHTML=td()==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>'}document.documentElement.dataset.theme="light";var Qr=[],pt=De.get("capture")==="1"&&De.get("brand")||null;function qS(){let e=k("brand-select");if(e.hidden=!Qr.length,e.options.length!==Qr.length||Qr.some((t,r)=>e.options[r].value!==t.name))e.replaceChildren(...Qr.map((t)=>Object.assign(document.createElement("option"),{value:t.name,textContent:t.name})));if(pt)e.value=pt,e.title=`Brand: ${pt}`}var Xu,MS=!0,Ac=!1,Uc,rd,Jc=!1,Yi=!1,hr,Bt,Qu=0,Ki,eo=new AbortController,Ct=new uS({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),jS=(e,t={},r={})=>Ct.callTool({name:e,arguments:t},{signal:eo.signal,...r}),Zc=zS((e)=>Ct.readResource(e,{signal:eo.signal}),{signal:eo.signal,onDiagnostic:(e)=>{if(e.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",e)}}),ad=async(e)=>JSON.parse((await Zc({uri:e})).contents.find((t)=>typeof t.text==="string").text);function LS(e){let t=Vc.find((r)=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return Ct.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(k("preview-error").hidden=!t,k("preview-error-message").textContent=t?o.split(`
|
|
120
120
|
`)[0]:"",k("preview-error-message").title=t?o:"",k("status").textContent=o,k("status").dataset.error=String(t),!t)for(let n of["errorCategory","errorCode","resourceUri"])delete k("status").dataset[n];if(t)k("status").removeAttribute("role");else k("status").setAttribute("role","status");k("preview-status").dataset.phase=r,k("preview-status").title=o,k("preview-status").setAttribute("aria-label",`Preview status: ${o.split(`
|
|
121
121
|
`)[0]}`),US()}function US(){let e=ea?.warmup,t=e?`Background views: ${e.completed}/${e.total} compiled${e.failed?`; ${e.failed} failed`:""}.`:"";k("warmup-status").hidden=!e,k("warmup-status").textContent=t,k("preview-status").dataset.warmup=e?.state??"disabled",k("preview-status").title=[k("status").textContent,t].filter(Boolean).join(`
|
|
122
122
|
`)}function ZS(){Se(fe?"Updating preview…":"Opening preview…",!1,"reloading")}function un(){return ta().find((e)=>e.id===Ze[te])}function dn(e=un()){let t=sn.find((r)=>r.id===jc&&sd.get(r.id)?.scenario===e?.id);return e?.drafts?.find((r)=>r.id===jc)??t??e?.drafts?.[0]}function cd(){return Boolean(dn()&&(un()?.draftOnly||ln))}function Xi(){return`${te}:${Ze[te]}${cd()?`:draft:${dn().id}`:""}`}function qc(e=fe){return e?.key===Xi()}function DS(e=ea){if(cd()){let t=e?.drafts?.find((r)=>r.id===dn()?.id);return t?.scenarios?.find((r)=>r.id===Ze[te])??t}return e?.previews?.find((t)=>t.id===Ze[te])}var FS=(e)=>JSON.stringify(e&&[e.session,e.revision,e.current,e.live]);function HS(){({scenarios:Hc,categories:id}=PS(nd,NS,sn,sd))}function Aw(e){sd.set(e.structuredContent.id,e.structuredContent),HS()}async function od(e,t,r=eo.signal){let o=(rt?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await jS(e,t,{signal:AbortSignal.any([eo.signal,r]),timeout:o})}catch(n){if(n.code!=="REQUEST_TIMEOUT")throw n;throw Object.assign(Error(`The preview request timed out after ${Math.ceil(o/1000)} seconds. No preview result was received. Retry the preview.`,{cause:n}),{code:"ADS_PREVIEW_REQUEST_TIMEOUT",category:"transport"})}}async function ld(e,t,r){let o=un()?.id===t&&un().pendingDraftScenario||e.units?.includes(t)&&!nd.some((i)=>i.id===t),n=await od("ads_show_draft",{id:e.id,...!o&&t?{scenario:t}:{}},r);if(n.isError)throw Error(n.content?.find((i)=>i.type==="text")?.text??"Draft preview failed.");if(o){let i=n.structuredContent.scenarios.find((s)=>t==="tokens"?s.kind==="tokens":s.unit?s.unit===t:Ku(t,s.id));if(!i)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(i.id!==n.structuredContent.scenario)n=await od("ads_show_draft",{id:e.id,scenario:i.id},r);if(n.isError)throw Error(n.content?.find((s)=>s.type==="text")?.text??"Draft preview failed.")}return Aw(n),n}function Wt(e=!1){if(e)on=fe?.key;an=void 0,k("loader").hidden=!0,k("preview").setAttribute("aria-busy","false")}function OS(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split","section"])t.searchParams.delete(n);if(te==="icons")return t.searchParams.set("section","icons"),t.pathname+t.search+t.hash;if(e)t.searchParams.set("scenario",e);let r=ta().find((n)=>n.id===e),o=dn(r);if(o&&(r.draftOnly||ln)){if(t.searchParams.set("draft",o.id),!r.draftOnly)t.searchParams.set("split","1")}return t.pathname+t.search+t.hash}function ta(){return te==="tokens"?id:te==="icons"?[]:Hc.filter((e)=>e.kind===te)}function VS(e,t){let{state:r,label:o}=TS(t,ea,jc),n=e.querySelector(".entry-preview");if(!n)n=document.createElement("span"),n.className="entry-preview",n.setAttribute("aria-hidden","true"),e.append(n);n.dataset.state=r,n.title=o,n.innerHTML=`<svg viewBox="0 0 16 16">${ES[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}var nn=!1;function to(){return{theme:td(),adsTheme:Kt,...pt?{adsBrand:pt}:{},gridOverlay:nn,displayMode:"inline",containerDimensions:{width:k("frame-slot").clientWidth,height:k("frame-slot").clientHeight}}}function ra(){let e=Hc.some((n)=>n.kind==="brand");if(k("sections").querySelector('[data-section="brand"]').hidden=!e,te==="brand"&&!e)te="tokens";if(k("sections").querySelector('[data-section="icons"]').hidden=!rt?.icons,te==="icons"&&!rt?.icons)te="tokens";document.body.dataset.activeSection=te;let t=ta();if(!t.some((n)=>n.id===Ze[te]))Ze[te]=t[0]?.id??null;history.replaceState(null,"",OS(Ze[te]));let r=k("sidebar").scrollTop;k("entries").setAttribute("aria-label",te[0].toUpperCase()+te.slice(1));let o=(n)=>{let i=document.createElement("a");if(i.textContent=n.title,n.drafts?.length){let s=document.createElement("span");s.className="draft-badge",s.textContent=n.drafts.length>1?`Drafts ${n.drafts.length}`:"Draft",s.title=n.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",i.append(" ",s)}if(i.href=OS(n.id),i.dataset.scenario=n.id,VS(i,n),n.id===Ze[te])i.setAttribute("aria-current","page");return i.addEventListener("click",(s)=>{if(s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey)return;s.preventDefault(),Ze[te]=n.id,ra(),Gt().catch(ht)}),i};k("entries").replaceChildren(...wS(t).flatMap((n)=>{if(!n.label)return n.entries.map(o);let i=`${te}:${n.label}`,s=document.createElement("details");s.className="entry-group",s.open=IS.get(i)??!0;let a=document.createElement("summary");a.textContent=n.label;let l=document.createElement("div");return l.setAttribute("role","group"),l.setAttribute("aria-label",n.label),l.append(...n.entries.map(o)),s.append(a,l),s.addEventListener("toggle",()=>{if(s.isConnected)IS.set(i,s.open)}),[s]})),k("sidebar").scrollTop=r;for(let n of k("sections").querySelectorAll("button"))if(n.dataset.section===te)n.setAttribute("aria-current","page");else n.removeAttribute("aria-current");Dc()}function ht(e){if(!Jc&&!Yi)Wt(),k("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),k("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Se(`${e.message}${fe?`
|
package/dist/showcase/icons.js
CHANGED
|
@@ -77,7 +77,7 @@ function card(item, sizes) {
|
|
|
77
77
|
if (item.grid) magnified.append(grid(item.grid));
|
|
78
78
|
magnified.append(glyph(item, 96));
|
|
79
79
|
const scale = element("div", { className: "icons-sizes" }, ...sizes.map(size => element("span", { className: "icons-size" }, glyph(item, size.px), element("small", { textContent: String(size.px), title: size.token }))));
|
|
80
|
-
article.append(...[header,
|
|
80
|
+
article.append(...[header, element("p", { className: "icons-alias", textContent: item.aliases.length ? `alias: ${item.aliases.join(", ")}` : "", title: item.aliases.join(", ") }), magnified, scale, ...item.findings.map(findingBox)].filter(Boolean));
|
|
81
81
|
article.setAttribute("aria-label", item.name);
|
|
82
82
|
return article;
|
|
83
83
|
}
|
package/dist/showcase/style.css
CHANGED
|
@@ -39,7 +39,7 @@ body[data-active-section="icons"] #sidebar{display:none}
|
|
|
39
39
|
.icons-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(200px,100%),1fr));gap:12px;align-items:start}
|
|
40
40
|
.icons-card{min-width:0;background:var(--icons-surface);border:1px solid var(--frame-line);border-radius:12px;padding:12px 14px}.icons-card[data-findings]{border-color:var(--icons-error)}
|
|
41
41
|
.icons-card-head{display:flex;gap:8px;align-items:center;justify-content:space-between}.icons-card h3{margin:0;font:600 14px/1.4 ui-monospace,SFMono-Regular,Consolas,monospace;overflow-wrap:anywhere}
|
|
42
|
-
.icons-badge{flex:none;background:var(--icons-error-bg);color:var(--icons-error);border-radius:999px;font-size:11px;font-weight:600;padding:1px 8px}.icons-alias{margin:2px 0 0;font-size:12px;color:var(--icons-muted);overflow-wrap:anywhere}
|
|
42
|
+
.icons-badge{flex:none;background:var(--icons-error-bg);color:var(--icons-error);border-radius:999px;font-size:11px;font-weight:600;padding:1px 8px}.icons-alias{margin:2px 0 0;font-size:12px;line-height:1.4;min-height:1.4em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--icons-muted);overflow-wrap:anywhere}
|
|
43
43
|
.icons-mag{position:relative;width:96px;height:96px;margin:10px auto;background:var(--icons-grid-bg)}.icons-mag>.icons-grid{position:absolute;inset:0;width:100%;height:100%}.icons-mag>.icons-glyph{position:absolute;inset:0}
|
|
44
44
|
.icons-grid line{stroke:var(--icons-grid);stroke-width:.5px;vector-effect:non-scaling-stroke}.icons-grid line.mid{stroke:var(--icons-grid-mid);stroke-width:1px}
|
|
45
45
|
.icons-sizes{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;justify-content:center}.icons-size{display:flex;flex-direction:column;align-items:center;gap:2px}.icons-size small{font-size:10px;color:var(--icons-muted)}
|
|
@@ -92,7 +92,7 @@ keeps independent component token definitions valid.
|
|
|
92
92
|
|
|
93
93
|
## Accessibility and rhythm checks
|
|
94
94
|
|
|
95
|
-
`ads check` checks token values in every theme and brand. Each finding below is an error:
|
|
95
|
+
`ads check` checks token values in every theme and brand. Each finding below is an error unless marked info:
|
|
96
96
|
|
|
97
97
|
- `token-contrast`: the roles that meet on screen fall below WCAG 2.2 AA: `--text-strong`,
|
|
98
98
|
`--text-body`, `--text-muted`, `--text-link` and `--accent-text` on `--bg-canvas`,
|
|
@@ -100,6 +100,13 @@ keeps independent component token definitions valid.
|
|
|
100
100
|
status's `-fg` on its solid and `-text` on its `-bg` (4.5:1); `--border-focus` and
|
|
101
101
|
`--border-strong` on the canvas and surface (3:1). Fix it by choosing a different ramp
|
|
102
102
|
step for the role, in the theme the message names, never with a one-off color.
|
|
103
|
+
Any CSS color is evaluated (hex, named, `rgb()`, `hsl()`, `hwb()`, `lab()`, `lch()`,
|
|
104
|
+
`oklab()`, `oklch()`, `color()`, `color-mix()`, `light-dark()`), through halves and
|
|
105
|
+
aliases. A translucent background counts as composited over `--bg-canvas`, a translucent
|
|
106
|
+
foreground as composited over its background.
|
|
107
|
+
- `token-contrast-unresolved` (info): a pair color ADS cannot resolve statically
|
|
108
|
+
(`currentColor`, relative color syntax, a system color), so that pair is not checked. Give
|
|
109
|
+
the role a color or a ramp step, or check the pages that use it with `ads audit`.
|
|
103
110
|
- `token-rhythm`: a numbered spacing step leaves the scale `--space-N` = N × 2 px.
|
|
104
111
|
- `control-padding`: pad a control with the token for its size. A block sized with
|
|
105
112
|
`--control-height-<size>` pads its sides with `--control-padding-<size>`; the small gap
|
|
@@ -152,7 +152,9 @@ current rendered revision and complete acceptance before finishing the change.
|
|
|
152
152
|
After rendered review, call `ads_accept({id,revision})` once. It checks that exact
|
|
153
153
|
revision, runs mandatory ADS guards plus `acceptance.checks` and, when
|
|
154
154
|
`acceptance.behaviorChecks` is enabled, affected registered behavior checks against an isolated candidate, and applies passing changes at
|
|
155
|
-
their normal paths.
|
|
155
|
+
their normal paths. When `acceptance.browserAudit` is enabled it also runs the axe-core
|
|
156
|
+
audit on the candidate's affected UI scenarios; an `a11y-axe` error rejects the draft.
|
|
157
|
+
Fix it in the component and accept the new revision. Changes during checking or baseline conflicts prevent
|
|
156
158
|
application. Successful acceptance removes the proposal and records an event.
|
|
157
159
|
There is no separate Apply or Iterate action. A failed attempt retains the draft;
|
|
158
160
|
inspect its returned resultId with `ads_results` and fix the reported boundary.
|
|
@@ -23,8 +23,9 @@ ads_apply_patch({"unit":"components/Example","patchFile":"<returned patchFile>",
|
|
|
23
23
|
The dry run validates the candidate in an isolated project copy using mandatory
|
|
24
24
|
ADS guards, `acceptance.checks` and, when `acceptance.behaviorChecks` is enabled,
|
|
25
25
|
affected registered behavior checks. Registration alone does not require a test
|
|
26
|
-
at acceptance.
|
|
27
|
-
|
|
26
|
+
at acceptance. With `acceptance.browserAudit`, axe-core also audits the candidate's
|
|
27
|
+
affected UI scenarios; `a11y-axe` errors reject the patch. See [validation policies](validation.md).
|
|
28
|
+
Configured browser checks use that candidate's managed preview, not the live showcase. Read the summary, then page failing
|
|
28
29
|
`outcomes`, `diagnostics` or pipeline `checks` through `ads_results` with its
|
|
29
30
|
`resultId`. Inspect one exact outcome with `ads_investigate({unit,check,runId})`;
|
|
30
31
|
fix the draft and diff again. See [evidence.md](evidence.md) for page/range limits.
|
|
@@ -43,7 +43,12 @@ implicitly requiring them at acceptance.
|
|
|
43
43
|
owners while project scripts and core gates retain full scope.
|
|
44
44
|
- `browserAudit: true` in either policy adds the axe-core audit of every rendered
|
|
45
45
|
UI scenario in every brand and theme (`browser-accessibility-audit`). Its `a11y-axe`
|
|
46
|
-
findings are errors that fail the policy
|
|
46
|
+
findings are errors that fail the policy. With `acceptance.browserAudit`, draft
|
|
47
|
+
acceptance and guarded patches/transactions audit the candidate's affected UI
|
|
48
|
+
scenarios (all after configuration, foundation, token or asset changes) and reject
|
|
49
|
+
the change on any `a11y-axe` error or a `browser-audit` failure to run. Declare
|
|
50
|
+
`"sideEffects": ["**/*.css"]` in the project's `package.json`, as the starters do, so a
|
|
51
|
+
component change audits only the scenarios that import it. See
|
|
47
52
|
ads://guides/accessibility.
|
|
48
53
|
- Draft create, edit and show are preview-only; they trigger neither policy.
|
|
49
54
|
`ads_verify` explicitly runs selected checks independently of either policy.
|
|
@@ -10,7 +10,7 @@ Each message names its WCAG criterion.
|
|
|
10
10
|
|
|
11
11
|
| Rule | What it reviews | WCAG |
|
|
12
12
|
|---|---|---|
|
|
13
|
-
| `token-contrast` | Text, link, accent and status text on their backgrounds (4.5:1); focus and control borders on canvas and surface (3:1); in every theme and brand | 1.4.3, 1.4.11 |
|
|
13
|
+
| `token-contrast` | Text, link, accent and status text on their backgrounds (4.5:1); focus and control borders on canvas and surface (3:1); in every theme and brand, for any CSS color syntax, with translucent colors composited over their background and the canvas. A pair color that cannot be resolved statically (`currentColor`, relative color syntax) is a `token-contrast-unresolved` info item | 1.4.3, 1.4.11 |
|
|
14
14
|
| `a11y-target-size` | `--control-height-*` of at least 24 px (44 px where touch is common) | 2.5.8 |
|
|
15
15
|
| `a11y-focus` | `--focus-w` of at least 2 px, and a `:focus-visible` indicator in `base.css` | 2.4.7, 2.4.13 |
|
|
16
16
|
| `a11y-text-resize` | Font-size tokens in `rem`, so text follows the reader's browser font size | 1.4.4 |
|
|
@@ -49,7 +49,9 @@ design-system/components/Broken.scenario.tsx:1:1 [error:a11y-axe] axe button-nam
|
|
|
49
49
|
- Token and brand scenarios are skipped; name one with `--scenario` to audit it.
|
|
50
50
|
- To run the audit in `ads validate`/`ads_validate`, set `browserAudit: true` in that
|
|
51
51
|
policy (`validation` or `acceptance`); its findings then fail that policy, as they fail
|
|
52
|
-
`ads audit`.
|
|
52
|
+
`ads audit`. With `acceptance.browserAudit`, `ads_accept`, `ads_apply_patch` and
|
|
53
|
+
`ads_apply_transaction` also audit the candidate's affected scenarios and reject the
|
|
54
|
+
change on any `a11y-axe` error; read the findings with `ads_results` (`diagnostics`).
|
|
53
55
|
- It needs the project's Playwright and browser, as captures do (`mcp.capture`).
|
|
54
56
|
|
|
55
57
|
A clean audit is not a pass: automated rules find only part of the WCAG failures. Keep the
|
|
@@ -92,7 +92,7 @@ keeps independent component token definitions valid.
|
|
|
92
92
|
|
|
93
93
|
## Accessibility and rhythm checks
|
|
94
94
|
|
|
95
|
-
`ads check` checks token values in every theme and brand. Each finding below is an error:
|
|
95
|
+
`ads check` checks token values in every theme and brand. Each finding below is an error unless marked info:
|
|
96
96
|
|
|
97
97
|
- `token-contrast`: the roles that meet on screen fall below WCAG 2.2 AA: `--text-strong`,
|
|
98
98
|
`--text-body`, `--text-muted`, `--text-link` and `--accent-text` on `--bg-canvas`,
|
|
@@ -100,6 +100,13 @@ keeps independent component token definitions valid.
|
|
|
100
100
|
status's `-fg` on its solid and `-text` on its `-bg` (4.5:1); `--border-focus` and
|
|
101
101
|
`--border-strong` on the canvas and surface (3:1). Fix it by choosing a different ramp
|
|
102
102
|
step for the role, in the theme the message names, never with a one-off color.
|
|
103
|
+
Any CSS color is evaluated (hex, named, `rgb()`, `hsl()`, `hwb()`, `lab()`, `lch()`,
|
|
104
|
+
`oklab()`, `oklch()`, `color()`, `color-mix()`, `light-dark()`), through halves and
|
|
105
|
+
aliases. A translucent background counts as composited over `--bg-canvas`, a translucent
|
|
106
|
+
foreground as composited over its background.
|
|
107
|
+
- `token-contrast-unresolved` (info): a pair color ADS cannot resolve statically
|
|
108
|
+
(`currentColor`, relative color syntax, a system color), so that pair is not checked. Give
|
|
109
|
+
the role a color or a ramp step, or check the pages that use it with `ads audit`.
|
|
103
110
|
- `token-rhythm`: a numbered spacing step leaves the scale `--space-N` = N × 2 px.
|
|
104
111
|
- `control-padding`: pad a control with the token for its size. A block sized with
|
|
105
112
|
`--control-height-<size>` pads its sides with `--control-padding-<size>`; the small gap
|