@reqvire-org/ads 0.3.26 → 0.3.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +21 -10
  2. package/dist/bootstrap-ds/README.md +7 -5
  3. package/dist/bootstrap-ds/ds.config.json +1 -1
  4. package/dist/bootstrap-ds/scripts/build-mcp-previews.mjs +7 -8
  5. package/dist/capture.mjs +1 -1
  6. package/dist/development-runtime.mjs +17 -0
  7. package/dist/index.mjs +1 -1
  8. package/dist/init.mjs +14 -12
  9. package/dist/mcp/apps.mjs +1 -1
  10. package/dist/mcp/context.mjs +5 -4
  11. package/dist/mcp/mutations.mjs +3 -2
  12. package/dist/mcp/preview-watch.mjs +2 -1
  13. package/dist/mcp/preview-widget.bundle.js +6 -6
  14. package/dist/mcp/project-widget.bundle.js +13 -13
  15. package/dist/mcp/resource-loader.js +10 -1
  16. package/dist/mcp/server.mjs +11 -4
  17. package/dist/mcp/widget.bundle.js +1 -1
  18. package/dist/preview-builder.mjs +108 -0
  19. package/dist/preview-files.mjs +33 -0
  20. package/dist/preview-inputs.mjs +14 -6
  21. package/dist/scenario-groups.mjs +47 -0
  22. package/dist/scenarios-compiler.mjs +10 -9
  23. package/dist/scenarios-vite.mjs +13 -5
  24. package/dist/scenarios.mjs +4 -1
  25. package/dist/showcase/client.bundle.js +21 -21
  26. package/dist/showcase/navigation.js +13 -0
  27. package/dist/showcase/sandbox.bundle.js +1 -1
  28. package/dist/showcase/style.css +1 -0
  29. package/dist/skills/README.md +7 -1
  30. package/dist/skills/ads-break-ui/SKILL.md +7 -3
  31. package/dist/skills/ads-break-ui/references/behaviors.md +6 -3
  32. package/dist/skills/ads-break-ui/references/layers.md +16 -0
  33. package/dist/skills/ads-break-ui/references/runtimes.md +127 -0
  34. package/dist/skills/ads-break-ui/references/scenarios.md +19 -0
  35. package/dist/skills/ads-designer/README.md +6 -0
  36. package/dist/skills/ads-designer/SKILL.md +11 -6
  37. package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +7 -5
  38. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -1
  39. package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +7 -8
  40. package/dist/skills/ads-designer/references/behaviors.md +6 -3
  41. package/dist/skills/ads-designer/references/cli.md +10 -7
  42. package/dist/skills/ads-designer/references/design-craft.md +31 -0
  43. package/dist/skills/ads-designer/references/layers.md +16 -0
  44. package/dist/skills/ads-designer/references/runtimes.md +127 -0
  45. package/dist/skills/ads-designer/references/scenarios.md +19 -0
  46. package/dist/skills/ads-import/SKILL.md +24 -4
  47. package/dist/skills/ads-import/agents/openai.yaml +2 -2
  48. package/dist/skills/ads-import/references/behaviors.md +6 -3
  49. package/dist/skills/ads-import/references/cli.md +10 -7
  50. package/dist/skills/ads-import/references/compatibility.md +113 -0
  51. package/dist/skills/ads-import/references/implementation.md +6 -0
  52. package/dist/skills/ads-import/references/layers.md +16 -0
  53. package/dist/skills/ads-import/references/runtimes.md +127 -0
  54. package/dist/skills/ads-import/references/scenarios.md +19 -0
  55. package/dist/skills/ads-motion/SKILL.md +7 -3
  56. package/dist/skills/ads-motion/references/behaviors.md +6 -3
  57. package/dist/skills/ads-motion/references/layers.md +16 -0
  58. package/dist/skills/ads-motion/references/runtimes.md +127 -0
  59. package/dist/skills/ads-motion/references/scenarios.md +19 -0
  60. package/dist/skills/ads-port/SKILL.md +7 -3
  61. package/dist/skills/ads-port/references/behaviors.md +6 -3
  62. package/dist/skills/ads-port/references/cli.md +10 -7
  63. package/dist/skills/ads-port/references/layers.md +16 -0
  64. package/dist/skills/ads-port/references/runtimes.md +127 -0
  65. package/dist/skills/ads-port/references/scenarios.md +19 -0
  66. package/dist/verification.mjs +4 -3
  67. package/docs/ADS.md +29 -2
  68. package/docs/ARCHITECTURE.md +85 -3
  69. package/docs/BEHAVIORS.md +13 -3
  70. package/docs/CHANGELOG.md +38 -1
  71. package/docs/COMPARISON.md +63 -0
  72. package/docs/GUIDE.md +51 -10
  73. package/docs/MCP.md +104 -14
  74. package/package.json +5 -4
@@ -115,9 +115,16 @@ export class PreviewResourceLoader {
115
115
  this.register(manifest);
116
116
  const scenario = manifest.scenarios.find(entry => entry.id === id);
117
117
  if (!scenario) throw new Error("The selected scenario is no longer registered.");
118
+ const signature = JSON.stringify(this.closure(scenario.module).map(uri => [uri, this.records.get(uri)]));
119
+ // A successful global graph revision may only affect another scenario.
120
+ // Retain this view's form/scroll state, then let the caller rerun its audits.
121
+ if (this.mounted?.id === id && this.mounted.container === container && this.mounted.signature === signature) return true;
118
122
  const module = await this.importModule(scenario.module);
119
123
  if (generation !== this.generation) return false;
120
- await this.unmount?.();
124
+ const unmount = this.unmount;
125
+ this.unmount = undefined;
126
+ this.mounted = undefined;
127
+ await unmount?.();
121
128
  if (generation !== this.generation || this.closed) return false;
122
129
  container.replaceChildren();
123
130
  const keep = new Set(this.closure(scenario.module));
@@ -126,6 +133,7 @@ export class PreviewResourceLoader {
126
133
  if (typeof module.mount !== "function") throw new Error("The compiled scenario has no mount adapter.");
127
134
  this.unmount = module.mount(container);
128
135
  if (typeof this.unmount !== "function") throw new Error("The scenario mount adapter must return an unmount callback.");
136
+ this.mounted = { id, container, signature };
129
137
  return true;
130
138
  }
131
139
  async dispose() {
@@ -133,6 +141,7 @@ export class PreviewResourceLoader {
133
141
  this.closed = true;
134
142
  ++this.generation;
135
143
  await this.unmount?.();
144
+ this.mounted = undefined;
136
145
  for (const style of this.styles.values()) style.remove();
137
146
  for (const url of this.urls.values()) URL.revokeObjectURL(url);
138
147
  this.styles.clear(); this.styleReady.clear(); this.urls.clear(); this.bytes.clear(); this.records.clear();
@@ -10,6 +10,7 @@ import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigatio
10
10
  import { failure } from "../evidence.mjs";
11
11
  import { inspectTokens } from "../tokens.mjs";
12
12
  import { inspectScenarios } from "../scenarios.mjs";
13
+ import { scenarioGroupFingerprint } from "../scenario-groups.mjs";
13
14
  import { startShowcaseHost } from "./showcase-host.mjs";
14
15
  import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
15
16
  import { inspectCatalog, projectDocuments, PROJECT_URI, readProjectDocument } from "./catalog.mjs";
@@ -31,6 +32,7 @@ import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
31
32
  import { compactProgress, resultBudgets } from "./result-pages.mjs";
32
33
  import { createReportStore, bugReportSchema, featureRequestSchema } from "./reports.mjs";
33
34
  import { createHash } from "node:crypto";
35
+ import { developmentRuntime } from "../development-runtime.mjs";
34
36
 
35
37
  const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
36
38
  class InvalidParamsError extends ProtocolError {
@@ -119,7 +121,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
119
121
 
120
122
  function reportContext(submission) {
121
123
  const captured = { ads: { package: pkg.name, version: pkg.version }, capturedAt: new Date().toISOString(), framework: null,
122
- runtime: { node: process.version, platform: process.platform, arch: process.arch }, warnings: [] };
124
+ runtime: { ...developmentRuntime(), platform: process.platform, arch: process.arch }, warnings: [] };
123
125
  try { const current=loadConfig(root);captured.framework=current.config.framework;captured.configurationRevision=createHash("sha256").update(JSON.stringify(current.config)).digest("hex");captured.sourceRevision=previewSourceRevision(current); }
124
126
  catch { captured.warnings.push("Current configuration/source revision could not be captured."); }
125
127
  try{const projectPackage=JSON.parse(readFileSync(path.join(root,"package.json"),"utf8"));if(typeof projectPackage.name==="string")captured.project={name:projectPackage.name.slice(0,160)};}catch{captured.warnings.push("Project package name could not be captured.");}
@@ -150,6 +152,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
150
152
  return [
151
153
  { uri: GUIDE_URI, name: "Start here: design-system workflow", description: "Read first for UI/ADS tasks, especially when only resource access is exposed. Explains the exact workspace, tool sequence, skill selection, previews, project commands and fallback.", mimeType: "text/markdown" },
152
154
  { uri: "ads://guides/behaviors", name: "Controller and behavioral verification guide", mimeType: "text/markdown" },
155
+ { uri: "ads://guides/runtimes", name: "Node and Bun setup, compiler and verification runtime", mimeType: "text/markdown" },
153
156
  { uri: "ads://guides/evidence", name: "Failure boundaries and compact investigations", mimeType: "text/markdown" },
154
157
  { uri: "ads://guides/atomic-styles", name: "Atomic styles: composition conflicts and custom-property extraction", mimeType: "text/markdown" },
155
158
  { uri: "ads://guides/scenarios", name: "Scenario coverage and public class-helper contracts", mimeType: "text/markdown" },
@@ -201,6 +204,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
201
204
  async function read(uri, signal) {
202
205
  if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
203
206
  if (uri === "ads://guides/behaviors") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/behaviors.md", import.meta.url), "utf8") }] };
207
+ if (uri === "ads://guides/runtimes") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/runtimes.md", import.meta.url), "utf8") }] };
204
208
  if (uri === "ads://guides/evidence") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/evidence.md", import.meta.url), "utf8") }] };
205
209
  if (uri === "ads://guides/tokens") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/design-data.md", import.meta.url), "utf8") }] };
206
210
  if (uri === "ads://guides/reporting") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/reporting.md", import.meta.url), "utf8") }] };
@@ -291,8 +295,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
291
295
  const units = edits.units();
292
296
  return json({ total: matches.length, items: matches.slice(0, limit).map(item => ({ ...item, unit: units.find(unit => unit.files.includes(item.file))?.id ?? null })), resourceUri: `${PROJECT_URI}/catalog` });
293
297
  } },
294
- { name: "ads_scenarios", description: "Find an independently mountable token, component, pattern or composition preview. IDs derive from source filenames; covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.", schema: query.extend({ kind: z.enum(["tokens", "components", "patterns", "composition"]).optional(), offset: z.number().int().min(0).default(0) }), call: ({ query: search = "", limit, kind, offset }) => {
295
- const matches = getRegistry().scenarios.filter(item => (!kind || item.kind === kind) && `${item.id} ${item.title} ${item.covers.join(" ")} ${(item.exercises ?? []).join(" ")} ${item.tokens.join(" ")}`.toLowerCase().includes(search.toLowerCase()));
298
+ { name: "ads_scenarios", description: "Find an independently mountable token, component, pattern or composition preview. IDs derive from source filenames. Optional group labels are derived from folder names and searchable; group is discovery output, never scenario metadata. covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.", schema: query.extend({ kind: z.enum(["tokens", "components", "patterns", "composition"]).optional(), offset: z.number().int().min(0).default(0) }), call: ({ query: search = "", limit, kind, offset }) => {
299
+ const matches = getRegistry().scenarios.filter(item => (!kind || item.kind === kind) && `${item.id} ${item.title} ${item.group ?? ""} ${item.covers.join(" ")} ${(item.exercises ?? []).join(" ")} ${item.tokens.join(" ")}`.toLowerCase().includes(search.toLowerCase()));
296
300
  const units = edits.units();
297
301
  return json({ total: matches.length, scenarios: matches.slice(offset, offset + limit).map(item => ({ ...item, unit: units.find(unit => unit.files.includes(item.file))?.id ?? null })), ...(offset + limit < matches.length ? { nextOffset: offset + limit } : {}), diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios` });
298
302
  } },
@@ -444,7 +448,10 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
444
448
  try { const stat = statSync(file); return `${file}:${stat.mtimeMs}:${stat.size}`; } catch { return `${file}:missing`; }
445
449
  }).join("\n");
446
450
  }
447
- const fingerprint = () => fileFingerprint([...sourceFiles(options.dsRoot), ...getDocuments().map((doc) => doc.file), path.join(root, "ds.config.json"), path.join(root, "package.json"), path.join(root, ".ds/behavior-results.json")]);
451
+ const fingerprint = () => {
452
+ const sources = sourceFiles(options.dsRoot);
453
+ return `${fileFingerprint([...sources, ...getDocuments().map(doc => doc.file), path.join(root, "ds.config.json"), path.join(root, "package.json"), path.join(root, ".ds/behavior-results.json")])}\n${scenarioGroupFingerprint(options, sources)}`;
454
+ };
448
455
  const artifactFingerprint = () => fileFingerprint(allApps().map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
449
456
  const assetFingerprint = () => resourceAssets().map(asset => asset.uri).sort().join("\n");
450
457
  let previous = fingerprint();
@@ -138,7 +138,7 @@ Boolean requesting whether a visible border and background is provided by the ho
138
138
  - omitted: host decides border`)}),q_=i.object({method:i.literal("ui/request-display-mode"),params:i.object({mode:Sa.describe("The display mode being requested.")})}),N_=i.object({mode:Sa.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),wR=i.union([i.literal("model"),i.literal("app")]).describe("Tool visibility scope - who can access the tool."),KT=i.object({resourceUri:i.string().optional(),visibility:i.array(wR).optional().describe(`Who can access this tool. Default: ["model", "app"]
139
139
  - "model": Tool visible to and callable by the agent
140
140
  - "app": Tool callable by the app from this server only`),csp:i.never().optional(),permissions:i.never().optional()}),GT=i.object({mimeTypes:i.array(i.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),xR=i.object({method:i.literal("ui/download-file"),params:i.object({contents:i.array(i.union([ht,mt])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),TR=i.object({method:i.literal("ui/message"),params:i.object({role:i.literal("user").describe('Message role, currently only "user" is supported.'),content:i.array(Ee).describe("Message content blocks (text, image, etc.).")})}),YT=i.object({method:i.literal("ui/notifications/sandbox-resource-ready"),params:i.object({html:i.string().describe("HTML content to load into the inner iframe."),sandbox:i.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Ef.optional().describe("CSP configuration from resource metadata."),permissions:kf.optional().describe("Sandbox permissions from resource metadata.")})}),QT=i.object({method:i.literal("ui/notifications/tool-result"),params:Ye.describe("Standard MCP tool execution result.")}),j_=i.object({toolInfo:i.object({id:Te.optional().describe("JSON-RPC id of the tools/call request."),tool:Ge.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:cR.optional().describe("Current color theme preference."),styles:_R.optional().describe("Style configuration for theming the app."),displayMode:Sa.optional().describe("How the UI is currently displayed."),availableDisplayModes:i.array(Sa).optional().describe("Display modes the host supports."),containerDimensions:i.union([i.object({height:i.number().describe("Fixed container height in pixels.")}),i.object({maxHeight:i.union([i.number(),i.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(i.union([i.object({width:i.number().describe("Fixed container width in pixels.")}),i.object({maxWidth:i.union([i.number(),i.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
141
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:i.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:i.string().optional().describe("User's timezone in IANA format."),userAgent:i.string().optional().describe("Host application identifier."),platform:i.union([i.literal("web"),i.literal("desktop"),i.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:i.object({touch:i.boolean().optional().describe("Whether the device supports touch input."),hover:i.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:i.object({top:i.number().describe("Top safe area inset in pixels."),right:i.number().describe("Right safe area inset in pixels."),bottom:i.number().describe("Bottom safe area inset in pixels."),left:i.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),XT=i.object({method:i.literal("ui/notifications/host-context-changed"),params:j_.describe("Partial context update containing only changed fields.")}),PR=i.object({method:i.literal("ui/update-model-context"),params:i.object({content:i.array(Ee).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:i.record(i.string(),i.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),ER=i.object({method:i.literal("ui/initialize"),params:i.object({appInfo:Pe.describe("App identification (name and version)."),appCapabilities:zR.describe("Features and capabilities this app provides."),protocolVersion:i.string().describe("Protocol version this app supports.")})}),kR=i.object({protocolVersion:i.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Pe.describe("Host application identification and version."),hostCapabilities:vR.describe("Features and capabilities provided by the host."),hostContext:j_.describe("Rich context about the host environment.")}).passthrough();var Ql=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,o){this.eventTarget=t,this.eventSource=o,this.messageListener=r=>{if(o&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let n=ct.safeParse(r.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,r):(console.error("Failed to parse message",n.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,o){t.method!==aR&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var $R=[A_],Xl=class extends ma{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Tf;_methods=new Pf;setRequestHandler=(...t)=>{let[o,...r]=O_("request",t)??t;this._methods.claim(o,"setRequestHandler"),super.setRequestHandler.call(this,o,...r)};setNotificationHandler=(...t)=>{let[o,...r]=O_("notification",t)??t;this._methods.claim(o,"setNotificationHandler"),super.setNotificationHandler.call(this,o,...r)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...o)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...o)};_wrapHandler(t,o){let r=super._wrapHandler(t,o);return t==="ui/initialize"||t==="ping"?r:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),r(n,s))}eventSchemas={sizechange:gR,sandboxready:fR,initialized:RR,requestteardown:yR,loggingmessage:bo};setEventHandler(t,o){this._ensureEventSlot(t),this._events.setHandler(t,o)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,o){this._ensureEventSlot(t),this._events.addEventListener(t,o)}removeEventListener(t,o){this._events.removeEventListener(t,o)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let o=this.eventSchemas[t];if(!o)throw Error(`Unknown event: ${String(t)}`);let r=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{r(n.params)}):this.setNotificationHandler(o.shape.method.value,{params:o.shape.params},n=>r(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,o,r){o&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,o,r,n){super(n),this._client=t,this._hostInfo=o,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:ER.shape.params,result:kR},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,a)=>(this.onping?.(s.params,a),{})),this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:TR.shape.params,result:mR},async(o,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(o,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:dR.shape.params,result:pR},async(o,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(o,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:xR.shape.params,result:hR},async(o,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(o,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},async(o,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(o,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:PR.shape.params,result:We},async(o,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(o,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(o,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(o,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(o.params,r)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(o,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(o.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(o,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(o.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(o,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(o.params,r)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(o,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(o.params,r)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let o=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:$R.includes(o)?o:A_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let o={},r=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],a=t[n];CR(s,a)||(o[n]=a,r=!0)}r&&(this._hostContext=t,this.sendHostContextChange(o))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,o){return this.request({method:"ui/resource-teardown",params:t},bR,o)}sendResourceTeardown=this.teardownResource;callTool(t,o){return this.request({method:"tools/call",params:t},o)}listTools(t,o){return this.request({method:"tools/list",params:t},o)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let o=this._client.getServerCapabilities();if(!o)throw Error("Client server capabilities not available");o.tools&&(this.oncalltool=async(r,n)=>this._client.request({method:"tools/call",params:r},{signal:n.mcpReq.signal}),o.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",r=>this.sendToolListChanged(r.params))),o.resources&&(this.onlistresources=async(r,n)=>this._client.request({method:"resources/list",params:r},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(r,n)=>this._client.request({method:"resources/templates/list",params:r},{signal:n.mcpReq.signal}),this.onreadresource=async(r,n)=>this._client.request({method:"resources/read",params:r},{signal:n.mcpReq.signal}),o.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",r=>this.sendResourceListChanged(r.params))),o.prompts&&(this.onlistprompts=async(r,n)=>this._client.request({method:"prompts/list",params:r},{signal:n.mcpReq.signal}),o.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",r=>this.sendPromptListChanged(r.params)))}return super.connect(t)}};function CR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function L_(e,t){let o=new DOMParser().parseFromString(e,"text/html"),r=o.createElement("meta");if(r.httpEquiv="Content-Security-Policy",r.content=t,o.head.prepend(r),!o.querySelector("base[href]")){let n=o.querySelector("base")??o.createElement("base");n.setAttribute("href","about:srcdoc"),r.after(n)}return"<!doctype html>"+o.documentElement.outerHTML}var $e=new Yl({name:"ADS preview",version:"1.0.0"},{},{autoResize:!0}),Wr=document.getElementById("ads-token-root"),Lt=document.getElementById("ads-widget-status"),tu=document.getElementById("ads-token-theme"),eu=document.getElementById("ads-scenario-root"),To,Me=0,U_="",Br=30,Z_=document.createElement("style");Wr&&document.head.append(Z_);function ou(e){e!=="light"&&e!=="dark"||(document.documentElement.dataset.theme=e,tu&&(tu.value=e),Wr&&To&&wo())}function Oe(e,t){let o=document.createElement(e);return o.textContent=t,o}function IR(e){let t=Oe("li","");t.dataset.token=e.name;let o=getComputedStyle(document.documentElement).getPropertyValue(e.name).trim(),r=Oe("details","");r.className="token-source";let n=Oe("summary","");n.title=`${e.name}: ${o||"Conditional or unset"}. Click to inspect source definitions.`;let s=Oe("code",e.name);s.className="token-name";let a=Oe("span",o||"Conditional or unset");n.append(s,a);let l=Oe("dl","");l.append(Oe("dt","Computed in preview"),Oe("dd",o||"Conditional or unset")),e.meaning&&l.append(Oe("dt","Meaning"),Oe("dd",e.meaning));for(let u of e.definitions)l.append(Oe("dt",u.scope),Oe("dd",`${u.value} \xB7 ${u.file}:${u.line}`));return r.append(n,l),t.append(r),t}function wo(){Z_.textContent=To.css;let e=To.tokens.filter(t=>`${t.name} ${t.type??""}`.toLowerCase().includes(U_.toLowerCase()));document.getElementById("ads-token-list").replaceChildren(...e.slice(Me,Me+Br).map(IR)),document.querySelector("footer").hidden=e.length<=Br,document.getElementById("ads-token-count").textContent=e.length?`${Me+1}\u2013${Math.min(Me+Br,e.length)} of ${e.length}`:"No matching tokens",document.getElementById("ads-token-prev").disabled=Me===0,document.getElementById("ads-token-next").disabled=Me+Br>=e.length,Lt.textContent=`${e.length} matching definitions \xB7 ${To.diagnostics.length} diagnostics`}Wr&&($e.ontoolinput=()=>{Me=0,To&&wo()},To=JSON.parse(document.getElementById("ads-token-seed").textContent),ou("light"),document.getElementById("ads-token-search").addEventListener("input",e=>{U_=e.target.value,Me=0,wo()}),tu.addEventListener("change",()=>ou(tu.value)),document.getElementById("ads-token-prev").addEventListener("click",()=>{Me=Math.max(0,Me-Br),wo()}),document.getElementById("ads-token-next").addEventListener("click",()=>{Me+=Br,wo()}),document.getElementById("ads-token-refresh").addEventListener("click",async()=>{try{let e=await $e.readServerResource({uri:"ads://project/tokens"});To=JSON.parse(e.contents.find(t=>"text"in t).text),Me=0,wo()}catch(e){Lt.textContent=`Refresh failed: ${e.message}`}}));var xo,$f,D_=!1,_a=0;async function H_(e){if($f=e,!D_||!eu)return;let t=e?.structuredContent?.scenario?.resourceUri;if(!t||!t.startsWith("ui://ads/previews/"))return;let o=++_a;Wr&&(Wr.hidden=!0,Lt=document.getElementById("ads-scenario-status")),eu.hidden=!1;try{if(!$e.getHostCapabilities()?.serverResources)throw new Error("This Apps host does not forward server resources. Use the project showcase URL from the tool result.");let n=(await $e.readServerResource({uri:t})).contents.find(u=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text=="string");if(!n)throw new Error("Scenario HTML is unavailable.");if(o!==_a)return;xo&&(await xo.close(),xo=void 0);let s=document.createElement("iframe");s.title=e.structuredContent.scenario.title,s.setAttribute("sandbox","allow-scripts allow-forms"),eu.replaceChildren(s);let a=new Xl(null,{name:"ADS scenario host",version:"1.0.0"},{serverResources:{},serverTools:{}},{hostContext:$e.getHostContext()});xo=a,a.onreadresource=u=>$e.readServerResource(u),a.oncalltool=u=>$e.callServerTool(u),a.onsizechange=({height:u})=>{u&&(s.height=String(Math.min(1e4,Math.max(120,u))))},a.oninitialized=async()=>{await a.sendToolInput({arguments:{}}),await a.sendToolResult(e),o===_a&&window.parent.postMessage({type:"ads-preview-ready"},"*")},await a.connect(new Ql(s.contentWindow,s.contentWindow));let l="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; worker-src blob: data:; connect-src 'none'; base-uri about:; object-src 'none'; form-action 'none'";s.srcdoc=L_(n.text,l),Lt.hidden=!0}catch(r){o===_a&&(Lt.hidden=!1,Lt.textContent=r.message,window.parent.postMessage({type:"ads-preview-ready"},"*"))}}eu&&($e.ontoolresult=e=>{H_(e)},$e.onteardown=async()=>{++_a;let e=xo;xo=void 0;try{await e?.teardownResource({},{timeout:500})}catch{}return await e?.close(),{}});$e.onhostcontextchanged=e=>{ou(e.theme),xo?.setHostContext(e)};try{await $e.connect(),D_=!0,$f&&H_($f),ou($e.getHostContext()?.theme),Wr&&(document.getElementById("ads-token-refresh").disabled=!$e.getHostCapabilities()?.serverResources,wo())}catch{Lt&&(Lt.textContent="Apps bridge unavailable. Samples remain usable; inspect project data through ADS tools/resources.")}
141
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:i.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:i.string().optional().describe("User's timezone in IANA format."),userAgent:i.string().optional().describe("Host application identifier."),platform:i.union([i.literal("web"),i.literal("desktop"),i.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:i.object({touch:i.boolean().optional().describe("Whether the device supports touch input."),hover:i.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:i.object({top:i.number().describe("Top safe area inset in pixels."),right:i.number().describe("Right safe area inset in pixels."),bottom:i.number().describe("Bottom safe area inset in pixels."),left:i.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),XT=i.object({method:i.literal("ui/notifications/host-context-changed"),params:j_.describe("Partial context update containing only changed fields.")}),PR=i.object({method:i.literal("ui/update-model-context"),params:i.object({content:i.array(Ee).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:i.record(i.string(),i.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),ER=i.object({method:i.literal("ui/initialize"),params:i.object({appInfo:Pe.describe("App identification (name and version)."),appCapabilities:zR.describe("Features and capabilities this app provides."),protocolVersion:i.string().describe("Protocol version this app supports.")})}),kR=i.object({protocolVersion:i.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Pe.describe("Host application identification and version."),hostCapabilities:vR.describe("Features and capabilities provided by the host."),hostContext:j_.describe("Rich context about the host environment.")}).passthrough();var Ql=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,o){this.eventTarget=t,this.eventSource=o,this.messageListener=r=>{if(o&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let n=ct.safeParse(r.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,r):(console.error("Failed to parse message",n.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,o){t.method!==aR&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var $R=[A_],Xl=class extends ma{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Tf;_methods=new Pf;setRequestHandler=(...t)=>{let[o,...r]=O_("request",t)??t;this._methods.claim(o,"setRequestHandler"),super.setRequestHandler.call(this,o,...r)};setNotificationHandler=(...t)=>{let[o,...r]=O_("notification",t)??t;this._methods.claim(o,"setNotificationHandler"),super.setNotificationHandler.call(this,o,...r)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...o)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...o)};_wrapHandler(t,o){let r=super._wrapHandler(t,o);return t==="ui/initialize"||t==="ping"?r:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),r(n,s))}eventSchemas={sizechange:gR,sandboxready:fR,initialized:RR,requestteardown:yR,loggingmessage:bo};setEventHandler(t,o){this._ensureEventSlot(t),this._events.setHandler(t,o)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,o){this._ensureEventSlot(t),this._events.addEventListener(t,o)}removeEventListener(t,o){this._events.removeEventListener(t,o)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let o=this.eventSchemas[t];if(!o)throw Error(`Unknown event: ${String(t)}`);let r=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{r(n.params)}):this.setNotificationHandler(o.shape.method.value,{params:o.shape.params},n=>r(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,o,r){o&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,o,r,n){super(n),this._client=t,this._hostInfo=o,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:ER.shape.params,result:kR},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,a)=>(this.onping?.(s.params,a),{})),this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:TR.shape.params,result:mR},async(o,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(o,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:dR.shape.params,result:pR},async(o,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(o,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:xR.shape.params,result:hR},async(o,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(o,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},async(o,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(o,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:PR.shape.params,result:We},async(o,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(o,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(o,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(o,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(o.params,r)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(o,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(o.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(o,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(o.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(o,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(o.params,r)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(o,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(o.params,r)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let o=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:$R.includes(o)?o:A_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let o={},r=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],a=t[n];CR(s,a)||(o[n]=a,r=!0)}r&&(this._hostContext=t,this.sendHostContextChange(o))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,o){return this.request({method:"ui/resource-teardown",params:t},bR,o)}sendResourceTeardown=this.teardownResource;callTool(t,o){return this.request({method:"tools/call",params:t},o)}listTools(t,o){return this.request({method:"tools/list",params:t},o)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let o=this._client.getServerCapabilities();if(!o)throw Error("Client server capabilities not available");o.tools&&(this.oncalltool=async(r,n)=>this._client.request({method:"tools/call",params:r},{signal:n.mcpReq.signal}),o.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",r=>this.sendToolListChanged(r.params))),o.resources&&(this.onlistresources=async(r,n)=>this._client.request({method:"resources/list",params:r},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(r,n)=>this._client.request({method:"resources/templates/list",params:r},{signal:n.mcpReq.signal}),this.onreadresource=async(r,n)=>this._client.request({method:"resources/read",params:r},{signal:n.mcpReq.signal}),o.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",r=>this.sendResourceListChanged(r.params))),o.prompts&&(this.onlistprompts=async(r,n)=>this._client.request({method:"prompts/list",params:r},{signal:n.mcpReq.signal}),o.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",r=>this.sendPromptListChanged(r.params)))}return super.connect(t)}};function CR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function L_(e,t){let o=new DOMParser().parseFromString(e,"text/html"),r=o.createElement("meta");if(r.httpEquiv="Content-Security-Policy",r.content=t,o.head.prepend(r),!o.querySelector("base[href]")){let n=o.querySelector("base")??o.createElement("base");n.setAttribute("href","about:srcdoc"),r.after(n)}return"<!doctype html>"+o.documentElement.outerHTML}var $e=new Yl({name:"ADS preview",version:"1.0.0"},{},{autoResize:!0}),Wr=document.getElementById("ads-token-root"),Lt=document.getElementById("ads-widget-status"),tu=document.getElementById("ads-token-theme"),eu=document.getElementById("ads-scenario-root"),To,Me=0,U_="",Br=30,Z_=document.createElement("style");Wr&&document.head.append(Z_);function ou(e){e!=="light"&&e!=="dark"||(document.documentElement.dataset.theme=e,tu&&(tu.value=e),Wr&&To&&wo())}function Oe(e,t){let o=document.createElement(e);return o.textContent=t,o}function IR(e){let t=Oe("li","");t.dataset.token=e.name;let o=getComputedStyle(document.documentElement).getPropertyValue(e.name).trim(),r=Oe("details","");r.className="token-source";let n=Oe("summary","");n.title=`${e.name}: ${o||"Conditional or unset"}. Click to inspect source definitions.`;let s=Oe("code",e.name);s.className="token-name";let a=Oe("span",o||"Conditional or unset");n.append(s,a);let l=Oe("dl","");l.append(Oe("dt","Computed in preview"),Oe("dd",o||"Conditional or unset")),e.meaning&&l.append(Oe("dt","Meaning"),Oe("dd",e.meaning));for(let u of e.definitions)l.append(Oe("dt",u.scope),Oe("dd",`${u.value} \xB7 ${u.file}:${u.line}`));return r.append(n,l),t.append(r),t}function wo(){Z_.textContent=To.css;let e=To.tokens.filter(t=>`${t.name} ${t.type??""}`.toLowerCase().includes(U_.toLowerCase()));document.getElementById("ads-token-list").replaceChildren(...e.slice(Me,Me+Br).map(IR)),document.querySelector("footer").hidden=e.length<=Br,document.getElementById("ads-token-count").textContent=e.length?`${Me+1}\u2013${Math.min(Me+Br,e.length)} of ${e.length}`:"No matching tokens",document.getElementById("ads-token-prev").disabled=Me===0,document.getElementById("ads-token-next").disabled=Me+Br>=e.length,Lt.textContent=`${e.length} matching definitions \xB7 ${To.diagnostics.length} diagnostics`}Wr&&($e.ontoolinput=()=>{Me=0,To&&wo()},To=JSON.parse(document.getElementById("ads-token-seed").textContent),ou("light"),document.getElementById("ads-token-search").addEventListener("input",e=>{U_=e.target.value,Me=0,wo()}),tu.addEventListener("change",()=>ou(tu.value)),document.getElementById("ads-token-prev").addEventListener("click",()=>{Me=Math.max(0,Me-Br),wo()}),document.getElementById("ads-token-next").addEventListener("click",()=>{Me+=Br,wo()}),document.getElementById("ads-token-refresh").addEventListener("click",async()=>{try{let e=await $e.readServerResource({uri:"ads://project/tokens"});To=JSON.parse(e.contents.find(t=>"text"in t).text),Me=0,wo()}catch(e){Lt.textContent=`Refresh failed: ${e.message}`}}));var xo,$f,D_=!1,_a=0;async function H_(e){if($f=e,!D_||!eu)return;let t=e?.structuredContent?.scenario?.resourceUri;if(!t||!t.startsWith("ui://ads/previews/"))return;let o=++_a;Wr&&(Wr.hidden=!0,Lt=document.getElementById("ads-scenario-status")),eu.hidden=!1;try{if(!$e.getHostCapabilities()?.serverResources)throw new Error("This Apps host does not forward server resources. Use the project showcase URL from the tool result.");let n=(await $e.readServerResource({uri:t})).contents.find(u=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text=="string");if(!n)throw new Error("Scenario HTML is unavailable.");if(o!==_a)return;xo&&(await xo.close(),xo=void 0);let s=document.createElement("iframe");s.title=e.structuredContent.scenario.title,s.setAttribute("sandbox","allow-scripts allow-forms"),eu.replaceChildren(s);let a=new Xl(null,{name:"ADS scenario host",version:"1.0.0"},{serverResources:{},serverTools:{}},{hostContext:$e.getHostContext()});xo=a,a.onreadresource=u=>$e.readServerResource(u),a.oncalltool=u=>$e.callServerTool(u),a.onsizechange=({height:u})=>{u&&(s.height=String(Math.min(1e4,Math.max(120,u))))},a.oninitialized=async()=>{await a.sendToolInput({arguments:{}}),await a.sendToolResult(e),o===_a&&window.parent.postMessage({type:"ads-preview-ready"},"*")},await a.connect(new Ql(s.contentWindow,s.contentWindow));let l="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; worker-src blob: data:; connect-src blob:; base-uri about:; object-src 'none'; form-action 'none'";s.srcdoc=L_(n.text,l),Lt.hidden=!0}catch(r){o===_a&&(Lt.hidden=!1,Lt.textContent=r.message,window.parent.postMessage({type:"ads-preview-ready"},"*"))}}eu&&($e.ontoolresult=e=>{H_(e)},$e.onteardown=async()=>{++_a;let e=xo;xo=void 0;try{await e?.teardownResource({},{timeout:500})}catch{}return await e?.close(),{}});$e.onhostcontextchanged=e=>{ou(e.theme),xo?.setHostContext(e)};try{await $e.connect(),D_=!0,$f&&H_($f),ou($e.getHostContext()?.theme),Wr&&(document.getElementById("ads-token-refresh").disabled=!$e.getHostCapabilities()?.serverResources,wo())}catch{Lt&&(Lt.textContent="Apps bridge unavailable. Samples remain usable; inspect project data through ADS tools/resources.")}
142
142
  /*! Bundled license information:
143
143
 
144
144
  @modelcontextprotocol/client/dist/src-WCy6ifGf.mjs:
@@ -0,0 +1,108 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { previewSourceRevision } from "./preview-inputs.mjs";
5
+ import { createPreviewResources } from "./preview-resources.mjs";
6
+
7
+ /** Project-owned Vite plugins/configuration, with a persistent development graph.
8
+ * Watch output is private scratch data; only the compiler may publish it after
9
+ * validation and its source/generation checks. Existing buildGraph adapters work
10
+ * unchanged; opt in by passing this function as buildGraph. */
11
+ export function createVitePreviewBuilder({ build, configure }) {
12
+ let graph;
13
+ async function close() {
14
+ const previous = graph;
15
+ graph = undefined;
16
+ if (!previous) return;
17
+ previous.closed = true;
18
+ previous.notify();
19
+ try { await previous.watcher?.close(); }
20
+ finally { rmSync(previous.directory, { recursive: true, force: true }); }
21
+ }
22
+ const builder = async (entries, options, track, { watched = false } = {}) => {
23
+ if (!watched) {
24
+ const config = await configure(entries, options);
25
+ const output = await build({ ...config, plugins: [...config.plugins ?? [], track], build: { ...config.build, write: false, watch: null } });
26
+ return createPreviewResources(output, options, entries);
27
+ }
28
+ // Metadata changes do not change virtual module identities. A changed entry
29
+ // list or project configuration does require a fresh configured graph.
30
+ const key = JSON.stringify([options.root, options.config, entries.map(entry => [entry.id, entry.file])]);
31
+ if (graph?.key !== key) {
32
+ await close();
33
+ const directory = path.join(options.root, ".ds/incremental", randomUUID());
34
+ mkdirSync(directory, { recursive: true });
35
+ const trigger = path.join(directory, "trigger");
36
+ writeFileSync(trigger, "0");
37
+ const listeners = new Set();
38
+ const current = { key, directory, closed: false, building: true, serial: 0,
39
+ notify() { for (const resolve of listeners) resolve(); listeners.clear(); },
40
+ wait(reconcile) { return new Promise(resolve => {
41
+ const done = () => { clearTimeout(timer); listeners.delete(done); resolve(); };
42
+ // Watch subscriptions can still be settling after END. Reconcile a
43
+ // missed scratch-file event rather than leave an idle request stuck.
44
+ const timer = reconcile ? setTimeout(done, 100) : undefined;
45
+ listeners.add(done);
46
+ }); },
47
+ };
48
+ graph = current;
49
+ let started;
50
+ let candidate;
51
+ const capture = { name: "ads-incremental-preview", enforce: "post",
52
+ buildStart() { started = previewSourceRevision(options); this.addWatchFile(trigger); },
53
+ writeBundle(_output, bundle) {
54
+ candidate = { source: started, output: { output: Object.values(bundle) }, modules: [...this.getModuleIds()] };
55
+ },
56
+ };
57
+ try {
58
+ const config = await configure(entries, options);
59
+ const output = config.build?.rollupOptions?.output;
60
+ if (Array.isArray(output) || output?.file) throw new Error("Incremental preview builds require one module output without output.file.");
61
+ current.watcher = await build({ ...config, plugins: [...config.plugins ?? [], capture],
62
+ build: { ...config.build, write: true, outDir: path.join(directory, "output"), emptyOutDir: true,
63
+ rollupOptions: { ...config.build?.rollupOptions, output: { ...output, dir: path.join(directory, "output") } },
64
+ watch: { ...config.build?.watch, skipWrite: false,
65
+ // Bun's native fs-watch reattachment can miss rapid subsequent
66
+ // edits on Linux. Poll only this compiler's dependency watches.
67
+ chokidar: { ...(process.versions.bun ? { usePolling: true, interval: 100 } : {}), ...config.build?.watch?.chokidar },
68
+ },
69
+ },
70
+ });
71
+ if (current.closed) {
72
+ await current.watcher.close();
73
+ rmSync(directory, { recursive: true, force: true });
74
+ throw new Error("Preview builder was closed.");
75
+ }
76
+ current.watcher.on("event", event => {
77
+ if (event.code === "START") { current.building = true; current.error = undefined; candidate = undefined; }
78
+ if (event.code === "ERROR") {
79
+ current.error = { source: started, value: event.error }; current.building = false; current.notify();
80
+ }
81
+ if (event.code === "END") {
82
+ if (candidate) current.snapshot = candidate;
83
+ current.building = false; current.notify();
84
+ }
85
+ });
86
+ } catch (error) { await close(); throw error; }
87
+ }
88
+ const current = graph;
89
+ const source = previewSourceRevision(options);
90
+ while (!current.closed) {
91
+ if (!current.building) {
92
+ if (previewSourceRevision(options) !== source) throw new Error("Sources changed during incremental compilation. Waiting for the current build.");
93
+ if (current.error?.source === source) throw current.error.value;
94
+ if (current.snapshot?.source === source) {
95
+ track.generateBundle.call({ getModuleIds: () => current.snapshot.modules });
96
+ return createPreviewResources(current.snapshot.output, options, entries);
97
+ }
98
+ // Metadata/policy/assets outside Rollup's module graph still require a
99
+ // current build. A watched scratch file requests it without touching UI.
100
+ writeFileSync(path.join(current.directory, "trigger"), String(++current.serial));
101
+ }
102
+ await current.wait(!current.building);
103
+ }
104
+ throw new Error("Preview builder was closed.");
105
+ };
106
+ builder.close = close;
107
+ return builder;
108
+ }
@@ -0,0 +1,33 @@
1
+ import { readdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { isInside } from "./config.mjs";
4
+
5
+ const metadata = new Set(["node_modules", ".git", ".ds", ".vite", "coverage"]);
6
+ const generated = new Set(["dist", "build", "target", "out", ".next", ".nuxt", ".svelte-kit", ".turbo"]);
7
+
8
+ /** Shared watch/fingerprint policy. Explicit source roots take priority over default outputs. */
9
+ export function previewFileIgnored({root, config}, file) {
10
+ const absolute = path.resolve(file), relative = path.relative(root, absolute);
11
+ if (relative.split(path.sep).some(name => metadata.has(name))) return true;
12
+ if (config.assets.generatedPaths.some(base => isInside(path.resolve(root, base), absolute))) return true;
13
+ const sources = [config.dsDir, config.sourceDir].map(base => path.resolve(root, base));
14
+ for (const name of relative.split(path.sep)) {
15
+ if (!generated.has(name)) continue;
16
+ if (!sources.some(source => isInside(source, absolute) || isInside(absolute, source))) return true;
17
+ }
18
+ return false;
19
+ }
20
+
21
+ /** Allocate individual watches so excluded descendants never consume OS watches. */
22
+ export function previewWatchDirectories(options) {
23
+ const directories = [];
24
+ function visit(directory) {
25
+ directories.push(directory);
26
+ for (const entry of readdirSync(directory, {withFileTypes:true})) {
27
+ const child = path.join(directory, entry.name);
28
+ if (entry.isDirectory() && !entry.isSymbolicLink() && !previewFileIgnored(options, child)) visit(child);
29
+ }
30
+ }
31
+ visit(options.root);
32
+ return directories;
33
+ }
@@ -1,23 +1,31 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { isInside } from "./config.mjs";
4
+ import { previewFileIgnored } from "./preview-files.mjs";
5
+ import { isScenarioFile } from "./config.mjs";
6
+ import { scenarioGroupFingerprint } from "./scenario-groups.mjs";
5
7
 
6
8
  /** Shared source evidence for compilation, watch recovery and status reads. */
7
- export function previewSourceRevision({root,config}, apps = config.mcp.apps ?? []) {
8
- const rows = [], generated = config.assets.generatedPaths.map(file => path.resolve(root,file));
9
+ export function previewSourceRevision(options, apps = options.config.mcp.apps ?? []) {
10
+ const {root} = options;
11
+ const rows = [];
12
+ const scenarios = [];
9
13
  const outputs = new Set(apps.map(app => path.resolve(root,app.file)));
10
14
  function digest(file) { return createHash("sha256").update(readFileSync(file)).digest("hex"); }
11
15
  function visit(directory) {
12
16
  for (const entry of readdirSync(directory,{withFileTypes:true})) {
13
- if (entry.isSymbolicLink() || ["node_modules",".git",".ds",".vite","coverage"].includes(entry.name)) continue;
17
+ if (entry.isSymbolicLink()) continue;
14
18
  const file = path.join(directory,entry.name);
15
- if (outputs.has(file) || generated.some(base => isInside(base,file))) continue;
19
+ if (outputs.has(file) || previewFileIgnored(options,file)) continue;
16
20
  if (entry.isDirectory()) visit(file);
17
- else if (entry.isFile() && /\.(?:[cm]?[jt]sx?|css|html|json|md|svg|png|jpe?g|webp|gif|woff2?|ttf|otf|lock|lockb)$/.test(file)) rows.push([path.relative(root,file),digest(file)]);
21
+ else if (entry.isFile() && /\.(?:[cm]?[jt]sx?|css|html|json|md|svg|png|jpe?g|webp|gif|woff2?|ttf|otf|lock|lockb)$/.test(file)) {
22
+ rows.push([path.relative(root,file),digest(file)]);
23
+ if (isScenarioFile(file)) scenarios.push(file);
24
+ }
18
25
  }
19
26
  }
20
27
  visit(root);
28
+ rows.push(["scenario-group-structure",scenarioGroupFingerprint(options,scenarios)]);
21
29
  const installed = path.join(root,"node_modules/.package-lock.json");
22
30
  rows.push(["installed-packages",existsSync(installed) ? digest(installed) : null]);
23
31
  return createHash("sha256").update(JSON.stringify(rows.sort((a,b)=>a[0].localeCompare(b[0])))).digest("hex");
@@ -0,0 +1,47 @@
1
+ import { readdirSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { isInside, isScenarioFile, sourceFiles } from "./config.mjs";
4
+
5
+ const children = directory => readdirSync(directory, { withFileTypes: true }).filter(entry => !entry.name.startsWith("."));
6
+
7
+ /** Grouping depends on directory entries, including files outside source globs. */
8
+ export function scenarioGroupFingerprint(options, files) {
9
+ const dsRoot = options.dsRoot ?? path.resolve(options.root, options.config.dsDir);
10
+ const directories = new Set();
11
+ for (const file of (files ?? sourceFiles(dsRoot)).filter(isScenarioFile)) {
12
+ const layer = path.relative(dsRoot, file).split(path.sep)[0];
13
+ if (!["components", "patterns", "composition"].includes(layer)) continue;
14
+ const boundary = path.join(dsRoot, layer);
15
+ for (let directory = path.dirname(file); directory !== boundary && isInside(boundary, directory); directory = path.dirname(directory)) directories.add(directory);
16
+ }
17
+ return JSON.stringify([...directories].sort().map(directory => [path.relative(dsRoot, directory), children(directory)
18
+ .map(entry => [entry.name, entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "file"])
19
+ .sort(([left], [right]) => left.localeCompare(right))]));
20
+ }
21
+
22
+ /** Group containers organize owners; an owner's own directory is never a group. */
23
+ export function createScenarioGroups({ dsRoot }) {
24
+ const containers = new Map();
25
+ function container(directory) {
26
+ if (!containers.has(directory)) {
27
+ try {
28
+ const entries = children(directory);
29
+ containers.set(directory, entries.length > 0 && entries.every(entry => entry.isDirectory() && !entry.isSymbolicLink()));
30
+ } catch { containers.set(directory, false); }
31
+ }
32
+ return containers.get(directory);
33
+ }
34
+ return (file, owner) => {
35
+ const relative = path.relative(dsRoot, file), layer = relative.split(path.sep)[0];
36
+ if (!["components", "patterns", "composition"].includes(layer)) return undefined;
37
+ const boundary = path.join(dsRoot, layer);
38
+ let directory = owner ? path.join(dsRoot, owner) : path.dirname(file);
39
+ try { if (!statSync(directory).isDirectory()) directory = path.dirname(directory); }
40
+ catch { directory = path.dirname(directory); }
41
+ const groups = [];
42
+ for (directory = path.dirname(directory); directory !== boundary && isInside(boundary, directory); directory = path.dirname(directory)) {
43
+ if (container(directory)) groups.unshift(path.basename(directory));
44
+ }
45
+ return groups.length ? groups.join(" / ") : undefined;
46
+ };
47
+ }
@@ -7,6 +7,7 @@ import { artifactDigest, createBuildReporter } from "./mcp/build-status.mjs";
7
7
  import { cachedPreviewPublication, previewArtifactHtml, readPreviewManifest } from "./preview-resources.mjs";
8
8
  import { previewArtifactPath, withPreviewSession } from "./preview-scope.mjs";
9
9
  import { previewSourceRevision } from "./preview-inputs.mjs";
10
+ import { previewFileIgnored, previewWatchDirectories } from "./preview-files.mjs";
10
11
 
11
12
  const digest = value => createHash("sha256").update(value).digest("hex");
12
13
  const fileDigest = file => { try { return digest(readFileSync(file)); } catch { return null; } };
@@ -15,7 +16,7 @@ const fileDigest = file => { try { return digest(readFileSync(file)); } catch {
15
16
  * Cache state is development output, never proof that a failed build is current. */
16
17
  export function createPreviewCache(options, compilerFiles = []) {
17
18
  const { root } = options;
18
- const adapterFiles = [import.meta.filename, ...["preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
19
+ const adapterFiles = [import.meta.filename, ...["preview-builder.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
19
20
  ...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "node_modules/.package-lock.json"].map(file => path.join(root, file))];
20
21
  const adapterDigest = () => digest(JSON.stringify(adapterFiles.map(file => [file, fileDigest(file)])));
21
22
  const loadedAdapter = adapterDigest();
@@ -205,7 +206,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
205
206
  try { readPreviewManifest(options, { verify: true }); }
206
207
  catch { reusable = false; }
207
208
  }
208
- const outcomes = await checkedBuild(stamp, () => reusable ? null : buildGraph(entries, options, track));
209
+ const outcomes = await checkedBuild(stamp, () => reusable ? null : buildGraph(entries, options, track, { watched }));
209
210
  const failure = outcomes.find(outcome => outcome.status === "rejected");
210
211
  if (failure) throw failure.reason;
211
212
  cache.assertCompiler();
@@ -265,7 +266,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
265
266
  }
266
267
  if (!watched) {
267
268
  for (const entry of entries) pending.add(entry.id);
268
- await drain();
269
+ try { await drain(); } finally { await buildGraph?.close?.(); }
269
270
  return;
270
271
  }
271
272
  let timer;
@@ -273,7 +274,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
273
274
  function sourceChanged(_event, file, topology = false) {
274
275
  if (!file || !topology && !/\.(?:[cm]?[jt]sx?|css|html|json|md|svg|png|jpe?g|webp|gif|woff2?|ttf|otf|lock|lockb)$/.test(file)) return;
275
276
  const absolute = path.join(root, file);
276
- if (file.split(path.sep).some(name => ["node_modules", ".git", ".ds", ".vite", "coverage"].includes(name)) || options.config.assets.generatedPaths.some(base => isInside(path.resolve(root, base), absolute))) return;
277
+ if (previewFileIgnored(options, absolute)) return;
277
278
  changed.add(absolute);
278
279
  clearTimeout(timer);
279
280
  timer = setTimeout(() => {
@@ -324,12 +325,11 @@ export async function runScenarioCompiler(directory, { watched = false, validate
324
325
  try {
325
326
  addWatch(root, sourceChanged);
326
327
  const wanted = new Set([root, path.join(root, ".ds")]);
327
- for (const entry of readdirSync(root, { withFileTypes: true })) {
328
- const directory = path.join(root, entry.name);
329
- if (!entry.isDirectory() || entry.isSymbolicLink() || ["node_modules", ".git", ".ds", ".vite", "coverage"].includes(entry.name)
330
- || options.config.assets.generatedPaths.some(base => isInside(path.resolve(root, base), directory))) continue;
328
+ for (const directory of previewWatchDirectories(options)) {
329
+ if (directory === root) continue;
331
330
  wanted.add(directory);
332
- if (addWatch(directory, (event, file) => sourceChanged(event, file && path.join(entry.name, file)), true) && !initial) sourceChanged("rename", entry.name, true);
331
+ const relative = path.relative(root, directory);
332
+ if (addWatch(directory, (event, file) => sourceChanged(event, file && path.join(relative, file))) && !initial) sourceChanged("rename", relative, true);
333
333
  }
334
334
  mkdirSync(path.join(root, ".ds"), { recursive: true });
335
335
  addWatch(path.join(root, ".ds"), (_event, file) => { if (file === path.basename(process.env.ADS_MCP_REQUEST_FILE ?? "")) request(); });
@@ -355,5 +355,6 @@ export async function runScenarioCompiler(directory, { watched = false, validate
355
355
  console.log(`Scenario compiler ready: ${entries.length} entries; builds are requested on demand.`);
356
356
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => {
357
357
  stopped = true; clearTimeout(timer); clearInterval(reconcileTimer); for (const { watcher } of watchers.values()) watcher.close();
358
+ void buildGraph?.close?.();
358
359
  });
359
360
  }
@@ -4,6 +4,7 @@ import { loadConfig, isInside } from "./config.mjs";
4
4
  import { inspectScenarios } from "./scenarios.mjs";
5
5
  import { configureReviewAlias } from "./preview-resources.mjs";
6
6
  export { createPreviewResources, previewEntriesPlugin } from "./preview-resources.mjs";
7
+ export { createVitePreviewBuilder } from "./preview-builder.mjs";
7
8
 
8
9
  /** Project-owned rendering; this plugin supplies only discoverable module entries. */
9
10
  export function scenarioRegistryPlugin(directory = process.cwd()) {
@@ -57,11 +58,18 @@ export function inlineScenarioHtml() {
57
58
  }
58
59
  for (const asset of Object.values(bundle)) {
59
60
  if (asset.type !== "asset" || !asset.fileName.endsWith(".html")) continue;
60
- asset.source = asset.source.toString().replace(/<script\b[^>]*\bsrc="([^"]+)"[^>]*><\/script>/g, (_match, src) => {
61
- const chunk = bundle[src.replace(/^\.\//, "").replace(/^\//, "")];
62
- if (!chunk || chunk.type !== "chunk") throw new Error(`Cannot inline scenario module: ${src}`);
63
- return `<script type="module">${chunk.code.replaceAll("</script", "<\\/script")}</script>`;
64
- }).replace(/<link\b[^>]*\bhref="([^"]+)"[^>]*>/g, (_match, href) => {
61
+ // Match whole script elements so HTML-looking framework strings inside
62
+ // inlined JavaScript are never mistaken for document stylesheet links.
63
+ asset.source = asset.source.toString().replace(/<script\b[^>]*>[\s\S]*?<\/script>|<link\b[^>]*>/g, tag => {
64
+ if (tag.startsWith("<script")) {
65
+ const src = tag.match(/^<script\b[^>]*\bsrc="([^"]+)"/)?.[1];
66
+ if (!src) return tag;
67
+ const chunk = bundle[src.replace(/^\.\//, "").replace(/^\//, "")];
68
+ if (!chunk || chunk.type !== "chunk") throw new Error(`Cannot inline scenario module: ${src}`);
69
+ return `<script type="module">${chunk.code.replaceAll("</script", "<\\/script")}</script>`;
70
+ }
71
+ const href = tag.match(/\bhref="([^"]+)"/)?.[1];
72
+ if (!href) return tag;
65
73
  const style = bundle[href.replace(/^\.\//, "").replace(/^\//, "")];
66
74
  if (!style || style.type !== "asset" || !style.fileName.endsWith(".css")) throw new Error(`Cannot inline scenario style: ${href}`);
67
75
  return `<style>${style.source.toString().replaceAll("</style", "<\\/style")}</style>`;
@@ -13,6 +13,7 @@ import { createScenarioTrace } from "./scenario-trace.mjs";
13
13
  import { inspectRuntimeContracts } from "./runtime-contracts.mjs";
14
14
  import { inspectUnitContracts } from "./unit-contracts.mjs";
15
15
  import { inspectPaintContracts } from "./paint-contracts.mjs";
16
+ import { createScenarioGroups } from "./scenario-groups.mjs";
16
17
 
17
18
  export const scenarioArtifact = (root, id) => path.join(root, ".ds/scenarios", id, "index.html");
18
19
 
@@ -52,6 +53,7 @@ export function inspectScenarios(options, suppliedProgram) {
52
53
  const tokenInventory = inspectTokens(root, options);
53
54
  const tokenNames = new Set(tokenInventory.tokens.map(token => token.name));
54
55
  const units = inspectUnits(options);
56
+ const scenarioGroup = createScenarioGroups(options);
55
57
  const scenarios = [];
56
58
  const diagnostics = [...inspectUnitContracts(options).diagnostics,...inspectRuntimeContracts(options,program).diagnostics,...inspectPaintContracts(options).diagnostics];
57
59
  const ids = new Set();
@@ -121,6 +123,7 @@ export function inspectScenarios(options, suppliedProgram) {
121
123
  continue;
122
124
  }
123
125
  for(const field of Object.keys(metadata))if(!["id","title","kind","covers","exercises","tokens","samples","captureTargets"].includes(field))report(file,`Unknown scenario field ${field}.`,entryNode(field),{entry:field});
126
+ const group = scenarioGroup(file, units.owner(relative));
124
127
  if(typeof metadata.title!=="string"||!metadata.title.trim()) {
125
128
  report(file,"Scenario title must be a nonempty static string; independent render evidence is retained.",entryNode("title"),{entry:"title"});
126
129
  metadata.title=id;
@@ -172,7 +175,7 @@ export function inspectScenarios(options, suppliedProgram) {
172
175
  if(bindingTrace) findBindings(source);
173
176
  const paintBindings = inspectRuntimeContracts(options,program).bindings.filter(binding=>reachable.has(binding.scope.apiName)).map(binding=>({owner:binding.unit,name:binding.name,scope:binding.scope.selector,prefix:binding.prefix,suffix:binding.suffix,tokens:tokenInventory.tokens.filter(token=>!token.owner||token.owner==="tokens"||token.owner===binding.unit).map(token=>token.name)}));
174
177
  const paintAudit=contractDeclarations.some(contract=>contract.paintInputs?.some(input=>reachable.has(input.apiName)));
175
- scenarios.push({ id, kind, title: metadata.title, ...(fixture ? { fixture: path.relative(root, fixture).replaceAll("\\", "/") } : {}), covers: [...new Set(metadata.covers)], ...(captureTargets ? { captureTargets } : {}), ...(Object.hasOwn(metadata, "exercises") ? { exercises: [...new Set(exercises)] } : {}), tokens, ...(metadata.samples ? { samples: metadata.samples } : {}), ...(paintBindings.length?{paintBindings}:{}), ...(paintAudit?{paintAudit:true}:{}), file: path.relative(root, file).replaceAll("\\", "/"), artifact: path.relative(root, scenarioArtifact(root, id)).replaceAll("\\", "/") });
178
+ scenarios.push({ id, kind, title: metadata.title, ...(group ? { group } : {}), ...(fixture ? { fixture: path.relative(root, fixture).replaceAll("\\", "/") } : {}), covers: [...new Set(metadata.covers)], ...(captureTargets ? { captureTargets } : {}), ...(Object.hasOwn(metadata, "exercises") ? { exercises: [...new Set(exercises)] } : {}), tokens, ...(metadata.samples ? { samples: metadata.samples } : {}), ...(paintBindings.length?{paintBindings}:{}), ...(paintAudit?{paintAudit:true}:{}), file: path.relative(root, file).replaceAll("\\", "/"), artifact: path.relative(root, scenarioArtifact(root, id)).replaceAll("\\", "/") });
176
179
  }
177
180
  return { scenarios: scenarios.sort((a, b) => a.id.localeCompare(b.id)), diagnostics };
178
181
  }