@widgentic/designer 0.11.0 → 0.12.0

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../core/src/contract/validate.ts", "../../../core/src/contract/urls.ts", "../../../core/src/contract/domains.ts", "../../../core/src/catalog/node.ts", "../../../core/src/catalog/descriptors.ts", "../../../core/src/catalog/schema.ts", "../../../core/src/catalog/widgets/format.ts", "../../../core/src/catalog/widgets/images.ts", "../../../core/src/catalog/widgets/card.ts", "../../../core/src/catalog/widgets/keys.ts", "../../../core/src/catalog/widgets/table.ts", "../../../core/src/catalog/widgets/tree.ts", "../../../core/src/catalog/widgets/group.ts", "../../../core/src/catalog/registry.ts", "../../../core/src/shared/plain-object.ts", "../../../core/src/shared/css-scan.ts", "../../../core/src/catalog/styles.ts", "../../../core/src/catalog/identifiers.ts", "../../../core/src/catalog/style-rules.ts", "../../../core/src/catalog/widgets/value-format.ts", "../../../core/src/theming/tokens.ts", "../../../core/src/theming/stylesheet.ts", "../../../core/src/theming/apply.ts", "../../../core/src/theming/registry.ts", "../../../core/src/theming/styles.ts", "../../../core/src/templates/guards.ts", "../../../core/src/templates/paths.ts", "../../../core/src/actions/types.ts", "../../../core/src/actions/validate.ts", "../../../core/src/templates/validate.ts", "../../../core/src/templates/locate.ts", "../../../core/src/templates/compile.ts", "../../../core/src/reactive/build.ts", "../../../core/src/reactive/diff.ts", "../../../core/src/reactive/mount.ts", "../../src/chrome-defaults.ts", "../../src/dom.ts", "../../src/internal.ts", "../../src/validate.ts", "../../src/highlight.ts", "../../src/io.ts", "../../src/json-tree-editor.ts", "../../src/schema-builder.ts", "../../src/record-editor.ts", "../../src/schema-form.ts", "../../src/styles-editor.ts", "../../src/styles-panel.ts", "../../src/schema-paths.ts", "../../src/action-editor.ts", "../../src/template-panel.ts", "../../src/theme-panel.ts", "../../src/panels.ts", "../../src/preview.ts", "../../src/store.ts", "../../src/shell.ts", "../../src/schema-designer.ts", "../../src/theme-designer.ts", "../../src/action-designer.ts", "../../src/settings-designer.ts", "../../src/element.ts", "../../src/browser.ts"],
4
- "sourcesContent": ["import type { WidgetPayload } from \"./types.js\";\nimport type { WidgetContractError } from \"./errors.js\";\n\nexport interface ValidateOptions {\n /**\n * If provided and non-empty, payloads whose `kind` is not in the set fail\n * with `UNKNOWN_KIND`. When omitted or empty, kind membership is not\n * checked (kind format is still validated).\n */\n knownKinds?: ReadonlySet<string>;\n}\n\nexport type ValidateResult =\n | { ok: true; payload: WidgetPayload }\n | { ok: false; error: WidgetContractError };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Validate an unknown input against the widget contract.\n *\n * Returns a discriminated result. The `payload` returned on success is the\n * original input (unknown top-level fields are preserved for forward\n * compatibility).\n */\nexport function validateWidgetPayload(\n input: unknown,\n options: ValidateOptions = {}\n): ValidateResult {\n if (!isPlainObject(input)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"\",\n message: \"Payload must be a plain object.\"\n }\n };\n }\n\n if (!(\"kind\" in input)) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"kind\",\n message: \"Payload is missing required field 'kind'.\"\n }\n };\n }\n\n const kind = input.kind;\n if (typeof kind !== \"string\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"kind\",\n message: \"Field 'kind' must be a string.\"\n }\n };\n }\n if (kind.length === 0) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"kind\",\n message: \"Field 'kind' must be a non-empty string.\"\n }\n };\n }\n\n if (!(\"data\" in input)) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"data\",\n message: \"Payload is missing required field 'data'.\"\n }\n };\n }\n\n if (\"hints\" in input && input.hints !== undefined && !isPlainObject(input.hints)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"hints\",\n message: \"Field 'hints' must be an object when present.\"\n }\n };\n }\n\n if (\"meta\" in input && input.meta !== undefined && !isPlainObject(input.meta)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"meta\",\n message: \"Field 'meta' must be an object when present.\"\n }\n };\n }\n\n const { knownKinds } = options;\n if (knownKinds && knownKinds.size > 0 && !knownKinds.has(kind)) {\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_KIND\",\n path: \"kind\",\n message: `Unknown widget kind '${kind}'.`\n }\n };\n }\n\n // Preserve unknown top-level fields by returning the original input.\n return { ok: true, payload: input as WidgetPayload };\n}\n", "/**\n * URL safety primitives shared by the template DSL and the catalog's image\n * rendering. They live in the contract layer \u2014 the zero-dependency base\n * both consumers sit on \u2014 so the strict and lenient layers can never drift\n * (`templates` imports from `catalog`, so `catalog` cannot import back).\n */\n\n/** Schemes allowed in URL-bearing attributes (plus relative references). */\nexport const ALLOWED_SCHEMES = new Set([\"http\", \"https\", \"mailto\", \"tel\"]);\n\n/**\n * Strip control characters and whitespace before scheme inspection,\n * mirroring how browsers parse URLs (defeats `java\\nscript:` obfuscation).\n */\nfunction cleanUrl(value: string): string {\n return value.replace(/[\\u0000-\\u0020]+/g, \"\");\n}\n\n/**\n * True when a URL value is safe for a URL-bearing attribute: an allowed\n * scheme or a relative reference.\n */\nexport function isSafeUrl(value: string): boolean {\n const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleanUrl(value));\n if (match === null) return true;\n const scheme = match[1];\n return scheme !== undefined && ALLOWED_SCHEMES.has(scheme.toLowerCase());\n}\n\n/**\n * True only for an EXPLICITLY-schemed allowed URL \u2014 unlike {@link isSafeUrl},\n * relative references do not qualify: as anchor targets they are dead\n * clicks inside the app frame and junk navigation on served pages.\n */\nexport function isLinkableUrl(value: string): boolean {\n const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleanUrl(value));\n if (match === null) return false;\n const scheme = match[1];\n return scheme !== undefined && ALLOWED_SCHEMES.has(scheme.toLowerCase());\n}\n\n/** `data:image/<subtype>;base64,<payload>` \u2014 the only `data:` form images accept. */\nconst DATA_IMAGE = /^data:image\\/[a-z0-9.+-]+;base64,[a-z0-9+/=]*$/i;\n\n/** Absolute http(s) \u2014 image sources are fetched, so relative refs are useless. */\nconst HTTP_URL = /^https?:\\/\\//i;\n\n/**\n * True when a value is acceptable as an image source: an absolute http(s)\n * URL or a base64 `data:image/*` URI. Broader `data:` stays banned here and\n * everywhere else \u2014 data-URI navigation is an XSS vector; data-URI images\n * are not.\n */\nexport function isSafeImageSrc(value: string): boolean {\n const cleaned = cleanUrl(value);\n return DATA_IMAGE.test(cleaned) || HTTP_URL.test(cleaned);\n}\n\nconst IMAGE_EXTENSION = /\\.(png|jpe?g|gif|webp|avif|svg)$/i;\n\n/**\n * Auto-detection predicate for the built-in renderers: a safe image source\n * that self-identifies as an image \u2014 `data:image/*`, or an http(s) URL\n * whose pathname ends in an image extension (query strings tolerated).\n * Extensionless image URLs need a `hints.images` entry instead.\n */\nexport function looksLikeImageUrl(value: string): boolean {\n const cleaned = cleanUrl(value);\n if (!isSafeImageSrc(cleaned)) return false;\n if (cleaned.toLowerCase().startsWith(\"data:image/\")) return true;\n try {\n return IMAGE_EXTENSION.test(new URL(cleaned).pathname);\n } catch {\n return false;\n }\n}\n", "/**\n * Resource domains: the origins an MCP Apps frame may load assets from\n * directly, declared as the app resource's `_meta.ui.csp.resourceDomains`.\n * One rule for every door \u2014 the store, the settings designer, the server\n * assembly and the host bundle \u2014 narrower than CSP's own grammar: https\n * only, a host of two or more DNS labels with an optional leading `*.`\n * wildcard, and no port, path, userinfo or IP literal. Hosts build their\n * frame CSP by joining the entries, so nothing that could end a source\n * expression (whitespace, `;`, `,`, quotes) ever passes. Checked label by\n * label over ASCII, never through `URL`, so every runtime reads an entry\n * alike.\n */\n\n/** The most domains one list may declare. */\nexport const RESOURCE_DOMAIN_LIMIT = 20;\n\nexport interface ResourceDomain {\n /** The canonical origin: `https://cdn.example.com` or `https://*.example.com`. */\n origin: string;\n /** The host without its wildcard label: `cdn.example.com`, `example.com`. */\n host: string;\n /** `*.host`: every subdomain of `host`, at any depth, never `host` itself. */\n wildcard: boolean;\n}\n\n/** An accepted entry, or why it is refused (a short clause a person can read). */\nexport type ResourceDomainResult = ResourceDomain | { error: string };\n\nconst LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction hostProblem(host: string, wildcard: boolean): string | undefined {\n if (host.length > 253) return \"the host is longer than 253 characters\";\n const labels = host.split(\".\");\n if (labels.some((label) => label.length === 0)) return \"the host has an empty label\";\n if (labels.every((label) => /^\\d+$/.test(label))) return \"an IP address cannot be declared, only a domain name\";\n if (labels.length < 2) {\n return wildcard\n ? \"a wildcard needs at least two labels after it, as in *.example.com\"\n : \"a single-label host such as localhost cannot be declared\";\n }\n if (labels[labels.length - 1] === \"localhost\") return \"a localhost name cannot be declared\";\n if (/^\\d+$/.test(labels[labels.length - 1] ?? \"\")) return \"the last label is a number, so this is not a domain name\";\n const bad = labels.find((label) => !LABEL.test(label));\n if (bad !== undefined) {\n return `the label '${bad}' is not 1-63 letters, digits or hyphens that start and end with a letter or digit`;\n }\n return undefined;\n}\n\n/**\n * Read one entry: `host`, `*.host`, or either behind `https://`, with at\n * most one trailing `/`. Case and surrounding whitespace are ignored.\n */\nexport function parseResourceDomain(input: string): ResourceDomainResult {\n const trimmed = input.trim();\n if (trimmed.length === 0) return { error: \"it is empty\" };\n if (/[\\s;,'\"`]/.test(trimmed)) return { error: \"it contains a space, ';', ',' or a quote, which no domain holds\" };\n if (/[^\\x21-\\x7e]/.test(trimmed)) return { error: \"it has a non-ASCII character: enter the punycode (xn--) form\" };\n const lower = trimmed.toLowerCase();\n\n let rest = lower;\n if (lower.startsWith(\"https://\")) {\n rest = lower.slice(\"https://\".length);\n } else if (/^[a-z][a-z0-9+.-]*:(?!\\d+\\/?$)/.test(lower)) {\n // A scheme other than https (`http://`, `data:`, `javascript:`); a\n // `host:8443` falls through to the port check instead.\n return { error: \"only https:// domains can be declared\" };\n }\n if (rest.endsWith(\"/\")) rest = rest.slice(0, -1);\n if (rest.includes(\"@\")) return { error: \"it carries a user name, which a domain cannot\" };\n if (rest.includes(\"/\")) return { error: \"it is a page, not a domain: drop the path\" };\n if (rest.includes(\"?\") || rest.includes(\"#\")) return { error: \"it carries a query or fragment, which a domain cannot\" };\n if (rest.startsWith(\"[\")) return { error: \"an IP address cannot be declared, only a domain name\" };\n if (rest.includes(\":\")) return { error: \"it names a port, which a domain cannot\" };\n\n const wildcard = rest.startsWith(\"*.\");\n const host = wildcard ? rest.slice(2) : rest;\n if (host.includes(\"*\")) return { error: \"a wildcard may only be the whole first label, as in *.example.com\" };\n const problem = hostProblem(host, wildcard);\n if (problem !== undefined) return { error: problem };\n return { origin: `https://${wildcard ? \"*.\" : \"\"}${host}`, host, wildcard };\n}\n\n/**\n * Read a list: the accepted domains, deduplicated by canonical origin in\n * first-seen order, and each refused entry with its reason.\n */\nexport function parseResourceDomains(entries: readonly string[]): {\n domains: ResourceDomain[];\n refused: { entry: string; error: string }[];\n} {\n const domains: ResourceDomain[] = [];\n const refused: { entry: string; error: string }[] = [];\n for (const entry of entries) {\n const parsed = parseResourceDomain(entry);\n if (\"error\" in parsed) refused.push({ entry, error: parsed.error });\n else if (!domains.some((domain) => domain.origin === parsed.origin)) domains.push(parsed);\n }\n return { domains, refused };\n}\n\n/** Whether `hostname` falls under `domain`, as a CSP host source matches it. */\nexport function matchesResourceDomain(hostname: string, domain: ResourceDomain): boolean {\n const host = hostname.toLowerCase();\n return domain.wildcard ? host.endsWith(`.${domain.host}`) : host === domain.host;\n}\n", "/**\n * Pure render tree produced by widget renderers.\n *\n * Plain, JSON-serializable data \u2014 no DOM or framework types \u2014 so renderers\n * are testable anywhere and the output layers (`renderToHtml`, `mountNode`)\n * stay thin and swappable. There is deliberately no raw-HTML node type: all\n * text is escaped at the output boundary. An element's optional `key` names\n * it among its siblings for keyed in-place patching; it is render-tree data\n * only, and no output layer emits it.\n */\nimport type { WidgetPayload } from \"../contract/types.js\";\n\n/** Attribute map. Values are plain strings (escaped by output layers). */\nexport type WidgetNodeAttrs = Record<string, string>;\n\n/** A tagged element in the render tree. */\nexport interface WidgetElementNode {\n tag: string;\n attrs?: WidgetNodeAttrs;\n children?: WidgetNode[];\n /** Identity among siblings for keyed patching; never serialized. */\n key?: string;\n}\n\n/** An element in the render tree: a text node or a tagged element. */\nexport type WidgetNode = string | WidgetElementNode;\n\n/** A widget renderer: pure function from payload to render tree. */\nexport type WidgetRenderer = (payload: WidgetPayload) => WidgetNode;\n\n/** Convenience node constructor (omits empty attrs/children and an absent key). */\nexport function el(\n tag: string,\n attrs?: WidgetNodeAttrs,\n children?: WidgetNode[],\n key?: string\n): WidgetElementNode {\n const node: WidgetElementNode = { tag };\n if (attrs && Object.keys(attrs).length > 0) node.attrs = attrs;\n if (children && children.length > 0) node.children = children;\n if (key !== undefined) node.key = key;\n return node;\n}\n", "import type { WidgetKind } from \"../contract/types.js\";\nimport type { DataSchema } from \"./schema.js\";\nimport type { WidgetStyles } from \"./styles.js\";\n\n/**\n * Agent-facing documentation for a widget kind. Descriptors make the\n * catalog reflectable: tooling (e.g. the widgentic MCP server's\n * `list_widgets`) lists them so agents can pick a widget and shape their\n * `data` without reading source.\n */\nexport interface WidgetDescriptor {\n kind: WidgetKind;\n /** What the widget is for. */\n description: string;\n /** Human-readable description of the expected `data` input. */\n dataShape: string;\n /** Small example `data` value an agent can imitate. */\n dataExample?: unknown;\n /** Supported hint keys and what they do. */\n hints?: Record<string, string>;\n /**\n * Optional JSON-Schema subset for `data` (see schema.ts). When present,\n * `catalog.render` validates data against it before rendering; kinds\n * without one keep their lenient fallback behavior.\n */\n dataSchema?: DataSchema;\n /**\n * Optional CSS-as-data for the kind's `.wg-` classes (see styles.ts).\n * Included in `page` output and exposable by hosts; guarded like themes.\n */\n styles?: WidgetStyles;\n}\n\n/** Descriptor as supplied at registration; `kind` is filled by the catalog. */\nexport type WidgetDescriptorInput = Omit<WidgetDescriptor, \"kind\">;\n\n/**\n * How agents should write the labels a reader sees \u2014 the `labels` hint of\n * the built-in card and table, and the literals a template writes. One\n * text, derived by every surface that steers agents.\n */\nexport const LABEL_STYLE_RULE =\n 'Labels are what the reader sees: write them in Title Case (\"First Name\", \"Order Total\") ' +\n \"unless the user asks for another style or language, and keep the data's keys as they are.\";\n\n/**\n * Honest documentation of the built-ins' actual (lenient) behavior. Every\n * `dataExample` is asserted by tests to render successfully.\n */\nexport const BUILTIN_DESCRIPTORS: Record<\n \"card\" | \"table\" | \"tree\" | \"group\",\n WidgetDescriptorInput\n> = {\n card: {\n description:\n \"Key/value details for a single entity, with optional title and subtitle.\",\n dataShape:\n \"A plain object. `title`, `subtitle`, and `fields` are used when present; \" +\n \"other entries become field key/value pairs. Primitives render as a single \" +\n \"value line. `meta.title`/`meta.subtitle` fill in missing chrome. Send \" +\n \"field values typed (e.g. price: 9.99, not '$9.99') and use \" +\n \"hints.fieldFormat for display formatting \u2014 the payload keeps the \" +\n \"typed value while the render gets its unit. Field values that are \" +\n \"image URLs render as images (see hints.images). Each field is labelled \" +\n \"by its key unless hints.labels names it.\",\n dataExample: {\n title: \"Essence Mascara\",\n subtitle: \"beauty\",\n fields: { price: 9.99, rating: 2.56, stock: 99 }\n },\n hints: {\n fieldFormat:\n \"Record<fieldKey, pattern> \u2014 formats matching field values by \" +\n \"substituting {value} in the pattern (e.g. { price: '${value}', \" +\n \"rating: '{value} / 5' }); a pattern without {value} is prefixed \" +\n \"to the value. Output is escaped like any text.\",\n images:\n \"Record<fieldKey, 'avatar' | 'thumb' | 'hero' | true | false> \u2014 \" +\n \"field values that are https image URLs (image extension) or \" +\n \"data:image/* URIs auto-render as images (default shape: thumb); \" +\n \"a shape forces image treatment (use for extensionless URLs), \" +\n \"true forces the default shape, false keeps the URL as text. \" +\n \"Unsafe sources always render as text; image treatment wins over \" +\n \"fieldFormat for the same key.\",\n labels:\n \"Record<fieldKey, string> \u2014 the label shown for a field instead of \" +\n \"its key (also an image field's alt text); every other hint still \" +\n \"names the key. \" +\n LABEL_STYLE_RULE,\n links:\n \"Record<fieldKey, boolean | prefix> \u2014 true links a field whose \" +\n \"value already IS an http(s)/mailto/tel URL; a prefix string \" +\n \"composes the href while the display stays the clean value \" +\n \"(e.g. { email: 'mailto:', phone: 'tel:' } shows a@b.c but links \" +\n \"mailto:a@b.c). Unsafe compositions and non-strings stay plain \" +\n \"text; image treatment wins for the same key. Links are never \" +\n \"automatic \u2014 opt in per field.\"\n }\n },\n table: {\n description: \"Rows and columns for arrays of records.\",\n dataShape:\n \"An array of records (plain objects). Columns are the union of record keys \" +\n \"in first-seen order; missing cells render empty; non-array data becomes a \" +\n \"single row. Cell values that are image URLs render as avatars (see \" +\n \"hints.images). meta.title/meta.subtitle render as the table's caption. \" +\n \"Send cell values typed (e.g. total: 11471334.78, not '11,471,334.78') \" +\n \"and use hints.fieldFormat for display formatting \u2014 the payload keeps \" +\n \"the typed value while the render gets its unit.\",\n dataExample: [\n { name: \"Ada\", role: \"eng\", avatar: \"https://picsum.photos/id/64/64/64.jpg\" },\n { name: \"Lin\", role: \"ops\", avatar: \"https://picsum.photos/id/65/64/64.jpg\" }\n ],\n hints: {\n columns: \"string[] \u2014 overrides column selection and order\",\n labels:\n \"Record<columnKey, string> \u2014 the header shown for a column instead \" +\n \"of its key (also its images' alt text); every other hint, \" +\n \"columns included, still names the key. \" +\n LABEL_STYLE_RULE,\n fieldFormat:\n \"Record<columnKey, pattern> \u2014 formats matching cell values by \" +\n \"substituting {value} in the pattern (e.g. { total: '${value}' }); \" +\n \"a pattern without {value} is prefixed to the value. Output is \" +\n \"escaped like any text; image treatment wins for the same column.\",\n links:\n \"Record<columnKey, boolean | prefix> \u2014 true links cells whose \" +\n \"value already IS an http(s)/mailto/tel URL; a prefix string \" +\n \"composes the href while the display stays the clean value \" +\n \"(e.g. { email: 'mailto:', phone: 'tel:' } shows a@b.c but links \" +\n \"mailto:a@b.c). Unsafe compositions and non-strings stay plain \" +\n \"text; image treatment wins for the same column. Links are never \" +\n \"automatic \u2014 opt in per column.\",\n images:\n \"Record<columnKey, 'avatar' | 'thumb' | 'hero' | true | false> \u2014 \" +\n \"cell values that are https image URLs (image extension) or \" +\n \"data:image/* URIs auto-render as images (default shape: avatar); \" +\n \"a shape forces image treatment (use for extensionless URLs), \" +\n \"true forces the default shape, false keeps the URL as text. \" +\n \"Unsafe sources always render as text.\"\n }\n },\n tree: {\n description:\n \"Collapsible hierarchy of labeled nodes \u2014 a person can expand and \" +\n \"collapse branches by click or keyboard.\",\n dataShape:\n \"Nested `{ label, icon?, children[] }` nodes \u2014 a single root object or an \" +\n \"array of them. A node with children renders as a native disclosure that \" +\n \"opens and closes; leaves are plain labels. Optional `icon` is ONE string \" +\n \"per node, shown before the label: a data:image/* URI or an https URL \" +\n \"ending in an image extension (.png, .jpg, .svg, ...) renders as a small \" +\n \"decorative image; any other string \u2014 an emoji, a glyph, an extensionless \" +\n \"URL \u2014 renders as text. Nodes without a usable `label` get a JSON fallback label (which \" +\n \"excludes `children` and `icon`). meta.title renders as a title line above \" +\n \"the tree.\",\n dataExample: {\n label: \"src\",\n icon: \"\\u{1F4C1}\",\n children: [{ label: \"index.ts\", icon: \"\\u{1F4C4}\", children: [] }]\n },\n hints: {\n expandDepth:\n \"number \u2014 branches at depth < value START expanded (default: \" +\n \"unlimited). Presentational only: the full subtree is always in the \" +\n \"markup, and collapsing is the disclosure's own behavior. The value \" +\n \"selects only the INITIAL state (the `open` attribute on branches); \" +\n \"a visitor's own expand/collapse survives later re-renders.\"\n }\n },\n group: {\n description:\n \"Several widgets in one response \u2014 mixed kinds in a single layout \" +\n \"container. Use ONE group render instead of repeated render calls \" +\n \"when showing multiple widgets together.\",\n dataShape:\n \"{ items: [{ kind, data, hints?, meta? }, ...] } \u2014 each item is a \" +\n \"full sub-widget rendered exactly as a top-level call would be \" +\n \"(any listed kind except 'group'; groups do not nest). At most 20 \" +\n \"items per group.\",\n dataExample: {\n items: [\n { kind: \"card\", data: { title: \"Ada\", fields: { role: \"eng\" } } },\n { kind: \"card\", data: { title: \"Lin\", fields: { role: \"ops\" } } }\n ]\n },\n hints: {\n layout:\n \"'stack' | 'row' | 'grid' \u2014 how items sit together (default: \" +\n \"stack). 'row' wraps; 'grid' uses equal columns.\",\n gap: \"'none' | 'sm' | 'md' | 'lg' \u2014 spacing between items (default: md).\",\n columns: \"number 1-4 \u2014 column count for layout: 'grid' (default: 2).\"\n }\n }\n};\n", "import type { WidgetContractError } from \"../contract/errors.js\";\n\n/**\n * A JSON-Schema *subset* for widget `data`: `type`, `properties`,\n * `required`, `items`, `enum`, `pattern`. Unknown keywords are ignored\n * (forward compatible), never misinterpreted \u2014 and that policy extends to\n * `pattern` values this module refuses to run (see the ReDoS bounds\n * below). Violations map to the existing contract vocabulary with dotted\n * paths into the data.\n */\nexport type DataSchema = Record<string, unknown>;\n\n// `pattern` bounds: schemas arrive from descriptor authors, but the strings\n// they test arrive from agents \u2014 an exponential-backtracking pattern over\n// attacker-lengthened input is a denial of service. Overlong patterns,\n// nested-quantifier shapes, and RegExp-invalid sources are IGNORED (never\n// misinterpreted as passing or failing); tested strings are capped.\n/** Longest `pattern` the validator will compile. */\nexport const PATTERN_MAX_LENGTH = 256;\nconst TESTED_STRING_MAX = 10_000;\nconst NESTED_QUANTIFIER = /(\\([^)]*[+*][^)]*\\)|\\[[^\\]]*\\][+*])[+*{]/;\n\nfunction compileSafePattern(pattern: unknown): RegExp | undefined {\n if (typeof pattern !== \"string\" || pattern.length > PATTERN_MAX_LENGTH) {\n return undefined;\n }\n if (NESTED_QUANTIFIER.test(pattern)) return undefined;\n try {\n return new RegExp(pattern);\n } catch {\n return undefined;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The `type` names the validator checks; any other name constrains nothing. */\nexport const DATA_SCHEMA_TYPES: readonly string[] = [\n \"object\",\n \"array\",\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"null\"\n];\n\nfunction matchesSingleType(type: string, data: unknown): boolean {\n switch (type) {\n case \"object\":\n return isPlainObject(data);\n case \"array\":\n return Array.isArray(data);\n case \"string\":\n return typeof data === \"string\";\n case \"number\":\n return typeof data === \"number\";\n case \"integer\":\n return typeof data === \"number\" && Number.isInteger(data);\n case \"boolean\":\n return typeof data === \"boolean\";\n case \"null\":\n return data === null;\n default:\n // Unknown type keyword: ignore rather than reject.\n return true;\n }\n}\n\nfunction matchesType(type: unknown, data: unknown): boolean {\n if (typeof type === \"string\") return matchesSingleType(type, data);\n if (Array.isArray(type)) {\n return type.some(\n (candidate) =>\n typeof candidate === \"string\" && matchesSingleType(candidate, data)\n );\n }\n return true;\n}\n\nfunction enumMatches(allowed: unknown[], data: unknown): boolean {\n return allowed.some((value) => {\n if (value === data) return true;\n try {\n return JSON.stringify(value) === JSON.stringify(data);\n } catch {\n return false;\n }\n });\n}\n\nfunction formatType(type: unknown): string {\n return Array.isArray(type) ? type.join(\" | \") : String(type);\n}\n\n/**\n * Validate `data` against a subset schema. Returns the first violation as a\n * contract-vocabulary error (`MISSING_FIELD` for required, `INVALID_TYPE`\n * for type/enum) with a dotted path, or `undefined` when valid. Never\n * throws.\n */\nexport function validateDataAgainstSchema(\n schema: DataSchema,\n data: unknown,\n path = \"data\"\n): WidgetContractError | undefined {\n if (Array.isArray(schema.enum) && !enumMatches(schema.enum, data)) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must be one of the enumerated options.`\n };\n }\n\n if (schema.type !== undefined && !matchesType(schema.type, data)) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must have type ${formatType(schema.type)}.`\n };\n }\n\n // Pattern applies to string data only \u2014 type mismatches are `type`'s job.\n if (typeof data === \"string\" && schema.pattern !== undefined) {\n const regex = compileSafePattern(schema.pattern);\n if (regex !== undefined && !regex.test(data.slice(0, TESTED_STRING_MAX))) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must match pattern ${String(schema.pattern)}.`\n };\n }\n }\n\n if (isPlainObject(data)) {\n if (Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (typeof key === \"string\" && !(key in data)) {\n return {\n code: \"MISSING_FIELD\",\n path: `${path}.${key}`,\n message: `Missing required property '${key}'.`\n };\n }\n }\n }\n if (isPlainObject(schema.properties)) {\n for (const [key, subschema] of Object.entries(schema.properties)) {\n if (key in data && isPlainObject(subschema)) {\n const error = validateDataAgainstSchema(\n subschema,\n data[key],\n `${path}.${key}`\n );\n if (error) return error;\n }\n }\n }\n }\n\n if (Array.isArray(data) && isPlainObject(schema.items)) {\n for (let i = 0; i < data.length; i++) {\n const error = validateDataAgainstSchema(\n schema.items as DataSchema,\n data[i],\n `${path}.${i}`\n );\n if (error) return error;\n }\n }\n\n return undefined;\n}\n\n/**\n * What the validator would silently ignore in a schema: an unknown `type`\n * name, a `pattern` it refuses to run, or a subset keyword of the wrong\n * shape. Warnings, never refusals \u2014 stores accept these (unknown input is\n * ignored, not misread), but an author meant something by them. Paths are\n * dotted from `path`. Never throws.\n */\nexport function auditDataSchema(schema: DataSchema, path = \"schema\"): string[] {\n const warnings: string[] = [];\n const type = schema.type;\n if (type !== undefined) {\n const names = typeof type === \"string\" ? [type] : Array.isArray(type) ? type : undefined;\n if (names === undefined) {\n warnings.push(`${path}.type: must be a type name or a list of them; it is ignored.`);\n } else {\n for (const name of names) {\n if (typeof name !== \"string\" || !DATA_SCHEMA_TYPES.includes(name)) {\n warnings.push(\n `${path}.type: '${String(name)}' is not one of ${DATA_SCHEMA_TYPES.join(\", \")}; it constrains nothing.`\n );\n }\n }\n }\n }\n if (schema.pattern !== undefined && compileSafePattern(schema.pattern) === undefined) {\n warnings.push(\n `${path}.pattern: not run \u2014 it must be a valid regular expression of at most ${PATTERN_MAX_LENGTH} characters without nested quantifiers.`\n );\n }\n if (schema.enum !== undefined && !Array.isArray(schema.enum)) {\n warnings.push(`${path}.enum: must be a list of values; it is ignored.`);\n }\n if (\n schema.required !== undefined &&\n !(Array.isArray(schema.required) && schema.required.every((key) => typeof key === \"string\"))\n ) {\n warnings.push(`${path}.required: must be a list of property names; it is ignored.`);\n }\n if (schema.properties !== undefined) {\n if (!isPlainObject(schema.properties)) {\n warnings.push(`${path}.properties: must be an object of schemas; it is ignored.`);\n } else {\n for (const [key, subschema] of Object.entries(schema.properties)) {\n if (isPlainObject(subschema)) warnings.push(...auditDataSchema(subschema, `${path}.properties.${key}`));\n else warnings.push(`${path}.properties.${key}: must be a schema object; it is ignored.`);\n }\n }\n }\n if (schema.items !== undefined) {\n if (isPlainObject(schema.items)) warnings.push(...auditDataSchema(schema.items, `${path}.items`));\n else warnings.push(`${path}.items: must be a schema object; it is ignored.`);\n }\n return warnings;\n}\n", "/** Shared helpers for the built-in renderers. */\nimport { isLinkableUrl } from \"../../contract/urls.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\n\n/** Same plain-object definition as the contract validator. */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Render any value as display text. Strings pass through; primitives\n * stringify; structured values fall back to compact JSON. Never throws.\n */\nexport function formatValue(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined) return \"\";\n if (\n value === null ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\"\n ) {\n return String(value);\n }\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * The label a reader sees for a card field or table column: its\n * `hints.labels` entry when that is a non-blank string, else the key.\n */\nexport function labelFor(key: string, hints: unknown): string {\n const labels = isPlainObject(hints) && isPlainObject(hints.labels) ? hints.labels : undefined;\n const label = labels?.[key];\n return typeof label === \"string\" && label.trim() !== \"\" ? label : key;\n}\n\n/** Apply a `fieldFormat` pattern: substitute `{value}`, or append when absent. */\nexport function applyPattern(pattern: string, value: string): string {\n return pattern.includes(\"{value}\")\n ? pattern.split(\"{value}\").join(value)\n : pattern + value;\n}\n\n/**\n * Wrap display text in an anchor when the caller opted this key into\n * `hints.links` AND the raw value is an explicitly-schemed safe URL.\n * Built-ins construct nodes directly (they never pass the template\n * compiler's URL guard), so the scheme check lives here \u2014 mirroring\n * `isSafeImageSrc` in the image path. Everything else stays plain text.\n */\nexport function linkOrText(\n key: string,\n raw: unknown,\n hints: unknown,\n display: string\n): WidgetNode {\n const links =\n isPlainObject(hints) && isPlainObject(hints.links) ? hints.links : undefined;\n const hint = links?.[key];\n if (typeof raw !== \"string\" || raw === \"\") return display;\n // true: the value IS the URL. String: an author-supplied prefix composed\n // with the value (e.g. \"mailto:\") \u2014 the display stays the clean value,\n // and the COMPOSED href faces the guard, so a hostile value can never\n // smuggle a scheme past an author prefix.\n const href =\n hint === true ? raw : typeof hint === \"string\" ? hint + raw : undefined;\n if (href === undefined || !isLinkableUrl(href)) return display;\n return el(\n \"a\",\n { class: \"wg-link\", href, rel: \"noopener noreferrer\" },\n [display]\n );\n}\n", "import { isSafeImageSrc, looksLikeImageUrl } from \"../../contract/urls.js\";\nimport type { WidgetElementNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { isPlainObject } from \"./format.js\";\n\n/** Image presentation variants; each maps to a `wg-img-<shape>` class. */\nexport type ImageShape = \"avatar\" | \"thumb\" | \"hero\";\n\n/**\n * Render-only shapes extend the hintable ones: `icon` is the tree's\n * per-node anchor and is deliberately not accepted by `hints.images`.\n */\nexport type RenderImageShape = ImageShape | \"icon\";\n\nconst HINTABLE_SHAPES: readonly ImageShape[] = [\"avatar\", \"thumb\", \"hero\"];\nconst SHAPES = new Set<string>(HINTABLE_SHAPES);\n\n/**\n * Decide whether a card-field / table-cell value renders as an image.\n * `hints.images` (keyed by field/column name) overrides auto-detection:\n * a shape string forces that shape, `true` forces the context default,\n * `false` suppresses. Hints never bypass safety \u2014 an unsafe source always\n * renders as text (`null` here). Auto-detection requires the value to\n * self-identify as an image (`looksLikeImageUrl`).\n */\nexport function resolveImage(\n key: string,\n value: unknown,\n hints: Record<string, unknown> | undefined,\n defaultShape: RenderImageShape\n): { src: string; shape: RenderImageShape } | null {\n if (typeof value !== \"string\") return null;\n const images = isPlainObject(hints?.images) ? hints.images : undefined;\n const hint = images?.[key];\n if (hint === false) return null;\n if (typeof hint === \"string\" && SHAPES.has(hint)) {\n return isSafeImageSrc(value)\n ? { src: value, shape: hint as ImageShape }\n : null;\n }\n if (hint === true) {\n return isSafeImageSrc(value) ? { src: value, shape: defaultShape } : null;\n }\n return looksLikeImageUrl(value) ? { src: value, shape: defaultShape } : null;\n}\n\n/**\n * The standard image element: stable classes, the field's label (its key\n * when unlabelled) as alt, lazy loading. An empty `alt` marks decorative\n * images whose meaning the neighbouring text already carries.\n */\nexport function imageNode(\n alt: string,\n src: string,\n shape: RenderImageShape\n): WidgetElementNode {\n return el(\"img\", {\n class: `wg-img wg-img-${shape}`,\n src,\n alt,\n loading: \"lazy\",\n decoding: \"async\"\n });\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { applyPattern, formatValue, isPlainObject, labelFor, linkOrText } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\n\n/**\n * `card` renderer.\n *\n * Uses `data.title`/`data.subtitle`/`data.fields` when present; other\n * plain-object entries become field key/value pairs; primitives and `null`\n * render as a single value line. `meta.title`/`meta.subtitle` fill in when\n * `data` does not provide them. A field shows its `hints.labels` entry, or\n * its key; every other hint still addresses it by key. Total: never throws.\n */\nexport function renderCard(payload: WidgetPayload): WidgetNode {\n const { data, meta } = payload;\n const fieldFormat = isPlainObject(payload.hints?.fieldFormat)\n ? payload.hints.fieldFormat\n : undefined;\n\n let title: unknown;\n let subtitle: unknown;\n let fieldEntries: [string, unknown][] = [];\n let value: string | undefined;\n\n if (isPlainObject(data)) {\n title = data.title;\n subtitle = data.subtitle;\n if (isPlainObject(data.fields)) {\n fieldEntries = Object.entries(data.fields);\n } else {\n fieldEntries = Object.entries(data).filter(\n ([key]) => key !== \"title\" && key !== \"subtitle\"\n );\n }\n } else {\n value = formatValue(data);\n }\n\n if (title === undefined) title = meta?.title;\n if (subtitle === undefined) subtitle = meta?.subtitle;\n\n const children: WidgetNode[] = [];\n if (title !== undefined) {\n children.push(el(\"div\", { class: \"wg-card-title\" }, [formatValue(title)]));\n }\n if (subtitle !== undefined) {\n children.push(\n el(\"div\", { class: \"wg-card-subtitle\" }, [formatValue(subtitle)])\n );\n }\n if (value !== undefined) {\n children.push(el(\"div\", { class: \"wg-card-value\" }, [value]));\n }\n if (fieldEntries.length > 0) {\n children.push(\n el(\n \"dl\",\n { class: \"wg-card-fields\" },\n fieldEntries.map(([key, fieldValue]) => {\n const label = labelFor(key, payload.hints);\n // Image treatment wins over fieldFormat for the same key.\n const image = resolveImage(key, fieldValue, payload.hints, \"thumb\");\n let display: WidgetNode;\n if (image) {\n display = imageNode(label, image.src, image.shape);\n } else {\n const raw = formatValue(fieldValue);\n const pattern = fieldFormat?.[key];\n const text =\n typeof pattern === \"string\" ? applyPattern(pattern, raw) : raw;\n display = linkOrText(key, fieldValue, payload.hints, text);\n }\n return el(\"div\", { class: \"wg-card-field\" }, [\n el(\"dt\", { class: \"wg-card-field-key\" }, [label]),\n el(\"dd\", { class: \"wg-card-field-value\" }, [display])\n ]);\n })\n )\n );\n }\n return el(\"div\", { class: \"wg-card\" }, children);\n}\n", "import { isPlainObject } from \"./format.js\";\n\n/**\n * Keys for a sibling list from record identity: every item must be an\n * object whose `id` is a string or a finite number, and the ids must be\n * distinct as strings (`1` and `\"1\"` collide). Otherwise the list stays\n * unkeyed and the patchers pair it by position.\n */\nexport function keysFromIds(items: readonly unknown[]): string[] | undefined {\n const keys: string[] = [];\n const seen = new Set<string>();\n for (const item of items) {\n if (!isPlainObject(item)) return undefined;\n const id = item.id;\n let key: string;\n if (typeof id === \"string\") key = id;\n else if (typeof id === \"number\" && Number.isFinite(id)) key = String(id);\n else return undefined;\n if (seen.has(key)) return undefined;\n seen.add(key);\n keys.push(key);\n }\n return keys;\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { applyPattern, formatValue, isPlainObject, labelFor, linkOrText } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\nimport { keysFromIds } from \"./keys.js\";\n\n/**\n * `table` renderer.\n *\n * One row per record; columns are the union of record keys in first-seen\n * order, overridable via `hints.columns`. Non-array data becomes a\n * single-record array; non-object rows are wrapped as `{ value }`. A\n * header shows its column's `hints.labels` entry, or its key. Missing\n * cells render empty. Body rows are keyed by record `id` when every record\n * carries a distinct one, so a reordering re-render moves rows instead of\n * re-pairing them. Total: never throws.\n */\nexport function renderTable(payload: WidgetPayload): WidgetNode {\n const rows = Array.isArray(payload.data) ? payload.data : [payload.data];\n const fieldFormat = isPlainObject(payload.hints?.fieldFormat)\n ? payload.hints.fieldFormat\n : undefined;\n const records: Record<string, unknown>[] = rows.map((row) =>\n isPlainObject(row) ? row : { value: row }\n );\n\n const hintColumns = payload.hints?.columns;\n let columns: string[];\n if (\n Array.isArray(hintColumns) &&\n hintColumns.every((column): column is string => typeof column === \"string\")\n ) {\n columns = hintColumns;\n } else {\n columns = [];\n const seen = new Set<string>();\n for (const record of records) {\n for (const key of Object.keys(record)) {\n if (!seen.has(key)) {\n seen.add(key);\n columns.push(key);\n }\n }\n }\n }\n\n const rowKeys = keysFromIds(records);\n\n // Caption chrome from meta \u2014 a table's data has no title slot, so meta\n // is the only source; absence means no caption. <caption> must be the\n // table's first child per the HTML content model.\n const chrome: WidgetNode[] = [];\n const title = payload.meta?.title;\n const subtitle = payload.meta?.subtitle;\n if (title !== undefined || subtitle !== undefined) {\n const parts: WidgetNode[] = [];\n if (title !== undefined) {\n parts.push(el(\"span\", { class: \"wg-table-title\" }, [formatValue(title)]));\n }\n if (subtitle !== undefined) {\n parts.push(\n el(\"span\", { class: \"wg-table-subtitle\" }, [formatValue(subtitle)])\n );\n }\n chrome.push(el(\"caption\", { class: \"wg-table-caption\" }, parts));\n }\n\n return el(\"table\", { class: \"wg-table\" }, [\n ...chrome,\n el(\"thead\", { class: \"wg-table-head\" }, [\n el(\n \"tr\",\n undefined,\n columns.map((column) =>\n el(\"th\", { class: \"wg-table-header\" }, [labelFor(column, payload.hints)])\n )\n )\n ]),\n el(\n \"tbody\",\n { class: \"wg-table-body\" },\n records.map((record, index) =>\n el(\n \"tr\",\n { class: \"wg-table-row\" },\n columns.map((column) => {\n if (!(column in record)) {\n return el(\"td\", { class: \"wg-table-cell\" }, [\"\"]);\n }\n const value = record[column];\n // Precedence per column: image > link > formatted text.\n const image = resolveImage(column, value, payload.hints, \"avatar\");\n let display: WidgetNode;\n if (image) {\n display = imageNode(labelFor(column, payload.hints), image.src, image.shape);\n } else {\n const raw = formatValue(value);\n const pattern = fieldFormat?.[column];\n const text =\n typeof pattern === \"string\" ? applyPattern(pattern, raw) : raw;\n display = linkOrText(column, value, payload.hints, text);\n }\n return el(\"td\", { class: \"wg-table-cell\" }, [display]);\n }),\n rowKeys?.[index]\n )\n )\n )\n ]);\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { formatValue, isPlainObject } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\nimport { keysFromIds } from \"./keys.js\";\n\n/**\n * `tree` renderer.\n *\n * Renders nested `{ label, icon?, children[] }` nodes; nodes without a\n * usable `label` get a JSON-snippet fallback (excluding `children` and\n * `icon`). Recurses only into array-valued `children`. A node with children\n * renders as a native `details`/`summary` disclosure, so branches expand and\n * collapse with no script in every context the HTML reaches;\n * `hints.expandDepth` (default unlimited) selects the INITIAL state by\n * marking nodes at depth < value `open`. Leaves carry no disclosure. Each\n * sibling list is keyed by node `id` when all its nodes carry distinct ones,\n * so a visitor's open branch follows its node through a reorder.\n * Total: never throws.\n */\nexport function renderTree(payload: WidgetPayload): WidgetNode {\n const depthHint = payload.hints?.expandDepth;\n // Negative depths clamp to 0 (everything collapsed): `depth < value` must\n // hold monotonically, or -1 would flip a fully-collapsed tree fully open.\n const expandDepth =\n typeof depthHint === \"number\" && !Number.isNaN(depthHint)\n ? Math.max(0, depthHint)\n : Infinity;\n const roots = Array.isArray(payload.data) ? payload.data : [payload.data];\n const list = el(\"ul\", { class: \"wg-tree\" }, renderList(roots, 0, expandDepth));\n // Title chrome from meta \u2014 tree data has no title slot, so meta is the\n // only source; absence means no title line.\n const title = payload.meta?.title;\n if (title === undefined) return list;\n return el(\"div\", { class: \"wg-tree-titled\" }, [\n el(\"div\", { class: \"wg-tree-title\" }, [formatValue(title)]),\n list\n ]);\n}\n\nfunction nodeLabel(node: unknown): string {\n if (isPlainObject(node)) {\n if (node.label !== undefined) return formatValue(node.label);\n // The fallback snippet always excludes `children` and `icon` \u2014 a node\n // carrying only those must not print its own subtree as its label.\n const { children: _children, icon: _icon, ...rest } = node;\n return formatValue(rest);\n }\n return formatValue(node);\n}\n\n/**\n * The node's optional visual anchor, before the label. The same gate card\n * and table use decides image treatment \u2014 one rule to audit \u2014 and anything\n * else (an emoji, a glyph, an unsafe URL) stays text. Decorative: the alt is\n * empty because the label already carries the meaning.\n */\nfunction iconNode(icon: unknown): WidgetNode | undefined {\n if (typeof icon !== \"string\") return undefined;\n const image = resolveImage(\"\", icon, undefined, \"icon\");\n if (image !== null) return imageNode(\"\", image.src, image.shape);\n return el(\"span\", { class: \"wg-tree-icon\" }, [icon]);\n}\n\nfunction labelChildren(node: unknown): WidgetNode[] {\n const icon = isPlainObject(node) ? iconNode(node.icon) : undefined;\n const label = nodeLabel(node);\n return icon === undefined ? [label] : [icon, label];\n}\n\n// Deeper trees than any honest payload; past it nodes render as leaves so a\n// hostile nesting cannot overflow the recursive renderer or the serializers.\nconst MAX_TREE_DEPTH = 64;\n\nconst childrenOf = (node: unknown): unknown[] | undefined =>\n isPlainObject(node) && Array.isArray(node.children) && node.children.length > 0\n ? node.children\n : undefined;\n\nfunction renderList(nodes: unknown[], depth: number, expandDepth: number): WidgetNode[] {\n const keys = keysFromIds(nodes);\n return nodes.map((node, index) => renderNode(node, depth, expandDepth, keys?.[index]));\n}\n\nfunction renderNode(\n node: unknown,\n depth: number,\n expandDepth: number,\n key: string | undefined\n): WidgetNode {\n const childNodes = depth < MAX_TREE_DEPTH ? childrenOf(node) : undefined;\n\n // Leaves are plain labels: the presence of the disclosure is what marks a\n // branch, so a leaf must not offer a toggle affordance.\n if (childNodes === undefined) {\n return el(\n \"li\",\n { class: \"wg-tree-node\" },\n [el(\"span\", { class: \"wg-tree-label\" }, labelChildren(node))],\n key\n );\n }\n // `open` is a pure function of data + hints, so an unchanged branch\n // re-emits the same attributes and the in-place patchers leave a\n // visitor's own toggle alone.\n const isOpen = depth < expandDepth;\n return el(\n \"li\",\n { class: \"wg-tree-node\" },\n [\n el(\n \"details\",\n { class: \"wg-tree-branch\", ...(isOpen ? { open: \"\" } : {}) },\n [\n el(\"summary\", { class: \"wg-tree-label\" }, labelChildren(node)),\n el(\n \"ul\",\n { class: \"wg-tree-children\" },\n renderList(childNodes, depth + 1, expandDepth)\n )\n ]\n )\n ],\n key\n );\n}\n", "/**\n * `group` built-in \u2014 several widgets in one render.\n *\n * The renderer here only builds the layout container; item rendering is\n * the catalog dispatch's job (items re-enter `catalog.render`, so\n * registered and composed kinds participate and per-item errors keep\n * their structured codes with `data.items[<i>]`-prefixed paths).\n */\nimport type { WidgetContractError } from \"../../contract/errors.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { isPlainObject } from \"./format.js\";\n\n/** Hard cap on `data.items` \u2014 bounds total render work per call. */\nexport const GROUP_MAX_ITEMS = 20;\n\nexport const GROUP_LAYOUTS = [\"stack\", \"row\", \"grid\"] as const;\nexport const GROUP_GAPS = [\"none\", \"sm\", \"md\", \"lg\"] as const;\n/** `columns` is clamped into this range (grid only). */\nexport const GROUP_MAX_COLUMNS = 4;\n\nexport interface GroupItem {\n kind: string;\n data: unknown;\n hints?: unknown;\n meta?: unknown;\n}\n\nexport type GroupEnvelopeResult =\n | { ok: true; items: GroupItem[] }\n | { ok: false; error: WidgetContractError };\n\n/**\n * Validate the group envelope: `data.items` is an array of sub-widget\n * objects with string kinds, no nested groups, within the item cap.\n * Item *content* is not judged here \u2014 each item faces the full contract\n * and schema validation when it re-enters the catalog.\n */\nexport function checkGroupEnvelope(data: unknown): GroupEnvelopeResult {\n if (!isPlainObject(data) || data.items === undefined) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"data.items\",\n message: \"'group' data must be an object with an 'items' array.\"\n }\n };\n }\n const items = data.items;\n if (!Array.isArray(items)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"data.items\",\n message: \"'items' must be an array of sub-widgets.\"\n }\n };\n }\n if (items.length > GROUP_MAX_ITEMS) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"data.items\",\n message: `'items' holds ${items.length} sub-widgets; a group renders at most ${GROUP_MAX_ITEMS}.`\n }\n };\n }\n const checked: GroupItem[] = [];\n for (let i = 0; i < items.length; i++) {\n const item: unknown = items[i];\n if (!isPlainObject(item)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}]`,\n message: \"each item must be an object: { kind, data, hints?, meta? }.\"\n }\n };\n }\n if (typeof item.kind !== \"string\" || item.kind === \"\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}].kind`,\n message: \"each item needs a widget kind (non-empty string).\"\n }\n };\n }\n if (item.kind === \"group\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}].kind`,\n message: \"a 'group' cannot contain another 'group'.\"\n }\n };\n }\n const entry: GroupItem = { kind: item.kind, data: item.data };\n if (item.hints !== undefined) entry.hints = item.hints;\n if (item.meta !== undefined) entry.meta = item.meta;\n checked.push(entry);\n }\n return { ok: true, items: checked };\n}\n\n/**\n * Build the layout container. Hints only ever SELECT from the fixed\n * class names below \u2014 no hint or data value contributes characters to\n * the class list. Unknown values fall back to the defaults (hint\n * diagnostics, not renderers, tell the caller).\n */\nexport function renderGroupContainer(\n hints: unknown,\n children: WidgetNode[]\n): WidgetNode {\n const h = isPlainObject(hints) ? hints : {};\n const layout = GROUP_LAYOUTS.some((known) => known === h.layout)\n ? (h.layout as string)\n : \"stack\";\n const gap = GROUP_GAPS.some((known) => known === h.gap)\n ? (h.gap as string)\n : \"md\";\n const classes = [`wg-group`, `wg-group-${layout}`, `wg-gap-${gap}`];\n if (layout === \"grid\") {\n const raw = typeof h.columns === \"number\" && Number.isFinite(h.columns) ? h.columns : 2;\n const columns = Math.min(GROUP_MAX_COLUMNS, Math.max(1, Math.trunc(raw)));\n classes.push(`wg-cols-${columns}`);\n }\n return el(\"div\", { class: classes.join(\" \") }, children);\n}\n", "import { validateWidgetPayload } from \"../contract/validate.js\";\nimport type { WidgetContractError } from \"../contract/errors.js\";\nimport type { WidgetKind } from \"../contract/types.js\";\nimport type { WidgetNode, WidgetRenderer } from \"./node.js\";\nimport type { WidgetDescriptor, WidgetDescriptorInput } from \"./descriptors.js\";\nimport { BUILTIN_DESCRIPTORS } from \"./descriptors.js\";\nimport { validateDataAgainstSchema } from \"./schema.js\";\nimport { renderCard } from \"./widgets/card.js\";\nimport { renderTable } from \"./widgets/table.js\";\nimport { renderTree } from \"./widgets/tree.js\";\nimport { checkGroupEnvelope, renderGroupContainer } from \"./widgets/group.js\";\n\n/**\n * Group composition: an item's action descriptors were compiled against\n * the ITEM's template, so they name the item's kind (`widget`) but not\n * where the item sits in the group payload. Stamping `at` lets the server\n * fold an action's result back into the right item and re-render the whole\n * group. Returns a NEW tree \u2014 renderers may hand back cached nodes, and\n * composition must not mutate what a pure renderer returned. Groups do not\n * nest, so the location is always one level: `data.items.<i>`.\n */\nfunction stampActionLocation(node: WidgetNode, location: string): WidgetNode {\n if (typeof node === \"string\") return node;\n const raw = node.attrs?.[\"data-wg-action\"];\n let attrs = node.attrs;\n if (typeof raw === \"string\") {\n try {\n const descriptor = JSON.parse(raw) as Record<string, unknown>;\n if (typeof descriptor === \"object\" && descriptor !== null) {\n attrs = { ...node.attrs, \"data-wg-action\": JSON.stringify({ ...descriptor, at: location }) };\n }\n } catch {\n /* not a descriptor */\n }\n }\n const children = node.children?.map((child) => stampActionLocation(child, location));\n return {\n tag: node.tag,\n ...(attrs !== undefined ? { attrs } : {}),\n ...(children !== undefined ? { children } : {})\n };\n}\n\n/**\n * Thrown when a widget kind is registered twice on the same catalog.\n * Double registration is a host programming error, surfaced loudly at\n * setup time \u2014 unlike render-time errors, which are structured results.\n */\nexport class DuplicateKindError extends Error {\n readonly code: \"DUPLICATE_KIND\" = \"DUPLICATE_KIND\";\n readonly kind: string;\n\n constructor(kind: string) {\n super(`Widget kind '${kind}' is already registered.`);\n this.name = \"DuplicateKindError\";\n this.kind = kind;\n }\n}\n\n/** Discriminated result of `catalog.render` (mirrors the contract pattern). */\nexport type RenderResult =\n | { ok: true; node: WidgetNode }\n | { ok: false; error: WidgetContractError };\n\n/** Options for one `catalog.render` call. */\nexport interface RenderOptions {\n /**\n * The data may still be arriving (a streaming preview): skip the\n * descriptor data-schema check for the payload and every group item. The\n * payload contract and interpretation bounds still apply.\n */\n partialData?: boolean;\n}\n\nexport interface WidgetCatalog {\n /**\n * Register a renderer for a new kind, optionally with agent-facing\n * documentation. Throws {@link DuplicateKindError} on duplicates\n * (built-ins included). Without a descriptor, a minimal one is generated\n * so every renderable kind stays listable.\n */\n register(\n kind: WidgetKind,\n renderer: WidgetRenderer,\n descriptor?: WidgetDescriptorInput\n ): void;\n has(kind: WidgetKind): boolean;\n resolve(kind: WidgetKind): WidgetRenderer | undefined;\n /** Currently registered kinds, as a fresh array. */\n kinds(): WidgetKind[];\n /** Descriptor for a kind, or undefined when the kind is unknown. */\n describe(kind: WidgetKind): WidgetDescriptor | undefined;\n /** All descriptors, as a fresh array. */\n list(): WidgetDescriptor[];\n /** Validate a payload against the contract (with this catalog's kinds) and render it. Never throws. */\n render(payload: unknown, options?: RenderOptions): RenderResult;\n}\n\n/**\n * Create an independent catalog instance with the built-ins (`card`,\n * `table`, `tree`, `group`) pre-registered.\n */\nexport function createCatalog(): WidgetCatalog {\n const renderers = new Map<WidgetKind, WidgetRenderer>();\n const descriptors = new Map<WidgetKind, WidgetDescriptor>();\n\n const catalog: WidgetCatalog = {\n register(kind, renderer, descriptor) {\n if (renderers.has(kind)) throw new DuplicateKindError(kind);\n renderers.set(kind, renderer);\n descriptors.set(kind, {\n kind,\n description: descriptor?.description ?? `Custom widget kind '${kind}'.`,\n dataShape: descriptor?.dataShape ?? \"Defined by the registered renderer.\",\n ...(descriptor?.dataExample !== undefined\n ? { dataExample: descriptor.dataExample }\n : {}),\n ...(descriptor?.hints ? { hints: descriptor.hints } : {}),\n ...(descriptor?.dataSchema ? { dataSchema: descriptor.dataSchema } : {}),\n ...(descriptor?.styles ? { styles: descriptor.styles } : {})\n });\n },\n has: (kind) => renderers.has(kind),\n resolve: (kind) => renderers.get(kind),\n kinds: () => [...renderers.keys()],\n describe: (kind) => descriptors.get(kind),\n list: () => [...descriptors.values()],\n render(payload, options = {}) {\n const validated = validateWidgetPayload(payload, {\n knownKinds: new Set(renderers.keys())\n });\n if (!validated.ok) return validated;\n // Opt-in structural validation: kinds with a dataSchema fail fast\n // with a dotted data path instead of rendering a lenient fallback.\n const schema = options.partialData === true\n ? undefined\n : descriptors.get(validated.payload.kind)?.dataSchema;\n if (schema) {\n const schemaError = validateDataAgainstSchema(\n schema,\n validated.payload.data\n );\n if (schemaError) return { ok: false, error: schemaError };\n }\n // `group` recurses through this same entry so registered and\n // composed kinds participate and per-item failures keep their\n // structured codes, re-pathed under `data.items[<i>]`. Renderers\n // stay pure `(payload) => WidgetNode`; composition is dispatch work.\n if (validated.payload.kind === \"group\") {\n const envelope = checkGroupEnvelope(validated.payload.data);\n if (!envelope.ok) return envelope;\n const children: WidgetNode[] = [];\n for (let i = 0; i < envelope.items.length; i++) {\n const item = envelope.items[i]!;\n const sub = catalog.render(\n {\n kind: item.kind,\n data: item.data,\n ...(item.hints !== undefined ? { hints: item.hints } : {}),\n ...(item.meta !== undefined ? { meta: item.meta } : {})\n },\n options\n );\n if (!sub.ok) {\n const subPath = sub.error.path;\n return {\n ok: false,\n error: {\n ...sub.error,\n path: `data.items[${i}]${subPath ? `.${subPath}` : \"\"}`\n }\n };\n }\n children.push(stampActionLocation(sub.node, `data.items.${i}`));\n }\n return {\n ok: true,\n node: renderGroupContainer(validated.payload.hints, children)\n };\n }\n const renderer = renderers.get(validated.payload.kind);\n if (renderer === undefined) {\n // Unreachable while knownKinds is non-empty; kept for totality.\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_KIND\",\n path: \"kind\",\n message: `Unknown widget kind '${validated.payload.kind}'.`\n }\n };\n }\n // Built-ins are total by construction; this guards the extension\n // point \u2014 a registered renderer that throws must surface as a\n // structured error, never a propagated exception.\n try {\n return { ok: true, node: renderer(validated.payload) };\n } catch (thrown) {\n return {\n ok: false,\n error: {\n code: \"RENDER_FAILED\",\n path: \"widget\",\n message: `Renderer for kind '${validated.payload.kind}' threw: ${\n thrown instanceof Error ? thrown.message : String(thrown)\n }`\n }\n };\n }\n }\n };\n\n // Built-ins go through register() so they get the same duplicate\n // protection and hosts cannot silently override them.\n catalog.register(\"card\", renderCard, BUILTIN_DESCRIPTORS.card);\n catalog.register(\"table\", renderTable, BUILTIN_DESCRIPTORS.table);\n catalog.register(\"tree\", renderTree, BUILTIN_DESCRIPTORS.tree);\n // `render()` intercepts 'group' before renderer lookup, so this renderer\n // only serves direct `resolve()` callers (e.g. designer previews); it\n // delegates back through the dispatch so items render for them too.\n catalog.register(\n \"group\",\n (payload) => {\n const result = catalog.render(payload);\n if (result.ok) return result.node;\n throw new Error(result.error.message);\n },\n BUILTIN_DESCRIPTORS.group\n );\n\n return catalog;\n}\n", "/**\n * The one `isPlainObject`. Every entry imports it relatively, so the\n * zero-dependency entries stay zero-dependency and the source-scan tests\n * keep passing.\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "/**\n * Bracket-aware reading of the CSS text the style and token guards inspect.\n * Depth counts `(` and `[` only outside quoted strings, so a parenthesis\n * inside an attribute value can neither hide a comma nor close a\n * pseudo-class early. Strings carry no escapes here: every guard bans `\\`.\n * As in CSS, a newline ends a string unclosed (a bad string), so a string\n * broken across lines never counts as closed.\n */\n\n/** A line break that ends a CSS string: LF, CR or FF. */\nconst isNewline = (char: string) => char === \"\\n\" || char === \"\\r\" || char === \"\\f\";\n\ninterface ScannedChar {\n char: string;\n /** Bracket depth around the character; a bracket itself sits at the outer depth. */\n depth: number;\n /** Part of a quoted string, quotes included. */\n quoted: boolean;\n}\n\nfunction scan(text: string): ScannedChar[] {\n const out: ScannedChar[] = [];\n let depth = 0;\n let quote: string | undefined;\n // UTF-16 units, so indices match `String.slice`; brackets and quotes are\n // never surrogate halves.\n for (let i = 0; i < text.length; i++) {\n const char = text.charAt(i);\n if (quote !== undefined) {\n out.push({ char, depth, quoted: true });\n if (char === quote || isNewline(char)) quote = undefined;\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n out.push({ char, depth, quoted: true });\n } else if (char === \"(\" || char === \"[\") {\n out.push({ char, depth, quoted: false });\n depth++;\n } else if (char === \")\" || char === \"]\") {\n depth = Math.max(0, depth - 1);\n out.push({ char, depth, quoted: false });\n } else {\n out.push({ char, depth, quoted: false });\n }\n }\n return out;\n}\n\nconst isBracket = (char: string) => char === \"(\" || char === \")\" || char === \"[\" || char === \"]\";\n\n/**\n * Every `(` and `[` closed in order and every string closed. An unclosed\n * bracket or string runs on through the rest of the stylesheet, swallowing\n * every rule after it.\n */\nexport function isBalanced(text: string): boolean {\n const open: string[] = [];\n let quote: string | undefined;\n for (let i = 0; i < text.length; i++) {\n const char = text.charAt(i);\n if (quote !== undefined) {\n if (isNewline(char)) return false;\n if (char === quote) quote = undefined;\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \"(\" || char === \"[\") {\n open.push(char === \"(\" ? \")\" : \"]\");\n } else if (char === \")\" || char === \"]\") {\n if (open.pop() !== char) return false;\n }\n }\n return open.length === 0 && quote === undefined;\n}\n\n/** Split on `separator` characters outside every bracket and string; empty pieces dropped. */\nexport function splitTopLevel(text: string, separator: (char: string) => boolean): string[] {\n const pieces: string[] = [];\n let current = \"\";\n for (const { char, depth, quoted } of scan(text)) {\n if (depth === 0 && !quoted && separator(char)) {\n pieces.push(current.trim());\n current = \"\";\n } else {\n current += char;\n }\n }\n pieces.push(current.trim());\n return pieces.filter((piece) => piece.length > 0);\n}\n\n/** The text outside every bracket and string: what a selector says at its own level. */\nexport function topLevelText(text: string): string {\n return scan(text)\n .filter(({ char, depth, quoted }) => depth === 0 && !quoted && !isBracket(char))\n .map(({ char }) => char)\n .join(\"\");\n}\n\n/** Index of the first character outside every bracket and string that passes `test`, or -1. */\nexport function indexOfTopLevel(text: string, test: (char: string) => boolean): number {\n return scan(text).findIndex(({ char, depth, quoted }) => depth === 0 && !quoted && test(char));\n}\n\n/**\n * The argument of each top-level functional pseudo-class named in `names`\n * (`:is(\u2026)` \u2192 `\u2026`), so a guard can look inside the ones that pass their\n * argument's matches through.\n */\nexport function pseudoArguments(text: string, names: readonly string[]): string[] {\n const chars = scan(text);\n const args: string[] = [];\n for (let i = 0; i < chars.length; i++) {\n const entry = chars[i];\n if (entry === undefined || entry.char !== \"(\" || entry.depth !== 0 || entry.quoted) continue;\n const before = text.slice(0, i).toLowerCase();\n if (!names.some((name) => before.endsWith(`:${name}`))) continue;\n let end = i + 1;\n while (end < chars.length) {\n const closer = chars[end];\n if (closer !== undefined && closer.char === \")\" && closer.depth === 0 && !closer.quoted) break;\n end++;\n }\n args.push(text.slice(i + 1, end));\n }\n return args;\n}\n", "/**\n * Registered widget styles: custom kinds ship their look as data alongside\n * their template/renderer, and themes ship shared classes the same way.\n * Same trust model as theme tokens \u2014 designer-authored \u2014 so selectors,\n * properties, and values are all guarded, and unsafe entries are skipped\n * rather than emitted.\n */\nimport { isPlainObject } from \"../shared/plain-object.js\";\nimport { indexOfTopLevel, isBalanced, pseudoArguments, splitTopLevel, topLevelText } from \"../shared/css-scan.js\";\n\nexport type WidgetStyles = Record<string, Record<string, string>>;\n\n/** Substrings that disqualify a selector, property or value. Exported\n * so the authoring guide derives the rule instead of restating it. */\nexport const UNSAFE = /[;{}<>@\\\\]/;\n/** The property-name allowlist: not merely \"no banned characters\". */\nexport const PROPERTY_NAME = /^-?[a-zA-Z][a-zA-Z-]*$/;\n\n/**\n * The shape both widget and theme styles must have: selectors mapping to\n * property/value strings. Shape only \u2014 unsafe entries pass here and are\n * dropped by the generator, so one rule decides what reaches CSS.\n */\nexport function isStyleMap(value: unknown): value is WidgetStyles {\n if (!isPlainObject(value)) return false;\n return Object.values(value).every(\n (declarations) =>\n isPlainObject(declarations) &&\n Object.values(declarations).every((v) => typeof v === \"string\")\n );\n}\n\n/**\n * CSS functions that fetch or execute, refused in values wherever they\n * appear \u2014 `image-set()` and `src()` carry URLs without spelling `url(`.\n * Exported so the guides derive the rule instead of restating it.\n */\nexport const UNSAFE_FUNCTIONS: readonly string[] = [\"url(\", \"expression(\", \"image-set(\", \"src(\"];\n\n/** A comment opener or closer: one can swallow every rule after it. */\nconst COMMENT = /\\/\\*|\\*\\//;\n\nfunction callsUnsafeFunction(text: string): boolean {\n return UNSAFE_FUNCTIONS.some((call) => new RegExp(`${call.slice(0, -1)}\\\\s*\\\\(`, \"i\").test(text));\n}\n\n/**\n * Pseudo-classes that pass their argument's matches through: `:is(.wg-a,\n * .wg-b)` matches only what its arguments match. `:not()` and `:has()` do\n * not \u2014 `body:not(.wg-x)` and `body:has(.wg-x)` match `body`.\n */\nconst FORWARDING_PSEUDOS = [\"is\", \"where\", \"matches\", \"-webkit-any\", \"-moz-any\"] as const;\n\n/** Combinators between compounds, read outside brackets and strings. */\nconst COMBINATOR = (char: string) => /[\\s>+~]/.test(char);\n\n/**\n * A selector list every one of whose parts is held to `.wg-` classes: some\n * compound of each part names a `.wg-` class at its own level, or forwards\n * through `:is()`/`:where()` to a list that does. A `.wg-` hidden in\n * `:not()`, `:has()`, an attribute test or a string constrains nothing.\n */\nfunction isConstrainedList(selector: string, depth: number): boolean {\n const parts = splitTopLevel(selector, (char) => char === \",\");\n return parts.length > 0 && parts.every((part) => isConstrainedPart(part, depth));\n}\n\n/**\n * How deep `:is()`/`:where()` may nest before a selector is refused: the\n * check recurses per level, and a generator that runs on every render must\n * never throw. Real selectors nest two or three levels.\n */\nconst MAX_FORWARDING_DEPTH = 16;\n\nfunction isConstrainedPart(part: string, depth = 0): boolean {\n if (depth > MAX_FORWARDING_DEPTH) return false;\n return splitTopLevel(part, COMBINATOR).some(\n (compound) =>\n topLevelText(compound).includes(\".wg-\") ||\n pseudoArguments(compound, FORWARDING_PSEUDOS).some((argument) => isConstrainedList(argument, depth + 1))\n );\n}\n\n/**\n * Every top-level selector part must be held to `.wg-` classes, and no\n * part may open with a combinator (`~ .wg-b` is invalid alone and would\n * only become valid once scoped). Brackets and strings must close, and\n * no comments: either would run on and swallow the rules after it.\n */\nfunction isSafeSelector(selector: string): boolean {\n if (UNSAFE.test(selector) || COMMENT.test(selector) || !isBalanced(selector)) return false;\n const parts = splitTopLevel(selector, (char) => char === \",\");\n return parts.length > 0 && parts.every((part) => !/^[>+~]/.test(part) && isConstrainedPart(part));\n}\n\nfunction isSafeValue(value: string): boolean {\n return !UNSAFE.test(value) && !COMMENT.test(value) && isBalanced(value) && !callsUnsafeFunction(value);\n}\n\n/**\n * One part under a scope that targets the root element. A part already\n * anchored at the root (`:root[data-theme=\"dark\"] .wg-x`, `html .wg-x`)\n * takes the scope as an extra condition on that root compound \u2014 prefixing\n * would demand a root inside the root and never match; any other part is\n * prefixed with `:where(<scope>) `.\n */\nfunction scopePart(part: string, scope: string): string {\n if (!/^(:root|html)(?![\\w-])/i.test(part)) return `:where(${scope}) ${part}`;\n const found = indexOfTopLevel(part, COMBINATOR);\n const end = found === -1 ? part.length : found;\n return `${part.slice(0, end)}:where(${scope})${part.slice(end)}`;\n}\n\n/**\n * Generate CSS from a styles map, emitting only guarded entries. Values may\n * reference theme tokens via `var(--wg-*)`. Never throws.\n */\nexport function widgetStylesToCss(styles: WidgetStyles): string {\n return guardedStylesToCss(styles, undefined);\n}\n\n/**\n * The one generator behind widget and theme styles. A `scope` (always a\n * caller constant, never style data) prefixes every selector part with\n * `:where(<scope>) `, so the rule applies inside the scope at the weight\n * its author wrote.\n */\nexport function guardedStylesToCss(styles: WidgetStyles, scope: string | undefined): string {\n const rules: string[] = [];\n for (const [selector, declarations] of Object.entries(styles)) {\n if (!isSafeSelector(selector)) continue;\n if (typeof declarations !== \"object\" || declarations === null) continue;\n const lines: string[] = [];\n for (const [property, value] of Object.entries(declarations)) {\n if (!PROPERTY_NAME.test(property)) continue;\n if (typeof value !== \"string\" || !isSafeValue(value)) continue;\n lines.push(` ${property}: ${value};`);\n }\n if (lines.length > 0) {\n const scoped = scope === undefined\n ? selector\n : splitTopLevel(selector, (char) => char === \",\").map((part) => scopePart(part, scope)).join(\", \");\n rules.push(`${scoped} {\\n${lines.join(\"\\n\")}\\n}`);\n }\n }\n return rules.join(\"\\n\");\n}\n", "/**\n * The identifier rule for widget kinds and theme, schema and principal\n * names: one charset every store adapter accepts identically (the file\n * store uses it as a path guard; Cosmos embeds it in document ids). Kept\n * here so the store, the designers and the guides read the same rule.\n */\nexport const SAFE_IDENTIFIER = /^[a-zA-Z0-9._-]+$/;\n", "/**\n * The style rules as text, built from the constants the guards enforce.\n * Both authoring guides, the tool descriptions and the designers' messages\n * read them from here, so none can drift from the guards or from another.\n */\nimport { PROPERTY_NAME, UNSAFE, UNSAFE_FUNCTIONS } from \"./styles.js\";\n\nexport const STYLE_RULES = {\n selectors:\n \"Every selector part (split on top-level commas) must be held to .wg- classes: \" +\n \"one of its compounds names a .wg- class itself, or through :is() or :where() \" +\n \"whose every argument does. A .wg- class only inside :not(), :has(), an \" +\n \"attribute test or a string does not count, and no part may open with a \" +\n \"combinator \u2014 e.g. '.wg-card .wg-xcard-head', '.wg-row:has(.wg-ok, .wg-warn)' \" +\n \"or ':is(.wg-btn, .wg-link):hover'.\",\n banned:\n `Selectors, properties, or values matching ${UNSAFE.source}, holding a ` +\n \"comment marker (/* or */) or an unclosed bracket or string, or calling \" +\n `${UNSAFE_FUNCTIONS.join(\", \")} are dropped.`,\n // An ALLOWLIST, not merely \"no banned characters\": a property with a\n // digit or underscore is dropped even though it contains nothing banned.\n propertyNames:\n `Property names must match ${PROPERTY_NAME.source} (letters and ` +\n \"hyphens, optionally leading '-'); anything else is dropped.\"\n} as const;\n", "/**\n * The bind format engine: a CLOSED, data-only presentation vocabulary.\n *\n * Formatting is render-time, never fold-time \u2014 the payload keeps the typed\n * value while the render gets its unit, so an initial render, a preview and\n * an action's re-render all present the same data the same way and a second\n * fold never formats an already-formatted string.\n *\n * Determinism is a hard requirement: server render, designer preview and\n * in-frame re-render must agree byte for byte, or the patcher would see\n * phantom text changes. Hence a fixed default locale, UTC throughout (an\n * unzoned ISO value is read as UTC \u2014 ECMAScript would read it as LOCAL\n * time), and ordinary spaces in numeric output (ICU builds differ in the\n * no-break spaces they emit).\n *\n * Total by construction: a value the format cannot parse renders as its\n * plain `formatValue` text. A format never hides data and never throws.\n */\nimport { isPlainObject } from \"../../shared/plain-object.js\";\nimport { formatValue } from \"./format.js\";\n\n/** Format kinds. Closed \u2014 an unknown `type` fails validation. */\nexport const FORMAT_TYPES = [\"number\", \"currency\", \"date\"] as const;\n\nexport type FormatType = (typeof FORMAT_TYPES)[number];\n\nexport const isFormatType = (value: unknown): value is FormatType =>\n FORMAT_TYPES.some((type) => type === value);\n\n/** Bounds on `decimals` (inclusive), shared by the validator and the guide. */\nexport const FORMAT_DECIMALS_MIN = 0;\nexport const FORMAT_DECIMALS_MAX = 8;\n\n/** How a currency names itself. `narrowSymbol` is the default: `$3,207`. */\nexport const CURRENCY_DISPLAYS = [\"narrowSymbol\", \"symbol\", \"code\"] as const;\n\nexport type CurrencyDisplay = (typeof CURRENCY_DISPLAYS)[number];\n\nexport const isCurrencyDisplay = (value: unknown): value is CurrencyDisplay =>\n CURRENCY_DISPLAYS.some((display) => display === value);\n\n/** ISO-4217: three uppercase letters. */\nexport const CURRENCY_CODE = /^[A-Z]{3}$/;\n\n/**\n * The date pattern's tokens, longest first \u2014 the tokenizer scans in this\n * order so `mm` cannot eat the tail of `MM`.\n */\nexport const DATE_TOKENS = [\"yyyy\", \"MM\", \"dd\", \"HH\", \"mm\", \"ss\"] as const;\n\n/** Characters a pattern may carry outside its tokens. */\nexport const DATE_PATTERN_SEPARATORS = \" -/:.,T\";\n\n/** Bound on a date pattern's length \u2014 a pattern is a format, not a document. */\nexport const DATE_PATTERN_MAX = 40;\n\n/** Every character a date pattern may contain (tokens + separators). */\nexport const DATE_PATTERN_ALLOWED = new RegExp(\n `^[${DATE_PATTERN_SEPARATORS.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")}yMdHms]*$`\n);\n\n/**\n * Epoch numbers below this are SECONDS, above it MILLISECONDS \u2014 the two\n * shapes APIs emit. 1e11 s is the year 5138, 1e11 ms is 1973, so no real\n * timestamp is ambiguous under the split.\n */\nexport const EPOCH_SECONDS_BELOW = 1e11;\n\n/**\n * A locale is an author literal, shape-bounded here; the validator also asks\n * the runtime whether it knows the tag, so a typo cannot reach a render.\n */\nexport const LOCALE_TAG = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\n/** The default locale \u2014 fixed so every surface formats identically. */\nexport const DEFAULT_FORMAT_LOCALE = \"en-US\";\n\nexport interface NumberFormatSpec {\n type: \"number\";\n decimals?: number;\n locale?: string;\n}\n\nexport interface CurrencyFormatSpec {\n type: \"currency\";\n currency: string;\n decimals?: number;\n currencyDisplay?: CurrencyDisplay;\n locale?: string;\n}\n\nexport interface DateFormatSpec {\n type: \"date\";\n pattern: string;\n}\n\n/** A bind's presentation transform. */\nexport type FormatSpec = NumberFormatSpec | CurrencyFormatSpec | DateFormatSpec;\n\n/** A tokenized pattern: literal runs and the tokens between them. */\nexport type DatePatternPart = { token: (typeof DATE_TOKENS)[number] } | { literal: string };\n\n/**\n * Split a pattern into tokens and literals. Every letter must belong to a\n * token \u2014 a stray `d` or `yy` would render as itself for every value, a\n * constant that hides the data \u2014 so a pattern with leftover letters or no\n * token at all tokenizes to `undefined`.\n */\nexport function tokenizeDatePattern(pattern: string): DatePatternPart[] | undefined {\n const parts: DatePatternPart[] = [];\n let literal = \"\";\n let tokens = 0;\n let i = 0;\n outer: while (i < pattern.length) {\n for (const token of DATE_TOKENS) {\n if (pattern.startsWith(token, i)) {\n if (literal !== \"\") parts.push({ literal });\n literal = \"\";\n parts.push({ token });\n tokens += 1;\n i += token.length;\n continue outer;\n }\n }\n const char = pattern[i] as string;\n if (/[A-Za-z]/.test(char)) return undefined;\n literal += char;\n i += 1;\n }\n if (literal !== \"\") parts.push({ literal });\n return tokens === 0 ? undefined : parts;\n}\n\n/** Whether the runtime knows a locale tag (a malformed tag throws \u2192 false). */\nexport function isKnownLocale(tag: string): boolean {\n try {\n return Intl.NumberFormat.supportedLocalesOf([tag]).length > 0;\n } catch {\n return false;\n }\n}\n\n/**\n * A finite number from a number or a numeric STRING \u2014 the shape every JSON\n * API that fears float precision returns.\n */\nfunction toFiniteNumber(value: unknown): number | undefined {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\n/**\n * Epoch milliseconds from an ISO-8601 string or an epoch number (seconds\n * below {@link EPOCH_SECONDS_BELOW}, milliseconds above). An unzoned value\n * is read as UTC; fractional seconds beyond three digits are truncated,\n * since `Date.parse` is not required to accept them.\n */\nfunction toEpochMillis(value: unknown): number | undefined {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) return undefined;\n return Math.abs(value) < EPOCH_SECONDS_BELOW ? value * 1000 : value;\n }\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const iso =\n /^(\\d{4}-\\d{2}-\\d{2})(?:[T ](\\d{2}:\\d{2}(?::\\d{2})?)(?:\\.(\\d+))?(Z|[+-]\\d{2}:?\\d{2})?)?$/.exec(\n trimmed\n );\n if (iso === null) return undefined;\n const [, date, time, fraction, zone] = iso;\n const millis = fraction === undefined ? \"\" : `.${fraction.slice(0, 3)}`;\n const clock = time === undefined ? \"00:00:00\" : time.length === 5 ? `${time}:00` : time;\n const parsed = Date.parse(`${date}T${clock}${millis}${zone ?? \"Z\"}`);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nconst pad = (value: number, width: number): string => String(value).padStart(width, \"0\");\n\n/** Substitute the tokens from the UTC fields of `millis`. */\nfunction formatDate(millis: number, parts: readonly DatePatternPart[]): string {\n const at = new Date(millis);\n const field = (token: (typeof DATE_TOKENS)[number]): string => {\n switch (token) {\n case \"yyyy\": return pad(at.getUTCFullYear(), 4);\n case \"MM\": return pad(at.getUTCMonth() + 1, 2);\n case \"dd\": return pad(at.getUTCDate(), 2);\n case \"HH\": return pad(at.getUTCHours(), 2);\n case \"mm\": return pad(at.getUTCMinutes(), 2);\n case \"ss\": return pad(at.getUTCSeconds(), 2);\n }\n };\n return parts.map((part) => (\"token\" in part ? field(part.token) : part.literal)).join(\"\");\n}\n\n/** ICU emits U+00A0 / U+202F / U+2009 where locales space digits and symbols. */\nconst UNICODE_SPACES = /[\\u00A0\\u202F\\u2009]/g;\n\n/** Every parse failure or malformed spec formats as the plain value. */\nconst plain = (value: unknown): string => formatValue(value);\n\ntype Formatter = (value: unknown) => string;\n\n/**\n * Narrow an author spec to the engine's typed shape, defaults applied. The\n * validator refuses everything this returns `undefined` for; it stays here\n * so a spec reaching the engine unvalidated degrades to plain text.\n */\nexport function parseFormatSpec(spec: unknown): FormatSpec | undefined {\n if (!isPlainObject(spec) || !isFormatType(spec.type)) return undefined;\n if (spec.type === \"date\") {\n return typeof spec.pattern === \"string\" ? { type: \"date\", pattern: spec.pattern } : undefined;\n }\n const decimals =\n typeof spec.decimals === \"number\" &&\n Number.isInteger(spec.decimals) &&\n spec.decimals >= FORMAT_DECIMALS_MIN &&\n spec.decimals <= FORMAT_DECIMALS_MAX\n ? spec.decimals\n : undefined;\n const locale =\n typeof spec.locale === \"string\" && LOCALE_TAG.test(spec.locale) ? spec.locale : undefined;\n const common = {\n ...(decimals === undefined ? {} : { decimals }),\n ...(locale === undefined ? {} : { locale })\n };\n if (spec.type === \"number\") return { type: \"number\", ...common };\n if (typeof spec.currency !== \"string\" || !CURRENCY_CODE.test(spec.currency)) return undefined;\n return {\n type: \"currency\",\n currency: spec.currency,\n ...(isCurrencyDisplay(spec.currencyDisplay) ? { currencyDisplay: spec.currencyDisplay } : {}),\n ...common\n };\n}\n\n/**\n * Build the formatter for one spec: the `Intl.NumberFormat` instance and the\n * tokenized pattern are created here, once, not per value \u2014 a table over a\n * list formats thousands of cells through one instance.\n */\nfunction buildFormatter(spec: FormatSpec): Formatter {\n if (spec.type === \"date\") {\n const parts = tokenizeDatePattern(spec.pattern);\n if (parts === undefined) return plain;\n return (value) => {\n const millis = toEpochMillis(value);\n return millis === undefined ? plain(value) : formatDate(millis, parts);\n };\n }\n const locale = spec.locale ?? DEFAULT_FORMAT_LOCALE;\n const digits: Intl.NumberFormatOptions =\n spec.decimals === undefined\n ? {}\n : { minimumFractionDigits: spec.decimals, maximumFractionDigits: spec.decimals };\n let intl: Intl.NumberFormat;\n try {\n intl =\n spec.type === \"number\"\n ? new Intl.NumberFormat(locale, digits)\n : new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: spec.currency,\n currencyDisplay: spec.currencyDisplay ?? \"narrowSymbol\",\n ...digits\n });\n } catch {\n // An engine that rejects an author literal must not break the render.\n return plain;\n }\n return (value) => {\n const numeric = toFiniteNumber(value);\n return numeric === undefined ? plain(value) : intl.format(numeric).replace(UNICODE_SPACES, \" \");\n };\n}\n\n/**\n * Formatters keyed by the spec OBJECT, which lives as long as the compiled\n * template that carries it. Holds locale/currency configuration only \u2014\n * never tenant data \u2014 so the per-request no-cache rule is untouched.\n */\nconst compiled = new WeakMap<object, Formatter>();\n\n/** The formatter for `spec`, built once per spec object. */\nexport function compileFormat(spec: unknown): Formatter {\n if (!isPlainObject(spec)) return plain;\n const cached = compiled.get(spec);\n if (cached !== undefined) return cached;\n const parsed = parseFormatSpec(spec);\n const formatter = parsed === undefined ? plain : buildFormatter(parsed);\n compiled.set(spec, formatter);\n return formatter;\n}\n\n/** Render `value` through `spec`, or as plain text when it cannot be parsed. */\nexport function formatBoundValue(value: unknown, spec: unknown): string {\n return compileFormat(spec)(value);\n}\n", "/**\n * Theme token registry. Tokens are the only theming surface: the base\n * stylesheet reads them via `var(--wg-<token>, <default>)` and themes are\n * plain maps of bare token names to values. The defaults table is the\n * single source of truth for the light look.\n */\nimport { UNSAFE_FUNCTIONS } from \"../catalog/styles.js\";\nimport { isBalanced } from \"../shared/css-scan.js\";\n\n/**\n * The token table: every token's default, its VALUE TYPE, and what it is\n * for. Type metadata is not decoration \u2014 tooling reads it (the theme\n * designer picks a color picker vs a text field from `type`, never by\n * guessing at the default's shape) and `list_theme_tokens` tells agents\n * what kind of value each token expects. `use` doubles as the\n * documentation that earns a token its place when the base stylesheet\n * cannot consume it.\n */\nexport type TokenType =\n | \"color\"\n | \"dimension\"\n | \"number\"\n | \"font-family\"\n | \"font-weight\"\n | \"shadow\";\n\nexport interface TokenSpec {\n default: string;\n type: TokenType;\n use: string;\n /**\n * Token this one inherits from when a theme leaves it unset. Declared\n * here rather than special-cased in the stylesheet because a literal\n * default at `:root` would sever that inheritance: a `var()` fallback\n * applies only when the property is UNSET, so defining\n * `--wg-surface: #ffffff` makes `var(--wg-surface, var(--wg-bg, \u2026))`\n * unreachable. The defaults block emits a chain for these instead.\n */\n fallback?: string;\n}\n\nexport const TOKEN_SPECS = {\n bg: { default: \"#ffffff\", type: \"color\", use: \"Page background behind widgets.\" },\n surface: {\n default: \"#ffffff\",\n type: \"color\",\n fallback: \"bg\",\n use: \"Widget panel background (cards, tables); falls back to bg when unset.\"\n },\n fg: { default: \"#1f2430\", type: \"color\", use: \"Primary text.\" },\n muted: { default: \"#6b7280\", type: \"color\", use: \"Secondary text: labels, captions, keys.\" },\n accent: { default: \"#2563eb\", type: \"color\", use: \"Emphasis: titles, links, filled badges.\" },\n \"accent-fg\": {\n default: \"#ffffff\",\n type: \"color\",\n use: \"Text drawn on an accent fill (filled badges and buttons).\"\n },\n border: { default: \"#e2e8f0\", type: \"color\", use: \"Hairlines: panel edges, row rules.\" },\n \"border-width\": { default: \"1px\", type: \"dimension\", use: \"Width of those hairlines.\" },\n radius: { default: \"6px\", type: \"dimension\", use: \"Default corner rounding.\" },\n \"radius-sm\": { default: \"3px\", type: \"dimension\", use: \"Tight rounding: pills, chips, inline marks.\" },\n \"radius-lg\": { default: \"12px\", type: \"dimension\", use: \"Generous rounding: hero media, large panels.\" },\n spacing: { default: \"8px\", type: \"dimension\", use: \"Base spacing step.\" },\n \"spacing-sm\": { default: \"4px\", type: \"dimension\", use: \"Half step: inline gaps inside a row.\" },\n \"spacing-lg\": { default: \"16px\", type: \"dimension\", use: \"Double step: section separation.\" },\n \"font-family\": {\n default: \"system-ui, -apple-system, 'Segoe UI', sans-serif\",\n type: \"font-family\",\n use: \"Body text family.\"\n },\n \"font-mono\": {\n default: \"ui-monospace, SFMono-Regular, Menlo, monospace\",\n type: \"font-family\",\n use: \"Monospace family for the wg-code block utility.\"\n },\n \"font-size\": { default: \"14px\", type: \"dimension\", use: \"Body text size.\" },\n \"font-size-sm\": { default: \"12px\", type: \"dimension\", use: \"Small text: captions, stats, pills.\" },\n \"font-size-lg\": { default: \"18px\", type: \"dimension\", use: \"Large text: widget titles.\" },\n \"font-weight-bold\": {\n default: \"600\",\n type: \"font-weight\",\n use: \"Weight for titles and emphasized labels.\"\n },\n \"line-height\": { default: \"1.45\", type: \"number\", use: \"Text density.\" },\n shadow: {\n default: \"0 1px 3px rgba(0, 0, 0, 0.12)\",\n type: \"shadow\",\n use: \"Panel elevation.\"\n },\n danger: { default: \"#b91c1c\", type: \"color\", use: \"Error status: fills and text (see .wg-status-danger).\" },\n \"danger-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a danger fill.\" },\n success: { default: \"#15803d\", type: \"color\", use: \"Success status (see .wg-status-success).\" },\n \"success-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a success fill.\" },\n warning: { default: \"#b45309\", type: \"color\", use: \"Warning status (see .wg-status-warning).\" },\n \"warning-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a warning fill.\" },\n info: { default: \"#0369a1\", type: \"color\", use: \"Informational status (see .wg-status-info).\" },\n \"info-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on an info fill.\" },\n \"avatar-size\": { default: \"32px\", type: \"dimension\", use: \"Box of .wg-img-avatar images.\" },\n \"thumb-size\": { default: \"48px\", type: \"dimension\", use: \"Box of .wg-img-thumb images.\" }\n} as const satisfies Record<string, TokenSpec>;\n\n/** Default value per token \u2014 derived, so the table stays the one source. */\nexport const TOKEN_DEFAULTS = Object.fromEntries(\n Object.entries(TOKEN_SPECS).map(([name, spec]) => [name, spec.default])\n) as { [K in keyof typeof TOKEN_SPECS]: (typeof TOKEN_SPECS)[K][\"default\"] };\n\nexport type ThemeToken = keyof typeof TOKEN_SPECS;\n\n/** All theme token names, in defaults-table order. */\nexport const THEME_TOKENS: readonly ThemeToken[] = Object.keys(\n TOKEN_SPECS\n) as ThemeToken[];\n\n/**\n * A theme: bare token names to CSS values. Bare keys make unknown-token\n * validation trivial and structurally prevent setting arbitrary custom\n * properties \u2014 the `--wg-` prefix is always applied by this module.\n */\nexport type WidgetTheme = Partial<Record<ThemeToken, string>>;\n\n/**\n * A theme plus author-defined `x-*` variables (emitted as `--wg-x-<name>`).\n * Kept as a separate type on purpose: `WidgetTheme` has only optional\n * properties, which is what makes TypeScript reject `{ sneaky: \"red\" }` via\n * weak-type detection \u2014 an index signature here would silently disable that\n * protection for every consumer. Functions accept this wider input; the\n * runtime validator is the authority on which keys are legal.\n */\nexport type WidgetThemeInput = WidgetTheme &\n Partial<Record<`x-${string}`, string>>;\n\nexport type ThemeErrorCode =\n | \"INVALID_THEME\"\n | \"UNKNOWN_TOKEN\"\n | \"INVALID_TOKEN_VALUE\";\n\nexport interface ThemeError {\n code: ThemeErrorCode;\n message: string;\n /** Offending token name, when applicable. */\n token?: string;\n}\n\n/**\n * Characters a token value may not hold: declaration and HTML escapes, and\n * the backslash, whose escapes can spell any banned call (`u\\72 l(` is\n * `url(`). Exported so the guides derive the rule.\n */\nexport const TOKEN_VALUE_UNSAFE = /[;{}<>\\\\]/;\n\n/**\n * Value guard shared by validation (strict) and application (lenient\n * defense in depth). Rejects exfiltration and execution vectors \u2014 not\n * invalid CSS: declaration/HTML escapes, backslash escapes, comment markers\n * and unclosed brackets or strings (each swallows the rest of the sheet),\n * `url()`, `image-set()` and `src()`\n * (resource fetching), and `expression()` (legacy script execution in old\n * embedded webviews).\n */\nexport function isSafeTokenValue(value: string): boolean {\n return (\n !TOKEN_VALUE_UNSAFE.test(value) &&\n // An unclosed bracket or string runs on through the rest of the sheet.\n isBalanced(value) &&\n // A comment opener swallows every declaration after it in the sheet.\n !/\\/\\*|\\*\\//.test(value) &&\n // The style guard's calls: url(), expression(), and the URL carriers\n // that do not spell url(.\n !UNSAFE_FUNCTIONS.some((call) => new RegExp(`${call.slice(0, -1)}\\\\s*\\\\(`, \"i\").test(value))\n );\n}\n\n/** The token-value rule as text, built from the constants that enforce it. */\nexport const TOKEN_VALUE_RULE =\n `Token values are plain CSS values. Rejected: anything matching ${TOKEN_VALUE_UNSAFE.source}, ` +\n \"a comment marker (/* or */), an unclosed bracket or string, and calls to \" +\n `${UNSAFE_FUNCTIONS.join(\", \")} (case-insensitive, whitespace-tolerant). ` +\n \"Keep values to colors, lengths, and font stacks.\";\n", "import type { ThemeToken } from \"./tokens.js\";\nimport { THEME_TOKENS, TOKEN_DEFAULTS } from \"./tokens.js\";\n\n/** `var(--wg-<token>, <light default>)` \u2014 every themeable knob goes through this. */\nfunction v(token: ThemeToken): string {\n return `var(--wg-${token}, ${TOKEN_DEFAULTS[token]})`;\n}\n\n/**\n * Every registry token DEFINED at :root with its default, so custom\n * widget styles may reference bare `var(--wg-<token>)` and always\n * resolve. The built-in rules below carry their own fallbacks and never\n * needed this; custom authors write plain references (per the authoring\n * guide), and before this block an applied theme was the only thing that\n * defined tokens \u2014 every token it didn't set silently collapsed the\n * author's declaration (observed live: a valid widget rendered jammed\n * because `--wg-spacing-lg` was \"not defined\"). Themes override these\n * (later style elements and element-level applyTheme both win).\n *\n * Literals only \u2014 a chain here would NOT work: `--wg-surface:\n * var(--wg-bg, \u2026)` substitutes against `:root`'s own `--wg-bg` at\n * computed-value time and inherits that resolved value, so a descendant\n * overriding `--wg-bg` never reaches it. Tokens declaring a `fallback`\n * are resolved where the theme is applied instead (see `withFallbacks`\n * in apply.ts); this block only guarantees a bare `var(--wg-<token>)`\n * always resolves to something.\n */\nconst tokenDefaultsBlock = `:root {\n${THEME_TOKENS.map((token) => ` --wg-${token}: ${TOKEN_DEFAULTS[token]};`).join(\"\\n\")}\n}`;\n\n/**\n * Predefined styles for the built-in `wg-*` classes. Generated from the\n * token defaults table, so the light theme lives in exactly one place and\n * every visual knob is overridable by a theme.\n */\n// One em-box for both icon forms, so an emoji and an image align on the\n// same slot by construction rather than by two literals kept equal.\nconst ICON_BOX = \"1.25em\";\n\nexport const baseStylesheet = `\n${tokenDefaultsBlock}\n.wg-card, .wg-table, .wg-tree, .wg-code, .wg-template {\n font-family: ${v(\"font-family\")};\n font-size: ${v(\"font-size\")};\n line-height: ${v(\"line-height\")};\n color: ${v(\"fg\")};\n}\n.wg-card {\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius-lg\")};\n box-shadow: ${v(\"shadow\")};\n padding: ${v(\"spacing-lg\")};\n}\n.wg-card-title {\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-card-subtitle {\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-card-fields {\n margin: 0;\n}\n.wg-card-field {\n display: flex;\n gap: ${v(\"spacing\")};\n padding: ${v(\"spacing-sm\")} 0;\n}\n.wg-card-field-key {\n color: ${v(\"muted\")};\n}\n.wg-card-field-value {\n margin: 0;\n}\n.wg-table {\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius\")};\n border-collapse: collapse;\n}\n.wg-table-header {\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n font-weight: ${v(\"font-weight-bold\")};\n text-align: left;\n border-bottom: calc(${v(\"border-width\")} * 2) solid ${v(\"border\")};\n padding: ${v(\"spacing\")};\n}\n.wg-table-cell {\n border-bottom: ${v(\"border-width\")} solid ${v(\"border\")};\n padding: ${v(\"spacing\")};\n}\n.wg-tree {\n list-style: none;\n margin: 0;\n padding-left: 0;\n}\n.wg-tree-children {\n list-style: none;\n padding-left: ${v(\"spacing-lg\")};\n border-left: ${v(\"border-width\")} solid ${v(\"border\")};\n}\n.wg-tree-node {\n padding: ${v(\"spacing-sm\")} 0;\n}\n.wg-tree-label {\n display: flex;\n align-items: center;\n gap: ${v(\"spacing-sm\")};\n}\n.wg-tree-branch > .wg-tree-label {\n cursor: pointer;\n list-style: none;\n}\n.wg-tree-branch > .wg-tree-label::-webkit-details-marker {\n display: none;\n}\n.wg-tree-branch > .wg-tree-label::before {\n content: \"\";\n flex: 0 0 auto;\n width: 0;\n height: 0;\n border-left: 0.4em solid ${v(\"muted\")};\n border-top: 0.3em solid transparent;\n border-bottom: 0.3em solid transparent;\n}\n.wg-tree-branch[open] > .wg-tree-label::before {\n transform: rotate(90deg);\n}\n.wg-tree-icon {\n flex: 0 0 auto;\n width: ${ICON_BOX};\n text-align: center;\n}\n.wg-img-icon {\n flex: 0 0 auto;\n width: ${ICON_BOX};\n height: ${ICON_BOX};\n border-radius: ${v(\"radius-sm\")};\n}\n/* Monospace block utility. No built-in emits it: it is a styling surface\n template authors opt into, and what keeps the font-mono token consumed. */\n.wg-code {\n font-family: ${v(\"font-mono\")};\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius\")};\n padding: ${v(\"spacing\")};\n overflow: auto;\n}\n.wg-status {\n display: inline-block;\n padding: 0 ${v(\"spacing-sm\")};\n border-radius: ${v(\"radius-sm\")};\n font-size: ${v(\"font-size-sm\")};\n font-weight: ${v(\"font-weight-bold\")};\n}\n.wg-status-danger { background: ${v(\"danger\")}; color: ${v(\"danger-fg\")}; }\n.wg-status-success { background: ${v(\"success\")}; color: ${v(\"success-fg\")}; }\n.wg-status-warning { background: ${v(\"warning\")}; color: ${v(\"warning-fg\")}; }\n.wg-status-info { background: ${v(\"info\")}; color: ${v(\"info-fg\")}; }\n.wg-status-accent { background: ${v(\"accent\")}; color: ${v(\"accent-fg\")}; }\n.wg-img {\n object-fit: cover;\n vertical-align: middle;\n background: ${v(\"border\")};\n}\n.wg-img-avatar {\n width: ${v(\"avatar-size\")};\n height: ${v(\"avatar-size\")};\n border-radius: 50%;\n}\n.wg-img-thumb {\n width: ${v(\"thumb-size\")};\n height: ${v(\"thumb-size\")};\n border-radius: ${v(\"radius\")};\n}\n.wg-img-hero {\n display: block;\n width: 100%;\n max-width: 100%;\n height: auto;\n border-radius: ${v(\"radius\")};\n}\n.wg-table-caption {\n caption-side: top;\n text-align: left;\n padding-bottom: ${v(\"spacing\")};\n}\n.wg-table-title {\n display: block;\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing-sm\")};\n}\n.wg-table-subtitle {\n display: block;\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n}\n.wg-tree-title {\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-link {\n color: ${v(\"accent\")};\n text-decoration: underline;\n}\n.wg-group {\n display: flex;\n flex-direction: column;\n}\n.wg-group-row {\n flex-direction: row;\n flex-wrap: wrap;\n}\n.wg-group-row > * {\n flex: 1 1 240px;\n min-width: 0;\n}\n.wg-group-grid {\n display: grid;\n}\n.wg-group-grid > * {\n min-width: 0;\n}\n.wg-cols-1 { grid-template-columns: 1fr; }\n.wg-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }\n.wg-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }\n.wg-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }\n.wg-gap-none { gap: 0; }\n.wg-gap-sm { gap: ${v(\"spacing-sm\")}; }\n.wg-gap-md { gap: ${v(\"spacing\")}; }\n.wg-gap-lg { gap: ${v(\"spacing-lg\")}; }\n`.trim();\n\nconst STYLE_MARKER = \"data-widgentic\";\n\n/**\n * Append the base stylesheet to the document head as a marked `<style>`\n * element. Idempotent: repeated calls leave exactly one element.\n */\nexport function injectBaseStyles(doc: Document): void {\n if (doc.head.querySelector(`style[${STYLE_MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(STYLE_MARKER, \"base\");\n style.textContent = baseStylesheet;\n doc.head.appendChild(style);\n}\n", "import type { ThemeError, TokenSpec, WidgetTheme, WidgetThemeInput } from \"./tokens.js\";\nimport { THEME_TOKENS, TOKEN_SPECS, isSafeTokenValue } from \"./tokens.js\";\n\nexport type ValidateThemeResult =\n | { ok: true; theme: WidgetThemeInput }\n | { ok: false; error: ThemeError };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst KNOWN_TOKENS: ReadonlySet<string> = new Set(THEME_TOKENS);\n\n/**\n * Author-defined variables: `x-<name>` keys are accepted alongside registry\n * tokens and emitted as `--wg-x-<name>`. This is the sanctioned escape\n * hatch for custom widgets that need their own knobs, so the registry does\n * not have to grow for every one-off. Names are lowercase/kebab so the\n * generated custom property is always a valid CSS identifier. Exported so\n * tooling states this rule by reading it, never by restating it.\n */\nexport const CUSTOM_VARIABLE = /^x-[a-z0-9][a-z0-9-]*$/;\n\n/** Custom-variable keys carried by a theme, in declaration order. */\nfunction customKeys(theme: WidgetThemeInput): string[] {\n return Object.keys(theme).filter((key) => CUSTOM_VARIABLE.test(key));\n}\n\n/** The `--wg-*` property name a theme key maps to. */\nfunction propertyName(key: string): string {\n return `--wg-${key}`;\n}\n\n/** Validate an unknown value as a theme. Never throws. */\nexport function validateTheme(input: unknown): ValidateThemeResult {\n if (!isPlainObject(input)) {\n return {\n ok: false,\n error: { code: \"INVALID_THEME\", message: \"Theme must be a plain object.\" }\n };\n }\n for (const [token, value] of Object.entries(input)) {\n if (!KNOWN_TOKENS.has(token) && !CUSTOM_VARIABLE.test(token)) {\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_TOKEN\",\n message:\n `Unknown theme token '${token}'. Use a registry token, or a ` +\n `custom variable named 'x-<lowercase-kebab>'.`,\n token\n }\n };\n }\n if (typeof value !== \"string\" || !isSafeTokenValue(value)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TOKEN_VALUE\",\n message: `Token '${token}' has an invalid or unsafe value.`,\n token\n }\n };\n }\n }\n return { ok: true, theme: input as WidgetThemeInput };\n}\n\n/**\n * Fill in tokens a theme left unset that declare a `fallback`, using the\n * fallback token's value FROM THIS THEME.\n *\n * This cannot live in the base stylesheet: a `:root` chain\n * (`--wg-surface: var(--wg-bg, \u2026)`) substitutes against `:root`'s own\n * `--wg-bg` at computed-value time and then inherits that resolved\n * value, so a descendant overriding `--wg-bg` never reaches it. Resolving\n * where the theme is applied puts both declarations on the same element,\n * which is the only place the relationship holds (observed live at v24: a\n * bg-only dark theme painted white cards).\n */\nfunction withFallbacks(theme: WidgetThemeInput): WidgetThemeInput {\n const source = theme as Record<string, unknown>;\n let filled: Record<string, unknown> | undefined;\n for (const token of THEME_TOKENS) {\n const { fallback } = TOKEN_SPECS[token] as TokenSpec;\n if (fallback === undefined) continue;\n if (typeof source[token] === \"string\") continue; // theme set it explicitly\n const inherited = source[fallback];\n if (typeof inherited !== \"string\") continue; // nothing to inherit from\n filled ??= { ...source };\n filled[token] = inherited;\n }\n return (filled ?? theme) as WidgetThemeInput;\n}\n\n/**\n * Apply a theme to a container as inline `--wg-*` custom properties\n * (scoped: descendants inherit them; siblings are unaffected). Replace\n * semantics \u2014 previously applied tokens are removed first, so\n * `applyTheme(el, {})` resets to the stylesheet defaults. Invalid entries\n * are skipped; the CSSOM path (`setProperty`) parses no stylesheet text,\n * so declaration escape is structurally impossible here.\n */\nexport function applyTheme(container: Element, input: WidgetThemeInput): void {\n const theme = withFallbacks(input);\n const style = (container as Partial<ElementCSSInlineStyle>).style;\n if (!style) return;\n // Replace semantics: clear every property this module could have set,\n // custom variables included (they are removed by name from the inline\n // style, which is the only place applyTheme writes).\n for (const token of THEME_TOKENS) {\n style.removeProperty(propertyName(token));\n }\n for (let i = style.length - 1; i >= 0; i--) {\n const property = style.item(i);\n if (property.startsWith(\"--wg-x-\")) style.removeProperty(property);\n }\n const keys: string[] = [...THEME_TOKENS, ...customKeys(theme)];\n for (const key of keys) {\n const value = (theme as Record<string, unknown>)[key];\n if (typeof value === \"string\" && isSafeTokenValue(value)) {\n style.setProperty(propertyName(key), value);\n }\n }\n}\n\n/**\n * Generate a CSS rule assigning the theme's tokens under `selector`\n * (default `:root`). Only entries passing the safety guard are emitted.\n */\nexport function themeToCss(input: WidgetThemeInput, selector = \":root\"): string {\n const theme = withFallbacks(input);\n const declarations: string[] = [];\n const keys: string[] = [...THEME_TOKENS, ...customKeys(theme)];\n for (const key of keys) {\n const value = (theme as Record<string, unknown>)[key];\n if (typeof value === \"string\" && isSafeTokenValue(value)) {\n declarations.push(` ${propertyName(key)}: ${value};`);\n }\n }\n return `${selector} {\\n${declarations.join(\"\\n\")}\\n}`;\n}\n\n/** Dark preset \u2014 ordinary theme data, a starting point for custom themes. */\nexport const darkTheme: WidgetTheme = {\n bg: \"#0f131c\",\n surface: \"#161b26\",\n fg: \"#e5e9f0\",\n muted: \"#8b93a7\",\n accent: \"#7aa2f7\",\n \"accent-fg\": \"#0f131c\",\n border: \"#2a3140\",\n shadow: \"0 1px 3px rgba(0, 0, 0, 0.6)\",\n danger: \"#f0a3a3\",\n success: \"#8fd19e\",\n warning: \"#e8b878\",\n info: \"#7cc4e8\"\n};\n", "/**\n * Named theme registry \u2014 themes as addressable entities rather than\n * anonymous token maps, mirroring the widget catalog's ergonomics. Each\n * entry is complete as registered: a host that derives one theme from\n * another merges the tokens and styles before registering. The registry\n * also knows which entry each mode falls back to when a render names no\n * theme \u2014 the built-ins until a caller's settings choose otherwise.\n */\nimport { isStyleMap } from \"../catalog/styles.js\";\nimport type { WidgetStyles } from \"../catalog/styles.js\";\nimport { darkTheme, validateTheme } from \"./apply.js\";\nimport type { WidgetThemeInput } from \"./tokens.js\";\n\n/** The host colour schemes a default theme is chosen for. */\nexport type ThemeMode = \"light\" | \"dark\";\n\n/** A registered theme: identity, optional prose, tokens and shared styles. */\nexport interface ThemeEntry {\n name: string;\n label?: string;\n description?: string;\n tokens: WidgetThemeInput;\n /** Shared `.wg-` classes for every widget the theme dresses. */\n styles?: WidgetStyles;\n}\n\n/** Entry as supplied to `register`. */\nexport type ThemeEntryInput = ThemeEntry;\n\nexport class DuplicateThemeError extends Error {\n readonly code: \"DUPLICATE_THEME\" = \"DUPLICATE_THEME\";\n readonly theme: string;\n\n constructor(name: string) {\n super(`Theme '${name}' is already registered.`);\n this.name = \"DuplicateThemeError\";\n this.theme = name;\n }\n}\n\nexport class InvalidThemeEntryError extends Error {\n readonly code: string;\n readonly theme: string;\n\n constructor(name: string, code: string, message: string) {\n super(`Theme '${name}' is invalid: ${message}`);\n this.name = \"InvalidThemeEntryError\";\n this.code = code;\n this.theme = name;\n }\n}\n\nexport interface ThemeRegistry {\n /** Register an entry. Throws on conflicts and invalid entries. */\n register(entry: ThemeEntryInput): void;\n get(name: string): ThemeEntry | undefined;\n list(): ThemeEntry[];\n names(): string[];\n /** Make a registered entry the mode's default. Throws for an unknown name. */\n setDefault(mode: ThemeMode, name: string): void;\n /** The mode's default entry: the built-in of that mode until set. */\n getDefault(mode: ThemeMode): ThemeEntry;\n /** The effective default name per mode. */\n defaults(): Record<ThemeMode, string>;\n}\n\n/** A copy of the styles, so later edits to the input never reach the registry. */\nfunction copyStyles(styles: WidgetStyles | undefined): WidgetStyles {\n const copy: WidgetStyles = {};\n for (const [selector, declarations] of Object.entries(styles ?? {})) copy[selector] = { ...declarations };\n return copy;\n}\n\n/**\n * A registry seeded with the built-ins: `light` (no tokens \u2014 the\n * stylesheet defaults) and `dark` (the shipped preset).\n */\nexport function createThemeRegistry(): ThemeRegistry {\n const entries = new Map<string, ThemeEntry>();\n const defaultNames: Record<ThemeMode, string> = { light: \"light\", dark: \"dark\" };\n\n const registry: ThemeRegistry = {\n register(entry) {\n if (\n typeof entry?.name !== \"string\" ||\n entry.name.trim() === \"\"\n ) {\n throw new InvalidThemeEntryError(\n String(entry?.name),\n \"INVALID_NAME\",\n \"name must be a non-empty string.\"\n );\n }\n if (entries.has(entry.name)) throw new DuplicateThemeError(entry.name);\n\n const validated = validateTheme(entry.tokens ?? {});\n if (!validated.ok) {\n throw new InvalidThemeEntryError(\n entry.name,\n validated.error.code,\n validated.error.message\n );\n }\n\n if (entry.styles !== undefined && !isStyleMap(entry.styles)) {\n throw new InvalidThemeEntryError(\n entry.name,\n \"INVALID_THEME\",\n \"styles must map selectors to objects of property/value strings.\"\n );\n }\n\n const styles = copyStyles(entry.styles);\n const stored: ThemeEntry = { name: entry.name, tokens: validated.theme };\n if (Object.keys(styles).length > 0) stored.styles = styles;\n if (entry.label !== undefined) stored.label = entry.label;\n if (entry.description !== undefined) stored.description = entry.description;\n entries.set(entry.name, stored);\n },\n get: (name) => entries.get(name),\n list: () => [...entries.values()],\n names: () => [...entries.keys()],\n setDefault(mode, name) {\n if (!entries.has(name)) {\n throw new InvalidThemeEntryError(name, \"UNKNOWN_THEME\", \"it is not registered, so it cannot be a default.\");\n }\n defaultNames[mode] = name;\n },\n getDefault(mode) {\n // Defaults only ever name registered entries and entries are never\n // removed, so this cannot miss; narrowed rather than asserted.\n const entry = entries.get(defaultNames[mode]);\n if (entry === undefined) throw new Error(`No ${mode} default theme is registered.`);\n return entry;\n },\n defaults: () => ({ ...defaultNames })\n };\n\n registry.register({\n name: \"light\",\n label: \"Light\",\n description: \"The built-in defaults \u2014 no tokens set.\",\n tokens: {}\n });\n registry.register({\n name: \"dark\",\n label: \"Dark\",\n description: \"Shipped dark preset with a lifted surface.\",\n tokens: darkTheme\n });\n\n return registry;\n}\n", "/**\n * Theme styles: the shared `.wg-` classes a theme defines for every widget\n * it dresses. Same shape and guards as a widget descriptor's styles \u2014 one\n * generator decides what reaches CSS for both.\n */\nimport { guardedStylesToCss } from \"../catalog/styles.js\";\nimport type { WidgetStyles } from \"../catalog/styles.js\";\n\n/**\n * Generate a theme's style CSS. With `scope` (a caller constant such as\n * `:root[data-theme=\"dark\"]`, never theme data) every selector part is\n * prefixed with `:where(<scope>) `, so the rule applies only inside the\n * scope and weighs what its author wrote. Never throws.\n */\nexport function themeStylesToCss(styles: WidgetStyles, scope?: string): string {\n return guardedStylesToCss(styles, scope);\n}\n", "/**\n * Safety constants shared by validation (strict) and interpretation\n * (lenient defense in depth). Both layers MUST consult these \u2014 keeping them\n * in one module is what prevents the two from drifting. URL safety itself\n * lives in the contract layer (`contract/urls.ts`) so the catalog's image\n * rendering shares the exact same rules; re-exported here to keep this\n * module the single import point for template safety.\n */\nexport {\n ALLOWED_SCHEMES,\n isSafeUrl,\n isSafeImageSrc\n} from \"../contract/urls.js\";\n\n/**\n * Attributes that are code or embedded documents: event handlers (`on*`)\n * and `srcdoc`, which smuggles a whole document past the tag policy.\n */\nexport const FORBIDDEN_ATTR = /^(?:on.*|srcdoc)$/i;\n\n/**\n * Tags that introduce active or foreign content into the frame. A template\n * is data, never a program: these fail validation and render as nothing\n * when validation was bypassed \u2014 the same two-layer stance as `on*`.\n */\nexport const FORBIDDEN_TAGS: ReadonlySet<string> = new Set([\n \"script\", \"iframe\", \"frame\", \"frameset\", \"object\", \"embed\", \"style\",\n \"link\", \"meta\", \"base\", \"template\", \"noscript\"\n]);\n\n/**\n * Renderer-owned attributes (`data-wg-*`): action descriptors and render\n * markers. Authors cannot write them \u2014 only a validated `action` binding\n * produces one \u2014 so a hand-written descriptor never reaches a tree.\n */\nexport const RESERVED_ATTR = /^data-wg-/i;\n\n/** Attributes whose values are URLs and can smuggle script schemes. */\nexport const URL_ATTRS = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"data\",\n \"poster\",\n \"ping\"\n]);\n\n/** Maximum template nesting depth accepted by validation. */\nexport const MAX_TEMPLATE_DEPTH = 64;\n", "/**\n * The template path grammar, shared by validation (strict) and\n * interpretation (lenient) so the two never drift:\n *\n * \".\" the current scope itself\n * \"$index\" zero-based position in the innermost `each`\n * \"$meta.<segments>\" reads payload.meta\n * \"$root[.<segments>]\" reads payload.data regardless of `each` nesting\n * \"$parent\"+ [.<rest>] steps out of one enclosing `each` per token;\n * <rest> is segments, \"$index\", or nothing\n * \"<segments>\" dot path against the current scope\n *\n * Reserved tokens (`$meta`, `$root`, `$parent`, `$index`) are only valid in\n * the positions above; anywhere else the path is invalid.\n */\nexport interface ParsedPath {\n base: \"scope\" | \"meta\" | \"root\";\n /** Enclosing-scope hops (`$parent` count). */\n up: number;\n /** The path names the current index rather than a value. */\n index: boolean;\n segments: string[];\n}\n\nconst RESERVED = new Set([\"$meta\", \"$root\", \"$parent\", \"$index\"]);\n\n/** Parse a path; `undefined` when the syntax is invalid. Never throws. */\nexport function parsePath(value: string): ParsedPath | undefined {\n if (value === \".\") return { base: \"scope\", up: 0, index: false, segments: [] };\n const tokens = value.split(\".\");\n let i = 0;\n let base: ParsedPath[\"base\"] = \"scope\";\n let up = 0;\n if (tokens[0] === \"$meta\") {\n base = \"meta\";\n i = 1;\n } else if (tokens[0] === \"$root\") {\n base = \"root\";\n i = 1;\n } else {\n while (tokens[i] === \"$parent\") {\n up++;\n i++;\n }\n }\n const rest = tokens.slice(i);\n if (rest.length === 1 && rest[0] === \"$index\") {\n if (base !== \"scope\") return undefined;\n return { base, up, index: true, segments: [] };\n }\n if (rest.length === 0) {\n if (base === \"meta\") return undefined;\n return { base, up, index: false, segments: [] };\n }\n if (rest.some((segment) => segment === \"\" || RESERVED.has(segment))) return undefined;\n return { base, up, index: false, segments: rest };\n}\n", "/**\n * The action model: what a widget can ask for when a person activates a\n * bound element. Two kinds \u2014 `prompt` proposes a user message through the\n * host, `http` performs a server-side request against an author-declared\n * URL \u2014 both plain JSON data, storable and validatable, never code.\n *\n * Zero-dependency by design: this module is shared by the template\n * compiler (which resolves bindings into descriptors at render time), the\n * store (which validates stored actions), the server (which executes) and\n * the designers (which edit).\n */\nimport type { DataSchema } from \"../catalog/index.js\";\n\n/** A prompt's text: literals and `{ bind }` segments resolved at render time. */\nexport type PromptSegment = string | { bind: string };\n\nexport interface PromptActionDefinition {\n kind: \"prompt\";\n text: PromptSegment[];\n}\n\n/** A by-name reference to one of the principal's secrets. */\nexport interface SecretRef {\n secret: string;\n}\n\n/** Header and query values: author literals or secret references. */\nexport type HeaderValue = string | SecretRef;\n\nexport type HttpMethod = \"GET\" | \"POST\";\n\nexport interface HttpActionDefinition {\n kind: \"http\";\n method: HttpMethod;\n /** Absolute https URL, fixed by the author \u2014 bindings never reach it. */\n url: string;\n /** JSON Schema (`type: \"object\"`) of the arguments. */\n input: DataSchema;\n /** JSON Schema the response body must satisfy. */\n output: DataSchema;\n headers?: Record<string, HeaderValue>;\n query?: Record<string, HeaderValue>;\n}\n\nexport type ActionDefinition = PromptActionDefinition | HttpActionDefinition;\n\n/** A shared, named action a principal owns. */\nexport interface StoredAction {\n name: string;\n label?: string;\n description?: string;\n definition: ActionDefinition;\n}\n\n/** Input mapping: input-schema field \u2192 template path or literal. */\nexport type InputMapping = Record<string, string | { const: unknown }>;\n\nexport type OutputMode = \"replace\" | \"merge\" | \"patch\";\n\nexport interface OutputBinding {\n /** Default `merge`. */\n mode?: OutputMode;\n /** Required for `patch`: the dotted data path the response is written at. */\n path?: string;\n /** Projection applied first: target data path \u2192 source response path. */\n map?: Record<string, string>;\n}\n\n/**\n * A binding names an action \u2014 a shared one by `ref`, or an inline one\n * under `definition` (nested so the definition's `input`/`output` schemas\n * never collide with the binding's `input` mapping and `output` mode) \u2014\n * plus how data flows.\n */\nexport type ActionBinding = ({ ref: string } | { definition: ActionDefinition }) & {\n input?: InputMapping;\n output?: OutputBinding;\n};\n\n/** Why an action renders unavailable. */\nexport type ActionDisabledReason = \"scope\" | \"unresolved\";\n\n/**\n * What a rendered element carries in `data-wg-action`: everything the\n * bridge needs, nothing it must evaluate.\n */\nexport interface ActionDescriptor {\n /** Binding identifier: the element's dotted template path, or \"load\". */\n id: string;\n kind?: ActionDefinition[\"kind\"];\n /** Resolved http arguments. */\n args?: Record<string, unknown>;\n /** Resolved prompt text. */\n text?: string;\n disabled?: ActionDisabledReason;\n /** The kind whose template declared the binding (set when registered). */\n widget?: string;\n /**\n * Inside a `group` render: the dotted path of the item payload within the\n * root payload (e.g. `data.items.2`), stamped by the group composition.\n */\n at?: string;\n}\n\n/** Structured validation error; `path` is dotted, relative to the caller's root. */\nexport interface ActionError {\n code: \"INVALID_ACTION\";\n message: string;\n path: string;\n}\n\n/** Upper bound on a resolved prompt message. */\nexport const PROMPT_TEXT_MAX = 2_000;\n\n/** Secret names: short, lowercase, URL- and header-safe. */\nexport const SECRET_NAME = /^[a-z][a-z0-9-]{0,63}$/;\n\n/** Action names share the secret-name discipline. */\nexport const ACTION_NAME = SECRET_NAME;\n\nexport const OUTPUT_MODES: readonly OutputMode[] = [\"replace\", \"merge\", \"patch\"];\n\nexport const HTTP_METHODS: readonly HttpMethod[] = [\"GET\", \"POST\"];\n", "import { isPlainObject } from \"../shared/plain-object.js\";\nimport type {\n ActionDefinition,\n ActionError\n} from \"./types.js\";\nimport {\n HTTP_METHODS,\n OUTPUT_MODES,\n PROMPT_TEXT_MAX,\n SECRET_NAME\n} from \"./types.js\";\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\nfunction fail(message: string, path: string): ActionError {\n return { code: \"INVALID_ACTION\", message, path };\n}\n\n/** RFC 7230 token: what a header or query parameter NAME may be. */\nconst HEADER_TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\n/** Header names the transport owns; an author must not set them. */\nconst RESERVED_HEADERS: ReadonlySet<string> = new Set([\n \"host\", \"content-length\", \"transfer-encoding\", \"connection\"\n]);\n\n/** Segments that would reach the prototype chain or the template grammar's reserved tokens. */\nconst FORBIDDEN_SEGMENTS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * The dotted-path grammar for output `path` and `map` entries: non-empty\n * segments, no `$`-tokens, nothing that addresses a prototype.\n */\nexport function isDataPath(value: string): boolean {\n if (value === \"\") return false;\n return value.split(\".\").every(\n (segment) => segment !== \"\" && !segment.startsWith(\"$\") && !FORBIDDEN_SEGMENTS.has(segment)\n );\n}\n\n/** A header/query value: literal string or `{ secret: name }`. */\nfunction checkHeaderValue(value: unknown, path: string): ActionError | undefined {\n if (typeof value === \"string\") return undefined;\n if (isPlainObject(value) && typeof value.secret === \"string\") {\n if (!SECRET_NAME.test(value.secret)) {\n return fail(`Secret reference '${value.secret}' is not a valid secret name.`, path);\n }\n if (Object.keys(value).length !== 1) {\n return fail(\"A secret reference carries only 'secret'.\", path);\n }\n return undefined;\n }\n return fail(\"Value must be a string or a { secret } reference.\", path);\n}\n\n/** Does any nested value look like a secret reference? */\nfunction containsSecretRef(value: unknown): boolean {\n if (!isPlainObject(value) && !Array.isArray(value)) return false;\n if (isPlainObject(value) && typeof value.secret === \"string\") return true;\n const entries = Array.isArray(value) ? value : Object.values(value);\n return entries.some(containsSecretRef);\n}\n\nfunction checkUrl(url: unknown, path: string): ActionError | undefined {\n if (typeof url !== \"string\" || url.length === 0) {\n return fail(\"'url' must be a non-empty string.\", path);\n }\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return fail(`'url' must be an absolute URL (got '${url}').`, path);\n }\n if (parsed.protocol !== \"https:\") return fail(\"'url' must use https.\", path);\n if (parsed.username !== \"\" || parsed.password !== \"\") {\n return fail(\"'url' must not carry userinfo.\", path);\n }\n if (parsed.hash !== \"\") return fail(\"'url' must not carry a fragment.\", path);\n return undefined;\n}\n\n/**\n * Validate an action definition. `path` locates it for the caller (an\n * element's `action`, a stored action's `definition`). Never throws.\n */\nexport interface DefinitionCheckOptions {\n /** Path-syntax check supplied by the template layer (owner of the grammar). */\n isPath?: (path: string) => boolean;\n}\n\nexport function validateActionDefinition(\n input: unknown,\n path = \"\",\n options: DefinitionCheckOptions = {}\n): ActionError | undefined {\n if (!isPlainObject(input)) return fail(\"Action definition must be an object.\", path);\n if (input.kind === \"prompt\") {\n if (!Array.isArray(input.text)) {\n return fail(\"'text' must be an array of literals and { bind } segments.\", join(path, \"text\"));\n }\n let literal = 0;\n for (let i = 0; i < input.text.length; i++) {\n const segment = input.text[i];\n if (typeof segment === \"string\") {\n literal += segment.length;\n continue;\n }\n if (isPlainObject(segment) && typeof segment.bind === \"string\" && Object.keys(segment).length === 1) {\n if (options.isPath && !options.isPath(segment.bind)) {\n return fail(`Invalid data path '${segment.bind}'.`, join(path, `text.${i}`));\n }\n continue;\n }\n return fail(\"Prompt segments are strings or { bind } objects.\", join(path, `text.${i}`));\n }\n if (literal > PROMPT_TEXT_MAX) {\n return fail(`Prompt text exceeds ${PROMPT_TEXT_MAX} characters.`, join(path, \"text\"));\n }\n return undefined;\n }\n if (input.kind === \"http\") {\n if (!HTTP_METHODS.some((m) => m === input.method)) {\n return fail(\"'method' must be GET or POST.\", join(path, \"method\"));\n }\n const urlError = checkUrl(input.url, join(path, \"url\"));\n if (urlError) return urlError;\n if (!isPlainObject(input.input) || input.input.type !== \"object\") {\n return fail(\"'input' must be a JSON Schema with type \\\"object\\\".\", join(path, \"input\"));\n }\n if (containsSecretRef(input.input)) {\n return fail(\"Secret references are allowed only in headers and query.\", join(path, \"input\"));\n }\n if (!isPlainObject(input.output)) {\n return fail(\"'output' must be a JSON Schema object.\", join(path, \"output\"));\n }\n for (const field of [\"headers\", \"query\"] as const) {\n const map = input[field];\n if (map === undefined) continue;\n if (!isPlainObject(map)) return fail(`'${field}' must be an object.`, join(path, field));\n for (const [name, value] of Object.entries(map)) {\n const namePath = join(path, `${field}.${name}`);\n if (!HEADER_TOKEN.test(name)) {\n return fail(`'${name}' is not a valid ${field === \"headers\" ? \"header\" : \"parameter\"} name.`, namePath);\n }\n if (field === \"headers\" && RESERVED_HEADERS.has(name.toLowerCase())) {\n return fail(`Header '${name}' is set by the transport and cannot be declared.`, namePath);\n }\n const error = checkHeaderValue(value, namePath);\n if (error) return error;\n }\n }\n return undefined;\n }\n return fail(\"'kind' must be \\\"prompt\\\" or \\\"http\\\".\", join(path, \"kind\"));\n}\n\nexport interface BindingCheckOptions {\n /** Path-syntax check supplied by the template layer (owner of the grammar). */\n isPath?: (path: string) => boolean;\n /** Resolve a `ref` to its definition when the caller knows the catalog. */\n resolve?: (ref: string) => ActionDefinition | undefined;\n /** `load` bindings: http GET only. */\n loadOnly?: boolean;\n}\n\nfunction definitionOf(\n binding: Record<string, unknown>,\n options: BindingCheckOptions\n): ActionDefinition | undefined {\n if (typeof binding.ref === \"string\") return options.resolve?.(binding.ref);\n return binding.definition as ActionDefinition | undefined;\n}\n\n/**\n * Validate a binding: `{ ref }` or an inline definition, plus `input` and\n * `output`. When the definition is known (inline, or resolved through\n * `options.resolve`), input keys are checked against its input schema and\n * `load` bindings are held to http GET. Never throws.\n */\nexport function validateActionBinding(\n input: unknown,\n path = \"\",\n options: BindingCheckOptions = {}\n): ActionError | undefined {\n if (!isPlainObject(input)) return fail(\"Action binding must be an object.\", path);\n const hasRef = \"ref\" in input;\n if (hasRef) {\n if (typeof input.ref !== \"string\" || input.ref.length === 0) {\n return fail(\"'ref' must name a shared action.\", join(path, \"ref\"));\n }\n if (\"definition\" in input) return fail(\"A binding is either a { ref } or a { definition }, not both.\", path);\n if (options.resolve && options.resolve(input.ref) === undefined) {\n return fail(`Unknown action '${input.ref}'.`, join(path, \"ref\"));\n }\n } else if (\"definition\" in input) {\n const definitionError = validateActionDefinition(input.definition, join(path, \"definition\"), {\n ...(options.isPath ? { isPath: options.isPath } : {})\n });\n if (definitionError) return definitionError;\n } else {\n return fail(\"A binding names a shared action ({ ref }) or carries an inline { definition }.\", path);\n }\n const definition = definitionOf(input, options);\n\n if (options.loadOnly && definition !== undefined) {\n if (definition.kind !== \"http\" || definition.method !== \"GET\") {\n return fail(\"'load' accepts only http GET actions.\", path);\n }\n }\n\n if (input.input !== undefined) {\n if (!isPlainObject(input.input)) return fail(\"'input' must be an object.\", join(path, \"input\"));\n if (definition?.kind === \"prompt\") {\n return fail(\"Prompt actions take no input mapping.\", join(path, \"input\"));\n }\n const declared = definition?.kind === \"http\" && isPlainObject(definition.input.properties)\n ? definition.input.properties\n : undefined;\n for (const [field, value] of Object.entries(input.input)) {\n const fieldPath = join(path, `input.${field}`);\n if (declared !== undefined && !(field in declared)) {\n return fail(`Input field '${field}' is not declared by the action's input schema.`, fieldPath);\n }\n if (typeof value === \"string\") {\n if (options.isPath && !options.isPath(value)) {\n return fail(`Invalid data path '${value}'.`, fieldPath);\n }\n continue;\n }\n if (isPlainObject(value) && \"const\" in value && Object.keys(value).length === 1) {\n if (containsSecretRef(value.const)) {\n return fail(\"Secret references are allowed only in headers and query.\", fieldPath);\n }\n continue;\n }\n return fail(\"Input values are data paths or { const } literals.\", fieldPath);\n }\n }\n\n if (input.output !== undefined) {\n const outPath = join(path, \"output\");\n if (!isPlainObject(input.output)) return fail(\"'output' must be an object.\", outPath);\n if (definition?.kind === \"prompt\") return fail(\"Prompt actions have no output.\", outPath);\n const { mode, path: target, map } = input.output;\n if (mode !== undefined && !OUTPUT_MODES.some((m) => m === mode)) {\n return fail(\"'mode' must be replace, merge or patch.\", join(outPath, \"mode\"));\n }\n if (mode === \"patch\") {\n if (typeof target !== \"string\" || !isDataPath(target)) {\n return fail(\"'patch' requires a valid data 'path'.\", join(outPath, \"path\"));\n }\n } else if (target !== undefined) {\n return fail(\"'path' is only meaningful with mode \\\"patch\\\".\", join(outPath, \"path\"));\n }\n if (map !== undefined) {\n if (!isPlainObject(map)) return fail(\"'map' must be an object of data paths.\", join(outPath, \"map\"));\n const entries = Object.entries(map);\n if (entries.length === 0) return fail(\"'map' must not be empty (omit it to take the whole response).\", join(outPath, \"map\"));\n for (const [key, value] of entries) {\n const entryPath = join(outPath, `map.${key}`);\n if (key !== \".\" && !isDataPath(key)) {\n return fail(`'${key}' is not a valid data path.`, entryPath);\n }\n if (typeof value !== \"string\" || (value !== \".\" && !isDataPath(value))) {\n return fail(\"Map values are data paths into the response ('.' for the whole response).\", entryPath);\n }\n }\n }\n }\n return undefined;\n}\n\n/** A widget's `load` binding: http GET only (see `BindingCheckOptions.loadOnly`). */\nexport function validateLoadBinding(\n input: unknown,\n path = \"load\",\n options: Omit<BindingCheckOptions, \"loadOnly\"> = {}\n): ActionError | undefined {\n return validateActionBinding(input, path, { ...options, loadOnly: true });\n}\n\n/** Secret names an http definition references in its headers and query. */\nexport function collectSecretRefs(definition: unknown): string[] {\n if (!isPlainObject(definition) || definition.kind !== \"http\") return [];\n const names = new Set<string>();\n for (const field of [\"headers\", \"query\"] as const) {\n const map = definition[field];\n if (!isPlainObject(map)) continue;\n for (const value of Object.values(map)) {\n if (isPlainObject(value) && typeof value.secret === \"string\") names.add(value.secret);\n }\n }\n return [...names];\n}\n", "import { isPlainObject } from \"../shared/plain-object.js\";\nimport type { TemplateError, WidgetTemplate } from \"./types.js\";\nimport { FORBIDDEN_ATTR, FORBIDDEN_TAGS, MAX_TEMPLATE_DEPTH, RESERVED_ATTR } from \"./guards.js\";\nimport { parsePath } from \"./paths.js\";\nimport { validateActionBinding } from \"../actions/validate.js\";\nimport {\n CURRENCY_CODE,\n CURRENCY_DISPLAYS,\n DATE_PATTERN_ALLOWED,\n DATE_PATTERN_MAX,\n DATE_TOKENS,\n FORMAT_DECIMALS_MAX,\n FORMAT_DECIMALS_MIN,\n FORMAT_TYPES,\n LOCALE_TAG,\n isCurrencyDisplay,\n isFormatType,\n isKnownLocale,\n parseFormatSpec,\n tokenizeDatePattern\n} from \"../catalog/widgets/value-format.js\";\n\nexport type ValidateTemplateResult =\n | { ok: true; template: WidgetTemplate }\n | { ok: false; error: TemplateError };\n\n/**\n * Thrown by `registerTemplate` when the template fails validation \u2014\n * registration is host setup, where failing loudly is the convention.\n * Carries the structured error for programmatic handling.\n */\nexport class InvalidTemplateError extends Error {\n readonly templateError: TemplateError;\n\n constructor(kind: string, error: TemplateError) {\n super(\n `Invalid widget template for kind '${kind}' at '${error.path}': ${error.message} (${error.code})`\n );\n this.name = \"InvalidTemplateError\";\n this.templateError = error;\n }\n}\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\nfunction nodeError(message: string, path: string): TemplateError {\n return { code: \"INVALID_TEMPLATE_NODE\", message, path };\n}\n\n/**\n * The `format` spec: a closed vocabulary of author literals. Every bound\n * comes from the engine's own exported constants, so a change to the\n * engine cannot leave the validator (or the guide) behind.\n */\nfunction checkFormat(\n spec: unknown,\n label: string,\n path: string\n): TemplateError | undefined {\n const bad = (message: string): TemplateError => nodeError(`${label}: ${message}`, path);\n if (!isPlainObject(spec)) return bad(\"'format' must be an object.\");\n if (!isFormatType(spec.type)) {\n return bad(`'format.type' must be one of ${FORMAT_TYPES.join(\", \")}.`);\n }\n if (spec.type === \"date\") {\n if (typeof spec.pattern !== \"string\") {\n return bad(\"'format.pattern' must be a string.\");\n }\n if (spec.pattern.length === 0 || spec.pattern.length > DATE_PATTERN_MAX) {\n return bad(`'format.pattern' must be 1-${DATE_PATTERN_MAX} characters.`);\n }\n if (!DATE_PATTERN_ALLOWED.test(spec.pattern)) {\n return bad(\"'format.pattern' may contain only the date tokens and separators.\");\n }\n if (tokenizeDatePattern(spec.pattern) === undefined) {\n return bad(\n `'format.pattern' must use at least one of ${DATE_TOKENS.join(\", \")} and no stray letters.`\n );\n }\n return undefined;\n }\n if (spec.decimals !== undefined) {\n if (\n typeof spec.decimals !== \"number\" ||\n !Number.isInteger(spec.decimals) ||\n spec.decimals < FORMAT_DECIMALS_MIN ||\n spec.decimals > FORMAT_DECIMALS_MAX\n ) {\n return bad(\n `'format.decimals' must be an integer ${FORMAT_DECIMALS_MIN}-${FORMAT_DECIMALS_MAX}.`\n );\n }\n }\n if (spec.locale !== undefined) {\n if (typeof spec.locale !== \"string\" || !LOCALE_TAG.test(spec.locale) || !isKnownLocale(spec.locale)) {\n return bad(\"'format.locale' must be a BCP-47 language tag this runtime knows.\");\n }\n }\n if (spec.type === \"currency\") {\n if (typeof spec.currency !== \"string\" || !CURRENCY_CODE.test(spec.currency)) {\n return bad(\"'format.currency' must be a three-letter uppercase ISO-4217 code.\");\n }\n if (spec.currencyDisplay !== undefined && !isCurrencyDisplay(spec.currencyDisplay)) {\n return bad(`'format.currencyDisplay' must be one of ${CURRENCY_DISPLAYS.join(\", \")}.`);\n }\n }\n // The engine narrows the same shape; a spec it would degrade never passes.\n return parseFormatSpec(spec) === undefined ? bad(\"'format' is not a spec the engine accepts.\") : undefined;\n}\n\n/** The value transforms a bind may carry \u2014 at most one of them per value. */\nexport const TRANSFORM_KEYS = [\"map\", \"prefix\", \"format\"] as const;\n\nexport type TransformKey = (typeof TRANSFORM_KEYS)[number];\n\n/** Which transform a bind value carries, or `undefined`; `\"conflict\"` when more than one. */\nexport function activeTransform(value: Record<string, unknown>): TransformKey | \"conflict\" | undefined {\n const present = TRANSFORM_KEYS.filter((key) => value[key] !== undefined);\n if (present.length > 1) return \"conflict\";\n return present[0];\n}\n\n/** Path syntax per paths.ts: \".\", \"$index\", \"$meta.\"/\"$root.\"/\"$parent.\"-prefixed, or dot segments. */\nfunction checkPathSyntax(value: string, path: string): TemplateError | undefined {\n if (parsePath(value) !== undefined) return undefined;\n return {\n code: \"INVALID_PATH\",\n message: `Invalid data path '${value}'.`,\n path\n };\n}\n\nfunction check(node: unknown, path: string, depth: number): TemplateError | undefined {\n if (depth > MAX_TEMPLATE_DEPTH) {\n return {\n code: \"TEMPLATE_TOO_DEEP\",\n message: `Template exceeds the maximum nesting depth of ${MAX_TEMPLATE_DEPTH}.`,\n path\n };\n }\n if (typeof node === \"string\") return undefined;\n if (!isPlainObject(node)) {\n return nodeError(\"Template node must be a string or a plain object.\", path);\n }\n\n if (\"bind\" in node) {\n if (typeof node.bind !== \"string\") {\n return nodeError(\"'bind' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.bind, path);\n if (pathError) return pathError;\n // A text bind takes `map` (value \u2192 authored label) or `format`, never\n // both. `prefix` is an attribute-value transform: ignored here and kept\n // valid, so no stored template is refused on read for carrying it.\n if (node.map !== undefined && node.format !== undefined) {\n return nodeError(\"A text bind carries either 'map' or 'format' \u2014 one transform per value.\", path);\n }\n if (node.map !== undefined) {\n if (!isPlainObject(node.map) || Object.values(node.map).some((entry) => typeof entry !== \"string\")) {\n return nodeError(\"Bind: 'map' must be an object of string values.\", path);\n }\n if (node.default !== undefined && typeof node.default !== \"string\") {\n return nodeError(\"Bind: 'default' must be a string.\", path);\n }\n return undefined;\n }\n if (node.default !== undefined) {\n return nodeError(\"Bind: 'default' requires 'map'.\", path);\n }\n if (node.format !== undefined) {\n return checkFormat(node.format, \"Bind\", path);\n }\n return undefined;\n }\n\n if (\"each\" in node) {\n if (typeof node.each !== \"string\") {\n return nodeError(\"'each' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.each, path);\n if (pathError) return pathError;\n if (\"key\" in node && node.key !== undefined) {\n if (typeof node.key !== \"string\") {\n return nodeError(\"'key' must be a string path.\", path);\n }\n const keyError = checkPathSyntax(node.key, path);\n if (keyError) return keyError;\n }\n if (!(\"template\" in node)) {\n return nodeError(\"'each' node requires a 'template'.\", path);\n }\n const templateError = check(node.template, join(path, \"template\"), depth + 1);\n if (templateError) return templateError;\n if (\"empty\" in node && node.empty !== undefined) {\n return check(node.empty, join(path, \"empty\"), depth + 1);\n }\n return undefined;\n }\n\n if (\"when\" in node) {\n if (typeof node.when !== \"string\") {\n return nodeError(\"'when' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.when, path);\n if (pathError) return pathError;\n if (!(\"template\" in node)) {\n return nodeError(\"'when' node requires a 'template'.\", path);\n }\n const templateError = check(node.template, join(path, \"template\"), depth + 1);\n if (templateError) return templateError;\n if (\"else\" in node && node.else !== undefined) {\n return check(node.else, join(path, \"else\"), depth + 1);\n }\n return undefined;\n }\n\n if (\"tag\" in node) {\n if (typeof node.tag !== \"string\" || node.tag.length === 0) {\n return nodeError(\"'tag' must be a non-empty string.\", path);\n }\n if (FORBIDDEN_TAGS.has(node.tag.toLowerCase())) {\n return {\n code: \"FORBIDDEN_TAG\",\n message: `Element '${node.tag}' is not allowed in templates (active or foreign content).`,\n path\n };\n }\n if (\"attrs\" in node && node.attrs !== undefined) {\n if (!isPlainObject(node.attrs)) {\n return nodeError(\"'attrs' must be an object.\", path);\n }\n for (const [name, value] of Object.entries(node.attrs)) {\n const attrPath = join(path, `attrs.${name}`);\n if (FORBIDDEN_ATTR.test(name)) {\n return {\n code: \"FORBIDDEN_ATTRIBUTE\",\n message: `Attribute '${name}' is not allowed in templates (event handlers and srcdoc).`,\n path: attrPath\n };\n }\n if (RESERVED_ATTR.test(name)) {\n return {\n code: \"FORBIDDEN_ATTRIBUTE\",\n message: `Attribute '${name}' is reserved for the renderer (data-wg-*); use an 'action' binding.`,\n path: attrPath\n };\n }\n if (typeof value === \"string\") continue;\n if (isPlainObject(value) && typeof value.bind === \"string\") {\n const pathError = checkPathSyntax(value.bind, attrPath);\n if (pathError) return pathError;\n // One transform per value: map selects an authored literal,\n // prefix glues one in front, format presents the value \u2014\n // combining them has no use case and every combination would\n // need teaching forever.\n const transform = activeTransform(value);\n const hasMap = transform === \"map\";\n const hasPrefix = transform === \"prefix\";\n const hasFormat = transform === \"format\";\n if (transform === \"conflict\") {\n return nodeError(\n `Attribute '${name}' carries more than one of 'map', 'prefix' and 'format' \u2014 one transform per value.`,\n attrPath\n );\n }\n if (hasMap) {\n if (\n !isPlainObject(value.map) ||\n Object.values(value.map).some((entry) => typeof entry !== \"string\")\n ) {\n return nodeError(\n `Attribute '${name}': 'map' must be an object of string values.`,\n attrPath\n );\n }\n if (value.default !== undefined && typeof value.default !== \"string\") {\n return nodeError(\n `Attribute '${name}': 'default' must be a string.`,\n attrPath\n );\n }\n } else if (value.default !== undefined) {\n return nodeError(\n `Attribute '${name}': 'default' requires 'map'.`,\n attrPath\n );\n }\n if (hasPrefix && typeof value.prefix !== \"string\") {\n return nodeError(\n `Attribute '${name}': 'prefix' must be a string.`,\n attrPath\n );\n }\n if (hasFormat) {\n const formatError = checkFormat(value.format, `Attribute '${name}'`, attrPath);\n if (formatError) return formatError;\n }\n continue;\n }\n return nodeError(\n `Attribute '${name}' must be a string, { bind }, { bind, map, default? }, { bind, prefix } or { bind, format } value.`,\n attrPath\n );\n }\n }\n if (\"action\" in node && node.action !== undefined) {\n // An element is a link OR an action \u2014 both would leave the bridge\n // guessing which the author meant.\n const hasHref =\n isPlainObject(node.attrs) &&\n Object.keys(node.attrs).some((name) => name.toLowerCase() === \"href\");\n if (hasHref) {\n return {\n code: \"CONFLICTING_ATTRIBUTES\",\n message: \"An element carries 'href' or an 'action' binding, never both.\",\n path\n };\n }\n const actionError = validateActionBinding(node.action, join(path, \"action\"), {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (actionError) {\n return { code: \"INVALID_ACTION\", message: actionError.message, path: actionError.path };\n }\n }\n if (\"children\" in node && node.children !== undefined) {\n if (!Array.isArray(node.children)) {\n return nodeError(\"'children' must be an array.\", path);\n }\n for (let i = 0; i < node.children.length; i++) {\n const childError = check(\n node.children[i],\n join(path, `children.${i}`),\n depth + 1\n );\n if (childError) return childError;\n }\n }\n return undefined;\n }\n\n return nodeError(\n \"Unknown template node form (expected text, bind, tag, each, or when).\",\n path\n );\n}\n\n/** Validate an unknown value as a widget template. Never throws. */\nexport function validateTemplate(input: unknown): ValidateTemplateResult {\n const error = check(input, \"\", 0);\n if (error) return { ok: false, error };\n return { ok: true, template: input as WidgetTemplate };\n}\n", "/**\n * Addressing nodes inside a template by the validator's dotted path\n * convention (`children.2.template`, `else`, \u2026) \u2014 the identifier an action\n * binding is known by \u2014 and enumerating the shared actions a template\n * references, so stores can enforce referential integrity without a\n * second grammar.\n */\nimport { isPlainObject } from \"../shared/plain-object.js\";\nimport type { ActionBinding } from \"../actions/types.js\";\n\n/** The template node at a dotted path (\"\" is the root); `undefined` when absent. */\nexport function findTemplateNode(template: unknown, path: string): unknown {\n if (path === \"\") return template;\n let current: unknown = template;\n for (const segment of path.split(\".\")) {\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = current[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/** The element's `action` binding at a dotted path, when that node is a bound element. */\nexport function findActionBinding(template: unknown, path: string): ActionBinding | undefined {\n const node = findTemplateNode(template, path);\n if (isPlainObject(node) && typeof node.tag === \"string\" && isPlainObject(node.action)) {\n return node.action as ActionBinding;\n }\n return undefined;\n}\n\n/** Visit every binding object a template (and an optional `load`) carries. */\nfunction eachBinding(template: unknown, load: unknown, onBinding: (binding: Record<string, unknown>) => void): void {\n const visit = (node: unknown): void => {\n if (!isPlainObject(node)) return;\n if (isPlainObject(node.action)) onBinding(node.action);\n for (const key of [\"template\", \"empty\", \"else\"] as const) {\n if (node[key] !== undefined) visit(node[key]);\n }\n if (Array.isArray(node.children)) for (const child of node.children) visit(child);\n };\n visit(template);\n if (isPlainObject(load)) onBinding(load);\n}\n\n/** Every shared-action name a template (and an optional `load`) references by `ref`. */\nexport function collectActionRefs(template: unknown, load?: unknown): string[] {\n const refs = new Set<string>();\n eachBinding(template, load, (binding) => {\n if (typeof binding.ref === \"string\") refs.add(binding.ref);\n });\n return [...refs];\n}\n\n/** Every inline action definition in a template (and `load`), for secret-reference scans. */\nexport function collectInlineActions(template: unknown, load?: unknown): unknown[] {\n const out: unknown[] = [];\n eachBinding(template, load, (binding) => {\n if (typeof binding.ref !== \"string\" && binding.definition !== undefined) out.push(binding.definition);\n });\n return out;\n}\n\n/** Does the template (or `load`) carry any action binding at all? */\nexport function hasActionBindings(template: unknown, load?: unknown): boolean {\n if (load !== undefined) return true;\n return collectActionRefs(template).length > 0 || collectInlineActions(template).length > 0;\n}\n", "import type { WidgetPayload } from \"../contract/types.js\";\nimport type {\n WidgetCatalog,\n WidgetDescriptorInput,\n WidgetElementNode,\n WidgetNode,\n WidgetNodeAttrs,\n WidgetRenderer\n} from \"../catalog/index.js\";\nimport type {\n ActionBinding,\n ActionDefinition,\n ActionDescriptor,\n ActionDisabledReason\n} from \"../actions/types.js\";\nimport { PROMPT_TEXT_MAX } from \"../actions/types.js\";\nimport type { WidgetTemplate } from \"./types.js\";\nimport {\n FORBIDDEN_ATTR,\n FORBIDDEN_TAGS,\n RESERVED_ATTR,\n URL_ATTRS,\n isSafeImageSrc,\n isSafeUrl\n} from \"./guards.js\";\nimport { parsePath } from \"./paths.js\";\nimport { InvalidTemplateError, validateTemplate } from \"./validate.js\";\nimport { formatValue } from \"../catalog/widgets/format.js\";\nimport { formatBoundValue } from \"../catalog/widgets/value-format.js\";\nimport { isPlainObject } from \"../shared/plain-object.js\";\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\n/**\n * One scope frame: the root frame holds `payload.data`; every `each`\n * pushes the current item with its position. `$parent` walks the stack,\n * `$root` reads the bottom, `$index` reads the top's position.\n */\ninterface Frame {\n scope: unknown;\n index?: number;\n}\n\n/**\n * Resolve a path against the scope chain (see paths.ts for the grammar).\n * Missing, non-traversable or malformed paths resolve to `undefined` \u2014\n * never throws.\n */\nfunction resolvePath(path: string, frames: Frame[], meta: unknown): unknown {\n const parsed = parsePath(path);\n if (parsed === undefined) return undefined;\n let current: unknown;\n if (parsed.base === \"meta\") {\n current = meta;\n } else if (parsed.base === \"root\") {\n current = frames[0]?.scope;\n } else {\n const depth = frames.length - 1 - parsed.up;\n if (depth < 0) return undefined;\n const frame = frames[depth];\n if (frame === undefined) return undefined;\n if (parsed.index) return frame.index;\n current = frame.scope;\n }\n for (const segment of parsed.segments) {\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = current[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/** A key's string form: strings and finite numbers only. */\nfunction keyOf(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return undefined;\n}\n\n/**\n * Interpretation budget. `each` multiplies template nodes by the length of\n * AGENT-supplied data, so template size bounds nothing on its own \u2014 a\n * stored template driven by a large payload could otherwise spend the\n * process. Counting work (nodes emitted, plus one unit per `each`\n * iteration so empty iterations are not free) rather than watching a\n * clock keeps the bound reproducible: the same template and data always\n * truncate at the same place.\n */\nexport const DEFAULT_MAX_NODES = 50_000;\n\ninterface Budget {\n remaining: number;\n truncated: boolean;\n}\n\n/** Render-time knowledge about actions the caller supplies. */\n/** The compile options the action layer reads; the options object itself serves. */\ntype ActionContext = Pick<CompileOptions, \"actions\" | \"httpDisabled\" | \"kind\">;\n\n/**\n * Resolve a binding into the descriptor an element carries. Everything the\n * bridge needs is decided here, in scope, at render time: the prompt's\n * text, the http arguments, and whether the action is available at all.\n */\nfunction buildDescriptor(\n binding: ActionBinding,\n id: string,\n frames: Frame[],\n meta: unknown,\n ctx: ActionContext\n): ActionDescriptor {\n const definition: ActionDefinition | undefined =\n \"ref\" in binding && typeof binding.ref === \"string\"\n ? ctx.actions?.(binding.ref)\n : \"definition\" in binding && isPlainObject(binding.definition)\n ? (binding.definition as ActionDefinition)\n : undefined;\n if (definition === undefined || (definition.kind !== \"prompt\" && definition.kind !== \"http\")) {\n const unresolved: ActionDescriptor = { id, disabled: \"unresolved\" };\n if (ctx.kind !== undefined) unresolved.widget = ctx.kind;\n return unresolved;\n }\n if (definition.kind === \"prompt\") {\n let text = \"\";\n const segments = Array.isArray(definition.text) ? definition.text : [];\n for (const segment of segments) {\n if (typeof segment === \"string\") text += segment;\n else if (isPlainObject(segment) && typeof segment.bind === \"string\") {\n text += formatValue(resolvePath(segment.bind, frames, meta));\n }\n if (text.length >= PROMPT_TEXT_MAX) break;\n }\n // Cap by code point so a surrogate pair is never split.\n const prompt: ActionDescriptor = { id, kind: \"prompt\", text: Array.from(text).slice(0, PROMPT_TEXT_MAX).join(\"\") };\n if (ctx.kind !== undefined) prompt.widget = ctx.kind;\n return prompt;\n }\n const args: Record<string, unknown> = {};\n if (isPlainObject(binding.input)) {\n for (const [field, value] of Object.entries(binding.input)) {\n let resolved: unknown;\n if (typeof value === \"string\") resolved = resolvePath(value, frames, meta);\n else if (isPlainObject(value) && \"const\" in value) resolved = value.const;\n if (resolved !== undefined) args[field] = resolved;\n }\n }\n const descriptor: ActionDescriptor = { id, kind: \"http\", args };\n if (ctx.httpDisabled !== undefined) descriptor.disabled = ctx.httpDisabled;\n if (ctx.kind !== undefined) descriptor.widget = ctx.kind;\n return descriptor;\n}\n\n/**\n * Interpret a template node into zero or more render-tree nodes.\n * Lenient by design: validation is the strict layer, so unknown or\n * malformed forms render as nothing rather than throwing (defense in\n * depth for templates that bypassed validation). `tpath` is the node's\n * dotted position in the TEMPLATE (the validator's path convention) \u2014 the\n * identifier an action binding is known by.\n */\nfunction interpretNode(\n node: unknown,\n frames: Frame[],\n meta: unknown,\n budget: Budget,\n tpath: string,\n ctx: ActionContext\n): WidgetNode[] {\n if (budget.remaining <= 0) {\n budget.truncated = true;\n return [];\n }\n if (typeof node === \"string\") {\n budget.remaining--;\n return [node];\n }\n if (!isPlainObject(node)) return [];\n\n if (typeof node.bind === \"string\") {\n budget.remaining--;\n const resolved = resolvePath(node.bind, frames, meta);\n if (isPlainObject(node.map)) {\n // The value, as a string, SELECTS an authored label: a hit emits that\n // literal, a miss falls to `default` or empty text \u2014 data chooses\n // among the author's words and never contributes characters.\n const key = formatValue(resolved);\n const hit = Object.prototype.hasOwnProperty.call(node.map, key) ? node.map[key] : undefined;\n return [typeof hit === \"string\" ? hit : typeof node.default === \"string\" ? node.default : \"\"];\n }\n // The payload keeps the typed value; only the render gets the unit.\n // (`prefix` is an attribute-value transform and is ignored here.)\n return [formatBoundValue(resolved, node.format)];\n }\n\n if (typeof node.each === \"string\") {\n const value = resolvePath(node.each, frames, meta);\n const items = Array.isArray(value) ? value : [];\n if (items.length === 0) {\n return node.empty === undefined\n ? []\n : interpretNode(node.empty, frames, meta, budget, join(tpath, \"empty\"), ctx);\n }\n const out: WidgetNode[] = [];\n const itemPath = join(tpath, \"template\");\n const keyPath = typeof node.key === \"string\" ? node.key : undefined;\n for (let i = 0; i < items.length; i++) {\n if (budget.remaining <= 0) {\n budget.truncated = true;\n break;\n }\n budget.remaining--; // the iteration itself costs, even when it renders nothing\n frames.push({ scope: items[i], index: i });\n const rendered = interpretNode(node.template, frames, meta, budget, itemPath, ctx);\n const only = rendered.length === 1 ? rendered[0] : undefined;\n if (keyPath !== undefined && only !== undefined && typeof only !== \"string\") {\n const key = keyOf(resolvePath(keyPath, frames, meta));\n if (key !== undefined) rendered[0] = { ...only, key };\n }\n out.push(...rendered);\n frames.pop();\n }\n return out;\n }\n\n if (typeof node.when === \"string\") {\n const truthy = Boolean(resolvePath(node.when, frames, meta));\n const branch = truthy ? node.template : node.else;\n return branch === undefined\n ? []\n : interpretNode(branch, frames, meta, budget, join(tpath, truthy ? \"template\" : \"else\"), ctx);\n }\n\n if (typeof node.tag === \"string\" && node.tag.length > 0) {\n if (FORBIDDEN_TAGS.has(node.tag.toLowerCase())) return []; // active content never reaches a tree\n budget.remaining--;\n const attrs: WidgetNodeAttrs = {};\n if (isPlainObject(node.attrs)) {\n for (const [name, raw] of Object.entries(node.attrs)) {\n // Handlers are code; data-wg-* is the renderer's own vocabulary.\n if (FORBIDDEN_ATTR.test(name) || RESERVED_ATTR.test(name)) continue;\n let value: string | undefined;\n if (typeof raw === \"string\") {\n value = raw;\n } else if (isPlainObject(raw) && typeof raw.bind === \"string\") {\n const resolved = resolvePath(raw.bind, frames, meta);\n if (isPlainObject(raw.map)) {\n // The resolved value SELECTS a key; every emitted character\n // is an author-written literal. A miss falls to `default`,\n // or empty \u2014 an unanticipated status degrades, never breaks.\n const key = formatValue(resolved);\n const hit = Object.prototype.hasOwnProperty.call(raw.map, key)\n ? raw.map[key]\n : undefined;\n value =\n typeof hit === \"string\"\n ? hit\n : typeof raw.default === \"string\"\n ? raw.default\n : \"\";\n } else if (typeof raw.prefix === \"string\") {\n // The prefix is never emitted alone: no dead mailto: hrefs.\n // The composed value still faces the URL guard below.\n const text = formatValue(resolved);\n value = text === \"\" ? \"\" : raw.prefix + text;\n } else if (raw.format !== undefined) {\n // Formats produce TEXT; a URL attribute's scheme guard still\n // runs below, so a format can never build a scheme.\n value = formatBoundValue(resolved, raw.format);\n } else {\n value = formatValue(resolved);\n }\n }\n if (value === undefined) continue;\n const lower = name.toLowerCase();\n if (URL_ATTRS.has(lower)) {\n // Image sources additionally accept data:image/*; every other\n // URL attribute keeps the strict scheme set (data-URI\n // navigation is an XSS vector; data-URI images are not).\n const imageContext = lower === \"src\" && node.tag.toLowerCase() === \"img\";\n const allowed =\n isSafeUrl(value) || (imageContext && isSafeImageSrc(value));\n if (!allowed) continue;\n }\n attrs[name] = value;\n }\n }\n if (isPlainObject(node.action)) {\n attrs[\"data-wg-action\"] = JSON.stringify(\n buildDescriptor(node.action as ActionBinding, tpath, frames, meta, ctx)\n );\n }\n const children = Array.isArray(node.children)\n ? node.children.flatMap((child, i) =>\n interpretNode(child, frames, meta, budget, join(tpath, `children.${i}`), ctx)\n )\n : [];\n const element: WidgetElementNode = { tag: node.tag };\n if (Object.keys(attrs).length > 0) element.attrs = attrs;\n if (children.length > 0) element.children = children;\n return [element];\n }\n\n return [];\n}\n\n/** Count the nodes a template's STRUCTURE contains (not its output). */\nexport function countTemplateNodes(template: unknown): number {\n if (typeof template === \"string\") return 1;\n if (!isPlainObject(template)) return 0;\n if (typeof template.bind === \"string\") return 1;\n let total = 1;\n for (const key of [\"template\", \"empty\", \"else\"] as const) {\n if (template[key] !== undefined) total += countTemplateNodes(template[key]);\n }\n if (Array.isArray(template.children)) {\n for (const child of template.children) total += countTemplateNodes(child);\n }\n return total;\n}\n\nexport interface CompileOptions {\n /** Node budget for one render (default {@link DEFAULT_MAX_NODES}). */\n maxNodes?: number;\n /**\n * Resolve `{ ref }` action bindings to their definitions (the\n * principal's shared actions). Unresolvable refs render disabled.\n */\n actions?: (ref: string) => ActionDefinition | undefined;\n /**\n * Render every http action disabled with this reason \u2014 the server sets\n * `\"scope\"` when the caller's key cannot execute.\n */\n httpDisabled?: ActionDisabledReason;\n /** The kind this template is registered as \u2014 stamped into descriptors. */\n kind?: string;\n}\n\n/**\n * Compile a template into an ordinary widget renderer. The renderer is pure\n * and total; when the root interprets to anything other than exactly one\n * node, the output is wrapped in a `div.wg-template`. Renders are bounded\n * by a node budget \u2014 an exhausted budget stops interpretation and marks\n * the output with `data-truncated`, so the outcome is visible rather than\n * silently short.\n */\nexport function compileTemplate(\n template: WidgetTemplate,\n options: CompileOptions = {}\n): WidgetRenderer {\n const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;\n const ctx: ActionContext = options;\n return (payload: WidgetPayload): WidgetNode => {\n const budget: Budget = { remaining: maxNodes, truncated: false };\n const frames: Frame[] = [{ scope: payload.data }];\n const nodes = interpretNode(template, frames, payload.meta, budget, \"\", ctx);\n if (!budget.truncated && nodes.length === 1) {\n const only = nodes[0];\n if (only !== undefined) return only;\n }\n const attrs: WidgetNodeAttrs = { class: \"wg-template\" };\n if (budget.truncated) attrs[\"data-truncated\"] = \"true\";\n return { tag: \"div\", attrs, children: nodes };\n };\n}\n\n/**\n * Resolve a binding outside the tree \u2014 the widget-level `load` binding,\n * whose descriptor rides `structuredContent.load` rather than an element.\n * Resolved against the payload's root scope.\n */\nexport function resolveActionDescriptor(\n binding: ActionBinding,\n id: string,\n payload: WidgetPayload,\n options: Pick<CompileOptions, \"actions\" | \"httpDisabled\" | \"kind\"> = {}\n): ActionDescriptor {\n const ctx: ActionContext = options;\n return buildDescriptor(binding, id, [{ scope: payload.data }], payload.meta, ctx);\n}\n\n/**\n * Validate, compile, and register a template as a widget kind. Throws\n * {@link InvalidTemplateError} on invalid templates and the catalog's\n * `DuplicateKindError` on duplicate kinds \u2014 registration is host setup.\n */\nexport function registerTemplate(\n catalog: WidgetCatalog,\n kind: string,\n template: unknown,\n descriptor?: WidgetDescriptorInput,\n options?: CompileOptions\n): void {\n const validated = validateTemplate(template);\n if (!validated.ok) {\n throw new InvalidTemplateError(kind, validated.error);\n }\n catalog.register(kind, compileTemplate(validated.template, { ...options, kind }), descriptor);\n}\n", "import type { WidgetNode } from \"../catalog/index.js\";\n\n/**\n * Materialize a render tree as fresh DOM. Text becomes text nodes (no HTML\n * parsing), matching the catalog DOM layer's safety discipline. Private to\n * the reactive module \u2014 the catalog's builder stays private to its own.\n */\nexport function buildDom(node: WidgetNode, doc: Document): Node {\n if (typeof node === \"string\") return doc.createTextNode(node);\n const element = doc.createElement(node.tag);\n if (node.attrs) {\n for (const [name, value] of Object.entries(node.attrs)) {\n element.setAttribute(name, value);\n }\n }\n if (node.children) {\n for (const child of node.children) {\n element.appendChild(buildDom(child, doc));\n }\n }\n return element;\n}\n", "import type { WidgetElementNode, WidgetNode } from \"../catalog/index.js\";\nimport { buildDom } from \"./build.js\";\n\n/**\n * Patch `dom` in place so it reflects `next`, given that it currently\n * reflects `prev`. Returns the node now representing `next` \u2014 the same node\n * when patched in place, a freshly built replacement when the shape (tag or\n * node type) changed. Identity is preserved wherever shape matches. Sibling\n * lists pair by `key` when every child of both lists is a uniquely keyed\n * element \u2014 existing nodes MOVE with their record \u2014 and by position\n * otherwise. The app template's inline patcher implements the same rule.\n */\nexport function patchNode(prev: WidgetNode, next: WidgetNode, dom: Node): Node {\n if (typeof prev === \"string\" && typeof next === \"string\") {\n if (prev !== next) dom.nodeValue = next;\n return dom;\n }\n if (\n typeof prev !== \"string\" &&\n typeof next !== \"string\" &&\n prev.tag === next.tag &&\n dom.nodeType === 1\n ) {\n patchElement(prev, next, dom as Element);\n return dom;\n }\n // Shape changed: replace only this subtree.\n const doc = dom.ownerDocument;\n if (!doc || !dom.parentNode) return dom;\n const replacement = buildDom(next, doc);\n dom.parentNode.replaceChild(replacement, dom);\n return replacement;\n}\n\nfunction patchElement(\n prev: WidgetElementNode,\n next: WidgetElementNode,\n element: Element\n): void {\n const prevAttrs = prev.attrs ?? {};\n const nextAttrs = next.attrs ?? {};\n for (const [name, value] of Object.entries(nextAttrs)) {\n if (prevAttrs[name] !== value) element.setAttribute(name, value);\n }\n for (const name of Object.keys(prevAttrs)) {\n if (!(name in nextAttrs)) element.removeAttribute(name);\n }\n patchChildren(prev.children ?? [], next.children ?? [], element);\n}\n\n/**\n * Key \u2192 index for a list in which every child is an element with a unique\n * key; `undefined` for any other list (text child, unkeyed element,\n * duplicate key), which then pairs by position.\n */\nfunction keyIndex(list: readonly WidgetNode[]): Map<string, number> | undefined {\n const index = new Map<string, number>();\n for (let i = 0; i < list.length; i++) {\n const node = list[i];\n if (node === undefined || typeof node === \"string\" || typeof node.key !== \"string\") {\n return undefined;\n }\n if (index.has(node.key)) return undefined;\n index.set(node.key, i);\n }\n return index;\n}\n\nfunction patchKeyed(\n prev: readonly WidgetNode[],\n next: readonly WidgetElementNode[],\n prevIndex: Map<string, number>,\n domChildren: readonly Node[],\n element: Element\n): void {\n const doc = element.ownerDocument;\n const kept = new Set<number>();\n const placed = next.map((child) => {\n const i = child.key === undefined ? undefined : prevIndex.get(child.key);\n const prevChild = i === undefined ? undefined : prev[i];\n const dom = i === undefined ? undefined : domChildren[i];\n if (i === undefined || prevChild === undefined || dom === undefined) {\n return buildDom(child, doc);\n }\n kept.add(i);\n return patchNode(prevChild, child, dom);\n });\n domChildren.forEach((dom, i) => {\n if (!kept.has(i) && dom.parentNode === element) element.removeChild(dom);\n });\n // Moving a node keeps its state (a visitor's `open`); only misplaced\n // nodes are touched.\n placed.forEach((dom, i) => {\n const at = element.childNodes[i] ?? null;\n if (dom !== at) element.insertBefore(dom, at);\n });\n}\n\nfunction patchChildren(\n prev: readonly WidgetNode[],\n next: readonly WidgetNode[],\n element: Element\n): void {\n const doc = element.ownerDocument;\n // Snapshot: childNodes is live and patchNode may replace entries.\n const domChildren: Node[] = [];\n for (let i = 0; i < element.childNodes.length; i++) {\n const child = element.childNodes[i];\n if (child) domChildren.push(child);\n }\n\n const prevIndex = keyIndex(prev);\n if (prevIndex !== undefined && keyIndex(next) !== undefined) {\n const elements = next.filter((child): child is WidgetElementNode => typeof child !== \"string\");\n patchKeyed(prev, elements, prevIndex, domChildren, element);\n return;\n }\n\n const shared = Math.min(prev.length, next.length);\n for (let i = 0; i < shared; i++) {\n const prevChild = prev[i];\n const nextChild = next[i];\n const childDom = domChildren[i];\n if (prevChild === undefined || nextChild === undefined) continue;\n if (childDom) {\n patchNode(prevChild, nextChild, childDom);\n } else {\n element.appendChild(buildDom(nextChild, doc));\n }\n }\n for (let i = shared; i < next.length; i++) {\n const extra = next[i];\n if (extra !== undefined) element.appendChild(buildDom(extra, doc));\n }\n for (let i = prev.length - 1; i >= shared; i--) {\n const surplus = domChildren[i];\n if (surplus) element.removeChild(surplus);\n }\n}\n", "import type { WidgetCatalog, WidgetNode } from \"../catalog/index.js\";\nimport { createCatalog } from \"../catalog/index.js\";\nimport type { WidgetContractError } from \"../contract/index.js\";\nimport type { ActionDescriptor } from \"../actions/index.js\";\nimport { buildDom } from \"./build.js\";\nimport { patchNode } from \"./diff.js\";\n\n/** Outcome of a mount or update. Failures leave the DOM untouched. */\nexport type UpdateResult =\n | { ok: true }\n | { ok: false; error: WidgetContractError };\n\n/** An activated element's descriptor, handed to the host untouched. */\nexport type ActionActivation = ActionDescriptor;\n\nexport interface MountOptions {\n /**\n * Catalog used for validation and rendering. Defaults to a fresh\n * `createCatalog()` per mount; pass a shared instance to render custom\n * registered kinds.\n */\n catalog?: WidgetCatalog;\n /**\n * Receives activations of mounted `[data-wg-action]` elements (click, or\n * Enter/Space on non-button hosts) with the parsed descriptor and the\n * currently mounted payload; the default action is prevented. Without\n * it, action elements are inert \u2014 the mount never executes anything.\n */\n onAction?: (activation: ActionActivation, payload: unknown) => void;\n}\n\nexport interface WidgetMount {\n /** Outcome of the initial render performed by `mountWidget`. */\n readonly initial: UpdateResult;\n /**\n * Re-render with a new payload, patching the DOM in place. Returns a\n * structured error (DOM untouched) for invalid payloads. Throws if the\n * mount was disposed \u2014 that is a host programming error.\n */\n update(payload: unknown): UpdateResult;\n /** Currently rendered tree (`undefined` before the first successful render). */\n node(): WidgetNode | undefined;\n /** Empty the container and end this mount. Idempotent. */\n dispose(): void;\n}\n\n/**\n * Mount a widget payload into `container` and keep updating it in place.\n * The first render is just an internal `update`; its outcome is exposed as\n * `initial`, so a failed first payload does not cost the caller the handle.\n */\nexport function mountWidget(\n payload: unknown,\n container: Element,\n options: MountOptions = {}\n): WidgetMount {\n const catalog = options.catalog ?? createCatalog();\n let current: WidgetNode | undefined;\n let root: Node | undefined;\n let disposed = false;\n let mountedPayload: unknown;\n\n // Delegated on the container: descriptors are data the host decides\n // about \u2014 this layer only parses and forwards them.\n const onAction = options.onAction;\n function parseDescriptor(el: Element): ActionDescriptor | undefined {\n try {\n const parsed = JSON.parse(el.getAttribute(\"data-wg-action\") ?? \"\") as unknown;\n if (typeof parsed === \"object\" && parsed !== null && typeof (parsed as { id?: unknown }).id === \"string\") {\n return parsed as ActionDescriptor;\n }\n } catch {\n /* malformed descriptor: inert */\n }\n return undefined;\n }\n function activation(event: Event): void {\n const target = event.target as Element | null;\n const el = target?.closest?.(\"[data-wg-action]\");\n if (!el || !container.contains(el)) return;\n if (event.type === \"keydown\") {\n const key = (event as KeyboardEvent).key;\n if (key !== \"Enter\" && key !== \" \") return;\n if (el.tagName === \"BUTTON\" || el.tagName === \"A\") return; // native keyboard \u2192 click\n }\n event.preventDefault();\n if (onAction === undefined) return;\n const descriptor = parseDescriptor(el);\n if (descriptor !== undefined) onAction(descriptor, mountedPayload);\n }\n container.addEventListener(\"click\", activation);\n container.addEventListener(\"keydown\", activation);\n\n function update(nextPayload: unknown): UpdateResult {\n if (disposed) {\n throw new Error(\n \"Widget mount is disposed; create a new mount instead of updating.\"\n );\n }\n const rendered = catalog.render(nextPayload);\n if (!rendered.ok) return rendered;\n\n if (current === undefined || root === undefined) {\n const built = buildDom(rendered.node, container.ownerDocument);\n container.replaceChildren(built);\n root = built;\n } else {\n root = patchNode(current, rendered.node, root);\n }\n current = rendered.node;\n mountedPayload = nextPayload;\n return { ok: true };\n }\n\n function dispose(): void {\n if (disposed) return;\n disposed = true;\n container.removeEventListener(\"click\", activation);\n container.removeEventListener(\"keydown\", activation);\n container.replaceChildren();\n current = undefined;\n root = undefined;\n mountedPayload = undefined;\n }\n\n return {\n initial: update(payload),\n update,\n node: () => current,\n dispose\n };\n}\n", "/**\n * The chrome tokens and the palettes painted through them.\n *\n * `CHROME_DEFAULTS` is not a description of the defaults \u2014 it IS them: the\n * injected stylesheet's token blocks are generated from this object, so a host\n * that paints its own surfaces from the export cannot drift from the\n * designers. There is deliberately no second palette to fall back to: a host\n * that wants a different look passes its own values through `chrome`, and\n * `chromeCss` renders whatever palette it hands back.\n *\n * Colours and shape carry the product's identity. Typography does not: a\n * library must never default to a webfont it cannot serve, so `font`,\n * `font-mono` and the three sizes stay system values in both palettes and a\n * host with its own typeface passes it through `chrome`.\n */\n\n/**\n * The chrome tokens \u2014 every `--wgd-<token>` the stylesheet paints with.\n * Colours (18) differ between the schemes; typography, shape and shadow are\n * declared per scheme too so each palette stands alone. Public API: a rename\n * is a spec change.\n */\nexport const CHROME_TOKENS = [\n \"bg\", \"panel\", \"border\", \"line\", \"text\", \"muted\",\n \"accent\", \"accent-bg\", \"accent-line\",\n \"danger\", \"danger-bg\", \"danger-line\", \"hover\",\n \"hl-key\", \"hl-str\", \"hl-num\", \"hl-bool\", \"hl-punct\",\n \"font\", \"font-mono\", \"font-size\", \"font-size-sm\", \"font-size-xs\",\n \"radius-sm\", \"radius\", \"radius-lg\", \"gap\", \"shadow\"\n] as const;\n\nexport type ChromeToken = (typeof CHROME_TOKENS)[number];\n\n/** A host's partial chrome: token \u2192 CSS value (`var()` references welcome). */\nexport type ChromeOptions = Partial<Record<ChromeToken, string>>;\n\n/** Every token valued \u2014 what a palette is. */\nexport type ChromeScheme = Record<ChromeToken, string>;\n\n/** A complete palette: both schemes, every token. */\nexport interface ChromePalette {\n light: ChromeScheme;\n dark: ChromeScheme;\n}\n\n/** Shared by both palettes: see the module header on why typography is not branded. */\nconst TYPOGRAPHY = {\n font: \"system-ui, sans-serif\",\n \"font-mono\": \"ui-monospace, monospace\",\n \"font-size\": \"13px\",\n \"font-size-sm\": \"12px\",\n \"font-size-xs\": \"11px\"\n} as const;\n\n/**\n * The widgentic palette \u2014 what the designers render with when a host passes\n * no `chrome`, and what a host paints its own page with to match them.\n *\n * Every colour sits on the logo mark's own hue (197.6deg, from `#40a0c8`).\n * Surfaces, text and accents come from the product's existing palette;\n * `border`, `accent-line` and `danger-line` are DERIVED, not chosen: each is\n * the lightest value on that hue which still clears 3:1 against the surface\n * it sits on, because those edges are what identifies a control, a focused tag\n * and a banner. Minimum weight that complies, so nothing is heavier than\n * accessibility requires. See chrome-contrast.test.ts for the gate.\n */\nexport const CHROME_DEFAULTS: ChromePalette = {\n light: {\n bg: \"#f6fafc\", panel: \"#ffffff\", border: \"#6e95a6\",\n line: \"#e4ecf2\", text: \"#0b1b26\", muted: \"#56707f\",\n accent: \"#1e6f92\", \"accent-bg\": \"#e3f1f7\", \"accent-line\": \"#4b91ae\",\n danger: \"#b42318\", \"danger-bg\": \"#fdf2f2\", \"danger-line\": \"#c97572\",\n hover: \"#eef5f9\",\n \"hl-key\": \"#1e6f92\", \"hl-str\": \"#2e7d5b\", \"hl-num\": \"#96620f\",\n \"hl-bool\": \"#7a4fbf\", \"hl-punct\": \"#56707f\",\n ...TYPOGRAPHY,\n \"radius-sm\": \"4px\", radius: \"6px\", \"radius-lg\": \"8px\", gap: \"16px\",\n shadow: \"0 8px 24px -12px rgba(11, 27, 38, 0.35)\"\n },\n dark: {\n bg: \"#0b141b\", panel: \"#10202a\", border: \"#437082\",\n line: \"#1b2f3d\", text: \"#e6f0f5\", muted: \"#93a9b6\",\n accent: \"#8acbe6\", \"accent-bg\": \"#14303d\", \"accent-line\": \"#3e7e98\",\n danger: \"#f0a3a3\", \"danger-bg\": \"#2a1a1c\", \"danger-line\": \"#a3524f\",\n hover: \"#152a36\",\n \"hl-key\": \"#8acbe6\", \"hl-str\": \"#6cc79a\", \"hl-num\": \"#e0b25a\",\n \"hl-bool\": \"#bb9af7\", \"hl-punct\": \"#93a9b6\",\n ...TYPOGRAPHY,\n \"radius-sm\": \"4px\", radius: \"6px\", \"radius-lg\": \"8px\", gap: \"16px\",\n shadow: \"0 8px 24px -12px rgba(0, 0, 0, 0.7)\"\n }\n};\n\nexport interface ChromeCssOptions {\n /** Custom-property prefix, dashes included. Default `--wgd`. */\n prefix?: string;\n /** Selector the light block is written under. Default `:root`. */\n selector?: string;\n /** Selector for the dark block inside `prefers-color-scheme: dark`; defaults to `selector`. */\n darkMediaSelector?: string;\n /** Optional selector for an unconditional dark block \u2014 an explicit host toggle. */\n darkSelector?: string;\n}\n\nfunction declarations(scheme: ChromeScheme, prefix: string, indent: string): string {\n return CHROME_TOKENS.map((token) => `${indent}${prefix}-${token}: ${scheme[token]};`).join(\"\\n\");\n}\n\n/**\n * Render a palette as CSS declaration blocks \u2014 the light values under\n * `selector`, the dark values under `prefers-color-scheme: dark`, and\n * optionally under an explicit selector a host toggles. Every token is\n * declared in every block, so nothing falls back to a browser value.\n *\n * A string builder, deliberately: no injection, no runtime, no dependency.\n * The designers' own stylesheet is built with it, and so is a host page that\n * wants its surfaces to match them.\n */\nexport function chromeCss(palette: ChromePalette, options: ChromeCssOptions = {}): string {\n const prefix = options.prefix ?? \"--wgd\";\n const selector = options.selector ?? \":root\";\n const darkMediaSelector = options.darkMediaSelector ?? selector;\n const blocks = [\n `${selector} {\\n${declarations(palette.light, prefix, \" \")}\\n}`,\n `@media (prefers-color-scheme: dark) {\\n ${darkMediaSelector} {\\n${declarations(palette.dark, prefix, \" \")}\\n }\\n}`\n ];\n if (options.darkSelector !== undefined) {\n blocks.push(`${options.darkSelector} {\\n${declarations(palette.dark, prefix, \" \")}\\n}`);\n }\n return blocks.join(\"\\n\");\n}\n\n/**\n * The full `chrome` map of `var()` references to a host page's own\n * properties under `prefix` \u2014 the other half of `chromeCss`: paint the page\n * with the derived palette, hand the designers these references, and the\n * two match by construction. Because inline `var()` resolves at the host,\n * the page's scheme handling (an explicit toggle included) reaches MOUNTED\n * designers through the cascade \u2014 no remount, no event, no API.\n *\n * A reference to a property the page never defines is invalid at\n * computed-value time; it does NOT fall back to the built-in defaults, so\n * always pair this map with `chromeCss` under the same prefix. Override\n * individual entries by spreading: `{ ...chromeReferences(), font: \"...\" }`.\n */\nexport function chromeReferences(prefix = \"--host\"): Record<ChromeToken, string> {\n return Object.fromEntries(\n CHROME_TOKENS.map((token) => [token, `var(${prefix}-${token})`])\n ) as Record<ChromeToken, string>;\n}\n\n", "/**\n * Tiny DOM helpers for the designer chrome \u2014 the same hand-rolled\n * discipline as the rest of the project, sized for form-heavy panels.\n * Designer chrome classes are prefixed `wgd-` (widget content inside the\n * preview keeps the normal `wg-` classes).\n */\nimport { CHROME_DEFAULTS, CHROME_TOKENS, chromeCss } from \"./chrome-defaults.js\";\nimport type { ChromeOptions } from \"./chrome-defaults.js\";\n\nexport type Child = Node | string;\n\n/** The first `<selector>` under `parent`, which the caller's own markup guarantees exists. */\nexport function requireChild<K extends keyof HTMLElementTagNameMap>(\n parent: ParentNode,\n selector: K\n): HTMLElementTagNameMap[K] {\n const found = parent.querySelector(selector);\n if (found === null) throw new Error(`Designer chrome is missing a <${selector}> element.`);\n return found;\n}\n\nexport function h<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attrs?: Record<string, string>,\n children?: Child[]\n): HTMLElementTagNameMap[K];\nexport function h(tag: string, attrs?: Record<string, string>, children?: Child[]): HTMLElement;\nexport function h(tag: string, attrs?: Record<string, string>, children?: Child[]): HTMLElement {\n const element = document.createElement(tag);\n if (attrs) {\n for (const [name, value] of Object.entries(attrs)) {\n element.setAttribute(name, value);\n }\n }\n if (children) {\n for (const child of children) {\n element.append(child);\n }\n }\n return element;\n}\n\n/** Labeled single-line input bound through a callback. */\nexport function textField(\n label: string,\n value: string,\n onInput: (value: string) => void\n): HTMLElement {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n input.value = value;\n input.addEventListener(\"input\", () => onInput(input.value));\n return h(\"label\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [label]),\n input\n ]);\n}\n\n/** Labeled multi-line textarea bound through a callback. */\nexport function textArea(\n label: string,\n value: string,\n onInput: (value: string) => void,\n rows = 6\n): HTMLElement {\n const area = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: String(rows),\n spellcheck: \"false\"\n });\n area.value = value;\n area.addEventListener(\"input\", () => onInput(area.value));\n // An empty label means the surrounding chrome already names the field \u2014\n // no legend row.\n return h(\"label\", { class: \"wgd-field\" }, [\n ...(label === \"\" ? [] : [h(\"span\", { class: \"wgd-field-label\" }, [label])]),\n area\n ]);\n}\n\n/** Collapsible titled section (open by default). */\nexport function section(title: string, children: Child[], open = true): HTMLElement {\n const attrs: Record<string, string> = { class: \"wgd-section\" };\n if (open) attrs.open = \"\";\n return h(\"details\", attrs, [\n h(\"summary\", { class: \"wgd-section-title\" }, [title]),\n h(\"div\", { class: \"wgd-section-body\" }, children)\n ]);\n}\n\n/**\n * Size a select to its SELECTED label (a bare <select> sizes to its\n * widest option, or to whatever flex hands it), so the caret sits beside\n * the text instead of drifting with leftover row width. ch tracks\n * monospace text exactly; the em term scales with padding, and the px\n * term covers the UA's caret region, which does NOT scale with font size\n * (11px selects clip under a pure em term). Re-fits on change.\n */\n/** A fitted select over `options`: value set, width fitted, `onChange` on change. */\nexport function select(\n options: { value: string; label?: string }[],\n value: string,\n className: string,\n onChange: (value: string) => void,\n title?: string\n): HTMLSelectElement {\n const el = h(\"select\", { class: className, ...(title === undefined ? {} : { title }) });\n for (const option of options) el.append(h(\"option\", { value: option.value }, [option.label ?? option.value]));\n el.value = value;\n fitSelect(el);\n el.addEventListener(\"change\", () => onChange(el.value));\n return el;\n}\n\nexport function fitSelect(select: HTMLSelectElement): void {\n const fit = (): void => {\n const label = select.options[select.selectedIndex]?.text ?? select.value;\n select.style.width = `calc(${Math.max(label.length, 1)}ch + 1.2em + 18px)`;\n };\n fit();\n select.addEventListener(\"change\", fit);\n}\n\n/**\n * Compact add-menu: one toggle button revealing the options on demand \u2014\n * the tree stays calm instead of carrying a button per option at every\n * level. Closes on pick, outside pointer-down, or Escape.\n */\nexport function menuButton(\n label: string,\n title: string,\n options: string[],\n onPick: (option: string) => void\n): HTMLElement {\n const wrap = h(\"span\", { class: \"wgd-menuwrap\" });\n const toggle = h(\n \"button\",\n { class: \"wgd-icon wgd-menu-toggle\", type: \"button\", title },\n [label]\n );\n const menu = h(\"div\", { class: \"wgd-menu\" });\n menu.hidden = true;\n\n const close = (): void => {\n menu.hidden = true;\n document.removeEventListener(\"pointerdown\", onOutside, true);\n document.removeEventListener(\"keydown\", onKey, true);\n };\n const onOutside = (event: Event): void => {\n if (!wrap.contains(event.target as Node)) close();\n };\n const onKey = (event: KeyboardEvent): void => {\n if (event.key === \"Escape\") close();\n };\n\n toggle.addEventListener(\"click\", () => {\n if (!menu.hidden) {\n close();\n return;\n }\n menu.hidden = false;\n document.addEventListener(\"pointerdown\", onOutside, true);\n document.addEventListener(\"keydown\", onKey, true);\n });\n for (const option of options) {\n const item = h(\n \"button\",\n { class: \"wgd-menu-item\", type: \"button\" },\n [option]\n );\n item.addEventListener(\"click\", () => {\n close();\n onPick(option);\n });\n menu.append(item);\n }\n wrap.append(toggle, menu);\n return wrap;\n}\n\n/** Inline diagnostic line (empty text removes it from the flow). */\nexport function diagnosticLine(text: string | undefined): HTMLElement {\n const el = h(\"div\", { class: \"wgd-diagnostic\" }, text === undefined ? [] : [text]);\n if (text === undefined) el.setAttribute(\"hidden\", \"\");\n return el;\n}\n\n// The token list and the palettes live in chrome-defaults.ts, which the\n// stylesheet below is generated from; re-exported here so the modules that\n// already import chrome types from this one keep working.\nexport { CHROME_TOKENS } from \"./chrome-defaults.js\";\nexport type { ChromeOptions, ChromeToken } from \"./chrome-defaults.js\";\n\nconst CHROME_TOKEN_SET: ReadonlySet<string> = new Set<string>(CHROME_TOKENS);\n\n// On a custom property a CSS-wide keyword acts on the property itself (it\n// inherits/resets the TOKEN, not the consumer), so it never expresses what\n// a host means by it; hosts pass `var(--their-token, fallback)` instead.\nconst CSS_WIDE_KEYWORD = /^(inherit|initial|unset|revert|revert-layer)$/i;\n\n/**\n * Apply a host's chrome on a designer root as inline custom properties \u2014\n * the style attribute outranks every rule in the injected stylesheet, so\n * the host's values win over the light/dark defaults. Unknown tokens,\n * non-string values and CSS-wide keywords are ignored at the door.\n */\nexport function applyChrome(root: HTMLElement, chrome: ChromeOptions | undefined): void {\n if (chrome === undefined) return;\n for (const [token, value] of Object.entries(chrome)) {\n if (!CHROME_TOKEN_SET.has(token)) continue;\n if (typeof value !== \"string\" || CSS_WIDE_KEYWORD.test(value.trim())) continue;\n root.style.setProperty(`--wgd-${token}`, value);\n }\n}\n\n/** The element form of the option: a `chrome` attribute holding JSON; anything else \u2192 nothing. */\nexport function parseChromeAttribute(value: string | null): ChromeOptions | undefined {\n if (value === null) return undefined;\n try {\n const parsed: unknown = JSON.parse(value);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return parsed as ChromeOptions;\n } catch {\n return undefined;\n }\n}\n\nconst STYLE_MARKER = \"data-widgentic-designer\";\n\n/** Designer chrome stylesheet \u2014 injected once per document. */\nexport function injectDesignerStyles(doc: Document): void {\n if (doc.head.querySelector(`style[${STYLE_MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(STYLE_MARKER, \"chrome\");\n style.textContent = `\n/* Chrome tokens (CHROME_TOKENS), generated from CHROME_DEFAULTS so the\n exported palette IS the applied one. A host overrides any of them through\n options.chrome (inline on the root, which outranks these rules). Widget\n content inside the preview keeps its own --wg-* theme tokens. */\n${chromeCss(CHROME_DEFAULTS, {\n selector: \".wgd-root\",\n darkMediaSelector: '.wgd-root:not([data-wgd-theme=\"light\"])',\n darkSelector: '.wgd-root[data-wgd-theme=\"dark\"]'\n})}\n.wgd-root { display: flex; gap: var(--wgd-gap); font-family: var(--wgd-font); font-size: var(--wgd-font-size); align-items: flex-start; color: var(--wgd-text); background: var(--wgd-bg); }\n/* Any chrome class that sets display would silently defeat the hidden\n attribute (learned live twice: the add menu, then the styles tree as a\n tab pane). hidden always wins \u2014 scoped to the designer's own tree. */\n.wgd-root [hidden] { display: none !important; }\n/* Read-only: editing surfaces are inert (visible, inoperable) and read\n de-emphasized; the preview and its selectors stay full-strength. The\n controls flatten into plain values \u2014 a form that cannot be typed in\n should not look like a form (opacity alone was invisible on dark). */\n.wgd-readonly .wgd-section-body[inert] { opacity: 0.75; }\n/* Empty preview state \u2014 shown only when there has never been a valid\n render to freeze on; a blank pane is the one state the contract bans. */\n.wgd-preview-empty { color: var(--wgd-muted); font-style: italic; font-size: var(--wgd-font-size-sm); }\n.wgd-readonly [inert] .wgd-input,\n.wgd-readonly [inert] .wgd-select,\n.wgd-readonly [inert] .wgd-textarea,\n.wgd-readonly [inert] textarea.wgd-hl-input {\n border-color: transparent; background: transparent; box-shadow: none;\n}\n.wgd-readonly [inert] .wgd-hl { background: transparent; }\n/* Controls that only exist to mutate carry no meaning here. */\n.wgd-readonly [inert] .wgd-button,\n.wgd-readonly [inert] .wgd-icon,\n.wgd-readonly [inert] .wgd-add,\n.wgd-readonly [inert] input[type=\"checkbox\"] { opacity: 0.4; }\n.wgd-panels { flex: 1 1 460px; min-width: 340px; display: flex; flex-direction: column; gap: 8px; }\n.wgd-side { flex: 1 1 420px; min-width: 320px; display: flex; flex-direction: column; gap: 8px; position: sticky; top: 8px; }\n.wgd-preview-pane { display: flex; flex-direction: column; gap: 8px; }\n.wgd-section { border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-lg); padding: 6px 10px; background: var(--wgd-panel); }\n.wgd-section-title { cursor: pointer; font-weight: 600; }\n.wgd-section-body { display: flex; flex-direction: column; gap: 8px; padding-top: 8px; }\n.wgd-field { display: flex; flex-direction: column; gap: 2px; }\n.wgd-field-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-sm); }\n.wgd-input, .wgd-textarea, .wgd-select { font: inherit; padding: 4px 6px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: var(--wgd-bg); color: var(--wgd-text); }\n/* Textareas fill their panel regardless of the intrinsic cols width. */\n.wgd-textarea { font-family: var(--wgd-font-mono); white-space: pre; width: 100%; box-sizing: border-box; min-width: 0; resize: vertical; }\n.wgd-preview .wg-designer-action { position: relative; outline: 1px dashed var(--wgd-muted); outline-offset: 2px; }\n.wgd-preview .wg-designer-action::after { content: \"\u26A1 action\"; position: absolute; top: -0.9em; right: 0; font: calc(var(--wgd-font-size-xs) - 1px) var(--wgd-font); color: var(--wgd-muted); background: var(--wgd-panel); padding: 0 4px; border-radius: var(--wgd-radius-sm); pointer-events: none; }\n.wgd-binding { display: flex; flex-direction: column; gap: 6px; padding: 6px 8px; border: 1px dashed var(--wgd-border); border-radius: var(--wgd-radius); margin: 4px 0; }\n.wgd-binding-field { min-width: 8ch; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-sm); }\n.wgd-action-definition { display: flex; flex-direction: column; gap: 6px; }\n.wgd-action-schema { display: flex; flex-direction: column; gap: 4px; padding: 4px 0; }\n.wgd-test-output { font: var(--wgd-font-size-sm) var(--wgd-font-mono); white-space: pre-wrap; word-break: break-all; max-height: 240px; overflow: auto; margin: 6px 0 0; }\n.wgd-diagnostic { color: var(--wgd-danger); font-size: var(--wgd-font-size-sm); white-space: pre-wrap; }\n.wgd-banner { border: 1px solid var(--wgd-danger-line); background: var(--wgd-danger-bg); color: var(--wgd-danger); border-radius: var(--wgd-radius-lg); padding: 8px 10px; margin-bottom: 8px; }\n/* The preview is the WIDGET's surface, not chrome: it establishes the\n --wg-* context (like composePage does for page output) so widget content\n \u2014 including custom kinds the base stylesheet doesn't color \u2014 never\n inherits the designer's own text/background. */\n.wgd-preview { border: 1px dashed var(--wgd-border); border-radius: var(--wgd-radius-lg); padding: 16px; background: var(--wg-bg); color: var(--wg-fg); }\n.wgd-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }\n.wgd-button { font: inherit; padding: 4px 10px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: var(--wgd-bg); color: var(--wgd-text); cursor: pointer; }\n.wgd-button:hover { background: var(--wgd-hover); }\n.wgd-tab-active { background: var(--wgd-accent-bg); border-color: var(--wgd-accent); }\n/* Shared tree/editor chrome (JSON tree, schema builder/form, template tree) */\n.wgd-jt-children, .wgd-children { margin-left: 10px; padding-left: 10px; border-left: 2px solid var(--wgd-line); display: flex; flex-direction: column; gap: 4px; }\n.wgd-jt-row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }\n.wgd-jt-entry { padding: 2px 0; }\n.wgd-jt-key { font-family: var(--wgd-font-mono); color: var(--wgd-muted); min-width: 2ch; }\n.wgd-jt-keyinput, .wgd-jt-type { max-width: 12ch; }\n.wgd-jt-summary { cursor: pointer; color: var(--wgd-muted); font-size: var(--wgd-font-size-sm); }\n.wgd-sf-object { border: 1px solid var(--wgd-line); border-radius: var(--wgd-radius-lg); padding: 6px 10px; margin: 4px 0; }\n/* Schema builder: property name + type + required on one row. */\n.wgd-sb-node { margin-left: 8px; padding: 1px 0 1px 8px; border-left: 2px solid var(--wgd-line); }\n.wgd-sb-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 1px 0; }\n.wgd-sb-constraints { padding-left: 12px; }\n.wgd-sb-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n.wgd-sb-prop { flex: 1 1 auto; min-width: 6ch; font-family: var(--wgd-font-mono); }\n.wgd-sb-type { flex: 0 0 auto; max-width: 11ch; font-size: var(--wgd-font-size-sm); }\n.wgd-sb-req { display: flex; gap: 2px; align-items: center; color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n.wgd-sb-constraint { flex: 1 1 auto; min-width: 6ch; font-size: var(--wgd-font-size-sm); }\n.wgd-sb-root { padding: 2px 0 2px 8px; border-left: 2px solid transparent; }\n/* Schema builder: the template tree's flat discipline \u2014 chrome on\n hover/focus only, removal revealed by the row, fitted type selects. */\n.wgd-schemabuilder .wgd-input, .wgd-schemabuilder .wgd-select { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-schemabuilder .wgd-input:hover, .wgd-schemabuilder .wgd-select:hover,\n.wgd-schemabuilder .wgd-input:focus, .wgd-schemabuilder .wgd-select:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-schemabuilder .wgd-sb-type { flex: 0 0 auto; box-sizing: border-box; max-width: none; color: var(--wgd-accent); }\n.wgd-schemabuilder .wgd-sb-prop { font-size: var(--wgd-font-size-sm); color: var(--wgd-hl-key); }\n.wgd-sb-row { border-radius: var(--wgd-radius-sm); }\n.wgd-sb-row:hover { background: var(--wgd-hover); }\n.wgd-sb-row > .wgd-icon { visibility: hidden; }\n.wgd-sb-row:hover > .wgd-icon, .wgd-sb-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-schemabuilder .wgd-button { font-size: var(--wgd-font-size-xs); padding: 0 6px; border-color: transparent; color: var(--wgd-accent); background: none; }\n.wgd-schemabuilder .wgd-button:hover { border-color: var(--wgd-border); background: var(--wgd-hover); }\n.wgd-remove { color: var(--wgd-danger); }\n/* Breathing room between a tab strip and its active pane. */\n.wgd-tabs > .wgd-row { margin-bottom: 6px; }\n/* Template tree: one node = one slim row; sub-structure indents below.\n Controls stay flat (chrome appears on hover/focus) so a deep template\n reads like the JSON it projects, not like a form. */\n.wgd-node { padding: 0 0 0 4px; }\n.wgd-node-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 1px 0; border-radius: var(--wgd-radius-sm); }\n.wgd-node-row:hover { background: var(--wgd-hover); }\n.wgd-node-badge { font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-xs); color: var(--wgd-accent); background: var(--wgd-accent-bg); border-radius: var(--wgd-radius-sm); padding: 0 5px; flex: 0 0 auto; }\n.wgd-node-icons { display: flex; gap: 2px; margin-left: auto; flex: 0 0 auto; visibility: hidden; }\n/* One reveal rule for every row type that hosts the icon group: a row that\n is not listed here would carry present-but-invisible controls. */\n:is(.wgd-node-row, .wgd-st-row, .wgd-attr-row):is(:hover, :focus-within) > .wgd-node-icons { visibility: visible; }\n.wgd-node-value { flex: 1 1 auto; min-width: 4ch; }\n.wgd-icon { font: inherit; font-size: var(--wgd-font-size-xs); line-height: 1.4; padding: 0 5px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-sm); background: var(--wgd-bg); cursor: pointer; color: var(--wgd-muted); }\n.wgd-icon:hover { background: var(--wgd-hover); }\n/* Compact controls: inside tree nodes, and wherever a section opts in with\n .wgd-compact (the Load action editor mirrors an element's binding editor). */\n.wgd-node .wgd-input, .wgd-node .wgd-select,\n.wgd-compact .wgd-input, .wgd-compact .wgd-select { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-node .wgd-input:hover, .wgd-node .wgd-select:hover, .wgd-compact .wgd-input:hover, .wgd-compact .wgd-select:hover,\n.wgd-node .wgd-input:focus, .wgd-node .wgd-select:focus, .wgd-compact .wgd-input:focus, .wgd-compact .wgd-select:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-compact .wgd-binding { border: none; padding: 0; }\n/* Busy controls (the host-supplied Test call): disabled, with a spinner. */\n.wgd-button.wgd-busy { opacity: 0.7; cursor: progress; }\n.wgd-button.wgd-busy::after { content: \"\"; display: inline-block; width: 10px; height: 10px; margin-left: 6px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; vertical-align: -1px; animation: wgd-spin 0.8s linear infinite; }\n@keyframes wgd-spin { to { transform: rotate(360deg); } }\n.wgd-tagwrap, .wgd-pathwrap { display: contents; }\n/* Collapse chevron: every tree row reserves the column so values align. */\n.wgd-chevron { flex: 0 0 auto; width: 16px; padding: 0; border: none; background: none; color: var(--wgd-muted); font-size: calc(var(--wgd-font-size-xs) - 1px); cursor: pointer; }\n.wgd-chevron-none { visibility: hidden; }\n.wgd-node-summary { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n/* Attrs vs children: attributes group under a dotted muted rail with\n key-colored names; children keep the solid accent rail. */\n.wgd-attrs { margin-left: 14px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-attr-row { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; padding: 0; }\n.wgd-attr-row > .wgd-icon { visibility: hidden; }\n.wgd-attr-row:is(:hover, :focus-within) > .wgd-icon { visibility: visible; }\n.wgd-attr-name { font-family: var(--wgd-font-mono); color: var(--wgd-hl-key); flex: 0 1 auto; min-width: 5ch; }\n.wgd-attr-prefix { flex: 0 1 auto; min-width: 6ch; max-width: 10ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-str); }\n.wgd-attr { display: flex; flex-direction: column; gap: 1px; }\n/* Transform block under a bind attr: one more dotted level in. */\n.wgd-attr-map { margin-left: 24px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-attr-map-default { flex: 1 1 auto; min-width: 8ch; }\n.wgd-attr-mode, .wgd-format-type, .wgd-format-display { flex: 0 0 auto; color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); }\n.wgd-format-decimals { flex: 0 0 auto; width: 4ch; min-width: 4ch; text-align: right; font-family: var(--wgd-font-mono); }\n.wgd-format-currency { flex: 0 0 auto; width: 5ch; min-width: 5ch; text-transform: uppercase; font-family: var(--wgd-font-mono); }\n.wgd-format-pattern { flex: 0 1 auto; min-width: 8ch; max-width: 16ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-str); }\n.wgd-children { margin-left: 14px; padding-left: 8px; border-left: 2px solid var(--wgd-accent-line); gap: 1px; }\n.wgd-slot { display: flex; flex-direction: column; gap: 1px; }\n.wgd-slot-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); font-style: italic; padding-left: 4px; }\n/* Add menu: one toggle, options in a popover. */\n.wgd-menuwrap { position: relative; display: inline-flex; }\n.wgd-menu-toggle { color: var(--wgd-accent); }\n.wgd-menu { position: absolute; top: 100%; left: 0; z-index: 10; min-width: 9ch; display: flex; flex-direction: column; background: var(--wgd-panel); border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); box-shadow: var(--wgd-shadow); padding: 2px; }\n/* An OPEN menu must not inherit the icons' hover-gated visibility:\n visibility (unlike display) lets a child re-assert visible. */\n.wgd-menu:not([hidden]) { visibility: visible; }\n.wgd-menuwrap:has(> .wgd-menu:not([hidden])) { visibility: visible; }\n/* Menus in the right-aligned icons area hang leftward, not off-panel. */\n.wgd-node-icons .wgd-menu { left: auto; right: 0; }\n.wgd-menu-item { font: inherit; font-size: var(--wgd-font-size-sm); text-align: left; padding: 3px 8px; border: none; border-radius: var(--wgd-radius-sm); background: none; color: var(--wgd-text); cursor: pointer; white-space: nowrap; }\n.wgd-menu-item:hover { background: var(--wgd-accent-bg); color: var(--wgd-accent); }\n/* Styles tree: selector rows with declaration rows \u2014 the same flat\n template-tree discipline (flat inputs, hover-revealed icons). */\n.wgd-styles { display: flex; flex-direction: column; gap: 2px; }\n.wgd-st-row { display: flex; gap: 4px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-st-row:hover { background: var(--wgd-hover); }\n.wgd-styles .wgd-input { padding: 1px 4px; font-size: var(--wgd-font-size-sm); font-family: var(--wgd-font-mono); border-color: transparent; background: transparent; }\n.wgd-styles .wgd-input:hover, .wgd-styles .wgd-input:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-st-selector { flex: 1 1 auto; min-width: 8ch; color: var(--wgd-accent); }\n.wgd-st-decls { margin-left: 14px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-st-decl { display: flex; gap: 2px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-st-decl:hover { background: var(--wgd-hover); }\n.wgd-st-decl > .wgd-icon { visibility: hidden; }\n.wgd-st-decl:hover > .wgd-icon, .wgd-st-decl:focus-within > .wgd-icon { visibility: visible; }\n.wgd-st-prop { flex: 0 1 auto; min-width: 8ch; color: var(--wgd-hl-key); }\n.wgd-st-value { flex: 1 1 auto; min-width: 8ch; }\n.wgd-st-colon { color: var(--wgd-muted); flex: 0 0 auto; }\n.wgd-st-add { font-size: var(--wgd-font-size-xs); padding: 0 6px; border-color: transparent; color: var(--wgd-accent); background: none; }\n.wgd-st-add:hover { border-color: var(--wgd-border); background: var(--wgd-hover); }\n/* Import and export stack as sibling sections with the column's rhythm. */\n.wgd-io { display: flex; flex-direction: column; gap: 8px; }\n/* Flat string\u2192string record rows (hints): mono keys, prose values. */\n.wgd-record { display: flex; flex-direction: column; gap: 1px; }\n.wgd-rec-row { display: flex; gap: 2px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-rec-row:hover { background: var(--wgd-hover); }\n.wgd-rec-row > .wgd-icon { visibility: hidden; }\n.wgd-rec-row:hover > .wgd-icon, .wgd-rec-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-record .wgd-input { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-record .wgd-input:hover, .wgd-record .wgd-input:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-rec-key { flex: 0 1 auto; min-width: 8ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-key); }\n.wgd-rec-value { flex: 1 1 auto; min-width: 8ch; }\n/* The tag select IS the element node's label: flat, accent, monospace.\n Tag and path selects are width-fitted to their SELECTED value by the\n panel (fitSelect), so carets hug the text \u2014 no flex stretching here. */\n.wgd-node .wgd-tag { flex: 0 0 auto; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-xs); color: var(--wgd-accent); background: var(--wgd-accent-bg); border: 1px solid transparent; border-radius: var(--wgd-radius-sm); padding: 0 4px; }\n.wgd-node .wgd-tag:hover, .wgd-node .wgd-tag:focus { border-color: var(--wgd-accent-line); }\n.wgd-node .wgd-path, .wgd-node .wgd-each-key { flex: 0 1 auto; min-width: 6ch; max-width: 100%; font-family: var(--wgd-font-mono); }\n.wgd-node .wgd-select { box-sizing: border-box; }\n/* Theme panel: swatch beside each color token. */\n/* Syntax coloring: <pre> layer behind a transparent-text textarea. Every\n metric here must mirror .wgd-textarea or the glyphs drift apart. */\n.wgd-hlwrap { position: relative; }\n.wgd-hl, .wgd-hl-input {\n font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size); line-height: 1.45;\n padding: 4px 6px; border: 1px solid transparent; border-radius: var(--wgd-radius);\n box-sizing: border-box; white-space: pre; tab-size: 2; letter-spacing: normal;\n}\n.wgd-hl {\n position: absolute; inset: 0; margin: 0; overflow: hidden;\n pointer-events: none; z-index: 0; background: var(--wgd-bg);\n color: var(--wgd-text);\n}\ntextarea.wgd-hl-input {\n position: relative; z-index: 1; background: transparent; color: transparent;\n caret-color: var(--wgd-text); border-color: var(--wgd-border);\n}\n.wgd-hl-k { color: var(--wgd-hl-key); }\n.wgd-hl-s { color: var(--wgd-hl-str); }\n.wgd-hl-n { color: var(--wgd-hl-num); }\n.wgd-hl-b { color: var(--wgd-hl-bool); }\n.wgd-hl-p { color: var(--wgd-hl-punct); }\n.wgd-swatch { flex: 0 0 auto; width: 26px; height: 22px; padding: 0; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: none; cursor: pointer; }\n.wgd-token-row { display: flex; gap: 6px; align-items: center; }\n.wgd-token-row .wgd-input { flex: 1 1 auto; min-width: 6ch; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-sm); }\n.wgd-token-ref { display: flex; flex-direction: column; gap: 2px; max-height: 220px; overflow-y: auto; margin-top: 4px; }\n.wgd-token-ref-row { display: flex; gap: 6px; align-items: center; font-size: var(--wgd-font-size-xs); }\n.wgd-token-ref-swatch { flex: 0 0 auto; width: 14px; height: 14px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-sm); }\n.wgd-token-ref-noswatch { border-style: dashed; opacity: 0.35; }\n.wgd-token-ref-name { font-family: var(--wgd-font-mono); color: var(--wgd-accent); }\n.wgd-token-ref-value { color: var(--wgd-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.wgd-token-ref-details summary { cursor: pointer; }\n`;\n doc.head.appendChild(style);\n}\n\n/** Tabbed container: first tab visible, buttons switch panes. */\nexport function tabs(entries: { label: string; element: HTMLElement }[]): HTMLElement {\n const buttons = entries.map((entry, index) => {\n const button = h(\n \"button\",\n { class: `wgd-button wgd-tab${index === 0 ? \" wgd-tab-active\" : \"\"}`, type: \"button\" },\n [entry.label]\n );\n button.addEventListener(\"click\", () => {\n entries.forEach((other, i) => {\n other.element.hidden = i !== index;\n buttons[i]?.classList.toggle(\"wgd-tab-active\", i === index);\n });\n });\n entry.element.hidden = index !== 0;\n return button;\n });\n return h(\"div\", { class: \"wgd-tabs\" }, [\n h(\"div\", { class: \"wgd-row\" }, buttons),\n ...entries.map((entry) => entry.element)\n ]);\n}\n", "/** Package-local helpers (kept here rather than exported from core \u2014 see design D4). */\n\n/** Structural copy of JSON-shaped data; the designers hand out copies, never their state. */\nexport function clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** A caught value's message without asserting it is an Error. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n", "/**\n * The designer's derive step: run widgentic's pure validators over the\n * draft and shape their structured errors into per-panel diagnostics.\n * Everything here goes through public package entries \u2014 the designer owns\n * no validation logic of its own.\n */\nimport { auditDataSchema, isPlainObject, PROPERTY_NAME, SAFE_IDENTIFIER, STYLE_RULES } from \"@widgentic/core\";\nimport {\n createCatalog,\n validateDataAgainstSchema,\n widgetStylesToCss\n} from \"@widgentic/core\";\nimport type { WidgetStyles } from \"@widgentic/core\";\nimport type { WidgetContractError } from \"@widgentic/core\";\nimport { collectActionRefs, parsePath, validateTemplate } from \"@widgentic/core\";\nimport { validateLoadBinding } from \"@widgentic/core\";\nimport { validateTheme } from \"@widgentic/core\";\nimport type { ThemeError } from \"@widgentic/core\";\nimport type { WidgetDraft } from \"./store.js\";\n\nexport interface TemplateIssue {\n code: string;\n message: string;\n /** Node path when the validator reports one. */\n path?: string;\n}\n\nexport interface StyleIssue {\n selector: string;\n property?: string;\n message: string;\n}\n\nexport interface DesignerDiagnostics {\n /** Problem with the kind id itself (empty, or colliding with a base kind). */\n kind?: string;\n template?: TemplateIssue;\n /** `descriptor.dataExample` vs `descriptor.dataSchema`. */\n example?: WidgetContractError;\n /** `sampleData` vs `descriptor.dataSchema`. */\n sample?: WidgetContractError;\n /** Entries the renderer's safety filters would skip. */\n styles: StyleIssue[];\n theme?: ThemeError;\n /** Shared-schema reference problems (unknown ref, or ref + inline). */\n schemaRef?: string;\n /** The widget-level `load` binding failed validation. */\n load?: string;\n /** Shared actions referenced by the template or `load` that are not among the supplied ones. */\n actionRefs?: string;\n /**\n * A warning, never blocking: without `descriptor.dataShape` agents that\n * list the widget see a placeholder instead of the data it expects.\n */\n dataShape?: string;\n /** Warnings, never blocking: what the validator would ignore in the inline `dataSchema`. */\n dataSchema?: string[];\n /** True when the draft can be registered and previewed. */\n previewable: boolean;\n}\n\n/** Host-supplied shared schemas the draft may reference by name. */\nexport interface DeriveOptions {\n schemas?: { name: string; schema: Record<string, unknown> }[];\n /** Host-supplied shared actions the draft may bind by name. */\n actions?: { name: string }[];\n}\n\n/**\n * The schema validation actually runs against: the inline one, or the\n * referenced shared one resolved from the supplied list \u2014 the same join\n * the server's composition performs.\n */\nexport function effectiveDataSchema(\n draft: WidgetDraft,\n schemas: { name: string; schema: Record<string, unknown> }[] = []\n): Record<string, unknown> | undefined {\n const ref = draft.descriptor?.dataSchemaRef;\n if (typeof ref === \"string\") {\n return schemas.find((entry) => entry.name === ref)?.schema;\n }\n const inline = draft.descriptor?.dataSchema;\n return isPlainObject(inline) ? inline : undefined;\n}\n\nconst BASE_KINDS = new Set(createCatalog().kinds());\n\n/** What saving would refuse about a kind, in the store's terms; `undefined` when acceptable. */\nexport function kindProblem(kind: string): string | undefined {\n if (!SAFE_IDENTIFIER.test(kind)) {\n return `INVALID_IDENTIFIER \u2014 '${kind}' may use letters, digits, '.', '_' or '-' only.`;\n }\n if (BASE_KINDS.has(kind)) {\n return `RESERVED_KIND \u2014 '${kind}' is a built-in kind; give the widget its own kind.`;\n }\n return undefined;\n}\n\n/**\n * Detect style entries the renderer would skip, using only the public\n * generator: a probe that produces no CSS was filtered by the safety\n * guards. Selector and per-declaration issues are reported separately.\n */\nexport function auditStyles(styles: WidgetStyles | undefined): StyleIssue[] {\n if (!isPlainObject(styles)) return [];\n const issues: StyleIssue[] = [];\n for (const [selector, declarations] of Object.entries(styles)) {\n if (widgetStylesToCss({ [selector]: { color: \"red\" } }) === \"\") {\n issues.push({\n selector,\n message: `Selector would be skipped. ${STYLE_RULES.selectors} ${STYLE_RULES.banned}`\n });\n continue;\n }\n if (!isPlainObject(declarations)) {\n issues.push({ selector, message: \"Declarations must be a property \u2192 value map.\" });\n continue;\n }\n for (const [property, value] of Object.entries(declarations)) {\n if (\n typeof value !== \"string\" ||\n widgetStylesToCss({ \".wg-probe\": { [property]: value } }) === \"\"\n ) {\n // Name the part at fault: the property name, or else the value.\n issues.push({\n selector,\n property,\n message: !PROPERTY_NAME.test(property)\n ? `Property would be skipped. ${STYLE_RULES.propertyNames}`\n : typeof value !== \"string\"\n ? \"Value would be skipped: it must be a string.\"\n : `Value would be skipped. ${STYLE_RULES.banned}`\n });\n }\n }\n }\n return issues;\n}\n\n/** Run every validator; total \u2014 never throws on any draft shape. */\nexport function deriveDiagnostics(\n draft: WidgetDraft,\n options: DeriveOptions = {}\n): DesignerDiagnostics {\n const diagnostics: DesignerDiagnostics = { styles: [], previewable: false };\n\n if (typeof draft.kind !== \"string\" || draft.kind.trim().length === 0) {\n diagnostics.kind = \"Kind must be a non-empty id.\";\n } else {\n const problem = kindProblem(draft.kind);\n if (problem !== undefined) diagnostics.kind = problem;\n }\n\n const dataShape = draft.descriptor?.dataShape;\n if (typeof dataShape !== \"string\" || dataShape.trim() === \"\") {\n diagnostics.dataShape =\n \"Data shape is empty \u2014 agents listing this widget will see a placeholder instead of the data it expects.\";\n }\n\n const inlineSchema = draft.descriptor?.dataSchema;\n if (isPlainObject(inlineSchema)) {\n const warnings = auditDataSchema(inlineSchema, \"dataSchema\");\n if (warnings.length > 0) diagnostics.dataSchema = warnings;\n }\n\n const template = validateTemplate(draft.template);\n if (!template.ok) {\n const issue: TemplateIssue = {\n code: template.error.code,\n message: template.error.message\n };\n const path = (template.error as { path?: unknown }).path;\n if (typeof path === \"string\") issue.path = path;\n diagnostics.template = issue;\n }\n\n // Shared-schema refs resolve here exactly as the server's composition\n // resolves them, so diagnostics match what the store will enforce.\n const ref = draft.descriptor?.dataSchemaRef;\n if (typeof ref === \"string\") {\n if (draft.descriptor?.dataSchema !== undefined) {\n diagnostics.schemaRef =\n \"A descriptor carries 'dataSchema' OR 'dataSchemaRef', never both.\";\n } else if (\n // Unverifiable without the host's schemas: never a false \"unknown\".\n options.schemas !== undefined &&\n options.schemas.every((entry) => entry.name !== ref)\n ) {\n diagnostics.schemaRef = `References unknown schema '${ref}' \u2014 it is not among the supplied shared schemas.`;\n }\n }\n const schema = effectiveDataSchema(draft, options.schemas ?? []);\n if (isPlainObject(schema)) {\n if (draft.descriptor.dataExample !== undefined) {\n const error = validateDataAgainstSchema(schema, draft.descriptor.dataExample);\n if (error) diagnostics.example = error;\n }\n if (draft.sampleData !== undefined) {\n const error = validateDataAgainstSchema(schema, draft.sampleData);\n if (error) diagnostics.sample = error;\n }\n }\n\n diagnostics.styles = auditStyles(draft.descriptor?.styles);\n\n if (draft.load !== undefined) {\n const problem = validateLoadBinding(draft.load, \"load\", {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (problem) diagnostics.load = `${problem.message} (at ${problem.path})`;\n }\n if (options.actions !== undefined) {\n const known = new Set(options.actions.map((action) => action.name));\n const unknown = collectActionRefs(draft.template, draft.load).filter((ref) => !known.has(ref));\n if (unknown.length > 0) {\n diagnostics.actionRefs = `References unknown shared action${unknown.length === 1 ? \"\" : \"s\"} ${unknown\n .map((ref) => `'${ref}'`)\n .join(\", \")} \u2014 bound elements will render disabled.`;\n }\n }\n\n if (draft.theme !== undefined) {\n const theme = validateTheme(draft.theme);\n if (!theme.ok) diagnostics.theme = theme.error;\n }\n\n diagnostics.previewable =\n diagnostics.kind === undefined && diagnostics.template === undefined;\n return diagnostics;\n}\n", "/**\n * Cheap syntax coloring for the JSON textareas: a highlighted <pre> layer\n * sits exactly behind a transparent-text <textarea>, so the browser keeps\n * doing all the real work (typing, selection, undo, IME) and we only paint\n * colors. No editor library, no parsing beyond a tokenizer \u2014 invalid JSON\n * still colors sensibly because the tokenizer is regex-based, never a\n * parser.\n *\n * The two layers must agree on every metric that affects glyph position\n * (font, size, line-height, padding, border width, white-space); the\n * stylesheet keeps them in lockstep.\n */\n\ninterface Token {\n /** Token class suffix: k(ey) s(tring) n(umber) b(oolean/null) p(unctuation). */\n cls: string;\n text: string;\n}\n\nconst JSON_TOKENS =\n /(\"(?:[^\"\\\\]|\\\\.)*\")(\\s*:)?|(-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)|\\b(true|false|null)\\b|([{}[\\],:])/g;\n\nexport function tokenizeJson(text: string): Token[] {\n const out: Token[] = [];\n let last = 0;\n let match: RegExpExecArray | null;\n JSON_TOKENS.lastIndex = 0;\n while ((match = JSON_TOKENS.exec(text)) !== null) {\n if (match.index > last) out.push({ cls: \"\", text: text.slice(last, match.index) });\n if (match[1] !== undefined) {\n // A string followed by ':' is an object key.\n if (match[2] !== undefined) {\n out.push({ cls: \"k\", text: match[1] });\n out.push({ cls: \"p\", text: match[2] });\n } else {\n out.push({ cls: \"s\", text: match[1] });\n }\n } else if (match[3] !== undefined) {\n out.push({ cls: \"n\", text: match[3] });\n } else if (match[4] !== undefined) {\n out.push({ cls: \"b\", text: match[4] });\n } else if (match[5] !== undefined) {\n out.push({ cls: \"p\", text: match[5] });\n }\n last = JSON_TOKENS.lastIndex;\n }\n if (last < text.length) out.push({ cls: \"\", text: text.slice(last) });\n return out;\n}\n\n/** Paint tokens into the layer as DOM nodes (never innerHTML). */\nfunction paint(layer: HTMLElement, text: string): void {\n const nodes: Node[] = [];\n for (const token of tokenizeJson(text)) {\n if (token.cls === \"\") {\n nodes.push(document.createTextNode(token.text));\n continue;\n }\n const span = document.createElement(\"span\");\n span.className = `wgd-hl-${token.cls}`;\n span.textContent = token.text;\n nodes.push(span);\n }\n // A trailing newline needs a following glyph box to render as a line.\n nodes.push(document.createTextNode(\"\\n\"));\n layer.replaceChildren(...nodes);\n}\n\n/**\n * Wrap a textarea in the highlight layer. Returns a disposer that restores\n * the original DOM shape.\n */\nexport function attachJsonHighlight(textarea: HTMLTextAreaElement): () => void {\n const parent = textarea.parentNode;\n if (parent === null) return () => undefined;\n\n const wrap = document.createElement(\"div\");\n wrap.className = \"wgd-hlwrap\";\n const layer = document.createElement(\"pre\");\n layer.className = \"wgd-hl\";\n layer.setAttribute(\"aria-hidden\", \"true\");\n\n parent.insertBefore(wrap, textarea);\n wrap.append(layer, textarea);\n textarea.classList.add(\"wgd-hl-input\");\n\n const sync = (): void => {\n paint(layer, textarea.value);\n layer.scrollTop = textarea.scrollTop;\n layer.scrollLeft = textarea.scrollLeft;\n };\n const syncScroll = (): void => {\n layer.scrollTop = textarea.scrollTop;\n layer.scrollLeft = textarea.scrollLeft;\n };\n // Tab indents instead of moving focus \u2014 these panes hold indented JSON.\n // Shift+Tab keeps its focus-moving default as the keyboard escape.\n const onTab = (event: KeyboardEvent): void => {\n if (event.key !== \"Tab\" || event.shiftKey || textarea.readOnly) return;\n event.preventDefault();\n const { selectionStart, selectionEnd, value } = textarea;\n textarea.value = `${value.slice(0, selectionStart)} ${value.slice(selectionEnd)}`;\n textarea.selectionStart = textarea.selectionEnd = selectionStart + 2;\n // The commit path listens for input; a synthetic one keeps the store\n // and the paint layer in step with the inserted spaces.\n textarea.dispatchEvent(new Event(\"input\", { bubbles: true }));\n };\n\n textarea.addEventListener(\"input\", sync);\n textarea.addEventListener(\"scroll\", syncScroll);\n textarea.addEventListener(\"keydown\", onTab);\n sync();\n\n return () => {\n textarea.removeEventListener(\"input\", sync);\n textarea.removeEventListener(\"scroll\", syncScroll);\n textarea.removeEventListener(\"keydown\", onTab);\n textarea.classList.remove(\"wgd-hl-input\");\n wrap.replaceWith(textarea);\n };\n}\n\n/**\n * Repaint after a programmatic value change (store refresh), which fires\n * no input event.\n */\nexport function repaintHighlight(textarea: HTMLTextAreaElement): void {\n const layer = textarea.parentElement?.querySelector(\".wgd-hl\");\n if (layer instanceof HTMLElement) paint(layer, textarea.value);\n}\n", "/**\n * Import/export in the server's shapes: widget JSON is exactly the\n * `CustomWidget` definition (`{ kind, template, descriptor }`) that\n * `examples/mcp-server/widgets/` registers; themes are bare token maps.\n * Imports are untrusted \u2014 everything re-validates, and a failed import\n * never touches the current draft.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject, SAFE_IDENTIFIER } from \"@widgentic/core\";\nimport { parsePath, validateTemplate } from \"@widgentic/core\";\nimport { validateLoadBinding } from \"@widgentic/core\";\nimport type { ActionBinding } from \"@widgentic/core\";\nimport { kindProblem } from \"./validate.js\";\nimport { diagnosticLine, h, section, textArea, requireChild } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\n\nexport interface WidgetDefinition {\n kind: WidgetDraft[\"kind\"];\n template: WidgetDraft[\"template\"];\n descriptor: WidgetDraft[\"descriptor\"];\n load?: ActionBinding;\n}\n\n/**\n * Validate an untrusted definition; errors instead of throws. The kind is\n * held to what saving accepts only when it differs from `currentKind`: a\n * kind the draft already has is the person's to fix (the diagnostics flag\n * it), and reloading the same draft with new data must not fail on it.\n */\nexport function checkDefinition(definition: unknown, currentKind?: string): string[] {\n const errors: string[] = [];\n if (!isPlainObject(definition)) return [\"Definition must be an object.\"];\n if (typeof definition.kind !== \"string\" || definition.kind.trim() === \"\") {\n errors.push(\"'kind' must be a non-empty string.\");\n } else if (definition.kind !== currentKind) {\n // What saving would refuse is refused here too, in the store's terms.\n const problem = kindProblem(definition.kind);\n if (problem !== undefined) errors.push(`kind: ${problem}`);\n }\n const template = validateTemplate(definition.template);\n if (!template.ok) {\n errors.push(`template: ${template.error.code} \u2014 ${template.error.message}`);\n }\n if (!isPlainObject(definition.descriptor)) {\n errors.push(\"'descriptor' must be an object.\");\n } else if (typeof definition.descriptor.description !== \"string\") {\n errors.push(\"'descriptor.description' must be a string.\");\n } else {\n // Refused at the door in the store's terms where Save refuses them; a\n // non-object `dataSchema` is refused because the designer cannot open it.\n const { dataSchema, dataSchemaRef } = definition.descriptor;\n if (dataSchema !== undefined && dataSchemaRef !== undefined) {\n errors.push(\"descriptor: INVALID_SHAPE \u2014 carries 'dataSchema' and 'dataSchemaRef'; keep one.\");\n } else if (dataSchema !== undefined && !isPlainObject(dataSchema)) {\n errors.push(\"descriptor: INVALID_SHAPE \u2014 'dataSchema' must be a schema object.\");\n } else if (dataSchemaRef !== undefined && (typeof dataSchemaRef !== \"string\" || !SAFE_IDENTIFIER.test(dataSchemaRef))) {\n errors.push(\"descriptor: INVALID_SHAPE \u2014 'dataSchemaRef' must be a valid schema name: letters, digits, '.', '_' or '-'.\");\n }\n }\n if (definition.load !== undefined) {\n const problem = validateLoadBinding(definition.load, \"load\", {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (problem) errors.push(`load: ${problem.message} (at ${problem.path})`);\n }\n return errors;\n}\n\nexport function exportWidgetJson(draft: WidgetDraft): string {\n const definition: WidgetDefinition = {\n kind: draft.kind,\n template: draft.template,\n descriptor: draft.descriptor,\n ...(draft.load !== undefined ? { load: draft.load } : {})\n };\n return JSON.stringify(definition, null, 2);\n}\n\nexport function exportThemeJson(draft: WidgetDraft): string {\n return JSON.stringify(draft.theme ?? {}, null, 2);\n}\n\nexport type ImportResult =\n | { ok: true; definition: WidgetDefinition }\n | { ok: false; errors: string[] };\n\nexport function importWidgetJson(text: string, currentKind?: string): ImportResult {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n return { ok: false, errors: [`Invalid JSON: ${errorMessage(error)}`] };\n }\n const errors = checkDefinition(parsed, currentKind);\n if (errors.length > 0) return { ok: false, errors };\n return { ok: true, definition: parsed as unknown as WidgetDefinition };\n}\n\n/** Apply a validated definition to the store, preserving the session theme. */\nexport function applyDefinition(store: DraftStore, definition: WidgetDefinition): void {\n // The preview theme is the designer's state, not the definition's: a load\n // keeps it whole, tokens and shared styles alike.\n const { theme, themeStyles, previewTheme } = store.get();\n store.replace({\n kind: definition.kind,\n template: definition.template,\n descriptor: definition.descriptor,\n ...(definition.load !== undefined ? { load: definition.load } : {}),\n ...(theme !== undefined ? { theme } : {}),\n ...(themeStyles !== undefined ? { themeStyles } : {}),\n ...(previewTheme !== undefined ? { previewTheme } : {})\n });\n}\n\nfunction camelCase(kind: string): string {\n return kind\n .split(/[^a-zA-Z0-9]+/)\n .filter((part) => part.length > 0)\n .map((part, i) => (i === 0 ? part : part[0]?.toUpperCase() + part.slice(1)))\n .join(\"\");\n}\n\n/**\n * Emit a module body compatible with `examples/mcp-server/widgets/` \u2014\n * the manual-registration bridge until wire registration exists.\n */\nexport function toTypeScriptModule(draft: WidgetDraft): string {\n const name = camelCase(draft.kind) || \"custom\";\n return (\n `import type { CustomWidget } from \"./index.js\";\\n\\n` +\n `export const ${name}Widget: CustomWidget = ${JSON.stringify(\n {\n kind: draft.kind,\n template: draft.template,\n descriptor: draft.descriptor,\n ...(draft.load !== undefined ? { load: draft.load } : {})\n },\n null,\n 2\n )};\\n`\n );\n}\n\nexport function mountIoPanel(store: DraftStore): {\n element: HTMLElement;\n dispose(): void;\n} {\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n\n function button(label: string, produce: () => string): HTMLElement {\n const el = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [label]);\n el.addEventListener(\"click\", () => {\n output.value = produce();\n repaintHighlight(output);\n });\n return el;\n }\n\n const importError = diagnosticLine(undefined);\n const importField = textArea(\"Import widget JSON\", \"\", () => undefined, 5);\n const importArea = requireChild(importField, \"textarea\");\n attachJsonHighlight(importArea);\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\n \"Import\"\n ]);\n importButton.addEventListener(\"click\", () => {\n const result = importWidgetJson(importArea.value, store.get().kind);\n if (!result.ok) {\n importError.hidden = false;\n importError.textContent = result.errors.join(\"\\n\");\n return; // current draft untouched\n }\n importError.hidden = true;\n importError.textContent = \"\";\n applyDefinition(store, result.definition);\n });\n\n // Import and export are independent flows \u2014 two sections, import first\n // (bringing a drafted definition in is the more common entry point).\n const importSection = section(\"Import\", [\n importField,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n // Export copies out what is already on screen, so read-only leaves it\n // operable: the mode restricts editing, not looking.\n const exportSection = section(\"Export\", [\n h(\"div\", { class: \"wgd-row\" }, [\n // The entry the store persists \u2014 named like the other designers'\n // export buttons. Themes export from the theme designer.\n button(\"Export widget entry\", () => exportWidgetJson(store.get())),\n button(\"Copy as TypeScript\", () => toTypeScriptModule(store.get()))\n ]),\n output\n ]);\n exportSection.classList.add(\"wgd-view-only\");\n const element = h(\"div\", { class: \"wgd-io\" }, [importSection, exportSection]);\n // After assembly: the layer wraps the textarea in place, so the element\n // must already have its parent.\n attachJsonHighlight(output);\n\n return { element, dispose: () => element.remove() };\n}\n", "/**\n * Generic JSON value editor: collapsible tree with in-place key/value\n * editing, type switching, and add/remove \u2014 the NanoJSON/JSONTree\n * interaction pattern, built in-house because the general libraries carry\n * far more (and weigh far more) than the designer needs.\n *\n * Structural operations re-render the tree; text edits commit on change\n * (blur/Enter) so typing is never interrupted.\n */\nimport { h } from \"./dom.js\";\n\ntype Path = (string | number)[];\n\nconst TYPE_OPTIONS = [\"string\", \"number\", \"boolean\", \"null\", \"object\", \"array\"] as const;\ntype TypeName = (typeof TYPE_OPTIONS)[number];\n\nfunction typeOf(value: unknown): TypeName {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return (typeof value) as TypeName;\n}\n\nfunction defaultFor(type: TypeName, previous: unknown): unknown {\n switch (type) {\n case \"string\":\n return typeof previous === \"number\" || typeof previous === \"boolean\"\n ? String(previous)\n : \"\";\n case \"number\": {\n const parsed = Number(previous);\n return Number.isFinite(parsed) ? parsed : 0;\n }\n case \"boolean\":\n return previous === \"true\" ? true : Boolean(previous) && previous !== \"false\";\n case \"null\":\n return null;\n case \"object\":\n return {};\n case \"array\":\n return [];\n }\n}\n\nfunction setAt(root: unknown, path: Path, value: unknown, remove = false): unknown {\n if (path.length === 0) return value;\n const [step, ...rest] = path as [string | number, ...Path];\n if (Array.isArray(root)) {\n const copy = [...root];\n if (rest.length === 0 && remove) copy.splice(step as number, 1);\n else copy[step as number] = setAt(copy[step as number], rest, value, remove);\n return copy;\n }\n if (typeof root === \"object\" && root !== null) {\n const copy = { ...(root as Record<string, unknown>) };\n if (rest.length === 0 && remove) delete copy[step as string];\n else copy[step as string] = setAt(copy[step as string], rest, value, remove);\n return copy;\n }\n return root;\n}\n\nfunction renameKey(root: unknown, path: Path, from: string, to: string): unknown {\n const holder = path.reduce<unknown>(\n (node, step) =>\n typeof node === \"object\" && node !== null\n ? (node as Record<string, unknown>)[step as string]\n : undefined,\n root\n );\n if (typeof holder !== \"object\" || holder === null || Array.isArray(holder)) return root;\n const entries = Object.entries(holder).map(([k, v]) =>\n k === from ? ([to, v] as const) : ([k, v] as const)\n );\n return setAt(root, path, Object.fromEntries(entries));\n}\n\nexport interface JsonTreeEditor {\n element: HTMLElement;\n getValue(): unknown;\n /** External update (skipped while the user is editing inside the tree). */\n setValue(value: unknown): void;\n}\n\nexport function createJsonTreeEditor(\n initial: unknown,\n onChange: (value: unknown) => void\n): JsonTreeEditor {\n let current: unknown = initial;\n const element = h(\"div\", { class: \"wgd-jsontree\" });\n\n function commit(next: unknown): void {\n current = next;\n render();\n onChange(current);\n }\n\n function commitText(path: Path, type: TypeName, text: string): void {\n const value =\n type === \"number\"\n ? Number.isFinite(Number(text))\n ? Number(text)\n : 0\n : text;\n current = setAt(current, path, value);\n onChange(current); // no re-render: in-place text edit\n }\n\n function typeSelect(value: unknown, path: Path): HTMLSelectElement {\n const select = h(\"select\", { class: \"wgd-select wgd-jt-type\" });\n for (const option of TYPE_OPTIONS) {\n select.append(h(\"option\", { value: option }, [option]));\n }\n select.value = typeOf(value);\n select.addEventListener(\"change\", () =>\n commit(setAt(current, path, defaultFor(select.value as TypeName, value)))\n );\n return select;\n }\n\n function valueControl(value: unknown, path: Path): Node {\n const type = typeOf(value);\n if (type === \"boolean\") {\n const box = h(\"input\", { type: \"checkbox\" });\n box.checked = value as boolean;\n box.addEventListener(\"change\", () => commit(setAt(current, path, box.checked)));\n return box;\n }\n if (type === \"null\") return h(\"code\", undefined, [\"null\"]);\n if (type === \"string\" || type === \"number\") {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n input.value = String(value);\n input.addEventListener(\"change\", () => commitText(path, type, input.value));\n return input;\n }\n return h(\"span\");\n }\n\n function entryRow(\n keyLabel: Node,\n value: unknown,\n path: Path,\n removable: boolean\n ): HTMLElement {\n const row = h(\"div\", { class: \"wgd-jt-row\" }, [keyLabel, typeSelect(value, path)]);\n const type = typeOf(value);\n if (type !== \"object\" && type !== \"array\") {\n row.append(valueControl(value, path));\n }\n if (removable) {\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => commit(setAt(current, path, undefined, true)));\n row.append(remove);\n }\n const wrap = h(\"div\", { class: \"wgd-jt-entry\" }, [row]);\n if (type === \"object\" || type === \"array\") {\n wrap.append(renderContainer(value, path));\n }\n return wrap;\n }\n\n function renderContainer(value: unknown, path: Path): HTMLElement {\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n body.append(\n entryRow(h(\"span\", { class: \"wgd-jt-key\" }, [String(index)]), item, [...path, index], true)\n );\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ item\"]);\n add.addEventListener(\"click\", () =>\n commit(setAt(current, [...path, value.length], \"\"))\n );\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n } else if (typeof value === \"object\" && value !== null) {\n for (const [key, item] of Object.entries(value)) {\n const keyInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-jt-keyinput\"\n });\n keyInput.value = key;\n keyInput.addEventListener(\"change\", () =>\n commit(renameKey(current, path, key, keyInput.value))\n );\n body.append(entryRow(keyInput, item, [...path, key], true));\n }\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ property\"]);\n add.addEventListener(\"click\", () => {\n const holder = value as Record<string, unknown>;\n let name = \"key\";\n for (let i = 1; name in holder; i++) name = `key${i}`;\n commit(setAt(current, [...path, name], \"\"));\n });\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n const details = h(\"details\", { class: \"wgd-jt-branch\", open: \"\" }, [\n h(\"summary\", { class: \"wgd-jt-summary\" }, [\n Array.isArray(value)\n ? `[ ${value.length} item${value.length === 1 ? \"\" : \"s\"} ]`\n : `{ ${Object.keys(value as object).length} propert${Object.keys(value as object).length === 1 ? \"y\" : \"ies\"} }`\n ]),\n body\n ]);\n return details;\n }\n\n function render(): void {\n element.replaceChildren(\n entryRow(h(\"span\", { class: \"wgd-jt-key\" }, [\"value\"]), current, [], false)\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(value) {\n if (element.contains(document.activeElement)) return;\n current = value;\n render();\n }\n };\n}\n", "/**\n * Structured editor for the dataSchema subset \u2014 the property-card pattern\n * from the React schema-builder ecosystem, sized to widgentic's six\n * keywords (type/properties/required/items/enum/pattern) so it stays a\n * dependency-free couple hundred lines.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { diagnosticLine, fitSelect, h } from \"./dom.js\";\n\nconst TYPES = [\"object\", \"array\", \"string\", \"number\", \"integer\", \"boolean\", \"null\", \"any\"] as const;\n\n/**\n * Types the builder offers `enum` for. The validator accepts `enum` on any\n * type (deep JSON comparison, per JSON Schema), but enumerating whole\n * objects/arrays belongs in the JSON tab, not a form.\n */\nconst ENUM_TYPES = new Set([\"string\", \"number\", \"integer\", \"any\"]);\n\nexport interface SchemaBuilder {\n element: HTMLElement;\n getValue(): DataSchema | undefined;\n setValue(schema: DataSchema | undefined): void;\n}\n\nexport function createSchemaBuilder(\n initial: DataSchema | undefined,\n onChange: (schema: DataSchema | undefined) => void\n): SchemaBuilder {\n let current: DataSchema | undefined = initial;\n const element = h(\"div\", { class: \"wgd-schemabuilder\" });\n\n function commit(next: DataSchema | undefined, rerender = true): void {\n current = next;\n onChange(current);\n if (rerender) render();\n }\n\n /** Rebuild a node with one key changed/removed (undefined removes). */\n function withKey(node: DataSchema, key: string, value: unknown): DataSchema {\n const copy: DataSchema = { ...node };\n if (value === undefined) delete copy[key];\n else copy[key] = value;\n return copy;\n }\n\n /**\n * One schema node. `lead`/`trail` let a parent put the property name and\n * its required/remove controls on the SAME row as the type select.\n */\n function renderNode(\n node: DataSchema,\n apply: (next: DataSchema) => void,\n depth: number,\n lead: (Node | string)[] = [],\n trail: (Node | string)[] = []\n ): HTMLElement {\n const rows: (Node | string)[] = [];\n\n const typeSelect = h(\"select\", { class: \"wgd-select wgd-sb-type\" });\n for (const t of TYPES) typeSelect.append(h(\"option\", { value: t }, [t]));\n // Nullable type arrays ([<type>, \"null\"], either order) present as the\n // PRIMARY type + a nullable toggle \u2014 never collapsing to \"any\", which\n // silently hid pattern/enum for agent-authored nullable fields.\n const rawType = node.type;\n const typeList = Array.isArray(rawType)\n ? rawType.filter((t): t is string => typeof t === \"string\")\n : undefined;\n const nullable = typeList?.includes(\"null\") ?? false;\n const currentType =\n typeof rawType === \"string\"\n ? rawType\n : (typeList?.find((t) => t !== \"null\") ?? (nullable ? \"null\" : \"any\"));\n typeSelect.value = TYPES.some((type) => type === currentType)\n ? currentType\n : \"any\";\n fitSelect(typeSelect);\n const nullBox = h(\"input\", {\n type: \"checkbox\",\n title: \"Also allows null\"\n });\n nullBox.checked = nullable;\n nullBox.disabled = typeSelect.value === \"any\" || typeSelect.value === \"null\";\n /** The `type` value the current controls describe. */\n function typeValue(selected: string, allowNull: boolean): unknown {\n if (selected === \"any\") return undefined;\n return allowNull && selected !== \"null\" ? [selected, \"null\"] : selected;\n }\n nullBox.addEventListener(\"change\", () => {\n apply(withKey(node, \"type\", typeValue(typeSelect.value, nullBox.checked)));\n });\n typeSelect.addEventListener(\"change\", () => {\n let next = withKey(node, \"type\", typeValue(typeSelect.value, nullBox.checked));\n if (typeSelect.value !== \"object\") {\n next = withKey(withKey(next, \"properties\", undefined), \"required\", undefined);\n }\n if (typeSelect.value !== \"array\") next = withKey(next, \"items\", undefined);\n if (typeSelect.value !== \"string\") next = withKey(next, \"pattern\", undefined);\n if (!ENUM_TYPES.has(typeSelect.value)) next = withKey(next, \"enum\", undefined);\n apply(next);\n });\n // Header row: [name?] [type] [nullable] [required?] [remove?]\n rows.push(\n h(\"div\", { class: \"wgd-sb-row\" }, [\n ...lead,\n typeSelect,\n h(\"label\", { class: \"wgd-sb-req wgd-sb-null\", title: \"Also allows null\" }, [\n nullBox,\n \"null\"\n ]),\n ...trail\n ])\n );\n\n // Constraints row \u2014 only the ones this type can actually use.\n const constraints: (Node | string)[] = [];\n if (typeSelect.value === \"string\") {\n const pattern = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-constraint\",\n placeholder: \"pattern (regex, optional)\"\n });\n pattern.value = typeof node.pattern === \"string\" ? node.pattern : \"\";\n pattern.addEventListener(\"change\", () =>\n apply(withKey(node, \"pattern\", pattern.value === \"\" ? undefined : pattern.value))\n );\n constraints.push(h(\"span\", { class: \"wgd-sb-label\" }, [\"pattern\"]), pattern);\n }\n const enumError = diagnosticLine(undefined);\n // `enum` is type-agnostic in the validator, but enumerating whole\n // objects/arrays is a JSON-tab affair \u2014 the builder offers it where\n // it is actually useful.\n if (ENUM_TYPES.has(typeSelect.value)) {\n const enumInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-constraint\",\n placeholder: 'enum [\"a\",\"b\"] (optional)'\n });\n enumInput.value = Array.isArray(node.enum) ? JSON.stringify(node.enum) : \"\";\n enumInput.addEventListener(\"change\", () => {\n if (enumInput.value.trim() === \"\") {\n enumError.hidden = true;\n apply(withKey(node, \"enum\", undefined));\n return;\n }\n try {\n const parsed: unknown = JSON.parse(enumInput.value);\n if (!Array.isArray(parsed)) throw new Error(\"must be a JSON array\");\n enumError.hidden = true;\n apply(withKey(node, \"enum\", parsed));\n } catch (error) {\n enumError.hidden = false;\n enumError.textContent = `enum ignored: ${errorMessage(error)}`;\n }\n });\n constraints.push(h(\"span\", { class: \"wgd-sb-label\" }, [\"enum\"]), enumInput);\n }\n if (constraints.length > 0) {\n rows.push(h(\"div\", { class: \"wgd-sb-row wgd-sb-constraints\" }, constraints), enumError);\n }\n\n // Object: property cards + required toggles\n if (typeSelect.value === \"object\") {\n const properties = isPlainObject(node.properties) ? node.properties : {};\n const required = Array.isArray(node.required)\n ? node.required.filter((k): k is string => typeof k === \"string\")\n : [];\n const cards = h(\"div\", { class: \"wgd-jt-children\" });\n for (const [name, sub] of Object.entries(properties)) {\n const nameInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-prop\",\n placeholder: \"property name\"\n });\n nameInput.value = name;\n nameInput.addEventListener(\"change\", () => {\n const entries = Object.entries(properties).map(([k, v]) =>\n k === name ? ([nameInput.value, v] as const) : ([k, v] as const)\n );\n const nextRequired = required.map((k) => (k === name ? nameInput.value : k));\n apply(\n withKey(\n withKey(node, \"properties\", Object.fromEntries(entries)),\n \"required\",\n nextRequired.length > 0 ? nextRequired : undefined\n )\n );\n });\n const requiredBox = h(\"input\", { type: \"checkbox\", title: \"required\" });\n requiredBox.checked = required.includes(name);\n requiredBox.addEventListener(\"change\", () => {\n const nextRequired = requiredBox.checked\n ? [...required, name]\n : required.filter((k) => k !== name);\n apply(withKey(node, \"required\", nextRequired.length > 0 ? nextRequired : undefined));\n });\n const removeProp = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove property\" }, [\"\u2715\"]);\n removeProp.addEventListener(\"click\", () => {\n const { [name]: _gone, ...rest } = properties;\n apply(\n withKey(\n withKey(node, \"properties\", Object.keys(rest).length > 0 ? rest : undefined),\n \"required\",\n required.filter((k) => k !== name).length > 0\n ? required.filter((k) => k !== name)\n : undefined\n )\n );\n });\n // Name, type, required and remove all share the property's first row.\n cards.append(\n renderNode(\n isPlainObject(sub) ? (sub as DataSchema) : {},\n (nextSub) =>\n apply(withKey(node, \"properties\", { ...properties, [name]: nextSub })),\n depth + 1,\n [nameInput],\n [\n h(\"label\", { class: \"wgd-sb-req\", title: \"required\" }, [requiredBox, \"req\"]),\n removeProp\n ]\n )\n );\n }\n const addProp = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ property\"\n ]);\n addProp.addEventListener(\"click\", () => {\n let name = \"field\";\n for (let i = 1; name in properties; i++) name = `field${i}`;\n apply(withKey(node, \"properties\", { ...properties, [name]: { type: \"string\" } }));\n });\n cards.append(h(\"div\", { class: \"wgd-toolbar\" }, [addProp]));\n rows.push(cards);\n }\n\n // Array: items node\n if (typeSelect.value === \"array\") {\n rows.push(\n h(\"div\", { class: \"wgd-slot\" }, [\n renderNode(\n isPlainObject(node.items) ? (node.items as DataSchema) : {},\n (nextItems) => apply(withKey(node, \"items\", nextItems)),\n depth + 1,\n [h(\"span\", { class: \"wgd-sb-label\" }, [\"items\"])]\n )\n ])\n );\n }\n\n return h(\"div\", { class: depth === 0 ? \"wgd-sb-root\" : \"wgd-sb-node\" }, rows);\n }\n\n function render(): void {\n if (current === undefined) {\n const start = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ add a data schema\"\n ]);\n start.addEventListener(\"click\", () => commit({ type: \"object\" }));\n element.replaceChildren(\n h(\"div\", undefined, [\n h(\"span\", { class: \"wgd-sb-label\" }, [\n \"No schema \u2014 data is accepted leniently.\"\n ]),\n h(\"div\", { class: \"wgd-toolbar\" }, [start])\n ])\n );\n return;\n }\n const clear = h(\"button\", { class: \"wgd-button wgd-add wgd-remove\", type: \"button\" }, [\n \"remove schema\"\n ]);\n clear.addEventListener(\"click\", () => commit(undefined));\n element.replaceChildren(\n renderNode(current, (next) => commit(next), 0),\n h(\"div\", { class: \"wgd-toolbar\" }, [clear])\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(schema) {\n if (element.contains(document.activeElement)) return;\n current = schema;\n render();\n }\n };\n}\n", "/**\n * Flat editor for a string\u2192string record (hints: name \u2192 doc), under the\n * same flat discipline as the styles tree \u2014 one slim row per entry,\n * removal revealed by the row. Values are strings by construction, so\n * the tree enforces the exact shape; anything looser is a JSON-tab\n * affair.\n */\nimport { h } from \"./dom.js\";\n\nexport interface RecordEditor {\n element: HTMLElement;\n getValue(): Record<string, string> | undefined;\n setValue(record: Record<string, string> | undefined): void;\n}\n\nexport function createRecordEditor(\n initial: Record<string, string> | undefined,\n placeholders: { key: string; value: string; add: string },\n onChange: (record: Record<string, string> | undefined) => void\n): RecordEditor {\n let current: Record<string, string> | undefined = initial;\n const element = h(\"div\", { class: \"wgd-record\" });\n\n function commit(next: Record<string, string>): void {\n // An emptied record means \"none\" \u2014 the owning key drops entirely.\n current = Object.keys(next).length > 0 ? next : undefined;\n onChange(current);\n render();\n }\n\n function changeInput(\n value: string,\n placeholder: string,\n className: string,\n onCommit: (value: string) => void\n ): HTMLInputElement {\n const input = h(\"input\", {\n type: \"text\",\n class: className,\n placeholder,\n spellcheck: \"false\"\n });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n function render(): void {\n const record = current ?? {};\n const rows = Object.entries(record).map(([key, value]) => {\n const keyInput = changeInput(\n key,\n placeholders.key,\n \"wgd-input wgd-rec-key\",\n (next) => {\n const entries = Object.entries(record).map(([k, v]) =>\n k === key ? ([next, v] as const) : ([k, v] as const)\n );\n commit(Object.fromEntries(entries));\n }\n );\n const valueInput = changeInput(\n value,\n placeholders.value,\n \"wgd-input wgd-rec-value\",\n (next) => commit({ ...record, [key]: next })\n );\n const remove = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove entry\" },\n [\"\u2715\"]\n );\n remove.addEventListener(\"click\", () => {\n const { [key]: _gone, ...rest } = record;\n commit(rest);\n });\n return h(\"div\", { class: \"wgd-rec-row\" }, [\n keyInput,\n h(\"span\", { class: \"wgd-st-colon\" }, [\":\"]),\n valueInput,\n remove\n ]);\n });\n const add = h(\n \"button\",\n { class: \"wgd-button wgd-add wgd-st-add\", type: \"button\" },\n [placeholders.add]\n );\n add.addEventListener(\"click\", () => {\n let key = \"\";\n for (let i = 1; key in record; i++) key = `key${i}`;\n commit({ ...record, [key]: \"\" });\n });\n element.replaceChildren(...rows, h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(record) {\n if (element.contains(document.activeElement)) return;\n current = record;\n render();\n }\n };\n}\n", "/**\n * Schema-driven data form: generates controls from widgentic's dataSchema\n * subset (type/properties/required/items/enum/pattern). This is the\n * @json-editor/json-editor interaction model, sized to the six keywords\n * the subset actually has \u2014 which is what makes an in-house generator a\n * few hundred lines instead of a 150 KB dependency.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\n\nfunction firstType(schema: DataSchema): string | undefined {\n const type = schema.type;\n if (typeof type === \"string\") return type;\n if (Array.isArray(type)) {\n // Nullable arrays pick the PRIMARY type regardless of order.\n const primary = type.find((t) => typeof t === \"string\" && t !== \"null\");\n if (typeof primary === \"string\") return primary;\n if (type.includes(\"null\")) return \"null\";\n }\n return undefined;\n}\n\nfunction seedFor(schema: DataSchema): unknown {\n if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];\n switch (firstType(schema)) {\n case \"object\": {\n const seed: Record<string, unknown> = {};\n if (isPlainObject(schema.properties) && Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (typeof key === \"string\" && isPlainObject(schema.properties[key])) {\n seed[key] = seedFor(schema.properties[key] as DataSchema);\n }\n }\n }\n return seed;\n }\n case \"array\":\n return [];\n case \"number\":\n case \"integer\":\n return 0;\n case \"boolean\":\n return false;\n case \"null\":\n return null;\n default:\n return \"\";\n }\n}\n\nexport interface SchemaForm {\n element: HTMLElement;\n getValue(): unknown;\n setValue(value: unknown): void;\n}\n\nexport function createSchemaForm(\n schema: DataSchema,\n initial: unknown,\n onChange: (value: unknown) => void\n): SchemaForm {\n let current: unknown = initial ?? seedFor(schema);\n const element = h(\"div\", { class: \"wgd-schemaform\" });\n\n type Path = (string | number)[];\n\n function setAt(root: unknown, path: Path, value: unknown, remove = false): unknown {\n if (path.length === 0) return value;\n const [step, ...rest] = path as [string | number, ...Path];\n if (Array.isArray(root)) {\n const copy = [...root];\n if (rest.length === 0 && remove) copy.splice(step as number, 1);\n else copy[step as number] = setAt(copy[step as number], rest, value, remove);\n return copy;\n }\n const holder = isPlainObject(root) ? { ...root } : {};\n if (rest.length === 0 && remove) delete holder[step as string];\n else holder[step as string] = setAt(holder[step as string], rest, value, remove);\n return holder;\n }\n\n function commit(path: Path, value: unknown, rerender = false): void {\n current = setAt(current, path, value);\n onChange(current);\n if (rerender) render();\n }\n\n function control(node: DataSchema, value: unknown, path: Path, label: string): HTMLElement {\n if (Array.isArray(node.enum)) {\n const select = h(\"select\", { class: \"wgd-select\" });\n for (const option of node.enum) {\n select.append(h(\"option\", { value: JSON.stringify(option) }, [JSON.stringify(option)]));\n }\n select.value = JSON.stringify(value ?? node.enum[0]);\n select.addEventListener(\"change\", () =>\n commit(path, JSON.parse(select.value) as unknown)\n );\n return field(label, select);\n }\n switch (firstType(node)) {\n case \"boolean\": {\n const box = h(\"input\", { type: \"checkbox\" });\n box.checked = value === true;\n box.addEventListener(\"change\", () => commit(path, box.checked));\n return field(label, box);\n }\n case \"number\":\n case \"integer\": {\n const input = h(\"input\", { type: \"number\", class: \"wgd-input\" });\n input.value = typeof value === \"number\" ? String(value) : \"0\";\n input.addEventListener(\"change\", () => {\n const parsed = Number(input.value);\n commit(path, Number.isFinite(parsed) ? parsed : 0);\n });\n return field(label, input);\n }\n case \"object\": {\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n const properties = isPlainObject(node.properties) ? node.properties : {};\n const required = Array.isArray(node.required) ? node.required : [];\n const holder = isPlainObject(value) ? value : {};\n for (const [name, sub] of Object.entries(properties)) {\n if (!isPlainObject(sub)) continue;\n const isRequired = required.includes(name);\n body.append(\n control(\n sub as DataSchema,\n holder[name] ?? (isRequired ? seedFor(sub as DataSchema) : undefined),\n [...path, name],\n isRequired ? `${name} *` : name\n )\n );\n }\n return h(\"fieldset\", { class: \"wgd-sf-object\" }, [\n h(\"legend\", { class: \"wgd-field-label\" }, [label]),\n body\n ]);\n }\n case \"array\": {\n const itemsSchema = isPlainObject(node.items) ? (node.items as DataSchema) : {};\n const items = Array.isArray(value) ? value : [];\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n items.forEach((item, index) => {\n const row = h(\"div\", { class: \"wgd-jt-entry\" }, [\n control(itemsSchema, item, [...path, index], `#${index}`)\n ]);\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove item\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => {\n current = setAt(current, [...path, index], undefined, true);\n onChange(current);\n render();\n });\n row.append(remove);\n body.append(row);\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ item\"]);\n add.addEventListener(\"click\", () =>\n commit([...path, items.length], seedFor(itemsSchema), true)\n );\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n return h(\"fieldset\", { class: \"wgd-sf-object\" }, [\n h(\"legend\", { class: \"wgd-field-label\" }, [label]),\n body\n ]);\n }\n default: {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n if (typeof node.pattern === \"string\") {\n input.setAttribute(\"placeholder\", `pattern: ${node.pattern}`);\n input.setAttribute(\"title\", `Must match ${node.pattern}`);\n }\n input.value = typeof value === \"string\" ? value : value === undefined ? \"\" : String(value);\n input.addEventListener(\"change\", () => commit(path, input.value));\n return field(label, input);\n }\n }\n }\n\n function field(label: string, controlEl: Node): HTMLElement {\n return h(\"label\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [label]),\n controlEl\n ]);\n }\n\n function render(): void {\n element.replaceChildren(control(schema, current, [], \"data\"));\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(value) {\n if (element.contains(document.activeElement)) return;\n current = value ?? seedFor(schema);\n render();\n }\n };\n}\n", "/**\n * Structured editor for the descriptor's styles \u2014 selector rows with\n * their declaration rows, under the template tree's flat discipline.\n * The value is `Record<selector, Record<property, value>>` (strings\n * only), so the tree enforces the exact shape the server's style guards\n * expect; anything looser belongs in the JSON tab.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\n\nexport type WidgetStylesValue = Record<string, Record<string, string>>;\n\nexport interface StylesEditor {\n element: HTMLElement;\n getValue(): WidgetStylesValue | undefined;\n setValue(styles: WidgetStylesValue | undefined): void;\n}\n\nexport function createStylesEditor(\n initial: WidgetStylesValue | undefined,\n onChange: (styles: WidgetStylesValue | undefined) => void\n): StylesEditor {\n let current: WidgetStylesValue | undefined = initial;\n const element = h(\"div\", { class: \"wgd-styles\" });\n\n function commit(next: WidgetStylesValue): void {\n // An emptied record means \"no styles\" \u2014 the descriptor drops the key.\n current = Object.keys(next).length > 0 ? next : undefined;\n onChange(current);\n render();\n }\n\n function changeInput(\n value: string,\n placeholder: string,\n className: string,\n onCommit: (value: string) => void\n ): HTMLInputElement {\n const input = h(\"input\", {\n type: \"text\",\n class: className,\n placeholder,\n spellcheck: \"false\"\n });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n function renderSelector(\n selector: string,\n declarations: Record<string, string>,\n styles: WidgetStylesValue\n ): HTMLElement {\n const rename = changeInput(\n selector,\n \".wg-selector\",\n \"wgd-input wgd-st-selector\",\n (next) => {\n const entries = Object.entries(styles).map(([k, v]) =>\n k === selector ? ([next, v] as const) : ([k, v] as const)\n );\n commit(Object.fromEntries(entries));\n }\n );\n const addDecl = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Add declaration\" },\n [\"+\"]\n );\n addDecl.addEventListener(\"click\", () => {\n commit({ ...styles, [selector]: { ...declarations, \"\": \"\" } });\n });\n const removeSelector = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove selector\" },\n [\"\u2715\"]\n );\n removeSelector.addEventListener(\"click\", () => {\n const { [selector]: _gone, ...rest } = styles;\n commit(rest);\n });\n const declRows = Object.entries(declarations).map(([property, value]) => {\n const propInput = changeInput(\n property,\n \"property\",\n \"wgd-input wgd-st-prop\",\n (next) => {\n const entries = Object.entries(declarations).map(([k, v]) =>\n k === property ? ([next, v] as const) : ([k, v] as const)\n );\n commit({ ...styles, [selector]: Object.fromEntries(entries) });\n }\n );\n const valueInput = changeInput(\n value,\n \"value (no url(...), no ;)\",\n \"wgd-input wgd-st-value\",\n (next) => {\n commit({\n ...styles,\n [selector]: { ...declarations, [property]: next }\n });\n }\n );\n const removeDecl = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove declaration\" },\n [\"\u2715\"]\n );\n removeDecl.addEventListener(\"click\", () => {\n const { [property]: _gone, ...rest } = declarations;\n commit({ ...styles, [selector]: rest });\n });\n return h(\"div\", { class: \"wgd-st-decl\" }, [\n propInput,\n h(\"span\", { class: \"wgd-st-colon\" }, [\":\"]),\n valueInput,\n removeDecl\n ]);\n });\n return h(\"div\", { class: \"wgd-st-rule\" }, [\n h(\"div\", { class: \"wgd-st-row\" }, [\n rename,\n h(\"span\", { class: \"wgd-node-icons\" }, [addDecl, removeSelector])\n ]),\n h(\"div\", { class: \"wgd-st-decls\" }, declRows)\n ]);\n }\n\n function render(): void {\n const styles = current ?? {};\n const addSelector = h(\n \"button\",\n { class: \"wgd-button wgd-add wgd-st-add\", type: \"button\" },\n [\"+ selector\"]\n );\n addSelector.addEventListener(\"click\", () => {\n let name = \".wg-\";\n for (let i = 1; name in styles; i++) name = `.wg-${i}`;\n commit({ ...styles, [name]: {} });\n });\n element.replaceChildren(\n ...Object.entries(styles).map(([selector, declarations]) =>\n renderSelector(\n selector,\n isPlainObject(declarations)\n ? (declarations as Record<string, string>)\n : {},\n styles\n )\n ),\n h(\"div\", { class: \"wgd-toolbar\" }, [addSelector])\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(styles) {\n if (element.contains(document.activeElement)) return;\n current = styles;\n render();\n }\n };\n}\n", "/**\n * The styles panel both designers mount \u2014 a widget's descriptor styles and\n * a theme's shared styles are one shape under one rule set, so they get one\n * editor: the structured Tree and a parse-gated JSON view over the same\n * value, plus the audit's list of entries the renderer would drop.\n */\nimport { isStyleMap } from \"@widgentic/core\";\nimport type { WidgetStyles } from \"@widgentic/core\";\nimport { diagnosticLine, h, requireChild, section, tabs, textArea } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { errorMessage } from \"./internal.js\";\nimport { createStylesEditor } from \"./styles-editor.js\";\nimport type { StyleIssue } from \"./validate.js\";\n\nexport interface StylesPanel {\n element: HTMLElement;\n /** Reflect a value set elsewhere; the JSON view keeps a focused edit. */\n setValue(styles: WidgetStyles | undefined): void;\n setIssues(issues: StyleIssue[]): void;\n}\n\nexport function createStylesPanel(\n initial: WidgetStyles | undefined,\n onChange: (styles: WidgetStyles | undefined) => void\n): StylesPanel {\n // The two views keep each other in step: an edit in one reaches the\n // other before the host hears of it, whatever the host refreshes.\n const tree = createStylesEditor(initial, (styles) => {\n showJson(styles);\n onChange(styles);\n });\n const parseError = diagnosticLine(undefined);\n // No legend \u2014 the section title already names the shape.\n const field = textArea(\"\", initial === undefined ? \"\" : JSON.stringify(initial, null, 2), (text) => {\n if (text.trim() === \"\") {\n parseError.hidden = true;\n tree.setValue(undefined);\n onChange(undefined);\n return;\n }\n try {\n const value: unknown = JSON.parse(text);\n parseError.hidden = true;\n parseError.textContent = \"\";\n // Last valid wins: only the styles shape reaches the value, and an\n // empty map is no styles, as the Tree view has it.\n if (!isStyleMap(value)) {\n parseError.hidden = false;\n parseError.textContent =\n \"Styles must map selectors to objects of property/value strings (the last valid value is kept).\";\n return;\n }\n const next = Object.keys(value).length > 0 ? value : undefined;\n tree.setValue(next);\n onChange(next);\n } catch (error) {\n parseError.hidden = false;\n parseError.textContent = `Invalid JSON (the last valid value is kept): ${errorMessage(error)}`;\n }\n });\n const area = requireChild(field, \"textarea\");\n attachJsonHighlight(area);\n\n function showJson(styles: WidgetStyles | undefined): void {\n if (document.activeElement === area) return;\n area.value = styles === undefined ? \"\" : JSON.stringify(styles, null, 2);\n repaintHighlight(area); // programmatic writes fire no input event\n // The text now shown is valid: an earlier parse error no longer applies.\n parseError.hidden = true;\n parseError.textContent = \"\";\n }\n\n const issues = h(\"div\");\n const element = section(\"Styles (.wg- selectors only)\", [\n tabs([\n { label: \"Tree\", element: tree.element },\n { label: \"JSON\", element: h(\"div\", undefined, [field, parseError]) }\n ]),\n issues\n ]);\n return {\n element,\n setValue(styles) {\n tree.setValue(styles);\n showJson(styles);\n },\n setIssues(list) {\n issues.replaceChildren(\n ...list.map((issue) =>\n diagnosticLine(`${issue.selector}${issue.property ? ` \u2192 ${issue.property}` : \"\"}: ${issue.message}`)\n )\n );\n }\n };\n}\n", "/**\n * Path helpers over widgentic's dataSchema subset, shared by the template\n * panel (bind/each/when completions) and the binding editor (input and\n * output mapping completions, type checks). Nullable type arrays pick the\n * PRIMARY type; `any` (no type) is treated as unknown, never mismatched.\n */\nimport { isPlainObject } from \"@widgentic/core\";\n/** The primary type a schema declares, if any. */\n/** How deep completions and type checks descend; schemas are JSON, but bounded anyway. */\nconst MAX_SCHEMA_DEPTH = 3;\n\nexport function schemaType(schema: unknown): string | undefined {\n if (!isPlainObject(schema)) return undefined;\n const type = schema.type;\n if (typeof type === \"string\") return type;\n if (Array.isArray(type)) {\n const primary = type.find((t) => typeof t === \"string\" && t !== \"null\");\n if (typeof primary === \"string\") return primary;\n }\n return undefined;\n}\n\n/**\n * Enumerate the paths a scope offers. Context-free on purpose: an array is\n * offered as ITSELF and never descended, because neither the template\n * resolver nor the projection steps into an array by name (`lines.qty`\n * resolves to nothing; `lines.0.qty` does). A caller whose scope IS the\n * item \u2014 a template inside an each, a projection over a list response \u2014\n * passes the item schema (`itemSchema`) instead.\n */\nexport function collectPaths(\n schema: unknown,\n prefix: string,\n out: { path: string; schema: unknown }[],\n depth = 0\n): void {\n if (!isPlainObject(schema) || depth > MAX_SCHEMA_DEPTH) return;\n if (schemaType(schema) !== \"object\" || !isPlainObject(schema.properties)) return;\n for (const [name, sub] of Object.entries(schema.properties)) {\n const path = prefix === \"\" ? name : `${prefix}.${name}`;\n out.push({ path, schema: sub });\n collectPaths(sub, path, out, depth + 1);\n }\n}\n\n/** The item schema of an array, or the schema itself when it is not one. */\nexport function itemSchema(schema: unknown): unknown {\n return isPlainObject(schema) && schemaType(schema) === \"array\"\n ? schema.items\n : schema;\n}\n\n/** The sub-schema at a dotted path (\"\" or \".\" is the schema itself). */\nexport function schemaAt(schema: unknown, path: string): unknown {\n if (path === \"\" || path === \".\") return schema;\n let current: unknown = schema;\n for (const segment of path.split(\".\")) {\n if (!isPlainObject(current)) return undefined;\n if (schemaType(current) === \"array\") {\n // Arrays are stepped into by INDEX only \u2014 the resolvers' own rule.\n if (!/^\\d+$/.test(segment)) return undefined;\n current = itemSchema(current);\n continue;\n }\n if (!isPlainObject(current.properties)) return undefined;\n current = current.properties[segment];\n }\n return current;\n}\n\n/** Numeric types agree with each other; unknown never mismatches. */\nexport function typesConflict(a: string | undefined, b: string | undefined): boolean {\n if (a === undefined || b === undefined) return false;\n const norm = (t: string) => (t === \"integer\" ? \"number\" : t);\n return norm(a) !== norm(b);\n}\n\n/**\n * Compare a source and a target schema for the projection editor,\n * descending MATCHED array sides so two lists are judged by their ITEM\n * types \u2014 the shape a per-item projection has. Returns the conflicting\n * type labels, or `undefined` when the two agree.\n */\nexport function schemaMismatch(\n source: unknown,\n target: unknown\n): { source: string | undefined; target: string | undefined } | undefined {\n let a = source;\n let b = target;\n for (let depth = 0; depth < MAX_SCHEMA_DEPTH; depth++) {\n if (schemaType(a) !== \"array\" || schemaType(b) !== \"array\") break;\n a = itemSchema(a);\n b = itemSchema(b);\n }\n const sourceType = schemaType(a);\n const targetType = schemaType(b);\n return typesConflict(sourceType, targetType)\n ? { source: sourceType, target: targetType }\n : undefined;\n}\n\n/** All dotted paths under a schema (leaves and branches), for completions. */\nexport function allPaths(schema: unknown): string[] {\n const entries: { path: string; schema: unknown }[] = [];\n collectPaths(schema, \"\", entries);\n return entries.map((entry) => entry.path);\n}\n", "/**\n * Shared editors for the action model: an action DEFINITION (prompt or\n * http) and a BINDING (shared ref or inline definition, plus the input\n * mapping and output mode). The standalone action designer edits\n * definitions; the widget designer binds them to elements and to the\n * widget's `load`. Everything is plain DOM over immutable values, and no\n * network I/O happens here \u2014 testing an action is the host's job.\n *\n * Handlers read the editor's live state at event time and a commit\n * re-renders only its own section, so two edits in a row never lose each\n * other and focus survives a commit. Rows without a name (a new header,\n * query parameter or projection) live in editor-local state until they are\n * named; only named rows reach `onChange`.\n */\nimport type { DataSchema } from \"@widgentic/core\";\nimport type {\n ActionBinding,\n ActionDefinition,\n HttpActionDefinition,\n InputMapping,\n OutputBinding,\n OutputMode,\n PromptSegment,\n StoredAction\n} from \"@widgentic/core\";\nimport { HTTP_METHODS, OUTPUT_MODES } from \"@widgentic/core\";\nimport { clone } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport { diagnosticLine, fitSelect, h, select } from \"./dom.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { allPaths, itemSchema, schemaAt, schemaMismatch, schemaType } from \"./schema-paths.js\";\n\n/** The path select's escape hatch to free text. */\nconst CUSTOM_PATH = \"__custom__\";\n\ntype HeaderValue = string | { secret: string };\ntype HeaderMap = Record<string, HeaderValue>;\ntype RefBinding = { ref: string } & Pick<ActionBinding, \"input\" | \"output\">;\n\nexport interface ActionEditorContext {\n /** Shared schemas offered as \"copy from\" sources for input/output. */\n schemas?: SchemaEntry[];\n /** Secret names offered for header/query values. */\n secretNames?: string[];\n}\n\nexport function starterPromptDefinition(): ActionDefinition {\n return { kind: \"prompt\", text: [\"Tell me more about \", { bind: \"title\" }] };\n}\n\nexport function starterHttpDefinition(): HttpActionDefinition {\n return {\n kind: \"http\",\n method: \"GET\",\n url: \"https://api.example.com/resource\",\n input: { type: \"object\", properties: {} },\n output: { type: \"object\" }\n };\n}\n\nfunction isRefBinding(binding: ActionBinding): binding is RefBinding {\n return \"ref\" in binding && typeof binding.ref === \"string\";\n}\n\nfunction textInput(value: string, className: string, onCommit: (value: string) => void, placeholder = \"\"): HTMLInputElement {\n const el = h(\"input\", { type: \"text\", class: className, placeholder });\n el.value = value;\n el.addEventListener(\"change\", () => onCommit(el.value));\n return el;\n}\n\n\nfunction label(text: string): HTMLElement {\n return h(\"span\", { class: \"wgd-field-label\" }, [text]);\n}\n\nfunction removeButton(onClick: () => void): HTMLElement {\n const button = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n button.addEventListener(\"click\", onClick);\n return button;\n}\n\n/**\n * Path picker: a select over the known paths (plus the current value when\n * it is off-schema) with a \"custom\u2026\" escape to free text \u2014 the template\n * panel's pathControl, for mappings. The placeholder option clears the\n * value. With no known paths it is a text input.\n */\nfunction pathSelect(\n value: string,\n options: string[],\n onCommit: (path: string) => void,\n placeholder: string,\n className = \"wgd-input wgd-rec-value\"\n): HTMLElement {\n if (options.length === 0) return textInput(value, className, onCommit, placeholder);\n const sel = h(\"select\", { class: \"wgd-select wgd-path\" });\n const known = options.includes(value);\n const listed = known || value === \"\" ? options : [value, ...options];\n sel.append(h(\"option\", { value: \"\" }, [placeholder]));\n for (const option of listed) {\n sel.append(h(\"option\", { value: option }, [option === value && !known ? `${option} (off-schema)` : option]));\n }\n sel.append(h(\"option\", { value: CUSTOM_PATH }, [\"custom\u2026\"]));\n sel.value = value;\n fitSelect(sel);\n const custom = textInput(value, className, onCommit, placeholder);\n custom.hidden = true;\n sel.addEventListener(\"change\", () => {\n if (sel.value === CUSTOM_PATH) {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(sel.value);\n });\n return h(\"span\", { class: \"wgd-pathwrap\" }, [sel, custom]);\n}\n\n/**\n * Header/query map rows: name, literal-or-secret mode, value. Unnamed rows\n * are editor-local; a rename onto an existing name is flagged, not applied.\n */\nfunction headerMapEditor(\n initial: HeaderMap | undefined,\n secretNames: string[],\n labels: { add: string; name: string },\n onChange: (next: HeaderMap | undefined) => void\n): HTMLElement {\n let current: HeaderMap = clone(initial ?? {});\n const pending: { value: HeaderValue }[] = [];\n const element = h(\"div\", { class: \"wgd-record wgd-headers\" });\n const duplicate = diagnosticLine(undefined);\n\n function commit(next: HeaderMap): void {\n current = next;\n onChange(Object.keys(current).length > 0 ? current : undefined);\n render();\n }\n function flagDuplicate(name: string): void {\n duplicate.hidden = false;\n duplicate.textContent = `'${name}' is already used; pick another ${labels.name} name.`;\n }\n function valueControl(value: HeaderValue, onValue: (next: HeaderValue) => void): HTMLElement[] {\n const isSecret = isPlainObject(value);\n const mode = select(\n [{ value: \"literal\" }, { value: \"secret\" }],\n isSecret ? \"secret\" : \"literal\",\n \"wgd-select wgd-attr-mode\",\n (next) => onValue(next === \"secret\" ? { secret: secretNames[0] ?? \"\" } : \"\")\n );\n if (isSecret) {\n const names = secretNames.includes(value.secret) ? secretNames : [value.secret, ...secretNames];\n const picker = select(\n names.map((n) => ({ value: n, label: n === \"\" ? \"(pick a secret)\" : n })),\n value.secret,\n \"wgd-select wgd-secret\",\n (next) => onValue({ secret: next })\n );\n return [mode, picker];\n }\n return [mode, textInput(value, \"wgd-input wgd-rec-value\", onValue, \"value\")];\n }\n function render(): void {\n element.replaceChildren();\n duplicate.hidden = true;\n for (const [name, value] of Object.entries(current)) {\n const nameInput = textInput(name, \"wgd-input wgd-rec-key\", (next) => {\n if (next === name) return;\n if (next === \"\" || Object.hasOwn(current, next)) { flagDuplicate(next || \"(empty)\"); return; }\n const entries = Object.entries(current).map(([k, v]) => (k === name ? [next, v] : [k, v]));\n commit(Object.fromEntries(entries));\n }, labels.name);\n const controls = valueControl(value, (next) => commit({ ...current, [name]: next }));\n const remove = removeButton(() => {\n const { [name]: _gone, ...rest } = current;\n commit(rest);\n });\n element.append(h(\"div\", { class: \"wgd-rec-row\" }, [nameInput, ...controls, remove]));\n }\n pending.forEach((row, index) => {\n const nameInput = textInput(\"\", \"wgd-input wgd-rec-key\", (next) => {\n if (next === \"\") return;\n if (Object.hasOwn(current, next)) { flagDuplicate(next); return; }\n pending.splice(index, 1);\n commit({ ...current, [next]: row.value });\n }, labels.name);\n const controls = valueControl(row.value, (next) => { row.value = next; render(); });\n const remove = removeButton(() => { pending.splice(index, 1); render(); });\n element.append(h(\"div\", { class: \"wgd-rec-row wgd-rec-pending\" }, [nameInput, ...controls, remove]));\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [labels.add]);\n add.addEventListener(\"click\", () => { pending.push({ value: \"\" }); render(); });\n element.append(h(\"div\", { class: \"wgd-row\" }, [add]), duplicate);\n }\n render();\n return element;\n}\n\n/** Prompt text: ordered literal/bind segments. */\nfunction segmentsEditor(initial: PromptSegment[], onChange: (next: PromptSegment[]) => void): HTMLElement {\n let current = clone(initial);\n const element = h(\"div\", { class: \"wgd-record wgd-segments\" });\n function commit(next: PromptSegment[]): void {\n current = next;\n onChange(current);\n render();\n }\n function render(): void {\n element.replaceChildren();\n current.forEach((segment, index) => {\n const isBind = typeof segment !== \"string\";\n const mode = select([{ value: \"text\" }, { value: \"bind\" }], isBind ? \"bind\" : \"text\", \"wgd-select wgd-attr-mode\", (next) => {\n const copy = [...current];\n copy[index] = next === \"bind\" ? { bind: \".\" } : \"\";\n commit(copy);\n });\n const value = textInput(\n isBind ? segment.bind : segment,\n \"wgd-input wgd-rec-value\",\n (next) => {\n const copy = [...current];\n copy[index] = isBind ? { bind: next } : next;\n commit(copy);\n },\n isBind ? \"data path\" : \"text\"\n );\n const remove = removeButton(() => commit(current.filter((_, i) => i !== index)));\n element.append(h(\"div\", { class: \"wgd-rec-row\" }, [mode, value, remove]));\n });\n const addText = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ text\"]);\n addText.addEventListener(\"click\", () => commit([...current, \"\"]));\n const addBind = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ bind\"]);\n addBind.addEventListener(\"click\", () => commit([...current, { bind: \".\" }]));\n element.append(h(\"div\", { class: \"wgd-row\" }, [addText, addBind]));\n }\n render();\n return element;\n}\n\nexport interface DefinitionEditor {\n element: HTMLElement;\n getValue(): ActionDefinition;\n setValue(definition: ActionDefinition): void;\n}\n\n/** Editor for one action definition, either kind. */\nexport function createDefinitionEditor(\n initial: ActionDefinition | undefined,\n ctx: ActionEditorContext,\n onChange: (definition: ActionDefinition) => void\n): DefinitionEditor {\n let current: ActionDefinition = clone(initial ?? starterPromptDefinition());\n const headEl = h(\"div\", { class: \"wgd-action-head\" });\n const schemasEl = h(\"div\", { class: \"wgd-action-schemas\" });\n const mapsEl = h(\"div\", { class: \"wgd-action-maps\" });\n const element = h(\"div\", { class: \"wgd-action-definition\" }, [headEl, schemasEl, mapsEl]);\n\n /** The live http definition; handlers call this at event time, never a render-time copy. */\n function http(): HttpActionDefinition {\n return current as HttpActionDefinition;\n }\n\n function commit(next: ActionDefinition, rerender: \"all\" | \"schemas\" | \"none\"): void {\n current = next;\n onChange(clone(current));\n if (rerender === \"all\") render();\n else if (rerender === \"schemas\") renderSchemas();\n }\n\n function schemaSection(title: string, which: \"input\" | \"output\"): HTMLElement {\n const builder = createSchemaBuilder(http()[which] as DataSchema, (schema) => {\n commit({ ...http(), [which]: schema ?? { type: \"object\" } }, \"none\");\n });\n const parts: (Node | string)[] = [label(title), builder.element];\n const shared = ctx.schemas ?? [];\n if (shared.length > 0) {\n // Actions store their schemas INLINE (a contract must not drift when a\n // shared schema is edited), so this is a copy \u2014 and says so.\n const copyFrom = select(\n [{ value: \"\", label: \"copy a shared schema into this action\u2026\" }, ...shared.map((s) => ({ value: s.name }))],\n \"\",\n \"wgd-select\",\n (name) => {\n const entry = shared.find((s) => s.name === name);\n if (entry) commit({ ...http(), [which]: clone(entry.schema) }, \"schemas\");\n }\n );\n parts.push(h(\"div\", { class: \"wgd-row\" }, [copyFrom, label(\"(a copy \u2014 later edits to the shared schema do not follow)\")]));\n }\n return h(\"div\", { class: \"wgd-action-schema\" }, parts);\n }\n\n function renderHead(): void {\n headEl.replaceChildren();\n const kind = select(\n [{ value: \"prompt\", label: \"prompt \u2014 propose a message\" }, { value: \"http\", label: \"http \u2014 call an API\" }],\n current.kind,\n \"wgd-select wgd-action-kind\",\n (next) => commit(next === \"http\" ? starterHttpDefinition() : starterPromptDefinition(), \"all\")\n );\n if (current.kind === \"prompt\") {\n headEl.append(\n h(\"div\", { class: \"wgd-row\" }, [label(\"Kind\"), kind]),\n label(\"Message (literals and bound values; the user reviews and sends it)\"),\n segmentsEditor(current.text, (text) => commit({ kind: \"prompt\", text }, \"none\"))\n );\n return;\n }\n const method = select(HTTP_METHODS.map((m) => ({ value: m })), current.method, \"wgd-select\", (next) =>\n commit({ ...http(), method: next as HttpActionDefinition[\"method\"] }, \"none\")\n );\n // Kind and method describe one thing \u2014 what call this is \u2014 so they share a row.\n const url = textInput(current.url, \"wgd-input wgd-action-url\", (next) => commit({ ...http(), url: next }, \"none\"), \"https://\u2026\");\n headEl.append(\n h(\"div\", { class: \"wgd-row\" }, [label(\"Kind\"), kind, label(\"Method\"), method]),\n h(\"label\", { class: \"wgd-field\" }, [label(\"URL (https, fixed)\"), url])\n );\n }\n\n function renderSchemas(): void {\n schemasEl.replaceChildren();\n if (current.kind !== \"http\") return;\n schemasEl.append(\n schemaSection(\"Input schema (arguments; GET \u2192 query, POST \u2192 JSON body)\", \"input\"),\n schemaSection(\"Output schema (the response must satisfy it)\", \"output\")\n );\n }\n\n function renderMaps(): void {\n mapsEl.replaceChildren();\n if (current.kind !== \"http\") return;\n const secretNames = ctx.secretNames ?? [];\n mapsEl.append(\n label(\"Headers\"),\n headerMapEditor(current.headers, secretNames, { add: \"+ header\", name: \"header\" }, (headers) => {\n const { headers: _h, ...rest } = http();\n commit(headers === undefined ? rest : { ...rest, headers }, \"none\");\n }),\n label(\"Fixed query parameters\"),\n headerMapEditor(current.query, secretNames, { add: \"+ parameter\", name: \"parameter\" }, (query) => {\n const { query: _q, ...rest } = http();\n commit(query === undefined ? rest : { ...rest, query }, \"none\");\n })\n );\n }\n\n function render(): void {\n renderHead();\n renderSchemas();\n renderMaps();\n }\n render();\n return {\n element,\n getValue: () => clone(current),\n setValue(definition) {\n current = clone(definition);\n render();\n }\n };\n}\n\nexport interface BindingEditorContext extends ActionEditorContext {\n /** Shared actions offered by name. */\n actions?: StoredAction[];\n /** Data paths in scope at the bound element, offered as completions. */\n scopePaths?: string[];\n /** The widget's effective data schema (inline or resolved ref) \u2014 drives output-map targets and type checks. */\n getDataSchema?: () => DataSchema | undefined;\n /** `load` bindings: http GET only, no prompt. */\n loadOnly?: boolean;\n}\n\nexport interface BindingEditor {\n element: HTMLElement;\n setValue(binding: ActionBinding | undefined): void;\n}\n\n/** Editor for a binding: none / shared / inline, input mapping, output mode. */\nexport function createBindingEditor(\n initial: ActionBinding | undefined,\n ctx: BindingEditorContext,\n onChange: (binding: ActionBinding | undefined) => void\n): BindingEditor {\n let current: ActionBinding | undefined = initial === undefined ? undefined : clone(initial);\n const headEl = h(\"div\", { class: \"wgd-binding-head\" });\n const inputEl = h(\"div\", { class: \"wgd-binding-input\" });\n const outputEl = h(\"div\", { class: \"wgd-binding-output\" });\n const element = h(\"div\", { class: \"wgd-binding\" }, [headEl, inputEl, outputEl]);\n\n function definitionOf(binding: ActionBinding | undefined): ActionDefinition | undefined {\n if (binding === undefined) return undefined;\n if (isRefBinding(binding)) return (ctx.actions ?? []).find((a) => a.name === binding.ref)?.definition;\n return binding.definition;\n }\n const inputOf = (): InputMapping => clone(current?.input ?? {});\n const outputOf = (): OutputBinding => clone(current?.output ?? {});\n\n function commit(next: ActionBinding | undefined, rerender: \"all\" | \"io\" | \"input\" | \"output\" | \"none\"): void {\n current = next;\n onChange(next === undefined ? undefined : clone(next));\n if (rerender === \"all\") render();\n else if (rerender === \"io\") { renderInput(); renderOutput(); }\n else if (rerender === \"input\") renderInput();\n else if (rerender === \"output\") renderOutput();\n }\n\n function withMapping(binding: ActionBinding, input: InputMapping | undefined, output: OutputBinding | undefined): ActionBinding {\n const head: { ref: string } | { definition: ActionDefinition } = isRefBinding(binding)\n ? { ref: binding.ref }\n : { definition: binding.definition };\n return {\n ...head,\n ...(input !== undefined && Object.keys(input).length > 0 ? { input } : {}),\n ...(output !== undefined && Object.keys(output).length > 0 ? { output } : {})\n };\n }\n\n /** Helper completions are complete paths: the scope markers alone, plus every root path. */\n function helperPaths(): string[] {\n const root = allPaths(ctx.getDataSchema?.()).map((p) => `$root.${p}`);\n return [\"$index\", \"$parent\", \"$root\", ...root];\n }\n\n function renderHead(): void {\n headEl.replaceChildren();\n const shared = (ctx.actions ?? []).filter((a) => !ctx.loadOnly || (a.definition.kind === \"http\" && a.definition.method === \"GET\"));\n const mode = current === undefined ? \"none\" : isRefBinding(current) ? \"shared\" : \"inline\";\n const modeSelect = select(\n [{ value: \"none\", label: ctx.loadOnly ? \"no load action\" : \"no action\" }, { value: \"shared\", label: \"shared action\" }, { value: \"inline\", label: \"inline definition\" }],\n mode,\n \"wgd-select wgd-binding-mode\",\n (next) => {\n if (next === \"none\") commit(undefined, \"all\");\n else if (next === \"shared\") commit({ ref: shared[0]?.name ?? \"\" }, \"all\");\n else commit({ definition: starterHttpDefinition() }, \"all\");\n }\n );\n headEl.append(h(\"div\", { class: \"wgd-row\" }, [modeSelect]));\n if (current === undefined) return;\n if (isRefBinding(current)) {\n const ref = current.ref;\n const names = shared.map((a) => a.name);\n const options = (names.includes(ref) ? names : [ref, ...names]).map((n) => ({ value: n, label: n === \"\" ? \"(pick an action)\" : names.includes(n) ? n : `${n} (unknown)` }));\n const refSelect = select(options, ref, \"wgd-select wgd-binding-ref\", (next) =>\n commit(withMapping({ ref: next }, inputOf(), outputOf()), \"io\")\n );\n headEl.append(h(\"div\", { class: \"wgd-row\" }, [label(\"Action\"), refSelect]));\n return;\n }\n const editor = createDefinitionEditor(current.definition, ctx, (definition) => {\n // The definition's schemas drive the mapping rows; the head keeps focus.\n commit(withMapping({ definition }, inputOf(), outputOf()), \"io\");\n });\n headEl.append(editor.element);\n }\n\n function renderInput(): void {\n inputEl.replaceChildren();\n const definition = definitionOf(current);\n if (current === undefined || definition?.kind !== \"http\") return;\n const binding = current;\n // Input mapping: one row per declared field, each a data path or a constant.\n const properties = isPlainObject(definition.input.properties) ? Object.keys(definition.input.properties) : [];\n // No element scope supplied (the widget-level `load`): the root data paths ARE the scope.\n const scopePaths = ctx.scopePaths ?? allPaths(ctx.getDataSchema?.());\n const pathOptions = [...new Set([...scopePaths, ...helperPaths()])];\n const mapping = inputOf();\n const rows = properties.map((field) => {\n const value = mapping[field];\n const isConst = isPlainObject(value) && \"const\" in value;\n const kindSelect = select([{ value: \"path\" }, { value: \"const\" }], isConst ? \"const\" : \"path\", \"wgd-select wgd-attr-mode\", (next) => {\n commit(withMapping(binding, { ...inputOf(), [field]: next === \"const\" ? { const: \"\" } : field }, outputOf()), \"input\");\n });\n const onValue = (next: string): void => {\n const nextMapping = inputOf();\n if (isConst) {\n let literal: unknown;\n try { literal = JSON.parse(next); } catch { literal = next; }\n nextMapping[field] = { const: literal };\n } else if (next === \"\") {\n delete nextMapping[field];\n } else {\n nextMapping[field] = next;\n }\n commit(withMapping(binding, nextMapping, outputOf()), \"none\");\n };\n const valueInput = isConst\n ? textInput(JSON.stringify(value.const), \"wgd-input wgd-rec-value\", onValue, \"JSON literal\")\n : pathSelect(typeof value === \"string\" ? value : \"\", pathOptions, onValue, \"data path\");\n return h(\"div\", { class: \"wgd-rec-row\" }, [h(\"span\", { class: \"wgd-rec-key wgd-binding-field\" }, [field]), kindSelect, valueInput]);\n });\n inputEl.append(\n label(\"Input mapping (field \u2190 data path or constant)\"),\n properties.length > 0 ? h(\"div\", { class: \"wgd-record\" }, rows) : h(\"div\", { class: \"wgd-diagnostic\" }, [\"The input schema declares no properties.\"])\n );\n }\n\n function renderOutput(): void {\n outputEl.replaceChildren();\n const definition = definitionOf(current);\n if (current === undefined || definition?.kind !== \"http\") return;\n const binding = current;\n const output = outputOf();\n const mode = output.mode ?? \"merge\";\n const modeSel = select(OUTPUT_MODES.map((m) => ({ value: m })), mode, \"wgd-select\", (next) => {\n const nextOutput: OutputBinding = { ...outputOf(), mode: next as OutputMode };\n if (next !== \"patch\") delete nextOutput.path;\n commit(withMapping(binding, inputOf(), nextOutput), \"output\");\n });\n const outputRow: (Node | string)[] = [label(\"Output\"), modeSel];\n if (mode === \"patch\") {\n outputRow.push(textInput(output.path ?? \"\", \"wgd-input\", (next) => {\n commit(withMapping(binding, inputOf(), { ...outputOf(), path: next }), \"output\");\n }, \"data path to write at\"));\n }\n outputEl.append(h(\"div\", { class: \"wgd-row\" }, outputRow));\n outputEl.append(outputMapEditor(definition, output, (map) => {\n const nextOutput = outputOf();\n if (map === undefined) delete nextOutput.map; else nextOutput.map = map;\n commit(withMapping(binding, inputOf(), nextOutput), \"none\");\n }));\n }\n\n /**\n * Output projection rows: target (a widget data path, relative to the\n * patch path when that mode is on) \u2190 source (a response path). Both\n * inputs complete from the respective schemas, and a type mismatch is\n * flagged here \u2014 at execution it would only surface as INVALID_TYPE.\n * Unnamed rows are editor-local until they get a target.\n */\n function outputMapEditor(\n definition: HttpActionDefinition,\n output: OutputBinding,\n onMap: (map: Record<string, string> | undefined) => void\n ): HTMLElement {\n const container = h(\"div\", { class: \"wgd-record wgd-output-map\" });\n let map: Record<string, string> = clone(output.map ?? {});\n const pending: { source: string }[] = [];\n const widgetSchema = ctx.getDataSchema?.();\n const mode = output.mode ?? \"merge\";\n const base = mode === \"patch\" && output.path ? output.path : \"\";\n // A list on either side is spoken to per ITEM: the projection maps each\n // element of a list response, and lands each in a list target \u2014 so the\n // columns and the type check work over the item schemas.\n const targetSide = base === \"\" ? widgetSchema : schemaAt(widgetSchema, base);\n const targetRoot = itemSchema(targetSide);\n // \".\" is always a valid target \u2014 the selection row \u2014 whatever the widget's shape.\n const targetOptions = [\".\", ...allPaths(targetRoot)];\n // A \".\" row SELECTS a sub-value the other rows then map (an enveloped\n // list: { \".\": \"data\", ask: \"ask\" }); the source column and the type\n // check follow that selection.\n const selectedSchema = (): unknown =>\n map[\".\"] === undefined ? definition.output : schemaAt(definition.output, map[\".\"]);\n const perItemResponse = (): boolean => schemaType(selectedSchema()) === \"array\";\n const sourceRoot = (): unknown => itemSchema(selectedSchema());\n const selectOptions = [\".\", ...allPaths(definition.output)];\n const mismatch = diagnosticLine(undefined);\n mismatch.classList.add(\"wgd-type-mismatch\");\n\n function commitMap(next: Record<string, string>): void {\n map = next;\n onMap(Object.keys(map).length > 0 ? map : undefined);\n render();\n }\n function flag(text: string): void {\n mismatch.hidden = false;\n mismatch.textContent = text;\n }\n function targetControl(target: string, onTarget: (next: string) => void): HTMLElement {\n const control = pathSelect(target, targetOptions, onTarget, \"target data path\", \"wgd-input wgd-rec-key\");\n control.classList.add(\"wgd-map-target\");\n return control;\n }\n function render(): void {\n container.replaceChildren();\n const problems: string[] = [];\n // A per-item projection yields a LIST; merge needs an object on both\n // sides and would only fail at execution.\n const mapped = Object.keys(map).filter((key) => key !== \".\");\n if (perItemResponse() && mode === \"merge\" && mapped.length > 0) {\n problems.push(\"a list projects per item \u2014 use replace or patch; merge needs an object.\");\n }\n const sourceOptions = [\".\", ...allPaths(sourceRoot())];\n for (const [target, source] of Object.entries(map)) {\n // The \".\" row selects against the response root; other rows map the selection.\n const options = target === \".\" ? selectOptions : sourceOptions;\n const conflict =\n target === \".\"\n ? undefined\n : schemaMismatch(schemaAt(sourceRoot(), source), schemaAt(targetRoot, target));\n if (conflict) {\n problems.push(`'${source}' is ${conflict.source} in the response but '${base ? `${base}.` : \"\"}${target}' is ${conflict.target} in the widget schema`);\n }\n const targetInput = targetControl(target, (next) => {\n if (next === target) return;\n if (next === \"\" || Object.hasOwn(map, next)) { flag(`'${next || \"(empty)\"}' is already a projection target.`); return; }\n const entries = Object.entries(map).map(([k, v]) => (k === target ? [next, v] : [k, v]));\n commitMap(Object.fromEntries(entries));\n });\n const sourceInput = pathSelect(source, options, (next) => commitMap({ ...map, [target]: next }), \"response path\");\n sourceInput.classList.add(\"wgd-map-source\");\n const remove = removeButton(() => {\n const { [target]: _gone, ...rest } = map;\n commitMap(rest);\n });\n container.append(h(\"div\", { class: \"wgd-rec-row\" }, [targetInput, h(\"span\", { class: \"wgd-st-colon\" }, [\"\u2190\"]), sourceInput, remove]));\n }\n pending.forEach((row, index) => {\n const targetInput = targetControl(\"\", (next) => {\n if (next === \"\") return;\n if (Object.hasOwn(map, next)) { flag(`'${next}' is already a projection target.`); return; }\n pending.splice(index, 1);\n commitMap({ ...map, [next]: row.source });\n });\n const sourceInput = pathSelect(row.source, sourceOptions, (next) => { row.source = next; render(); }, \"response path\");\n sourceInput.classList.add(\"wgd-map-source\");\n const remove = removeButton(() => { pending.splice(index, 1); render(); });\n container.append(h(\"div\", { class: \"wgd-rec-row wgd-rec-pending\" }, [targetInput, h(\"span\", { class: \"wgd-st-colon\" }, [\"\u2190\"]), sourceInput, remove]));\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ projection\"]);\n add.addEventListener(\"click\", () => { pending.push({ source: \"\" }); render(); });\n mismatch.hidden = problems.length === 0;\n mismatch.textContent = problems.length === 0 ? \"\" : `Type mismatch: ${problems.join(\"; \")}.`;\n container.append(h(\"div\", { class: \"wgd-row\" }, [add]), mismatch);\n }\n render();\n return container;\n }\n\n function render(): void {\n renderHead();\n renderInput();\n renderOutput();\n }\n render();\n return {\n element,\n setValue(binding) {\n current = binding === undefined ? undefined : clone(binding);\n render();\n }\n };\n}\n", "/**\n * Template editing: a structured node tree and a JSON source pane \u2014 two\n * projections of one canonical model (the draft's template). The JSON\n * pane is parse-gated (invalid JSON never reaches the store; last valid\n * wins); structural edits from either side may still fail\n * `validateTemplate`, which surfaces as diagnostics pinned to the node\n * path without ever losing the draft.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { collectActionRefs } from \"@widgentic/core\";\nimport {\n CURRENCY_DISPLAYS,\n DATE_TOKENS,\n FORMAT_DECIMALS_MAX,\n FORMAT_DECIMALS_MIN,\n FORMAT_TYPES,\n activeTransform,\n isCurrencyDisplay,\n isFormatType\n} from \"@widgentic/core\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { WidgetTemplate } from \"@widgentic/core\";\nimport type { ActionBinding, StoredAction } from \"@widgentic/core\";\nimport { createBindingEditor } from \"./action-editor.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { collectPaths, itemSchema, schemaAt, schemaType } from \"./schema-paths.js\";\nimport { effectiveDataSchema } from \"./validate.js\";\nimport { diagnosticLine, fitSelect, h, menuButton, select } from \"./dom.js\";\nimport { createRecordEditor } from \"./record-editor.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\n\ntype Path = (string | number)[];\n\n/** What a data path is being used for \u2014 decides which paths are offered. */\ntype PathUse = \"bind\" | \"each\" | \"when\";\n\n/** Paths worth offering for a given use. */\nfunction pathOptions(scope: unknown, use: PathUse): string[] {\n // An ARRAY scope offers only itself: nothing but an index resolves inside\n // it, and its item's properties belong to the each that walks it.\n if (schemaType(scope) === \"array\") return [\".\"];\n const entries: { path: string; schema: unknown }[] = [];\n collectPaths(scope, \"\", entries);\n const scalars = new Set([\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"null\",\n undefined\n ]);\n const filtered = entries.filter(({ schema }) => {\n const type = schemaType(schema);\n if (use === \"each\") return type === \"array\";\n if (use === \"bind\") return scalars.has(type);\n return true; // `when` tests truthiness of anything\n });\n const paths = filtered.map((entry) => entry.path);\n // \".\" is the scope itself \u2014 the item inside an each over scalars.\n if (use !== \"each\" && scalars.has(schemaType(scope))) paths.unshift(\".\");\n return paths;\n}\n\n/**\n * Schema in effect inside `each: <path>` \u2014 the item schema of the array\n * that path resolves to. `schemaAt` does the walking, so `each: \".\"` over\n * a root-array schema scopes to its item like any other each.\n */\nfunction itemScope(scope: unknown, eachPath: string): unknown {\n const target = schemaAt(scope, eachPath);\n return schemaType(target) === \"array\" ? itemSchema(target) : undefined;\n}\n\nconst REMOVE = Symbol(\"remove\");\n\nfunction pathString(path: Path): string {\n let out = \"\";\n for (const step of path) {\n const segment = typeof step === \"number\" ? `children.${step}` : step;\n out = out === \"\" ? segment : `${out}.${segment}`;\n }\n return out;\n}\n\n/** Immutable set/remove at a node path (numbers index `children`). */\nfunction setNode(node: unknown, path: Path, next: unknown): unknown {\n if (path.length === 0) return next === REMOVE ? undefined : next;\n const [step, ...rest] = path as [string | number, ...Path];\n if (typeof step === \"number\") {\n if (!isPlainObject(node) || !Array.isArray(node.children)) return node;\n const children = [...(node.children as unknown[])];\n if (rest.length === 0 && next === REMOVE) {\n children.splice(step, 1);\n } else {\n children[step] = setNode(children[step], rest, next);\n }\n return { ...node, children };\n }\n if (!isPlainObject(node)) return node;\n if (rest.length === 0 && next === REMOVE) {\n const { [step]: _removed, ...remaining } = node;\n return remaining;\n }\n return { ...node, [step]: setNode(node[step], rest, next) };\n}\n\nfunction swapChildren(root: unknown, parent: Path, a: number, b: number): unknown {\n const holder = parent.length === 0 ? root : getNode(root, parent);\n if (!isPlainObject(holder) || !Array.isArray(holder.children)) return root;\n const children = [...(holder.children as unknown[])];\n if (a < 0 || b < 0 || a >= children.length || b >= children.length) return root;\n const [x, y] = [children[a], children[b]];\n children[a] = y;\n children[b] = x;\n const swapped = { ...holder, children };\n return parent.length === 0 ? swapped : setNode(root, parent, swapped);\n}\n\nfunction getNode(node: unknown, path: Path): unknown {\n let current = node;\n for (const step of path) {\n if (!isPlainObject(current)) return undefined;\n current =\n typeof step === \"number\"\n ? Array.isArray(current.children)\n ? (current.children as unknown[])[step]\n : undefined\n : current[step];\n }\n return current;\n}\n\nconst NODE_PRESETS: Record<string, () => unknown> = {\n text: () => \"text\",\n bind: () => ({ bind: \".\" }),\n element: () => ({ tag: \"div\", children: [] }),\n each: () => ({ each: \".\", template: \"item\" }),\n when: () => ({ when: \".\", template: \"shown\" })\n};\n\n/** What element bindings can reach: shared actions, secrets, schemas. */\nexport interface TemplateActionContext {\n actions: StoredAction[];\n secretNames: string[];\n schemas: SchemaEntry[];\n}\n\nexport interface TemplatePanelOptions {\n actionContext?: TemplateActionContext;\n}\n\n/** A bound attribute value, narrowed once per attribute row (a type literal: comparable with the raw record). */\ntype AttrBind = {\n bind: string;\n prefix?: string;\n map?: Record<string, string>;\n default?: string;\n format?: Record<string, unknown>;\n};\n\nexport function mountTemplatePanel(\n store: DraftStore,\n refreshers: ((draft: WidgetDraft) => void)[],\n options: TemplatePanelOptions = {}\n): {\n element: HTMLElement;\n refresh(draft: WidgetDraft, diagnostics: DesignerDiagnostics): void;\n dispose(): void;\n} {\n const actionContext: TemplateActionContext = options.actionContext ?? { actions: [], secretNames: [], schemas: [] };\n // Shared refs the draft binds that no supplied action answers to.\n let unknownRefs = new Set<string>();\n const treeHost = h(\"div\", { class: \"wgd-tree\" });\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", {\n class: \"wgd-textarea wgd-template-json\",\n rows: \"14\",\n spellcheck: \"false\"\n });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n attachJsonHighlight(jsonArea);\n jsonWrap.hidden = true;\n\n const treeTab = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Tree\"]);\n const jsonTab = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"JSON\"]);\n treeTab.addEventListener(\"click\", () => {\n treeHost.hidden = false;\n jsonWrap.hidden = true;\n });\n jsonTab.addEventListener(\"click\", () => {\n treeHost.hidden = true;\n jsonWrap.hidden = false;\n });\n\n const templateDiag = diagnosticLine(undefined);\n const element = h(\"details\", { class: \"wgd-section\", open: \"\" }, [\n h(\"summary\", { class: \"wgd-section-title\" }, [\"Template\"]),\n h(\"div\", { class: \"wgd-section-body\" }, [\n h(\"div\", { class: \"wgd-row\" }, [treeTab, jsonTab]),\n templateDiag,\n treeHost,\n jsonWrap\n ])\n ]);\n\n function commit(next: unknown): void {\n store.update((draft) => ({ ...draft, template: next as WidgetTemplate }));\n }\n\n function commitAt(path: Path, next: unknown): void {\n commit(setNode(store.get().template, path, next));\n }\n\n // --- JSON pane: parse-gated projection --------------------------------\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n commit(parsed);\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid JSON (template keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n });\n\n // --- Tree editor -------------------------------------------------------\n function changeInput(\n value: string,\n onCommit: (value: string) => void,\n className = \"wgd-input wgd-node-value\"\n ): HTMLInputElement {\n const input = h(\"input\", { type: \"text\", class: className });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n /**\n * The compact format editor shared by text binds and attribute binds:\n * a type select revealing that type's fields. Switching type commits a\n * COMPLETE spec (a real currency code, a real pattern) so the draft is\n * never momentarily invalid \u2014 the same discipline the binding editor's\n * unnamed rows follow.\n */\n function formatEditor(\n spec: Record<string, unknown> | undefined,\n onCommit: (next: Record<string, unknown> | undefined) => void\n ): HTMLElement[] {\n const active = spec !== undefined && isFormatType(spec.type) ? spec : undefined;\n const typeSelect = select(\n [{ value: \"none\", label: \"raw\" }, ...FORMAT_TYPES.map((value) => ({ value }))],\n active === undefined ? \"none\" : (active.type as string),\n \"wgd-select wgd-format-type\",\n (next) => {\n // Switching type commits a COMPLETE spec, so the draft is never\n // momentarily invalid.\n if (next === \"number\") onCommit({ type: \"number\", decimals: 2 });\n else if (next === \"currency\") onCommit({ type: \"currency\", currency: \"USD\", decimals: 2 });\n else if (next === \"date\") onCommit({ type: \"date\", pattern: \"yyyy-MM-dd\" });\n else onCommit(undefined);\n },\n \"Present the bound value as a number, a currency amount or a date\"\n );\n if (active === undefined) return [typeSelect];\n\n const decimalsInput = (): HTMLInputElement => {\n const input = changeInput(\n active.decimals === undefined ? \"\" : String(active.decimals),\n (next) => {\n const { decimals: _gone, ...rest } = active;\n const parsed = Number(next);\n onCommit(next === \"\" ? rest : { ...rest, decimals: Number.isFinite(parsed) ? parsed : next });\n },\n \"wgd-input wgd-format-decimals\"\n );\n input.placeholder = \"dec\";\n input.title = `Decimal places (${FORMAT_DECIMALS_MIN}-${FORMAT_DECIMALS_MAX})`;\n return input;\n };\n\n if (active.type === \"currency\") {\n const code = changeInput(\n typeof active.currency === \"string\" ? active.currency : \"\",\n (next) => onCommit({ ...active, currency: next.toUpperCase() }),\n \"wgd-input wgd-format-currency\"\n );\n code.placeholder = \"CUR\";\n code.title = \"ISO-4217 currency code, e.g. COP\";\n const display = select(\n CURRENCY_DISPLAYS.map((value) => ({ value })),\n isCurrencyDisplay(active.currencyDisplay) ? active.currencyDisplay : CURRENCY_DISPLAYS[0],\n \"wgd-select wgd-format-display\",\n (next) => onCommit({ ...active, currencyDisplay: next }),\n \"How the currency names itself\"\n );\n return [typeSelect, code, decimalsInput(), display];\n }\n if (active.type === \"number\") return [typeSelect, decimalsInput()];\n const pattern = changeInput(\n typeof active.pattern === \"string\" ? active.pattern : \"\",\n (next) => onCommit({ ...active, pattern: next }),\n \"wgd-input wgd-format-pattern\"\n );\n pattern.placeholder = \"pattern\";\n pattern.title = `Date pattern from ${DATE_TOKENS.join(\" \")} plus separators, e.g. dd-MM-yyyy HH:mm`;\n return [typeSelect, pattern];\n }\n\n\n /**\n * Collapse state, keyed by node path so it survives the full re-render\n * every draft edit triggers. Paths shift when siblings move or vanish \u2014\n * an accepted approximation, exactly like text-editor fold markers.\n */\n const collapsedPaths = new Set<string>();\n\n /**\n * One node = one header row: chevron, badge, the node's own value\n * control(s), then add/move/remove icons (revealed on hover). Sub-\n * structure (attrs, children, slots) nests below and folds away when\n * the node is collapsed; a muted summary keeps the hidden shape legible.\n */\n function nodeShell(\n /** Omitted for elements \u2014 their tag select already names the node. */\n badge: string | undefined,\n path: Path,\n inline: (Node | string)[],\n body: (Node | string)[],\n errorText: string | undefined,\n removable: boolean,\n moves?: { parent: Path; index: number; count: number },\n extras?: { icons?: (Node | string)[]; summary?: string }\n ): HTMLElement {\n const key = pathString(path);\n const collapsible = body.length > 0;\n const isCollapsed = collapsible && collapsedPaths.has(key);\n let chevron: HTMLElement;\n if (collapsible) {\n chevron = h(\n \"button\",\n {\n class: \"wgd-chevron\",\n type: \"button\",\n title: isCollapsed ? \"Expand\" : \"Collapse\"\n },\n [isCollapsed ? \"\u25B8\" : \"\u25BE\"]\n );\n chevron.addEventListener(\"click\", () => {\n if (isCollapsed) collapsedPaths.delete(key);\n else collapsedPaths.add(key);\n renderTree();\n });\n } else {\n // Every row reserves the chevron column so values align.\n chevron = h(\"span\", { class: \"wgd-chevron wgd-chevron-none\" });\n }\n const header: (Node | string)[] =\n badge === undefined\n ? [chevron, ...inline]\n : [chevron, h(\"span\", { class: \"wgd-node-badge\" }, [badge]), ...inline];\n if (isCollapsed && extras?.summary !== undefined) {\n header.push(h(\"span\", { class: \"wgd-node-summary\" }, [extras.summary]));\n }\n const icons: (Node | string)[] = [...(extras?.icons ?? [])];\n if (moves && moves.count > 1) {\n if (moves.index > 0) {\n const up = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Move up\" }, [\"\u2191\"]);\n up.addEventListener(\"click\", () =>\n commit(swapChildren(store.get().template, moves.parent, moves.index, moves.index - 1))\n );\n icons.push(up);\n }\n if (moves.index < moves.count - 1) {\n const down = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Move down\" }, [\"\u2193\"]);\n down.addEventListener(\"click\", () =>\n commit(swapChildren(store.get().template, moves.parent, moves.index, moves.index + 1))\n );\n icons.push(down);\n }\n }\n if (removable) {\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () =>\n path.length === 0 ? commit(\"\") : commitAt(path, REMOVE)\n );\n icons.push(remove);\n }\n if (icons.length > 0) {\n header.push(h(\"span\", { class: \"wgd-node-icons\" }, icons));\n }\n const children: (Node | string)[] = [h(\"div\", { class: \"wgd-node-row\" }, header)];\n // Diagnostics stay visible even on a collapsed node \u2014 folding must\n // never hide an error.\n if (errorText !== undefined) children.push(diagnosticLine(errorText));\n if (!isCollapsed) children.push(...body);\n return h(\"div\", { class: \"wgd-node\", \"data-path\": key }, children);\n }\n\n /** Tags the built-in styles and typical widget markup actually use. */\n const TAG_OPTIONS = [\n \"div\", \"span\", \"p\", \"section\", \"article\", \"header\", \"footer\",\n \"h1\", \"h2\", \"h3\", \"h4\", \"strong\", \"em\", \"small\", \"code\", \"pre\",\n \"ul\", \"ol\", \"li\", \"dl\", \"dt\", \"dd\",\n \"table\", \"thead\", \"tbody\", \"tr\", \"th\", \"td\",\n \"img\", \"a\", \"figure\", \"figcaption\", \"hr\", \"br\", \"label\"\n ];\n\n /**\n * Data-path control. With a schema in scope it is a select of the paths\n * that scope actually offers (plus the current value if it is off-schema,\n * and a custom escape); without one it stays a free-text input.\n */\n function pathControl(\n value: string,\n scope: unknown,\n use: PathUse,\n onCommit: (path: string) => void,\n className = \"wgd-input wgd-node-value\"\n ): HTMLElement {\n const options = isPlainObject(scope) ? pathOptions(scope, use) : [];\n if (options.length === 0) {\n return changeInput(value, onCommit, className);\n }\n const select = h(\"select\", { class: \"wgd-select wgd-path\" });\n const known = options.includes(value);\n for (const option of known ? options : [value, ...options]) {\n select.append(\n h(\"option\", { value: option }, [\n option === value && !known ? `${option} (off-schema)` : option\n ])\n );\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = value;\n fitSelect(select);\n const custom = changeInput(value, onCommit, className);\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(select.value);\n });\n // The wrap carries the row-shape marker (e.g. wgd-attr-value) so rows\n // read the same whether the value is a select or free text.\n const marker = className.includes(\"wgd-attr-value\") ? \" wgd-attr-value\" : \"\";\n return h(\"span\", { class: `wgd-pathwrap${marker}` }, [select, custom]);\n }\n\n /**\n * An `each` node's optional key: the item path that identifies a row, so\n * a reordered list patches by identity. Completions are the item scope's\n * bind paths; the empty choice (or an emptied input) removes the key.\n */\n function keyControl(\n value: string | undefined,\n scope: unknown,\n onCommit: (key: string | undefined) => void\n ): HTMLElement {\n const current = value ?? \"\";\n const commit = (next: string) => onCommit(next === \"\" ? undefined : next);\n const title = \"Optional item key (e.g. id): a reordered list keeps each item's state\";\n const options = isPlainObject(scope) ? pathOptions(scope, \"bind\") : [];\n if (options.length === 0) {\n const input = changeInput(current, commit, \"wgd-input wgd-each-key\");\n input.placeholder = \"key path\";\n input.title = title;\n return input;\n }\n const select = h(\"select\", { class: \"wgd-select wgd-each-key\", title });\n const known = current === \"\" || options.includes(current);\n select.append(h(\"option\", { value: \"\" }, [\"no key\"]));\n for (const option of known ? options : [current, ...options]) {\n select.append(\n h(\"option\", { value: option }, [option === current && !known ? `${option} (off-schema)` : option])\n );\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = current;\n fitSelect(select);\n const custom = changeInput(current, commit, \"wgd-input wgd-each-key\");\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n commit(select.value);\n });\n return h(\"span\", { class: \"wgd-pathwrap\" }, [select, custom]);\n }\n\n function tagControl(tag: string, onCommit: (tag: string) => void): HTMLElement {\n const select = h(\"select\", { class: \"wgd-select wgd-tag\" });\n const options = TAG_OPTIONS.includes(tag) ? TAG_OPTIONS : [tag, ...TAG_OPTIONS];\n for (const option of options) {\n select.append(h(\"option\", { value: option }, [option]));\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = tag;\n fitSelect(select);\n const custom = changeInput(tag, onCommit, \"wgd-input wgd-tag-custom\");\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(select.value);\n });\n return h(\"span\", { class: \"wgd-tagwrap\" }, [select, custom]);\n }\n\n function slotEditor(\n label: string,\n parentPath: Path,\n slot: \"template\" | \"empty\" | \"else\",\n node: unknown,\n required: boolean,\n errorPath: string | undefined,\n scope: unknown\n ): HTMLElement {\n const slotPath = [...parentPath, slot];\n if (node === undefined) {\n const menu = menuButton(\n `+ ${label}`,\n `Set '${label}' to a node`,\n Object.keys(NODE_PRESETS),\n (name) => {\n const preset = NODE_PRESETS[name];\n if (preset) commitAt(slotPath, preset());\n }\n );\n return required\n ? h(\"div\", { class: \"wgd-slot\" }, [\n diagnosticLine(`Missing required '${label}'.`),\n menu\n ])\n : h(\"div\", { class: \"wgd-slot wgd-slot-unset\" }, [menu]);\n }\n return h(\"div\", { class: \"wgd-slot\" }, [\n h(\"span\", { class: \"wgd-slot-label\" }, [label]),\n renderNode(node, slotPath, errorPath, !required, undefined, scope)\n ]);\n }\n\n function renderNode(\n node: unknown,\n path: Path,\n errorPath: string | undefined,\n removable = true,\n moves?: { parent: Path; index: number; count: number },\n scope?: unknown\n ): HTMLElement {\n const here = pathString(path);\n const errorHere =\n errorPath !== undefined &&\n (errorPath === here ||\n ((errorPath.startsWith(here === \"\" ? \"attrs.\" : `${here}.attrs.`) ||\n errorPath.startsWith(here === \"\" ? \"action\" : `${here}.action`)) &&\n isPlainObject(node) &&\n typeof node.tag === \"string\"))\n ? currentError\n : undefined;\n\n if (typeof node === \"string\") {\n return nodeShell(\n \"text\",\n path,\n [changeInput(node, (value) => commitAt(path, value))],\n [],\n errorHere,\n removable,\n moves\n );\n }\n if (!isPlainObject(node)) {\n return nodeShell(\n \"invalid\",\n path,\n [h(\"code\", undefined, [JSON.stringify(node)])],\n [],\n errorHere ?? \"Not a template node.\",\n removable,\n moves\n );\n }\n if (typeof node.bind === \"string\") {\n const bind = node.bind;\n const transform = activeTransform(node);\n const bindFormat = isPlainObject(node.format) ? node.format : undefined;\n const bindMap = isPlainObject(node.map) ? (node.map as Record<string, string>) : undefined;\n // A text bind carries `map` (value \u2192 authored label) or `format`; the\n // other control hides while one is active, mirroring the validator.\n // `prefix` is attribute-only and is not offered here.\n const withBind = (extra: Record<string, unknown>): Record<string, unknown> => ({ bind, ...extra });\n const inline: (Node | string)[] = [\n pathControl(bind, scope, \"bind\", (value) => commitAt(path, { ...node, bind: value }))\n ];\n if (transform === undefined || transform === \"format\") {\n inline.push(\n ...formatEditor(bindFormat, (next) => commitAt(path, next === undefined ? { bind } : withBind({ format: next })))\n );\n }\n const icons: (Node | string)[] = [];\n if (transform === undefined) {\n const addMap = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Map values to authored labels (e.g. status \u2192 text)\" },\n [\"map\"]\n );\n addMap.addEventListener(\"click\", () => commitAt(path, withBind({ map: {} })));\n icons.push(addMap);\n }\n const body: (Node | string)[] = [];\n if (transform === \"map\") {\n const mapEditor = createRecordEditor(\n bindMap,\n { key: \"data value\", value: \"authored label\", add: \"+ mapping\" },\n (nextMap) => commitAt(path, nextMap === undefined ? { bind } : withBind({ map: nextMap, ...(typeof node.default === \"string\" ? { default: node.default } : {}) }))\n );\n const defaultInput = changeInput(\n typeof node.default === \"string\" ? node.default : \"\",\n (next) => commitAt(path, withBind({ map: bindMap ?? {}, ...(next === \"\" ? {} : { default: next }) })),\n \"wgd-input wgd-attr-map-default\"\n );\n defaultInput.placeholder = \"default (on miss)\";\n body.push(\n h(\"div\", { class: \"wgd-attr-map\" }, [\n mapEditor.element,\n h(\"div\", { class: \"wgd-rec-row\" }, [h(\"span\", { class: \"wgd-st-colon\" }, [\"\u21B3\"]), defaultInput])\n ])\n );\n }\n return nodeShell(\"bind\", path, inline, body, errorHere, removable, moves, icons.length > 0 ? { icons } : undefined);\n }\n if (typeof node.each === \"string\") {\n const each = node.each;\n const { each: _each, key: _key, ...rest } = node;\n return nodeShell(\n \"each\",\n path,\n [\n pathControl(each, scope, \"each\", (value) =>\n commitAt(path, { ...node, each: value })\n ),\n h(\"span\", { class: \"wgd-st-colon\" }, [\"key\"]),\n keyControl(typeof node.key === \"string\" ? node.key : undefined, itemScope(scope, each), (key) =>\n commitAt(path, { each, ...(key === undefined ? {} : { key }), ...rest })\n )\n ],\n [\n // Inside an each, the scope becomes the array's item schema.\n slotEditor(\n \"template\",\n path,\n \"template\",\n node.template,\n true,\n errorPath,\n itemScope(scope, node.each)\n ),\n slotEditor(\n \"empty\",\n path,\n \"empty\",\n node.empty,\n false,\n errorPath,\n scope\n )\n ],\n errorHere,\n removable,\n moves,\n { summary: node.empty !== undefined ? \"template \u00B7 empty\" : \"template\" }\n );\n }\n if (typeof node.when === \"string\") {\n return nodeShell(\n \"when\",\n path,\n [\n pathControl(node.when, scope, \"when\", (value) =>\n commitAt(path, { ...node, when: value })\n )\n ],\n [\n slotEditor(\"template\", path, \"template\", node.template, true, errorPath, scope),\n slotEditor(\"else\", path, \"else\", node.else, false, errorPath, scope)\n ],\n errorHere,\n removable,\n moves,\n { summary: node.else !== undefined ? \"template \u00B7 else\" : \"template\" }\n );\n }\n if (typeof node.tag === \"string\") {\n const attrs = isPlainObject(node.attrs) ? node.attrs : {};\n const binding = isPlainObject(node.action) ? (node.action as ActionBinding) : undefined;\n const attrRows = Object.entries(attrs).map(([name, value]) => {\n // The bind's transform fields, when present. Every write goes\n // through rebuild() so editing one field never drops the others.\n // `bound` is meaningful only while `isBind`; narrowed once here.\n const bound: AttrBind =\n isPlainObject(value) && typeof value.bind === \"string\" ? (value as AttrBind) : { bind: \"\" };\n const isBind = isPlainObject(value) && typeof value.bind === \"string\";\n const bindValue = isBind ? bound : undefined;\n const rebuild = (fields: {\n bind: string;\n prefix?: string | undefined;\n map?: Record<string, string> | undefined;\n default?: string | undefined;\n format?: Record<string, unknown> | undefined;\n }): Record<string, unknown> => {\n const out: Record<string, unknown> = { bind: fields.bind };\n // One transform per value, in the validator's own precedence.\n if (fields.map !== undefined) {\n out.map = fields.map;\n if (fields.default !== undefined && fields.default !== \"\") {\n out.default = fields.default;\n }\n } else if (fields.prefix !== undefined && fields.prefix !== \"\") {\n out.prefix = fields.prefix;\n } else if (fields.format !== undefined) {\n out.format = fields.format;\n }\n return out;\n };\n const setAttr = (nextValue: unknown): void => {\n commitAt(path, { ...node, attrs: { ...attrs, [name]: nextValue } });\n };\n const nameInput = changeInput(\n name,\n (nextName) => {\n const entries = Object.entries(attrs).map(([k, v]) =>\n k === name ? ([nextName, v] as const) : ([k, v] as const)\n );\n commitAt(path, { ...node, attrs: Object.fromEntries(entries) });\n },\n \"wgd-input wgd-attr-name\"\n );\n const mode = h(\"select\", { class: \"wgd-select wgd-attr-mode\" });\n mode.append(h(\"option\", { value: \"literal\" }, [\"literal\"]));\n mode.append(h(\"option\", { value: \"bind\" }, [\"bind\"]));\n mode.value = isBind ? \"bind\" : \"literal\";\n fitSelect(mode);\n // Literal: free text. Bind: the same path dropdown the bind/each/when nodes use.\n const literalInput = changeInput(String(isBind ? \"\" : value), (next) => setAttr(next), \"wgd-input wgd-attr-value\");\n const valueInput: HTMLElement = isBind\n ? pathControl(\n bound.bind,\n scope,\n \"bind\",\n (next) => setAttr(rebuild({ ...bound, bind: next })),\n \"wgd-input wgd-attr-value\"\n )\n : literalInput;\n mode.addEventListener(\"change\", () => {\n // Switching modes carries the current text across as a starting point.\n const current = isBind ? bound.bind : literalInput.value;\n setAttr(mode.value === \"bind\" ? { bind: current || \".\" } : current);\n });\n const removeAttr = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove attribute\" }, [\"\u2715\"]);\n removeAttr.addEventListener(\"click\", () => {\n const { [name]: _gone, ...rest } = attrs;\n commitAt(path, { ...node, attrs: rest });\n });\n\n const row: (Node | string)[] = [nameInput, mode, valueInput];\n const transform = bindValue === undefined ? undefined : activeTransform(bindValue);\n const attrFormat = isPlainObject(bindValue?.format) ? bindValue.format : undefined;\n // One transform per value, mirroring the validator: each editor shows\n // while nothing else is active (or it is the active one).\n const showFormat = isBind && (transform === undefined || transform === \"format\");\n const showPrefix = isBind && (transform === undefined || transform === \"prefix\");\n const showAddMap = isBind && transform === undefined;\n if (showFormat) {\n row.push(...formatEditor(attrFormat, (next) => setAttr(rebuild({ ...bound, format: next }))));\n }\n if (showPrefix) {\n const prefixInput = changeInput(\n bindValue?.prefix ?? \"\",\n (next) => setAttr(rebuild({ ...bound, prefix: next })),\n \"wgd-input wgd-attr-prefix\"\n );\n prefixInput.placeholder = \"prefix\";\n prefixInput.title = \"Literal prefix, e.g. mailto: \u2014 emitted only when the bound value is non-empty\";\n row.push(prefixInput);\n }\n if (showAddMap) {\n const addMap = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Map values to authored literals (e.g. status \u2192 class)\" },\n [\"map\"]\n );\n addMap.addEventListener(\"click\", () => setAttr(rebuild({ ...bound, map: {} })));\n row.push(h(\"span\", { class: \"wgd-node-icons\" }, [addMap, removeAttr]));\n } else {\n row.push(removeAttr);\n }\n\n const attrRow = h(\"div\", { class: \"wgd-attr-row\" }, row);\n const parts: (Node | string)[] = [attrRow];\n if (isBind && transform === \"map\") {\n // The map block: data value \u2192 authored literal rows, plus the\n // miss default. Emptying the record drops the transform.\n const mapEditor = createRecordEditor(\n bound.map,\n { key: \"data value\", value: \"authored literal\", add: \"+ mapping\" },\n (nextMap) => {\n setAttr(\n nextMap === undefined\n ? { bind: bound.bind }\n : rebuild({ ...bound, map: nextMap })\n );\n }\n );\n const defaultInput = changeInput(\n bound.default ?? \"\",\n (next) => setAttr(rebuild({ ...bound, default: next })),\n \"wgd-input wgd-attr-map-default\"\n );\n defaultInput.placeholder = \"default (on miss)\";\n parts.push(\n h(\"div\", { class: \"wgd-attr-map\" }, [\n mapEditor.element,\n h(\"div\", { class: \"wgd-rec-row\" }, [\n h(\"span\", { class: \"wgd-st-colon\" }, [\"\u21B3\"]),\n defaultInput\n ])\n ])\n );\n }\n return parts.length === 1\n ? attrRow\n : h(\"div\", { class: \"wgd-attr\" }, parts);\n });\n const childNodes = Array.isArray(node.children) ? (node.children as unknown[]) : [];\n // One add menu per element covers attributes and every child form \u2014\n // the tree carries no persistent per-form button rows.\n const addMenu = menuButton(\n \"+\",\n \"Add attribute or child node\",\n // Actions belong on activatable elements: buttons and links.\n [\n \"attribute\",\n ...(binding === undefined && (node.tag === \"button\" || node.tag === \"a\") ? [\"action\"] : []),\n ...Object.keys(NODE_PRESETS)\n ],\n (choice) => {\n collapsedPaths.delete(pathString(path)); // never add into a fold\n const preset = NODE_PRESETS[choice];\n if (choice === \"attribute\") {\n commitAt(path, { ...node, attrs: { ...attrs, \"\": \"\" } });\n } else if (choice === \"action\") {\n const first = actionContext.actions[0];\n commitAt(path, {\n ...node,\n action: first !== undefined ? { ref: first.name } : { definition: { kind: \"prompt\", text: [\"Tell me more\"] } }\n });\n } else if (preset) {\n commitAt([...path, childNodes.length], preset());\n }\n }\n );\n const body: (Node | string)[] = [];\n if (attrRows.length > 0) body.push(h(\"div\", { class: \"wgd-attrs\" }, attrRows));\n // Action binding: the element becomes activatable in Apps hosts. The\n // editor commits the whole binding; `undefined` drops the key.\n if (binding !== undefined) {\n const scopePaths = isPlainObject(scope) ? pathOptions(scope, \"when\") : [];\n const bindingEditor = createBindingEditor(\n binding,\n {\n ...actionContext,\n scopePaths,\n // The widget's effective data schema drives output-map targets.\n getDataSchema: () => effectiveDataSchema(store.get(), actionContext.schemas)\n },\n (next) => {\n if (next === undefined) {\n const { action: _gone, ...rest } = node;\n commitAt(path, rest);\n } else {\n commitAt(path, { ...node, action: next });\n }\n }\n );\n const actionParts: (Node | string)[] = [h(\"span\", { class: \"wgd-slot-label\" }, [\"action\"]), bindingEditor.element];\n // An unknown shared ref is flagged at the element carrying it.\n const ref = \"ref\" in binding && typeof binding.ref === \"string\" ? binding.ref : undefined;\n if (ref !== undefined && unknownRefs.has(ref)) {\n actionParts.push(diagnosticLine(`Unknown shared action '${ref}' \u2014 this element renders disabled.`));\n }\n body.push(h(\"div\", { class: \"wgd-attrs wgd-node-action\" }, actionParts));\n }\n if (childNodes.length > 0) {\n body.push(\n h(\n \"div\",\n { class: \"wgd-children\" },\n childNodes.map((child, index) =>\n renderNode(\n child,\n [...path, index],\n errorPath,\n true,\n { parent: path, index, count: childNodes.length },\n scope\n )\n )\n )\n );\n }\n const summaryParts: string[] = [];\n if (attrRows.length > 0) {\n summaryParts.push(`${attrRows.length} attr${attrRows.length === 1 ? \"\" : \"s\"}`);\n }\n if (binding !== undefined) summaryParts.push(\"action\");\n if (childNodes.length > 0) {\n summaryParts.push(\n `${childNodes.length} ${childNodes.length === 1 ? \"child\" : \"children\"}`\n );\n }\n return nodeShell(\n undefined, // the tag select is the node's label\n path,\n [tagControl(node.tag, (value) => commitAt(path, { ...node, tag: value }))],\n body,\n errorHere,\n removable,\n moves,\n { icons: [addMenu], summary: summaryParts.join(\" \u00B7 \") }\n );\n }\n return nodeShell(\n \"unknown\",\n path,\n [h(\"code\", undefined, [JSON.stringify(node)])],\n [],\n errorHere ?? \"Unknown template node form.\",\n removable,\n moves\n );\n }\n\n let currentError: string | undefined;\n let lastDraft: WidgetDraft | undefined;\n let lastErrorPath: string | undefined;\n\n /** Rebuild the tree from the last refresh inputs (collapse toggles). */\n function renderTree(): void {\n if (lastDraft === undefined) return;\n // Shared refs resolve like inline schemas \u2014 a ref-based widget gets the same path completions.\n treeHost.replaceChildren(\n renderNode(\n lastDraft.template,\n [],\n lastErrorPath,\n true,\n undefined,\n effectiveDataSchema(lastDraft, actionContext.schemas)\n )\n );\n }\n\n function refresh(draft: WidgetDraft, diagnostics: DesignerDiagnostics): void {\n currentError = diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}`\n : undefined;\n lastDraft = draft;\n lastErrorPath = diagnostics.template?.path;\n const known = new Set(actionContext.actions.map((action) => action.name));\n unknownRefs = new Set(collectActionRefs(draft.template, draft.load).filter((ref) => !known.has(ref)));\n const templateMessage = diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}` +\n (diagnostics.template.path !== undefined && diagnostics.template.path !== \"\"\n ? ` (at ${diagnostics.template.path})`\n : \"\")\n : diagnostics.actionRefs;\n templateDiag.hidden = templateMessage === undefined;\n templateDiag.textContent = templateMessage ?? \"\";\n if (!treeHost.hidden || treeHost.childNodes.length === 0) {\n renderTree();\n }\n if (document.activeElement !== jsonArea) {\n jsonArea.value = JSON.stringify(draft.template, null, 2);\n repaintHighlight(jsonArea);\n }\n }\n\n refreshers.push(() => undefined); // template refresh runs via refresh() below\n\n return { element, refresh, dispose: () => element.remove() };\n}\n", "/**\n * Preview controls in the widget designer: which of the host-supplied\n * named themes the DRAFT renders under \u2014 plus a read-only reference of\n * the effective tokens, so style authoring can reach for\n * `var(--wg-\u2026)` by sight instead of memory.\n *\n * Theme *authoring* lives in the standalone theme designer \u2014 this panel\n * only selects and displays. There is deliberately no preview-kind\n * selector: the widget designer previews the draft, and previewing\n * arbitrary kinds under a theme is the theme designer's job.\n */\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { TOKEN_SPECS } from \"@widgentic/core\";\nimport { diagnosticLine, h, section } from \"./dom.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\n\nexport function mountThemePanel(\n store: DraftStore,\n refreshers: ((draft: WidgetDraft) => void)[],\n themes: ThemeEntry[] = []\n): {\n element: HTMLElement;\n /** Show the theme validator's error \u2014 this panel owns the value. */\n setDiagnostic(message: string | undefined): void;\n dispose(): void;\n} {\n // Theme validation errors were computed and dropped before this: the\n // panel that owns the offending value showed nothing at all.\n const themeDiag = diagnosticLine(undefined);\n // Theme selector: \"none\" plus whatever the host supplied.\n const themeSelect = h(\"select\", {\n class: \"wgd-select wgd-theme-select\"\n });\n themeSelect.append(h(\"option\", { value: \"\" }, [\"(none \u2014 defaults)\"]));\n for (const entry of themes) {\n themeSelect.append(\n h(\"option\", { value: entry.name }, [entry.label ?? entry.name])\n );\n }\n // The selection is the person's: it names the draft's `previewTheme`\n // and only a pick here changes it \u2014 tokens a host or agent layers on\n // top never re-select by content.\n const showChoice = (draft: WidgetDraft) => {\n themeSelect.value = themes.some((entry) => entry.name === draft.previewTheme) ? draft.previewTheme ?? \"\" : \"\";\n };\n showChoice(store.get());\n themeSelect.addEventListener(\"change\", () => {\n const entry = themes.find((candidate) => candidate.name === themeSelect.value);\n store.update((draft) => {\n const { theme: _theme, themeStyles: _styles, previewTheme: _name, ...rest } = draft;\n if (entry === undefined) return rest;\n // A pick replaces any layered tokens. The entry's shared styles dress\n // the preview too, so its classes look in the draft as they will\n // under this theme.\n return {\n ...rest,\n theme: entry.tokens,\n previewTheme: entry.name,\n ...(entry.styles === undefined ? {} : { themeStyles: entry.styles })\n };\n });\n });\n\n // Token reference: the EFFECTIVE preview tokens \u2014 the selected entry\n // merged over the registry defaults \u2014 plus the entry's x-* customs.\n // Types come from TOKEN_SPECS metadata (color \u2192 swatch), never inferred.\n const tokenList = h(\"div\", { class: \"wgd-token-ref\" });\n\n function renderTokenReference(theme: Record<string, string> | undefined): void {\n tokenList.replaceChildren();\n for (const [name, spec] of Object.entries(TOKEN_SPECS)) {\n const value = theme?.[name] ?? spec.default;\n const row = h(\"div\", { class: \"wgd-token-ref-row\", title: spec.use }, [\n spec.type === \"color\"\n ? h(\"span\", {\n class: \"wgd-token-ref-swatch\",\n style: `background: ${value}`\n })\n : h(\"span\", { class: \"wgd-token-ref-swatch wgd-token-ref-noswatch\" }),\n h(\"code\", { class: \"wgd-token-ref-name\" }, [`--wg-${name}`]),\n h(\"span\", { class: \"wgd-token-ref-value\" }, [value])\n ]);\n tokenList.append(row);\n }\n for (const [name, value] of Object.entries(theme ?? {})) {\n if (!name.startsWith(\"x-\")) continue;\n const row = h(\"div\", { class: \"wgd-token-ref-row\", title: \"Custom variable\" }, [\n h(\"span\", { class: \"wgd-token-ref-swatch wgd-token-ref-noswatch\" }),\n h(\"code\", { class: \"wgd-token-ref-name\" }, [`--wg-${name}`]),\n h(\"span\", { class: \"wgd-token-ref-value\" }, [value])\n ]);\n tokenList.append(row);\n }\n }\n renderTokenReference(store.get().theme);\n\n refreshers.push((draft) => {\n showChoice(draft);\n renderTokenReference(draft.theme);\n });\n\n const rows: (Node | string)[] = [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Preview theme\"]),\n themeSelect\n ]),\n h(\"span\", { class: \"wgd-field-label\" }, [\n themes.length === 0\n ? \"No themes supplied by the host \u2014 design themes in the theme designer.\"\n : \"Themes come from the host; edit them in the theme designer.\"\n ]),\n themeDiag,\n h(\"details\", { class: \"wgd-token-ref-details\" }, [\n h(\"summary\", { class: \"wgd-field-label\" }, [\n \"Theme tokens (reference for styles)\"\n ]),\n tokenList\n ])\n ];\n\n const element = section(\"Preview\", rows);\n return {\n element,\n setDiagnostic(message) {\n themeDiag.hidden = message === undefined;\n themeDiag.textContent = message ?? \"\";\n },\n dispose: () => element.remove()\n };\n}\n", "/**\n * Editor panels: plain modules over the draft store. Refresh discipline:\n * every store change re-derives diagnostics and refreshes bound controls,\n * but never overwrites the control the user is typing in\n * (`document.activeElement` wins) \u2014 the store is the single model, the\n * DOM is a projection.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { diagnosticLine, h, section, tabs, textArea, textField, requireChild } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { mountIoPanel } from \"./io.js\";\nimport { createJsonTreeEditor } from \"./json-tree-editor.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\nimport { createRecordEditor } from \"./record-editor.js\";\nimport { createSchemaForm } from \"./schema-form.js\";\nimport { createStylesPanel } from \"./styles-panel.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { mountTemplatePanel } from \"./template-panel.js\";\nimport type { TemplateActionContext } from \"./template-panel.js\";\nimport { createBindingEditor } from \"./action-editor.js\";\nimport type { ActionBinding } from \"@widgentic/core\";\nimport { mountThemePanel } from \"./theme-panel.js\";\nimport { deriveDiagnostics, effectiveDataSchema } from \"./validate.js\";\n\n/** Column layout: definition (exported) on the left, presentation on the right. */\nexport interface PanelColumns {\n left: HTMLElement;\n right: HTMLElement;\n}\n\ntype Refresher = (draft: WidgetDraft) => void;\n\n/**\n * JSON-valued textarea with parse gating: invalid JSON never reaches the\n * store (last-valid-wins) \u2014 the parse error shows beside the field.\n */\nfunction jsonField(\n label: string,\n read: (draft: WidgetDraft) => unknown,\n write: (draft: WidgetDraft, value: unknown) => WidgetDraft,\n clear: ((draft: WidgetDraft) => WidgetDraft) | undefined,\n store: DraftStore,\n refreshers: Refresher[],\n rows = 6\n): HTMLElement {\n const parseError = diagnosticLine(undefined);\n const initial = read(store.get());\n const field = textArea(\n label,\n initial === undefined ? \"\" : JSON.stringify(initial, null, 2),\n (text) => {\n if (text.trim() === \"\") {\n parseError.hidden = true;\n if (clear) store.update((draft) => clear(draft));\n return;\n }\n try {\n const value: unknown = JSON.parse(text);\n parseError.hidden = true;\n parseError.textContent = \"\";\n store.update((draft) => write(draft, value));\n } catch (error) {\n parseError.hidden = false;\n parseError.textContent = `Invalid JSON (draft keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n },\n rows\n );\n const area = requireChild(field, \"textarea\");\n attachJsonHighlight(area);\n refreshers.push((draft) => {\n if (document.activeElement === area) return;\n const value = read(draft);\n area.value = value === undefined ? \"\" : JSON.stringify(value, null, 2);\n repaintHighlight(area); // programmatic writes fire no input event\n });\n return h(\"div\", undefined, [field, parseError]);\n}\n\nexport function mountPanels(\n store: DraftStore,\n columns: PanelColumns,\n themes: ThemeEntry[] = [],\n schemas: SchemaEntry[] = [],\n actionContext: TemplateActionContext = { actions: [], secretNames: [], schemas: [] }\n): { dispose(): void } {\n const refreshers: Refresher[] = [];\n const disposers: (() => void)[] = [];\n\n function bindText(\n label: string,\n read: (draft: WidgetDraft) => string,\n write: (draft: WidgetDraft, value: string) => WidgetDraft\n ): HTMLElement {\n const field = textField(label, read(store.get()), (value) =>\n store.update((draft) => write(draft, value))\n );\n const input = requireChild(field, \"input\");\n refreshers.push((draft) => {\n if (document.activeElement !== input) input.value = read(draft);\n });\n return field;\n }\n\n // --- General: kind + prose descriptor fields (left) -------------------\n const kindDiag = diagnosticLine(undefined);\n // Hints: name\u2192doc rows beside the parse-gated JSON pane \u2014 the same\n // Tree/JSON pair as styles, scaled down to a flat record.\n const hintsEditor = createRecordEditor(\n store.get().descriptor.hints,\n { key: \"hint name\", value: \"what the hint does\", add: \"+ hint\" },\n (hints) =>\n store.update((d) => {\n if (hints === undefined) {\n const { hints: _h, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, hints } };\n })\n );\n refreshers.push((draft) => hintsEditor.setValue(draft.descriptor.hints));\n const dataShapeDiag = diagnosticLine(undefined);\n const generalPanel = section(\"General\", [\n bindText(\"Kind (id)\", (d) => d.kind, (d, v) => ({ ...d, kind: v })),\n kindDiag,\n bindText(\n \"Description\",\n (d) => d.descriptor.description ?? \"\",\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, description: v } })\n ),\n bindText(\n \"Data shape (prose)\",\n (d) => d.descriptor.dataShape ?? \"\",\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataShape: v } })\n ),\n dataShapeDiag,\n h(\"div\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Hints\"]),\n tabs([\n { label: \"Tree\", element: hintsEditor.element },\n {\n label: \"JSON\",\n element: jsonField(\n \"\",\n (d) => d.descriptor.hints,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n const hints = Object.fromEntries(\n Object.entries(v).map(([k, doc]) => [k, String(doc)])\n ) as Record<string, string>;\n return { ...d, descriptor: { ...d.descriptor, hints } };\n },\n (d) => {\n const { hints: _hints, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers,\n 3\n )\n }\n ])\n ])\n ]);\n\n // --- Data schema (left, definition): inline editing OR a shared ref ----\n // Two modes, mirroring the store's contract: an inline dataSchema, or a\n // dataSchemaRef into the host-supplied shared schemas \u2014 never both.\n const schemaBuilder = createSchemaBuilder(store.get().descriptor.dataSchema, (schema) =>\n store.update((d) => {\n if (schema === undefined) {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, dataSchema: schema } };\n })\n );\n refreshers.push((draft) => schemaBuilder.setValue(draft.descriptor.dataSchema));\n const inlineEditors = tabs([\n { label: \"Builder\", element: schemaBuilder.element },\n {\n label: \"JSON\",\n element: jsonField(\n \"dataSchema (JSON-Schema subset: type/properties/required/items/enum/pattern)\",\n (d) => d.descriptor.dataSchema,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n return { ...d, descriptor: { ...d.descriptor, dataSchema: v } };\n },\n (d) => {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]);\n\n const modeSelect = h(\"select\", { class: \"wgd-select wgd-schema-mode\" });\n modeSelect.append(h(\"option\", { value: \"inline\" }, [\"define inline\"]));\n const sharedOption = h(\"option\", { value: \"shared\" }, [\"use shared\"]);\n if (schemas.length === 0) sharedOption.disabled = true;\n modeSelect.append(sharedOption);\n\n const refSelect = h(\"select\", { class: \"wgd-select wgd-schema-ref\" });\n for (const entry of schemas) {\n refSelect.append(h(\"option\", { value: entry.name }, [entry.label ?? entry.name]));\n }\n refSelect.addEventListener(\"change\", () => {\n store.update((d) => ({\n ...d,\n descriptor: { ...d.descriptor, dataSchemaRef: refSelect.value }\n }));\n });\n\n // The shared schema shows read-only: editing it from inside a widget\n // draft would be edit-at-a-distance \u2014 that belongs to the schema section.\n const sharedView = h(\"textarea\", {\n class: \"wgd-textarea wgd-schema-shared\",\n rows: \"10\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const schemaRefDiag = diagnosticLine(undefined);\n const schemaAuditDiag = diagnosticLine(undefined);\n const sharedWrap = h(\"div\", undefined, [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Shared schema\"]),\n refSelect\n ]),\n sharedView,\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Read-only here \u2014 edit shared schemas in the Data schemas section.\"\n ])\n ]);\n\n modeSelect.addEventListener(\"change\", () => {\n if (modeSelect.value === \"shared\") {\n const name =\n store.get().descriptor.dataSchemaRef ?? schemas[0]?.name ?? \"\";\n store.update((d) => {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: { ...rest, dataSchemaRef: name } };\n });\n } else {\n // Back to inline: seed with the resolved shared schema (a copy), so\n // \"customize from here\" is one switch away.\n const resolved = effectiveDataSchema(store.get(), schemas);\n store.update((d) => {\n const { dataSchemaRef: _r, ...rest } = d.descriptor;\n return {\n ...d,\n descriptor: {\n ...rest,\n dataSchema: (resolved ?? { type: \"object\" }) as Record<string, unknown>\n }\n };\n });\n }\n });\n\n function refreshSchemaMode(draft: WidgetDraft): void {\n const ref = draft.descriptor.dataSchemaRef;\n const shared = typeof ref === \"string\";\n modeSelect.value = shared ? \"shared\" : \"inline\";\n inlineEditors.hidden = shared;\n sharedWrap.hidden = !shared;\n if (shared) {\n if (refSelect.value !== ref) refSelect.value = ref;\n const resolved = schemas.find((entry) => entry.name === ref)?.schema;\n sharedView.value =\n resolved === undefined ? \"\" : JSON.stringify(resolved, null, 2);\n repaintHighlight(sharedView); // programmatic writes fire no input event\n }\n }\n refreshers.push(refreshSchemaMode);\n refreshSchemaMode(store.get());\n\n const schemaPanel = section(\n \"Data schema\",\n [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Source\"]),\n modeSelect\n ]),\n schemaRefDiag,\n inlineEditors,\n schemaAuditDiag,\n sharedWrap\n ],\n false\n );\n // The highlight layer wraps the textarea in place, so attach after the\n // section assembly gives it a parent.\n attachJsonHighlight(sharedView);\n\n /**\n * Adaptive data editor: schema-driven form when a dataSchema exists,\n * generic JSON tree otherwise \u2014 rebuilt when the schema changes; the raw\n * JSON textarea remains as a sibling tab either way.\n */\n function adaptiveDataEditor(\n read: (d: WidgetDraft) => unknown,\n write: (d: WidgetDraft, v: unknown) => WidgetDraft\n ): HTMLElement {\n const hostEl = h(\"div\");\n let schemaKey = \"\";\n let editor:\n | { element: HTMLElement; setValue(v: unknown): void }\n | undefined;\n\n function rebuild(draft: WidgetDraft): void {\n const schema = effectiveDataSchema(draft, schemas);\n const key = schema === undefined ? \"\" : JSON.stringify(schema);\n if (editor !== undefined && key === schemaKey) {\n editor.setValue(read(draft));\n return;\n }\n schemaKey = key;\n const onChange = (value: unknown): void =>\n store.update((d) => write(d, value));\n editor =\n schema !== undefined && isPlainObject(schema)\n ? createSchemaForm(schema as DataSchema, read(draft), onChange)\n : createJsonTreeEditor(read(draft), onChange);\n hostEl.replaceChildren(editor.element);\n }\n\n rebuild(store.get());\n refreshers.push(rebuild);\n return hostEl;\n }\n\n // --- Sample data = the descriptor's dataExample (left, exported) -------\n const exampleDiag = diagnosticLine(undefined);\n const samplePanel = section(\n \"Sample data\",\n [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"dataExample \u2014 ships with the widget as the example agents imitate\"\n ]),\n tabs([\n {\n label: \"Edit\",\n element: adaptiveDataEditor(\n (d) => d.descriptor.dataExample,\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataExample: v } })\n )\n },\n {\n label: \"JSON\",\n element: jsonField(\n \"dataExample (JSON)\",\n (d) => d.descriptor.dataExample,\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataExample: v } }),\n (d) => {\n const { dataExample: _e, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]),\n exampleDiag\n ],\n false\n );\n\n // --- Data for preview (right, session-only) ----------------------------\n const sampleDiag = diagnosticLine(undefined);\n const previewDataPanel = section(\n \"Data for preview\",\n [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Overrides dataExample in the preview only (not exported)\"\n ]),\n tabs([\n {\n label: \"Edit\",\n element: adaptiveDataEditor(\n (d) => d.sampleData,\n (d, v) => ({ ...d, sampleData: v })\n )\n },\n {\n label: \"JSON\",\n element: jsonField(\n \"Preview data (JSON)\",\n (d) => d.sampleData,\n (d, v) => ({ ...d, sampleData: v }),\n (d) => {\n const { sampleData: _s, ...rest } = d;\n return rest;\n },\n store,\n refreshers,\n 4\n )\n }\n ]),\n sampleDiag\n ],\n false\n );\n\n // --- Styles panel (right, presentation): the panel the theme designer\n // shares \u2014 Tree and JSON over the one draft value, plus the audit.\n const stylesPanel = createStylesPanel(store.get().descriptor.styles, (styles) =>\n store.update((d) => {\n if (styles === undefined) {\n const { styles: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, styles } };\n })\n );\n refreshers.push((draft) => stylesPanel.setValue(draft.descriptor.styles));\n\n const templatePanel = mountTemplatePanel(store, refreshers, { actionContext });\n const themePanel = mountThemePanel(store, refreshers, themes);\n\n // --- Load: the widget-level http GET action run once per instance -------\n const loadDiag = diagnosticLine(undefined);\n const loadEditor = createBindingEditor(\n store.get().load,\n {\n ...actionContext,\n loadOnly: true,\n getDataSchema: () => effectiveDataSchema(store.get(), schemas)\n },\n (binding: ActionBinding | undefined) =>\n store.update((d) => {\n if (binding === undefined) {\n const { load: _l, ...rest } = d;\n return rest;\n }\n return { ...d, load: binding };\n })\n );\n refreshers.push((draft) => {\n if (!loadEditor.element.contains(document.activeElement)) loadEditor.setValue(draft.load);\n });\n // Same compact chrome as an element's binding editor in the tree.\n const loadPanel = section(\n \"Load action (http GET, runs once when the widget first renders in an Apps host)\",\n [h(\"div\", { class: \"wgd-compact wgd-load\" }, [loadEditor.element]), loadDiag],\n false\n );\n const ioPanel = mountIoPanel(store);\n\n // Read-only marks the right column's EDITING sections; the theme panel\n // (preview selector + token reference) stays live in that mode.\n previewDataPanel.classList.add(\"wgd-edit-only\");\n stylesPanel.element.classList.add(\"wgd-edit-only\");\n\n // Left: the widget definition (what export produces). Right: presentation.\n columns.left.append(\n generalPanel,\n schemaPanel,\n samplePanel,\n templatePanel.element,\n loadPanel,\n ioPanel.element\n );\n columns.right.append(previewDataPanel, stylesPanel.element, themePanel.element);\n disposers.push(templatePanel.dispose, themePanel.dispose, ioPanel.dispose);\n\n // Diagnostics refresh: derive once per change here (cheap, pure) \u2014 and\n // once immediately, so the tree/JSON projections render before any edit.\n function applyDiagnostics(draft: WidgetDraft): void {\n const diagnostics = deriveDiagnostics(draft, { schemas, actions: actionContext.actions });\n kindDiag.hidden = diagnostics.kind === undefined;\n // Unknown refs are flagged in the template panel, at the element; the\n // Load section only ever speaks about the load binding.\n loadDiag.hidden = diagnostics.load === undefined;\n loadDiag.textContent = diagnostics.load ?? \"\";\n kindDiag.textContent = diagnostics.kind ?? \"\";\n exampleDiag.hidden = diagnostics.example === undefined;\n exampleDiag.textContent = diagnostics.example\n ? `dataExample vs dataSchema: ${diagnostics.example.code} at ${diagnostics.example.path} \u2014 ${diagnostics.example.message}`\n : \"\";\n sampleDiag.hidden = diagnostics.sample === undefined;\n sampleDiag.textContent = diagnostics.sample\n ? `sample vs dataSchema: ${diagnostics.sample.code} at ${diagnostics.sample.path} \u2014 ${diagnostics.sample.message}`\n : \"\";\n dataShapeDiag.hidden = diagnostics.dataShape === undefined;\n dataShapeDiag.textContent = diagnostics.dataShape ?? \"\";\n schemaRefDiag.hidden = diagnostics.schemaRef === undefined;\n schemaRefDiag.textContent = diagnostics.schemaRef ?? \"\";\n schemaAuditDiag.hidden = diagnostics.dataSchema === undefined;\n schemaAuditDiag.textContent = diagnostics.dataSchema?.join(\"\\n\") ?? \"\";\n themePanel.setDiagnostic(\n diagnostics.theme\n ? `${diagnostics.theme.code}: ${diagnostics.theme.message}`\n : undefined\n );\n stylesPanel.setIssues(diagnostics.styles);\n for (const refresh of refreshers) refresh(draft);\n templatePanel.refresh(draft, diagnostics);\n }\n\n const off = store.subscribe(applyDiagnostics);\n disposers.push(off);\n applyDiagnostics(store.get());\n\n return {\n dispose() {\n for (const dispose of disposers) dispose();\n columns.left.replaceChildren();\n columns.right.replaceChildren();\n }\n };\n}\n", "/**\n * Live preview through the real pipeline: the draft template compiles into\n * a delegating renderer registered ONCE under a stable internal kind, so a\n * single `mountWidget` handle survives every template revision and updates\n * patch the DOM in place (`reactive-rendering` dogfooded). Built-in kinds\n * share the same scratch catalog for theme-designer previews.\n *\n * Invalid drafts freeze the last good render behind an error banner \u2014\n * never a blank pane (the app-template error-state lesson).\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport { createCatalog } from \"@widgentic/core\";\nimport type { WidgetRenderer } from \"@widgentic/core\";\nimport type { WidgetPayload } from \"@widgentic/core\";\nimport { mountWidget } from \"@widgentic/core\";\nimport type { WidgetMount } from \"@widgentic/core\";\nimport { compileTemplate, validateTemplate } from \"@widgentic/core\";\nimport { applyTheme, injectBaseStyles, themeStylesToCss } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\nimport type { StoredAction } from \"@widgentic/core\";\n\n/** Internal kind the draft renders under (stable across recompiles). */\nexport const PREVIEW_KIND = \"designer-preview\";\n\n/**\n * A host-supplied definition the preview can render by kind. `descriptor`\n * stays `unknown` on purpose: hosts hand these straight off the wire, so\n * the preview narrows what it needs and ignores the rest.\n */\nexport interface PreviewWidget {\n kind: string;\n template: unknown;\n descriptor?: unknown;\n}\n\nexport interface PreviewOptions {\n /**\n * Custom widget definitions to make previewable by kind \u2014 a theme is\n * judged against the widgets it will actually dress, not only the\n * built-ins. Definitions that fail template validation are skipped.\n */\n widgets?: PreviewWidget[];\n /** Shared actions, so `{ ref }` bindings preview with their real kind. */\n actions?: StoredAction[];\n}\n\nexport interface PreviewController {\n readonly pane: HTMLElement;\n /** Selectable kinds: built-ins plus the registered customs. */\n readonly kinds: string[];\n /**\n * Re-render for a draft revision. The WIDGET designer always renders\n * the draft (no `previewKind`); the optional kind parameter exists for\n * the THEME designer, whose job is previewing catalog kinds under a\n * theme.\n */\n update(\n draft: WidgetDraft,\n diagnostics: DesignerDiagnostics,\n previewKind?: string\n ): void;\n dispose(): void;\n}\n\n/**\n * Distinguishes previews on one page, so a theme's styles stay in theirs.\n * The random part keeps two copies of this module (two bundles on one page)\n * from handing out the same id.\n */\nlet previewCount = 0;\nconst previewSalt = Math.random().toString(36).slice(2, 8);\n\nexport function createPreview(options: PreviewOptions = {}): PreviewController {\n injectBaseStyles(document);\n\n const banner = h(\"div\", { class: \"wgd-banner\" });\n banner.hidden = true;\n // Theme styles first: the previewed kind's own rule wins a tie, as it\n // does in a render.\n const themeStyles = h(\"style\");\n const kindStyles = h(\"style\");\n const scope = `wgd-preview-${previewSalt}-${++previewCount}`;\n const mountRoot = h(\"div\", { class: \"wgd-preview\", \"data-wgd-scope\": scope });\n // Every style the preview emits \u2014 the widget's and the theme's \u2014 is\n // scoped to this preview at no added weight: the preview shares the host\n // page's DOM, and a widget's `.wg-title` must not restyle the page.\n const scoped = (styles: Record<string, Record<string, string>>) =>\n themeStylesToCss(styles, `[data-wgd-scope=\"${scope}\"]`);\n const pane = h(\"div\", { class: \"wgd-preview-pane\" }, [banner, themeStyles, kindStyles, mountRoot]);\n\n const catalog = createCatalog();\n let renderer: WidgetRenderer = () => ({ tag: \"div\", children: [\"\u2026\"] });\n catalog.register(\n PREVIEW_KIND,\n (payload: WidgetPayload) => renderer(payload),\n {\n description: \"Designer preview delegate.\",\n dataShape: \"Defined by the draft being designed.\"\n }\n );\n\n // Host-supplied customs join the scratch catalog so the theme designer\n // can preview them. Each carries its own styles, emitted when selected.\n const customStyles = new Map<string, string>();\n for (const widget of options.widgets ?? []) {\n const validated = validateTemplate(widget.template);\n // Untrusted-ish input: a bad definition is skipped, never fatal.\n if (!validated.ok || typeof widget.kind !== \"string\" || widget.kind === \"\") continue;\n const compiled = compileTemplate(validated.template);\n const descriptor = isPlainObject(widget.descriptor) ? widget.descriptor : {};\n try {\n catalog.register(widget.kind, (payload: WidgetPayload) => compiled(payload), {\n description: `Custom widget '${widget.kind}' supplied for preview.`,\n dataShape: \"Defined by the supplied definition.\",\n ...(descriptor.dataExample !== undefined\n ? { dataExample: descriptor.dataExample }\n : {})\n });\n } catch {\n continue; // a reserved/duplicate kind never breaks the designer\n }\n if (isPlainObject(descriptor.styles)) {\n customStyles.set(\n widget.kind,\n scoped(descriptor.styles as Record<string, Record<string, string>>)\n );\n }\n }\n const kinds = catalog.kinds().filter((kind) => kind !== PREVIEW_KIND);\n\n let mount: WidgetMount | undefined;\n\n function update(\n draft: WidgetDraft,\n diagnostics: DesignerDiagnostics,\n previewKind?: string\n ): void {\n const renderingDraft = previewKind === undefined || previewKind === PREVIEW_KIND;\n if (renderingDraft && !diagnostics.previewable) {\n const issue =\n diagnostics.kind ??\n (diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}` +\n (diagnostics.template.path ? ` (at ${diagnostics.template.path})` : \"\")\n : \"Draft is not previewable.\");\n banner.hidden = false;\n // Freezing needs something to freeze ON. On the first update there\n // is no mount yet \u2014 reachable whenever a host supplies an invalid\n // or reserved-kind `initialWidget` \u2014 and returning here left the\n // pane blank, the one state the contract forbids.\n if (mount === undefined) {\n banner.textContent = `Nothing to preview yet \u2014 ${issue}`;\n mountRoot.replaceChildren(\n h(\"div\", { class: \"wgd-preview-empty\" }, [\n \"No preview: the draft has never been valid.\"\n ])\n );\n return;\n }\n banner.textContent = `Preview frozen on the last valid draft \u2014 ${issue}`;\n return; // keep the last good render mounted\n }\n // A first valid render replaces the empty state.\n mountRoot.querySelector(\".wgd-preview-empty\")?.remove();\n banner.hidden = true;\n banner.textContent = \"\";\n\n if (renderingDraft) {\n const validated = validateTemplate(draft.template);\n if (!validated.ok) return; // defensive: previewable implies ok\n const shared = options.actions ?? [];\n renderer = compileTemplate(validated.template, {\n actions: (ref) => shared.find((action) => action.name === ref)?.definition\n });\n }\n // Styles follow whatever is on screen: the draft's own, or the\n // selected custom kind's (a built-in needs none).\n kindStyles.textContent = renderingDraft\n ? draft.descriptor.styles\n ? scoped(draft.descriptor.styles)\n : \"\"\n : customStyles.get(previewKind as string) ?? \"\";\n // Unsafe values are also skipped inside applyTheme (lenient layer).\n applyTheme(mountRoot, draft.theme ?? {});\n // The guards drop unsafe entries.\n themeStyles.textContent = draft.themeStyles ? scoped(draft.themeStyles) : \"\";\n\n const payload = {\n kind: renderingDraft ? PREVIEW_KIND : (previewKind as string),\n data: renderingDraft\n ? draft.sampleData ?? draft.descriptor.dataExample ?? null\n : sampleFor(previewKind as string)\n };\n if (mount === undefined) {\n // No onAction: the preview never executes anything; bound elements\n // only wear the inert badge below.\n mount = mountWidget(payload, mountRoot, { catalog });\n } else {\n mount.update(payload);\n }\n for (const bound of mountRoot.querySelectorAll(\"[data-wg-action]\")) {\n bound.classList.add(\"wg-designer-action\");\n }\n }\n\n /** Built-in preview data for the THEME designer's kind previews. */\n function sampleFor(kind: string): unknown {\n return catalog.describe(kind)?.dataExample ?? { value: \"preview\" };\n }\n\n return {\n pane,\n kinds,\n update,\n dispose() {\n mount?.dispose();\n mount = undefined;\n pane.replaceChildren();\n }\n };\n}\n", "/**\n * Designer draft store: one micro-store per designer instance \u2014 get,\n * immutable update, subscribe, and a bounded undo stack. Deliberately\n * framework-free (the \"Arrow JS direction\": fine-grained subscriptions,\n * no VDOM) so the designer stays a zero-dependency embeddable.\n */\nimport type { WidgetDescriptorInput } from \"@widgentic/core\";\nimport type { WidgetTemplate } from \"@widgentic/core\";\nimport type { WidgetStyles, WidgetTheme } from \"@widgentic/core\";\nimport type { ActionBinding } from \"@widgentic/core\";\n\n/** The draft being designed \u2014 the server's `CustomWidget` shape plus session extras. */\nexport interface WidgetDraft {\n kind: string;\n template: WidgetTemplate;\n /**\n * Mirrors the store's shape: `dataSchemaRef` names a shared schema in\n * place of an inline `dataSchema` (never both). Export carries the ref\n * as authored \u2014 resolution belongs to the server's composition.\n */\n descriptor: WidgetDescriptorInput & { dataSchemaRef?: string };\n /** Optional http GET action run once when the widget first renders. */\n load?: ActionBinding;\n /** Optional preview data overriding `descriptor.dataExample`. */\n sampleData?: unknown;\n /** Preview theme (also the theme-designer working copy). */\n theme?: WidgetTheme;\n /** The preview theme's shared styles; preview-only, never exported. */\n themeStyles?: WidgetStyles;\n /**\n * The supplied theme the person chose for the preview, by name; `theme`\n * is its tokens with any programmatic tokens layered over them.\n * Preview-only, never exported.\n */\n previewTheme?: string;\n}\n\nexport type DraftListener = (draft: WidgetDraft) => void;\n\nconst UNDO_LIMIT = 50;\n\nexport interface DraftStore {\n get(): WidgetDraft;\n /** Replace the draft via an updater; records undo history. */\n update(updater: (draft: WidgetDraft) => WidgetDraft): void;\n /** Replace wholesale (imports/loads); clears history. */\n replace(draft: WidgetDraft): void;\n undo(): boolean;\n subscribe(listener: DraftListener): () => void;\n}\n\n/** Structured-clone with JSON semantics \u2014 drafts are serializable by contract. */\nexport function cloneDraft(draft: WidgetDraft): WidgetDraft {\n return JSON.parse(JSON.stringify(draft)) as WidgetDraft;\n}\n\nexport function starterDraft(): WidgetDraft {\n // Everything the starter binds is DECLARED in its dataSchema \u2014 the\n // preferred pattern: schema-declared properties validate, `$meta.*`\n // paths do not, so new drafts start on the validated side.\n return {\n kind: \"my-widget\",\n template: {\n tag: \"div\",\n attrs: { class: \"wg-template\" },\n children: [{ tag: \"h2\", children: [{ bind: \"title\" }] }, { bind: \"message\" }]\n },\n descriptor: {\n description: \"Describe what this widget is for.\",\n dataShape: \"{ title?, message }\",\n dataExample: {\n title: \"My widget\",\n message: \"Hello from the widgentic designer\"\n },\n dataSchema: {\n type: \"object\",\n required: [\"message\"],\n properties: {\n title: { type: \"string\" },\n message: { type: \"string\" }\n }\n }\n }\n };\n}\n\nexport function createDraftStore(initial?: WidgetDraft): DraftStore {\n let current = cloneDraft(initial ?? starterDraft());\n const history: WidgetDraft[] = [];\n const listeners = new Set<DraftListener>();\n\n function notify(): void {\n for (const listener of [...listeners]) listener(current);\n }\n\n return {\n get: () => current,\n update(updater) {\n history.push(current);\n if (history.length > UNDO_LIMIT) history.shift();\n current = cloneDraft(updater(cloneDraft(current)));\n notify();\n },\n replace(draft) {\n history.length = 0;\n current = cloneDraft(draft);\n notify();\n },\n undo() {\n const previous = history.pop();\n if (previous === undefined) return false;\n current = previous;\n notify();\n return true;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n };\n}\n", "/**\n * The designer shell: layout, store wiring, and the embedding handle.\n * Panels and the preview are plain modules receiving the store \u2014 every\n * designer instance is fully closure-scoped so multiple instances coexist\n * in one document.\n */\nimport { validateTheme } from \"@widgentic/core\";\nimport type { ThemeEntry, WidgetTheme } from \"@widgentic/core\";\nimport { applyChrome, h, injectDesignerStyles } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { applyDefinition, checkDefinition } from \"./io.js\";\nimport type { WidgetDefinition } from \"./io.js\";\nimport { mountPanels } from \"./panels.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport type { StoredAction } from \"@widgentic/core\";\nimport { createPreview } from \"./preview.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport { cloneDraft, createDraftStore, starterDraft } from \"./store.js\";\nimport { deriveDiagnostics } from \"./validate.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\n\nexport type { WidgetDefinition } from \"./io.js\";\n\nexport interface DesignerOptions {\n initialWidget?: WidgetDefinition;\n initialTheme?: WidgetTheme;\n /**\n * Named themes offered as preview options. Theme authoring belongs to\n * the standalone theme designer; the widget designer only selects.\n */\n themes?: ThemeEntry[];\n /**\n * The name of one of `themes` to open with as the preview theme \u2014 its\n * tokens and styles applied \u2014 e.g. the person's light default. A name\n * that matches no supplied entry is ignored. Wins over `initialTheme`.\n */\n previewTheme?: string;\n /**\n * Shared data schemas the draft may reference by name (the Data schema\n * section's \"use shared\" mode). Schema authoring belongs to the\n * standalone schema designer; the widget designer only selects.\n */\n schemas?: SchemaEntry[];\n /**\n * Shared actions the draft may bind by name (element `action` bindings\n * and the widget-level `load`). Action authoring belongs to the\n * standalone action designer; the widget designer only binds.\n */\n actions?: StoredAction[];\n /** Secret names offered when an inline http action needs a header or query secret. */\n secretNames?: string[];\n /**\n * Designer chrome appearance. \"auto\" (default) follows the host's\n * `prefers-color-scheme`; the explicit values pin it. This is the\n * designer's own UI \u2014 the widget preview uses the draft's theme.\n */\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Mount with editing disabled: panels stay visible but inert, only the\n * preview and its theme selector operate. Toggle later via\n * `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type LoadResult = { ok: true } | { ok: false; errors: string[] };\nexport type WidgetCheckResult = { ok: true; diagnostics: DesignerDiagnostics } | { ok: false; errors: string[] };\n\nexport interface DesignerHandle {\n getDraft(): WidgetDraft;\n /**\n * The current draft's diagnostics, resolved against the shared schemas and\n * actions the host supplied \u2014 what subscribers receive on every change.\n */\n getDiagnostics(): DesignerDiagnostics;\n loadWidget(definition: unknown): LoadResult;\n /**\n * Check a definition exactly as `loadWidget` would \u2014 the same refusals \u2014\n * and return its diagnostics against the host's shared entries, without\n * touching the draft.\n */\n checkWidget(definition: unknown): WidgetCheckResult;\n loadTheme(theme: unknown): LoadResult;\n /** Disable/enable editing; the preview and theme selector stay live. */\n setReadOnly(readOnly: boolean): void;\n subscribe(\n listener: (draft: WidgetDraft, diagnostics: DesignerDiagnostics) => void\n ): () => void;\n dispose(): void;\n}\n\nexport function createDesigner(\n container: Element,\n options: DesignerOptions = {}\n): DesignerHandle {\n injectDesignerStyles(document);\n\n const base: WidgetDraft = options.initialWidget\n ? cloneDraft({ ...options.initialWidget })\n : starterDraft();\n const preselected = options.themes?.find((entry) => entry.name === options.previewTheme);\n const initial: WidgetDraft =\n preselected !== undefined\n ? {\n ...base,\n theme: preselected.tokens,\n previewTheme: preselected.name,\n ...(preselected.styles === undefined ? {} : { themeStyles: preselected.styles })\n }\n : options.initialTheme !== undefined\n ? { ...base, theme: options.initialTheme }\n : base;\n const store = createDraftStore(initial);\n\n const listeners = new Set<\n (draft: WidgetDraft, diagnostics: DesignerDiagnostics) => void\n >();\n\n const preview = createPreview({ actions: options.actions ?? [] });\n const leftColumn = h(\"div\", { class: \"wgd-panels\" });\n const rightSections = h(\"div\", { class: \"wgd-preview-pane\" });\n const rightColumn = h(\"div\", { class: \"wgd-side\" }, [preview.pane, rightSections]);\n const root = h(\"div\", { class: \"wgd-root\" }, [leftColumn, rightColumn]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n const actionContext = {\n actions: options.actions ?? [],\n secretNames: options.secretNames ?? [],\n schemas: options.schemas ?? []\n };\n const panels = mountPanels(\n store,\n { left: leftColumn, right: rightSections },\n options.themes ?? [],\n options.schemas ?? [],\n actionContext\n );\n\n // Every diagnostic resolves against the shared entries the host supplied;\n // with no schemas supplied a reference is unverifiable, never \"unknown\".\n const diagnose = (draft: WidgetDraft): DesignerDiagnostics =>\n deriveDiagnostics(draft, {\n ...(options.schemas === undefined ? {} : { schemas: options.schemas }),\n actions: options.actions ?? []\n });\n\n function refresh(draft: WidgetDraft): void {\n const diagnostics = diagnose(draft);\n preview.update(draft, diagnostics);\n for (const listener of [...listeners]) listener(draft, diagnostics);\n }\n\n const unsubscribe = store.subscribe(refresh);\n refresh(store.get());\n\n /**\n * Read-only: every editing surface goes inert (visible, inoperable \u2014\n * section summaries stay clickable so content can still be inspected),\n * while the preview and the theme panel's selector keep working. inert\n * is applied to section BODIES, which are stable elements: panel\n * re-renders replace children inside them, never the bodies themselves.\n */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n // Complex selectors inside :not() are not universally supported, so\n // the view-only exclusion is filtered here rather than in the query.\n const bodies = [\n ...root.querySelectorAll(\n \".wgd-panels .wgd-section-body, .wgd-edit-only > .wgd-section-body\"\n )\n ].filter((body) => !body.parentElement?.classList.contains(\"wgd-view-only\"));\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getDraft: () => cloneDraft(store.get()),\n getDiagnostics: () => diagnose(store.get()),\n setReadOnly,\n loadWidget(definition) {\n const errors = checkDefinition(definition, store.get().kind);\n if (errors.length > 0) return { ok: false, errors };\n applyDefinition(store, definition as unknown as WidgetDefinition);\n return { ok: true };\n },\n checkWidget(definition) {\n const errors = checkDefinition(definition, store.get().kind);\n if (errors.length > 0) return { ok: false, errors };\n const { kind, template, descriptor, load } = definition as unknown as WidgetDefinition;\n return { ok: true, diagnostics: diagnose({ kind, template, descriptor, ...(load === undefined ? {} : { load }) }) };\n },\n loadTheme(theme) {\n const validated = validateTheme(theme);\n if (!validated.ok) {\n return { ok: false, errors: [validated.error.message] };\n }\n // Tokens layer over the person's chosen preview theme, which stays\n // chosen with its shared styles, so `{}` returns to it exactly. With\n // nothing chosen they are the whole preview theme.\n store.update((draft) => {\n const { themeStyles: _previous, ...rest } = draft;\n const chosen = options.themes?.find((entry) => entry.name === draft.previewTheme);\n return {\n ...rest,\n theme: { ...(chosen?.tokens ?? {}), ...validated.theme },\n ...(chosen?.styles === undefined ? {} : { themeStyles: chosen.styles })\n };\n });\n return { ok: true };\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n unsubscribe();\n panels.dispose();\n preview.dispose();\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone schema designer: edits a stored-schema entry\n * (`{ name, label?, description?, schema }` \u2014 the widget-store's shape)\n * so one definition (`person`) can serve many widgets. Split out like the\n * theme designer: an app routes to \"design a schema\" as its own\n * destination, and a host embedding one designer should not ship the\n * others. Shares the chrome, the schema builder, and the parse-gated\n * JSON discipline.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { auditDataSchema, isPlainObject, SAFE_IDENTIFIER } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\n\nexport interface SchemaEntry {\n name: string;\n label?: string;\n description?: string;\n schema: Record<string, unknown>;\n}\n\nexport interface SchemaDesignerOptions {\n initialSchema?: SchemaEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Mount with editing disabled: panels stay visible but inert. Toggle\n * later via `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type SchemaLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface SchemaDesignerHandle {\n getSchema(): SchemaEntry;\n loadSchema(entry: unknown): SchemaLoadResult;\n /** Disable/enable editing. */\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: SchemaEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): SchemaEntry {\n return {\n name: \"my-schema\",\n label: \"My schema\",\n schema: { type: \"object\", properties: {} }\n };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkSchemaEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(entry)) return [\"Schema entry must be an object.\"];\n if (typeof entry.name !== \"string\" || entry.name.trim() === \"\") {\n errors.push(\"'name' must be a non-empty string.\");\n } else if (!SAFE_IDENTIFIER.test(entry.name)) {\n errors.push(\n `'${entry.name}' is not a valid schema name \u2014 use letters, digits, '.', '_' or '-'.`\n );\n }\n if (!isPlainObject(entry.schema)) {\n errors.push(\"'schema' must be a plain object.\");\n }\n return errors;\n}\n\nexport function createSchemaDesigner(\n container: Element,\n options: SchemaDesignerOptions = {}\n): SchemaDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: SchemaEntry = options.initialSchema\n ? (JSON.parse(JSON.stringify(options.initialSchema)) as SchemaEntry)\n : starterEntry();\n const listeners = new Set<(entry: SchemaEntry) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-schema-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n function getEntry(): SchemaEntry {\n return JSON.parse(JSON.stringify(entry)) as SchemaEntry;\n }\n\n // What the validator would ignore in the schema: a warning the person\n // sees while editing, never a refusal (the store accepts it).\n const schemaDiag = diagnosticLine(undefined);\n function showSchemaWarnings(): void {\n const warnings = isPlainObject(entry.schema) ? auditDataSchema(entry.schema) : [];\n schemaDiag.hidden = warnings.length === 0;\n schemaDiag.textContent = warnings.join(\"\\n\");\n }\n\n function notify(): void {\n showSchemaWarnings();\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n // --- Identity panel ----------------------------------------------------\n const identityRefreshers: (() => void)[] = [];\n const nameDiag = diagnosticLine(undefined);\n\n function identityField(\n label: string,\n read: () => string,\n write: (value: string) => void\n ): HTMLElement {\n const field = textField(label, read(), write);\n const input = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== input) input.value = read();\n });\n return field;\n }\n\n const identity = section(\"Schema\", [\n identityField(\n \"Name (id)\",\n () => entry.name,\n (value) => {\n entry = { ...entry, name: value };\n const bad = value.trim() === \"\" || !SAFE_IDENTIFIER.test(value);\n nameDiag.hidden = !bad;\n nameDiag.textContent = bad\n ? \"Name must be non-empty using letters, digits, '.', '_' or '-'.\"\n : \"\";\n notify();\n }\n ),\n nameDiag,\n identityField(\n \"Label\",\n () => entry.label ?? \"\",\n (value) => {\n entry = { ...entry, label: value };\n notify();\n }\n ),\n identityField(\n \"Description\",\n () => entry.description ?? \"\",\n (value) => {\n entry = { ...entry, description: value };\n notify();\n }\n )\n ]);\n\n // --- Definition panel: builder + parse-gated JSON, one view at a time --\n const builder = createSchemaBuilder(entry.schema as DataSchema, (schema) => {\n entry = { ...entry, schema: (schema ?? {}) as Record<string, unknown> };\n syncJson();\n notify();\n });\n\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"12\",\n spellcheck: \"false\"\n });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n jsonArea.value = JSON.stringify(entry.schema, null, 2);\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n if (!isPlainObject(parsed)) throw new Error(\"schema must be an object\");\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n entry = { ...entry, schema: parsed };\n builder.setValue(parsed as DataSchema);\n notify();\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid JSON (schema keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n });\n\n function syncJson(): void {\n if (document.activeElement === jsonArea) return;\n jsonArea.value = JSON.stringify(entry.schema, null, 2);\n repaintHighlight(jsonArea);\n }\n\n const builderTab = h(\n \"button\",\n { class: \"wgd-button wgd-tab wgd-tab-active\", type: \"button\" },\n [\"Builder\"]\n );\n const jsonTab = h(\"button\", { class: \"wgd-button wgd-tab\", type: \"button\" }, [\n \"JSON\"\n ]);\n jsonWrap.hidden = true;\n builderTab.addEventListener(\"click\", () => {\n builder.element.hidden = false;\n jsonWrap.hidden = true;\n builderTab.classList.add(\"wgd-tab-active\");\n jsonTab.classList.remove(\"wgd-tab-active\");\n });\n jsonTab.addEventListener(\"click\", () => {\n builder.element.hidden = true;\n jsonWrap.hidden = false;\n jsonTab.classList.add(\"wgd-tab-active\");\n builderTab.classList.remove(\"wgd-tab-active\");\n syncJson();\n });\n\n const definition = section(\"Definition\", [\n h(\"div\", { class: \"wgd-row\" }, [builderTab, jsonTab]),\n builder.element,\n jsonWrap,\n schemaDiag\n ]);\n\n // --- Import / Export: the agent hand-off -------------------------------\n // Live testing surfaced this within a day of list_schemas shipping: an\n // agent drafts the complete entry JSON from the guide, and Import is\n // where the user pastes it. Same two-section shape as the siblings.\n const importError = diagnosticLine(undefined);\n const importArea = h(\"textarea\", {\n class: \"wgd-textarea wgd-schema-import\",\n rows: \"6\",\n spellcheck: \"false\"\n });\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\n \"Import\"\n ]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadSchema(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n const importSection = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Import schema entry JSON ({ name, label?, description?, schema })\"\n ]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"Export schema entry\"\n ]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n repaintHighlight(output);\n });\n const exportSection = section(\"Export\", [\n h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]),\n output\n ]);\n // Export copies out what is on screen \u2014 read-only leaves it operable.\n exportSection.classList.add(\"wgd-view-only\");\n\n panels.append(identity, definition, importSection, exportSection);\n showSchemaWarnings();\n // The JSON layer wraps the textareas in place, so attach after assembly.\n attachJsonHighlight(jsonArea);\n attachJsonHighlight(importArea);\n attachJsonHighlight(output);\n\n function loadSchema(input: unknown): SchemaLoadResult {\n const errors = checkSchemaEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = JSON.parse(JSON.stringify(input)) as SchemaEntry;\n for (const refresh of identityRefreshers) refresh();\n nameDiag.hidden = true;\n builder.setValue(entry.schema as DataSchema);\n syncJson();\n notify();\n return { ok: true };\n }\n\n /** Same mechanism as the other designers: inert the section bodies \u2014\n * except the view-only Export, which restricts nothing. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getSchema: getEntry,\n loadSchema,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone theme designer: edits a NAMED theme entry\n * (`{ name, label?, description?, tokens, styles? }` \u2014 the theme\n * registry's shape, which is also what a host persists) with live preview\n * against any catalog kind. Its styles are edited with the widget\n * designer's own styles panel: one shape, one rule set, one editor.\n *\n * Split from the widget designer on purpose: an app routes to \"design a\n * theme\" and \"design a widget\" as separate destinations, and a host\n * embedding one should not ship the other. Both share the preview\n * controller, chrome, and store discipline.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { createCatalog, createThemeRegistry, SAFE_IDENTIFIER } from \"@widgentic/core\";\nimport {\n THEME_TOKENS,\n TOKEN_DEFAULTS,\n TOKEN_SPECS,\n isSafeTokenValue,\n TOKEN_VALUE_RULE,\n isStyleMap,\n validateTheme\n} from \"@widgentic/core\";\nimport type { ThemeEntry, WidgetStyles, WidgetThemeInput } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { createPreview } from \"./preview.js\";\nimport type { PreviewWidget } from \"./preview.js\";\nimport { starterDraft } from \"./store.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport { createStylesPanel } from \"./styles-panel.js\";\nimport { auditStyles } from \"./validate.js\";\n\nconst BASE_KINDS = createCatalog().kinds();\n\n/** Hex form the native color input accepts. */\nconst HEX = /^#[0-9a-f]{3}([0-9a-f]{3})?$/i;\nconst CUSTOM_NAME = /^x-[a-z0-9][a-z0-9-]*$/;\n\nfunction toHexInput(value: string): string | undefined {\n if (!HEX.test(value)) return undefined;\n if (value.length === 7) return value.toLowerCase();\n const [, r, g, b] = value.toLowerCase();\n return `#${r}${r}${g}${g}${b}${b}`;\n}\n\nexport interface ThemeDesignerOptions {\n initialTheme?: ThemeEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Custom widget definitions to offer in the preview-kind selector\n * beside the built-ins \u2014 a theme is judged against the widgets it will\n * actually dress. Invalid definitions are skipped.\n */\n widgets?: PreviewWidget[];\n /**\n * Mount with editing disabled: panels stay visible but inert, only the\n * preview and its kind selector operate. Toggle later via `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type ThemeLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface ThemeDesignerHandle {\n getTheme(): ThemeEntry;\n loadTheme(entry: unknown): ThemeLoadResult;\n /** Disable/enable editing; the preview and kind selector stay live. */\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: ThemeEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): ThemeEntry {\n return { name: \"my-theme\", label: \"My theme\", tokens: {} };\n}\n\n/** Theme names a stored theme may never take, read from the registry. */\nconst BUILT_IN_THEMES: ReadonlySet<string> = new Set(createThemeRegistry().names());\n\n/** What saving would refuse about a name, in the store's terms. */\nfunction nameProblem(name: string): string | undefined {\n if (!SAFE_IDENTIFIER.test(name)) {\n return `INVALID_IDENTIFIER \u2014 '${name}' may use letters, digits, '.', '_' or '-' only.`;\n }\n if (BUILT_IN_THEMES.has(name)) {\n return `RESERVED_THEME \u2014 '${name}' is a built-in theme; give yours its own name.`;\n }\n return undefined;\n}\n\n/**\n * A copy of an entry for the designer to hold. A retired `extends` is left\n * behind: the registry ignores it, and a field the designer handed back\n * (to `getTheme`, Export, Save or an agent) would look meaningful.\n */\nfunction takeEntry(input: unknown): ThemeEntry {\n const { extends: _retired, ...entry } = JSON.parse(JSON.stringify(input)) as ThemeEntry & { extends?: unknown };\n return entry;\n}\n\n/**\n * Validate an untrusted entry; errors instead of throwing. The name is held\n * to what saving accepts only when it differs from `currentName`: a name the\n * entry already has is the person's to fix (the Name field flags it), and\n * reloading the same entry with new tokens must not fail on it.\n */\nexport function checkThemeEntry(entry: unknown, currentName?: string): string[] {\n const errors: string[] = [];\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n return [\"Theme entry must be an object.\"];\n }\n const candidate = entry as Record<string, unknown>;\n if (typeof candidate.name !== \"string\" || candidate.name.trim() === \"\") {\n errors.push(\"'name' must be a non-empty string.\");\n } else if (candidate.name !== currentName) {\n const problem = nameProblem(candidate.name);\n if (problem !== undefined) errors.push(`name: ${problem}`);\n }\n const validated = validateTheme(candidate.tokens ?? {});\n if (!validated.ok) {\n errors.push(`tokens: ${validated.error.code} \u2014 ${validated.error.message}`);\n }\n if (candidate.styles !== undefined && !isStyleMap(candidate.styles)) {\n errors.push(\"styles: must map selectors to objects of property/value strings.\");\n }\n return errors;\n}\n\nexport function createThemeDesigner(\n container: Element,\n options: ThemeDesignerOptions = {}\n): ThemeDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: ThemeEntry = options.initialTheme ? takeEntry(options.initialTheme) : starterEntry();\n const listeners = new Set<(entry: ThemeEntry) => void>();\n\n const preview = createPreview(\n options.widgets ? { widgets: options.widgets } : {}\n );\n // Built-ins plus whatever custom definitions the host supplied.\n const previewKinds = preview.kinds.length > 0 ? preview.kinds : BASE_KINDS;\n let previewKind = previewKinds[0] ?? \"card\";\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const side = h(\"div\", { class: \"wgd-side\" }, [preview.pane]);\n const root = h(\"div\", { class: \"wgd-root wgd-theme-designer\" }, [panels, side]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n /** A draft carrying only what the preview needs: kind + this theme. */\n function previewDraft(): WidgetDraft {\n const draft: WidgetDraft = { ...starterDraft(), theme: entry.tokens };\n return entry.styles === undefined ? draft : { ...draft, themeStyles: entry.styles };\n }\n\n function refresh(): void {\n preview.update(previewDraft(), { styles: [], previewable: true }, previewKind);\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n function getEntry(): ThemeEntry {\n return JSON.parse(JSON.stringify(entry)) as ThemeEntry;\n }\n\n function setToken(key: string, value: string): void {\n const tokens = { ...entry.tokens } as Record<string, string>;\n if (value === \"\") delete tokens[key];\n else tokens[key] = value;\n entry = { ...entry, tokens: tokens as WidgetThemeInput };\n refresh();\n }\n\n // --- Identity panel ----------------------------------------------------\n /** Bind a text field and register its refresher (import must update it). */\n const identityRefreshers: (() => void)[] = [];\n function identityField(\n label: string,\n read: () => string,\n write: (value: string) => void\n ): HTMLElement {\n const field = textField(label, read(), write);\n const input = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== input) input.value = read();\n });\n return field;\n }\n\n // A name saving would refuse is flagged as it is typed, in the store's terms.\n const nameDiag = diagnosticLine(undefined);\n function showNameProblem(): void {\n const problem = entry.name.trim() === \"\" ? \"'name' must be a non-empty string.\" : nameProblem(entry.name);\n nameDiag.hidden = problem === undefined;\n nameDiag.textContent = problem ?? \"\";\n }\n identityRefreshers.push(showNameProblem);\n const identity = section(\"Theme\", [\n identityField(\n \"Name (id)\",\n () => entry.name,\n (value) => {\n entry = { ...entry, name: value };\n showNameProblem();\n refresh();\n }\n ),\n nameDiag,\n identityField(\n \"Label\",\n () => entry.label ?? \"\",\n (value) => {\n entry = { ...entry, label: value };\n refresh();\n }\n ),\n identityField(\n \"Description\",\n () => entry.description ?? \"\",\n (value) => {\n entry = { ...entry, description: value };\n refresh();\n }\n )\n ]);\n\n showNameProblem();\n\n // The kind selector is a PREVIEW control, so it lives beside the\n // preview, outside the editing panels \u2014 read-only mode keeps it live.\n const kindSelect = h(\"select\", {\n class: \"wgd-select wgd-preview-kind\"\n });\n for (const kind of previewKinds) {\n kindSelect.append(h(\"option\", { value: kind }, [kind]));\n }\n kindSelect.value = previewKind;\n kindSelect.addEventListener(\"change\", () => {\n previewKind = kindSelect.value;\n refresh();\n });\n side.prepend(\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Preview kind\"]),\n kindSelect\n ])\n );\n\n // --- Token panel -------------------------------------------------------\n const tokenRefreshers: (() => void)[] = [];\n const tokenRows: (Node | string)[] = [];\n for (const token of THEME_TOKENS) {\n const input = h(\"input\", {\n type: \"text\",\n class: \"wgd-input\",\n placeholder: TOKEN_DEFAULTS[token]\n });\n input.value = entry.tokens[token] ?? \"\";\n const issue = diagnosticLine(undefined);\n // Control choice comes from the token's declared type \u2014 no guessing.\n const swatch = TOKEN_SPECS[token].type === \"color\"\n ? (h(\"input\", {\n type: \"color\",\n class: \"wgd-swatch\",\n title: `Pick --wg-${token}`\n }))\n : undefined;\n\n const paint = (value: string): void => {\n const effective = value === \"\" ? TOKEN_DEFAULTS[token] : value;\n if (swatch !== undefined) {\n const hex = toHexInput(effective);\n if (hex !== undefined) swatch.value = hex;\n swatch.style.background = isSafeTokenValue(effective) ? effective : \"transparent\";\n }\n };\n paint(input.value);\n swatch?.addEventListener(\"input\", () => {\n input.value = swatch.value;\n input.dispatchEvent(new Event(\"input\", { bubbles: true }));\n });\n input.addEventListener(\"input\", () => {\n const unsafe = input.value !== \"\" && !isSafeTokenValue(input.value);\n issue.hidden = !unsafe;\n issue.textContent = unsafe\n ? `INVALID_TOKEN_VALUE: unsafe value withheld from the preview. ${TOKEN_VALUE_RULE}`\n : \"\";\n paint(input.value);\n setToken(token, input.value);\n });\n tokenRefreshers.push(() => {\n if (document.activeElement !== input) {\n input.value = entry.tokens[token] ?? \"\";\n paint(input.value);\n }\n });\n tokenRows.push(\n h(\"div\", undefined, [\n h(\"label\", { class: \"wgd-field\", title: TOKEN_SPECS[token].use }, [\n h(\"span\", { class: \"wgd-field-label\" }, [`--wg-${token}`]),\n h(\n \"div\",\n { class: \"wgd-token-row\" },\n swatch === undefined ? [input] : [input, swatch]\n )\n ]),\n issue\n ])\n );\n }\n const tokenPanel = section(\"Tokens\", tokenRows);\n\n // --- Custom variables --------------------------------------------------\n const customHost = h(\"div\", { class: \"wgd-jt-children\" });\n const customError = diagnosticLine(undefined);\n\n function customEntries(): [string, string][] {\n return Object.entries(entry.tokens).filter(([key]) =>\n CUSTOM_NAME.test(key)\n ) as [string, string][];\n }\n\n function renderCustom(): void {\n const rows = customEntries().map(([key, value]) => {\n const nameInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-jt-keyinput\"\n });\n nameInput.value = key;\n nameInput.addEventListener(\"change\", () => {\n const next = nameInput.value;\n if (!CUSTOM_NAME.test(next)) {\n customError.hidden = false;\n customError.textContent = `'${next}' is not a valid custom name \u2014 use x-<lowercase-kebab>.`;\n nameInput.value = key;\n return;\n }\n customError.hidden = true;\n const tokens = { ...entry.tokens } as Record<string, string>;\n delete tokens[key];\n tokens[next] = value;\n entry = { ...entry, tokens: tokens as WidgetThemeInput };\n renderCustom();\n refresh();\n });\n const valueInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input\"\n });\n valueInput.value = value;\n valueInput.addEventListener(\"input\", () => setToken(key, valueInput.value));\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => {\n setToken(key, \"\");\n renderCustom();\n });\n return h(\"div\", { class: \"wgd-attr-row\" }, [nameInput, valueInput, remove]);\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ variable\"\n ]);\n add.addEventListener(\"click\", () => {\n let name = \"x-custom\";\n for (let i = 1; name in entry.tokens; i++) name = `x-custom${i}`;\n setToken(name, \"0\");\n renderCustom();\n });\n customHost.replaceChildren(...rows, h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n renderCustom();\n const customPanel = section(\"Custom variables (--wg-x-*)\", [\n customHost,\n customError\n ]);\n\n // --- Import / export ---------------------------------------------------\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"Export theme entry\"\n ]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n });\n const importArea = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"5\",\n spellcheck: \"false\"\n });\n const importError = diagnosticLine(undefined);\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Import\"]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadTheme(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n // Two independent sections, import first \u2014 the same shape the widget\n // designer uses, so both designers read alike.\n const importPanel = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Import theme entry JSON\"]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n const exportPanel = section(\"Export\", [\n h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]),\n output\n ]);\n exportPanel.classList.add(\"wgd-view-only\");\n\n // Shared classes for every widget the theme dresses \u2014 the widget\n // designer's own panel, so the shape, guards and audit are identical.\n const stylesPanel = createStylesPanel(entry.styles, (styles: WidgetStyles | undefined) => {\n const { styles: _previous, ...rest } = entry;\n entry = styles === undefined ? rest : { ...rest, styles };\n stylesPanel.setIssues(auditStyles(entry.styles));\n refresh();\n });\n stylesPanel.setIssues(auditStyles(entry.styles));\n\n panels.append(identity, tokenPanel, customPanel, importPanel, exportPanel);\n // Under the preview, where the widget designer keeps its Styles panel:\n // styles are judged against what they dress.\n stylesPanel.element.classList.add(\"wgd-edit-only\");\n side.append(stylesPanel.element);\n\n function loadTheme(input: unknown): ThemeLoadResult {\n const errors = checkThemeEntry(input, entry.name);\n if (errors.length > 0) return { ok: false, errors };\n entry = takeEntry(input);\n for (const refreshIdentity of identityRefreshers) refreshIdentity();\n for (const refreshToken of tokenRefreshers) refreshToken();\n renderCustom();\n stylesPanel.setValue(entry.styles);\n stylesPanel.setIssues(auditStyles(entry.styles));\n refresh();\n return { ok: true };\n }\n\n refresh();\n\n /** Same mechanism as the widget designer: inert the section bodies. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [\n ...root.querySelectorAll(\".wgd-panels .wgd-section-body, .wgd-edit-only > .wgd-section-body\")\n ].filter((body) => !body.parentElement?.classList.contains(\"wgd-view-only\"));\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getTheme: getEntry,\n loadTheme,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n preview.dispose();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone action designer: edits a stored-action entry\n * (`{ name, label?, description?, definition }` \u2014 the widget-store's\n * shape). Split out like the theme and schema designers. The Test control\n * appears only when the host supplies `options.testCall`: the library\n * performs no network I/O, and a test call must run through the host's\n * production execution path (secrets, SSRF guard, redaction).\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { ActionDefinition, HttpActionDefinition, StoredAction } from \"@widgentic/core\";\nimport { ACTION_NAME, validateActionDefinition } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { clone } from \"./internal.js\";\nimport { createDefinitionEditor } from \"./action-editor.js\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { createSchemaForm } from \"./schema-form.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\n\nexport type ActionEntry = StoredAction;\n\nexport interface ActionDesignerOptions {\n initialAction?: ActionEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n readOnly?: boolean;\n /** Shared schemas offered as \"copy from\" sources for input/output. */\n schemas?: SchemaEntry[];\n /** Secret names offered for header/query values. */\n secretNames?: string[];\n /**\n * Host-supplied test call (the production execute path). Without it no\n * Test control renders. Resolves to whatever the host wants shown \u2014\n * typically the redacted response or a structured error.\n */\n testCall?: (definition: HttpActionDefinition, args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport type ActionLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface ActionDesignerHandle {\n getAction(): ActionEntry;\n loadAction(entry: unknown): ActionLoadResult;\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: ActionEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): ActionEntry {\n return {\n name: \"my-action\",\n label: \"My action\",\n definition: { kind: \"prompt\", text: [\"Tell me more about \", { bind: \"title\" }] }\n };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkActionEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(entry)) return [\"Action entry must be an object.\"];\n if (typeof entry.name !== \"string\" || !ACTION_NAME.test(entry.name)) {\n errors.push(\"'name' must be lowercase letters, digits and dashes, starting with a letter (max 64).\");\n }\n for (const field of [\"label\", \"description\"] as const) {\n if (entry[field] !== undefined && typeof entry[field] !== \"string\") {\n errors.push(`'${field}' must be a string when present.`);\n }\n }\n const problem = validateActionDefinition(entry.definition, \"definition\");\n if (problem) errors.push(`${problem.message} (at ${problem.path})`);\n return errors;\n}\n\n/** A checked entry with only the fields the shape declares; empty texts are dropped. */\nfunction normalizeEntry(input: Record<string, unknown>): ActionEntry {\n const entry: ActionEntry = { name: input.name as string, definition: clone(input.definition as ActionDefinition) };\n if (typeof input.label === \"string\" && input.label !== \"\") entry.label = input.label;\n if (typeof input.description === \"string\" && input.description !== \"\") entry.description = input.description;\n return entry;\n}\n\n/** Set or drop an optional text field: an emptied field leaves the entry. */\nfunction withText(current: ActionEntry, field: \"label\" | \"description\", value: string): ActionEntry {\n const { [field]: _gone, ...rest } = current;\n return value === \"\" ? rest : { ...rest, [field]: value };\n}\n\nexport function createActionDesigner(\n container: Element,\n options: ActionDesignerOptions = {}\n): ActionDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: ActionEntry = options.initialAction ? clone(options.initialAction) : starterEntry();\n const testCall = options.testCall;\n const listeners = new Set<(entry: ActionEntry) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-action-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n const getEntry = (): ActionEntry => clone(entry);\n function notify(): void {\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n // --- Identity --------------------------------------------------------\n const identityRefreshers: (() => void)[] = [];\n const nameDiag = diagnosticLine(undefined);\n function identityField(label: string, read: () => string, write: (value: string) => void): HTMLElement {\n const field = textField(label, read(), write);\n const inputEl = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== inputEl) inputEl.value = read();\n });\n return field;\n }\n const identity = section(\"Action\", [\n identityField(\"Name (id)\", () => entry.name, (value) => {\n entry = { ...entry, name: value };\n const bad = !ACTION_NAME.test(value);\n nameDiag.hidden = !bad;\n nameDiag.textContent = bad ? \"Name must be lowercase letters, digits and dashes, starting with a letter.\" : \"\";\n notify();\n }),\n nameDiag,\n identityField(\"Label\", () => entry.label ?? \"\", (value) => {\n entry = withText(entry, \"label\", value);\n notify();\n }),\n identityField(\"Description\", () => entry.description ?? \"\", (value) => {\n entry = withText(entry, \"description\", value);\n notify();\n })\n ]);\n\n // --- Definition: editor + parse-gated JSON -----------------------------\n const definitionDiag = diagnosticLine(undefined);\n const editor = createDefinitionEditor(\n entry.definition,\n { ...(options.schemas ? { schemas: options.schemas } : {}), ...(options.secretNames ? { secretNames: options.secretNames } : {}) },\n (definition) => {\n entry = { ...entry, definition };\n syncJson();\n refreshDefinitionDiag();\n refreshTest();\n notify();\n }\n );\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", { class: \"wgd-textarea\", rows: \"12\", spellcheck: \"false\" });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n jsonArea.value = JSON.stringify(entry.definition, null, 2);\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n const problem = validateActionDefinition(parsed, \"definition\");\n if (problem) throw new Error(`${problem.message} (at ${problem.path})`);\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n entry = { ...entry, definition: parsed as ActionDefinition };\n editor.setValue(entry.definition);\n refreshDefinitionDiag();\n refreshTest();\n notify();\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid (definition keeps the last valid value): ${errorMessage(error)}`;\n }\n });\n function syncJson(): void {\n if (document.activeElement === jsonArea) return;\n jsonArea.value = JSON.stringify(entry.definition, null, 2);\n repaintHighlight(jsonArea);\n }\n function refreshDefinitionDiag(): void {\n const problem = validateActionDefinition(entry.definition, \"definition\");\n definitionDiag.hidden = problem === undefined;\n definitionDiag.textContent = problem ? `${problem.message} (at ${problem.path})` : \"\";\n }\n refreshDefinitionDiag();\n\n const builderTab = h(\"button\", { class: \"wgd-button wgd-tab wgd-tab-active\", type: \"button\" }, [\"Editor\"]);\n const jsonTab = h(\"button\", { class: \"wgd-button wgd-tab\", type: \"button\" }, [\"JSON\"]);\n jsonWrap.hidden = true;\n builderTab.addEventListener(\"click\", () => {\n editor.element.hidden = false;\n jsonWrap.hidden = true;\n builderTab.classList.add(\"wgd-tab-active\");\n jsonTab.classList.remove(\"wgd-tab-active\");\n });\n jsonTab.addEventListener(\"click\", () => {\n editor.element.hidden = true;\n jsonWrap.hidden = false;\n jsonTab.classList.add(\"wgd-tab-active\");\n builderTab.classList.remove(\"wgd-tab-active\");\n syncJson();\n });\n const definition = section(\"Definition\", [\n h(\"div\", { class: \"wgd-row\" }, [builderTab, jsonTab]),\n definitionDiag,\n editor.element,\n jsonWrap\n ]);\n\n // --- Test (host-supplied) ------------------------------------------------\n const testHost = h(\"div\", { class: \"wgd-action-test\" });\n const testSection = section(\"Test\", [testHost]);\n let testArgs: Record<string, unknown> = {};\n // Arguments belong to one input schema: a different schema starts them over.\n let testInputJson: string | undefined;\n function refreshTest(): void {\n if (testCall === undefined) return;\n testHost.replaceChildren();\n if (entry.definition.kind !== \"http\") {\n testInputJson = undefined;\n testArgs = {};\n testHost.append(h(\"p\", { class: \"wgd-diagnostic\" }, [\"Prompt actions run in the host's composer; nothing to test.\"]));\n return;\n }\n const definitionNow = entry.definition;\n const inputJson = JSON.stringify(definitionNow.input);\n if (inputJson !== testInputJson) testArgs = {};\n testInputJson = inputJson;\n const form = createSchemaForm(definitionNow.input as DataSchema, testArgs, (value) => {\n testArgs = isPlainObject(value) ? value : {};\n });\n testArgs = isPlainObject(form.getValue()) ? (form.getValue() as Record<string, unknown>) : {};\n const output = h(\"pre\", { class: \"wgd-test-output\" });\n const run = h(\"button\", { class: \"wgd-button wgd-add wgd-test-run\", type: \"button\" }, [\"Test call\"]);\n run.addEventListener(\"click\", () => {\n run.disabled = true;\n run.classList.add(\"wgd-busy\");\n run.setAttribute(\"aria-busy\", \"true\");\n output.textContent = \"\u2026\";\n void testCall(definitionNow, testArgs)\n .then((result) => {\n output.textContent = typeof result === \"string\" ? result : JSON.stringify(result, null, 2);\n })\n .catch((error: Error) => {\n output.textContent = `Test failed: ${error.message}`;\n })\n .finally(() => {\n run.disabled = false;\n run.classList.remove(\"wgd-busy\");\n run.removeAttribute(\"aria-busy\");\n });\n });\n testHost.append(h(\"span\", { class: \"wgd-field-label\" }, [\"Arguments\"]), form.element, h(\"div\", { class: \"wgd-row\" }, [run]), output);\n }\n refreshTest();\n\n // --- Import / Export ------------------------------------------------------\n const importError = diagnosticLine(undefined);\n const importArea = h(\"textarea\", { class: \"wgd-textarea wgd-action-import\", rows: \"6\", spellcheck: \"false\" });\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Import\"]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadAction(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n const importSection = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Import action entry JSON ({ name, label?, description?, definition })\"]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n const output = h(\"textarea\", { class: \"wgd-textarea\", rows: \"8\", readonly: \"\", spellcheck: \"false\" });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"Export action entry\"]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n repaintHighlight(output);\n });\n const exportSection = section(\"Export\", [h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]), output]);\n exportSection.classList.add(\"wgd-view-only\");\n\n panels.append(identity, definition, ...(testCall === undefined ? [] : [testSection]), importSection, exportSection);\n attachJsonHighlight(jsonArea);\n attachJsonHighlight(importArea);\n attachJsonHighlight(output);\n\n function loadAction(input: unknown): ActionLoadResult {\n const errors = checkActionEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = normalizeEntry(input as Record<string, unknown>);\n testArgs = {};\n for (const refresh of identityRefreshers) refresh();\n nameDiag.hidden = true;\n editor.setValue(entry.definition);\n syncJson();\n refreshDefinitionDiag();\n refreshTest();\n notify();\n return { ok: true };\n }\n\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getAction: getEntry,\n loadAction,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Settings designer: edits a principal's settings record \u2014 account-wide\n * preferences, one titled subsection per section. This version edits\n * `defaultThemes` (the theme light hosts and dark hosts get when a render\n * names none; one choice per mode, so choosing a theme replaces the mode's\n * previous one) and `resourceDomains` (the domains MCP Apps frames may load\n * images from directly), each entry checked live by the core rule the store\n * applies: a valid one is recorded canonical, an invalid one as typed, so\n * the save's refusal names what the person sees. Sections it does not edit\n * pass through untouched, and the host saves (the designer writes nothing).\n */\nimport { RESOURCE_DOMAIN_LIMIT, isPlainObject, parseResourceDomain } from \"@widgentic/core\";\nimport type { ThemeEntry, ThemeMode } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { clone } from \"./internal.js\";\n\n/** The settings record as the designer sees it: known sections plus any it passes through. */\nexport interface SettingsRecord {\n defaultThemes?: Partial<Record<ThemeMode, string>>;\n /** Canonical origins, plus any entry the person typed that the rule refuses. */\n resourceDomains?: string[];\n [section: string]: unknown;\n}\n\nexport interface SettingsDesignerOptions {\n initialSettings?: SettingsRecord;\n /** The person's themes, offered as choices beside the built-ins. */\n themes?: Pick<ThemeEntry, \"name\" | \"label\">[];\n appearance?: \"auto\" | \"light\" | \"dark\";\n /** Host chrome, as for the other designers. */\n chrome?: ChromeOptions;\n /** Mount with the choices visible but inert. Toggle later via `setReadOnly`. */\n readOnly?: boolean;\n}\n\nexport type SettingsLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface SettingsDesignerHandle {\n /** The record, built-in choices omitted; unedited sections as supplied. */\n getSettings(): SettingsRecord;\n loadSettings(settings: unknown): SettingsLoadResult;\n /** Replace the themes offered as choices; the record is kept as it is. */\n setThemes(themes: Pick<ThemeEntry, \"name\" | \"label\">[]): void;\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (settings: SettingsRecord) => void): () => void;\n dispose(): void;\n}\n\nconst MODES: readonly { mode: ThemeMode; label: string; builtIn: string }[] = [\n { mode: \"light\", label: \"Light hosts\", builtIn: \"Built-in light\" },\n { mode: \"dark\", label: \"Dark hosts\", builtIn: \"Built-in dark\" }\n];\n\n/** Shape check for an untrusted record; errors instead of throwing. */\nfunction checkSettings(settings: unknown): string[] {\n if (!isPlainObject(settings)) return [\"Settings must be an object of named sections.\"];\n const errors: string[] = [];\n const domains = settings.resourceDomains;\n if (domains !== undefined && (!Array.isArray(domains) || !domains.every((entry) => typeof entry === \"string\"))) {\n errors.push(\"resourceDomains: must be a list of domain strings.\");\n }\n const themes = settings.defaultThemes;\n if (themes === undefined) return errors;\n if (!isPlainObject(themes)) return [...errors, \"defaultThemes: must be an object of { light?, dark? }.\"];\n for (const [mode, name] of Object.entries(themes)) {\n if (!MODES.some((known) => known.mode === mode)) errors.push(`defaultThemes: '${mode}' is not a theme mode.`);\n else if (typeof name !== \"string\") errors.push(`defaultThemes: the ${mode} default must be a theme name.`);\n }\n return errors;\n}\n\nexport function createSettingsDesigner(\n container: Element,\n options: SettingsDesignerOptions = {}\n): SettingsDesignerHandle {\n injectDesignerStyles(document);\n\n let themes = options.themes ?? [];\n let record: SettingsRecord = options.initialSettings ? clone(options.initialSettings) : {};\n const listeners = new Set<(settings: SettingsRecord) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-settings-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n function getSettings(): SettingsRecord {\n // The edited section is always present (possibly empty), so a host\n // saving it clears a mode the person set back to the built-in.\n return { ...clone(record), defaultThemes: clone(record.defaultThemes ?? {}) };\n }\n\n function notify(): void {\n for (const listener of [...listeners]) listener(getSettings());\n }\n\n // --- Default themes ----------------------------------------------------\n const selects = new Map<ThemeMode, HTMLSelectElement>();\n\n function fillSelect(select: HTMLSelectElement, mode: ThemeMode, builtIn: string): void {\n const current = record.defaultThemes?.[mode];\n select.replaceChildren(h(\"option\", { value: \"\" }, [builtIn]));\n for (const theme of themes) {\n select.append(h(\"option\", { value: theme.name }, [theme.label ?? theme.name]));\n }\n // A default whose theme the host did not supply stays visible and\n // selected until the person picks another \u2014 never dropped silently.\n if (current !== undefined && !themes.some((theme) => theme.name === current)) {\n select.append(h(\"option\", { value: current, class: \"wgd-unavailable\" }, [`${current} (unavailable)`]));\n }\n select.value = current ?? \"\";\n }\n\n const rows = MODES.map(({ mode, label, builtIn }) => {\n const select = h(\"select\", { class: \"wgd-select wgd-default-theme\", \"data-mode\": mode });\n fillSelect(select, mode, builtIn);\n select.addEventListener(\"change\", () => {\n const next = { ...(record.defaultThemes ?? {}) };\n if (select.value === \"\") delete next[mode];\n else next[mode] = select.value;\n record = { ...record, defaultThemes: next };\n notify();\n });\n selects.set(mode, select);\n return h(\"label\", { class: \"wgd-row\" }, [h(\"span\", { class: \"wgd-field-label\" }, [label]), select]);\n });\n\n const defaultsPanel = section(\"Default themes\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"The theme a render uses when it names none: light hosts get the light default, dark hosts the dark one.\"\n ]),\n ...rows\n ]);\n panels.append(defaultsPanel);\n\n // --- Resource domains --------------------------------------------------\n // The section is in the record once supplied or edited (possibly empty),\n // so a save clears a list the person emptied and never adds one unasked.\n const domainRows = h(\"div\", { class: \"wgd-domains\" });\n const addInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-domain-add\",\n placeholder: \"cdn.example.com\",\n spellcheck: \"false\",\n \"aria-label\": \"Add a resource domain\"\n });\n const addButton = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Add domain\" }, [\"+\"]);\n\n /** A typed entry as the record keeps it: canonical when the rule accepts it, else as typed. */\n function recorded(typed: string): { value: string; mark: string; error: boolean } {\n const parsed = parseResourceDomain(typed);\n return \"error\" in parsed\n ? { value: typed.trim(), mark: `Not a resource domain: ${parsed.error}.`, error: true }\n : { value: parsed.origin, mark: parsed.origin, error: false };\n }\n\n function setDomains(next: string[]): void {\n record = { ...record, resourceDomains: next };\n renderDomains();\n notify();\n }\n\n function renderDomains(): void {\n const domains = record.resourceDomains ?? [];\n domainRows.replaceChildren(\n ...domains.map((entry, index) => {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input wgd-domain\", spellcheck: \"false\", \"aria-label\": `Resource domain ${index + 1}` });\n input.value = entry;\n input.addEventListener(\"change\", () => {\n const next = [...domains];\n next[index] = recorded(input.value).value;\n setDomains(next);\n });\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove domain\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => setDomains(domains.filter((_entry, at) => at !== index)));\n const { mark, error } = recorded(entry);\n return h(\"div\", { class: \"wgd-domain-entry\" }, [\n h(\"div\", { class: \"wgd-row\" }, [input, remove]),\n error ? diagnosticLine(mark) : h(\"span\", { class: \"wgd-field-label wgd-domain-origin\" }, [mark])\n ]);\n })\n );\n const full = domains.length >= RESOURCE_DOMAIN_LIMIT;\n addInput.disabled = full;\n addButton.disabled = full;\n }\n\n function addDomain(): void {\n if (addInput.value.trim() === \"\" || (record.resourceDomains ?? []).length >= RESOURCE_DOMAIN_LIMIT) return;\n const entry = recorded(addInput.value).value;\n addInput.value = \"\";\n setDomains([...(record.resourceDomains ?? []), entry]);\n }\n addButton.addEventListener(\"click\", addDomain);\n addInput.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Enter\") {\n event.preventDefault();\n addDomain();\n }\n });\n\n const domainsPanel = section(\"Resource domains\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Domains your widgets' images may load from directly in chat hosts that honor them, \" +\n \"when the server does not copy an image inline. Enter cdn.example.com or *.example.com, \" +\n `optionally with https:// (no ports, paths or IP addresses), at most ${RESOURCE_DOMAIN_LIMIT}.`\n ]),\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Any render, including image addresses an agent supplies, may load from these domains in the \" +\n \"viewer's browser, so list only domains you control. A domain that redirects needs its target \" +\n \"listed too, and a chat client keeps the list it read until it reloads.\"\n ]),\n domainRows,\n h(\"div\", { class: \"wgd-row\" }, [addInput, addButton])\n ]);\n panels.append(domainsPanel);\n renderDomains();\n\n function loadSettings(settings: unknown): SettingsLoadResult {\n const errors = checkSettings(settings);\n if (errors.length > 0) return { ok: false, errors };\n record = clone(settings as SettingsRecord);\n for (const { mode, builtIn } of MODES) {\n const select = selects.get(mode);\n if (select !== undefined) fillSelect(select, mode, builtIn);\n }\n renderDomains();\n notify();\n return { ok: true };\n }\n\n /** Same mechanism as the other designers: inert the section bodies. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n for (const body of panels.querySelectorAll(\".wgd-section-body\")) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n function setThemes(next: Pick<ThemeEntry, \"name\" | \"label\">[]): void {\n themes = [...next];\n for (const { mode, builtIn } of MODES) {\n const select = selects.get(mode);\n if (select !== undefined) fillSelect(select, mode, builtIn);\n }\n }\n\n return {\n getSettings,\n loadSettings,\n setThemes,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Opt-in custom element wrapping the factory. Registration only ever\n * happens through the explicit call \u2014 importing this module has no\n * custom-element registry side effects, so hosts stay in control.\n */\nimport { createDesigner } from \"./shell.js\";\nimport type { DesignerHandle } from \"./shell.js\";\nimport { createSchemaDesigner } from \"./schema-designer.js\";\nimport type { SchemaDesignerHandle } from \"./schema-designer.js\";\nimport { createThemeDesigner } from \"./theme-designer.js\";\nimport type { ThemeDesignerHandle } from \"./theme-designer.js\";\nimport { createActionDesigner } from \"./action-designer.js\";\nimport type { ActionDesignerHandle } from \"./action-designer.js\";\nimport { createSettingsDesigner } from \"./settings-designer.js\";\nimport type { SettingsDesignerHandle } from \"./settings-designer.js\";\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { parseChromeAttribute } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\n\n/**\n * The attributes every designer element shares, read once at connect:\n * `appearance` pins the chrome scheme, `chrome` (JSON) hands over the\n * host's chrome tokens. Anything invalid is ignored, never thrown.\n */\nfunction elementOptions(\n element: Element\n): { appearance?: \"light\" | \"dark\"; chrome?: ChromeOptions } {\n const appearance = element.getAttribute(\"appearance\");\n const chrome = parseChromeAttribute(element.getAttribute(\"chrome\"));\n return {\n ...(appearance === \"light\" || appearance === \"dark\" ? { appearance } : {}),\n ...(chrome === undefined ? {} : { chrome })\n };\n}\n\nexport const DEFAULT_TAG = \"widgentic-designer\";\nexport const DEFAULT_THEME_TAG = \"widgentic-theme-designer\";\nexport const DEFAULT_SCHEMA_TAG = \"widgentic-schema-designer\";\nexport const DEFAULT_ACTION_TAG = \"widgentic-action-designer\";\nexport const DEFAULT_SETTINGS_TAG = \"widgentic-settings-designer\";\n\nexport function defineDesignerElement(tagName: string = DEFAULT_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticDesignerElement extends HTMLElement {\n #handle: DesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((draft, diagnostics) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", {\n detail: { draft, diagnostics },\n bubbles: true\n })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n /** The embedding host's programmatic access to the wrapped handle. */\n get designer(): DesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticDesignerElement);\n}\n\n/** Sibling registrar for the standalone theme designer. */\nexport function defineThemeDesignerElement(tagName: string = DEFAULT_THEME_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticThemeDesignerElement extends HTMLElement {\n #handle: ThemeDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createThemeDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { theme: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): ThemeDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticThemeDesignerElement);\n}\n\n/** Sibling registrar for the standalone schema designer. */\nexport function defineSchemaDesignerElement(tagName: string = DEFAULT_SCHEMA_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticSchemaDesignerElement extends HTMLElement {\n #handle: SchemaDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createSchemaDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { schema: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): SchemaDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticSchemaDesignerElement);\n}\n\n/** Sibling registrar for the standalone action designer. */\nexport function defineActionDesignerElement(tagName: string = DEFAULT_ACTION_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticActionDesignerElement extends HTMLElement {\n #handle: ActionDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createActionDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { action: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): ActionDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticActionDesignerElement);\n}\n\n/**\n * A property set on an element before its class was defined is an own\n * property shadowing the class accessor; at upgrade, move it onto the\n * accessor so the value is not lost.\n */\nexport function upgradeProperty(element: HTMLElement, name: string): void {\n if (!Object.prototype.hasOwnProperty.call(element, name)) return;\n const own = element as unknown as Record<string, unknown>;\n const value = own[name];\n delete own[name];\n own[name] = value;\n}\n\n/** Sibling registrar for the settings designer. */\nexport function defineSettingsDesignerElement(tagName: string = DEFAULT_SETTINGS_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticSettingsDesignerElement extends HTMLElement {\n #handle: SettingsDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n #themes: Pick<ThemeEntry, \"name\" | \"label\">[] = [];\n\n constructor() {\n super();\n upgradeProperty(this, \"themes\");\n }\n\n /** The themes offered as choices; settable before or after connecting, or before the element is defined. */\n get themes(): Pick<ThemeEntry, \"name\" | \"label\">[] {\n return [...this.#themes];\n }\n\n set themes(themes: Pick<ThemeEntry, \"name\" | \"label\">[]) {\n this.#themes = Array.isArray(themes) ? [...themes] : [];\n this.#handle?.setThemes(this.#themes);\n }\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createSettingsDesigner(this, { ...elementOptions(this), themes: this.#themes });\n this.#unsubscribe = this.#handle.subscribe((settings) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { settings }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): SettingsDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticSettingsDesignerElement);\n}\n", "/**\n * Browser bundle entry (`@widgentic/designer/browser`): loading this module\n * from a <script type=\"module\"> registers the designer custom elements, so a\n * page without a bundler can host the designers. Bundler users import the\n * package root instead.\n */\nimport {\n defineActionDesignerElement,\n defineDesignerElement,\n defineSchemaDesignerElement,\n defineSettingsDesignerElement,\n defineThemeDesignerElement\n} from \"./index.js\";\n\ndefineActionDesignerElement();\ndefineDesignerElement();\ndefineSchemaDesignerElement();\ndefineThemeDesignerElement();\ndefineSettingsDesignerElement();\n\nexport {};\n"],
5
- "mappings": "AAgBA,SAASA,GAAcC,EAAkD,CACvE,OAAO,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,CAC5E,CASO,SAASC,GACdC,EACAC,EAA2B,CAAC,EACZ,CAChB,GAAI,CAACJ,GAAcG,CAAK,EACtB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,GACN,QAAS,iCACX,CACF,EAGF,GAAI,EAAE,SAAUA,GACd,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,gBACN,KAAM,OACN,QAAS,2CACX,CACF,EAGF,IAAME,EAAOF,EAAM,KACnB,GAAI,OAAOE,GAAS,SAClB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,OACN,QAAS,gCACX,CACF,EAEF,GAAIA,EAAK,SAAW,EAClB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,gBACN,KAAM,OACN,QAAS,0CACX,CACF,EAGF,GAAI,EAAE,SAAUF,GACd,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,gBACN,KAAM,OACN,QAAS,2CACX,CACF,EAGF,GAAI,UAAWA,GAASA,EAAM,QAAU,QAAa,CAACH,GAAcG,EAAM,KAAK,EAC7E,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,QACN,QAAS,+CACX,CACF,EAGF,GAAI,SAAUA,GAASA,EAAM,OAAS,QAAa,CAACH,GAAcG,EAAM,IAAI,EAC1E,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,OACN,QAAS,8CACX,CACF,EAGF,GAAM,CAAE,WAAAG,CAAW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Kinds", "ALLOWED_SCHEMES", "cleanUrl", "value", "isSafeUrl", "match", "scheme", "isLinkableUrl", "DATA_IMAGE", "HTTP_URL", "isSafeImageSrc", "cleaned", "IMAGE_EXTENSION", "looksLikeImageUrl", "LABEL", "hostProblem", "host", "wildcard", "labels", "label", "bad", "parseResourceDomain", "input", "trimmed", "lower", "rest", "problem", "el", "tag", "attrs", "children", "key", "node", "LABEL_STYLE_RULE", "BUILTIN_DESCRIPTORS", "NESTED_QUANTIFIER", "compileSafePattern", "pattern", "isPlainObject", "value", "DATA_SCHEMA_TYPES", "matchesSingleType", "type", "data", "matchesType", "candidate", "enumMatches", "allowed", "formatType", "validateDataAgainstSchema", "schema", "path", "regex", "key", "subschema", "error", "i", "auditDataSchema", "warnings", "names", "name", "isPlainObject", "value", "formatValue", "labelFor", "key", "hints", "label", "applyPattern", "pattern", "linkOrText", "raw", "display", "hint", "href", "isLinkableUrl", "el", "HINTABLE_SHAPES", "SHAPES", "resolveImage", "key", "value", "hints", "defaultShape", "hint", "isPlainObject", "isSafeImageSrc", "looksLikeImageUrl", "imageNode", "alt", "src", "shape", "el", "renderCard", "payload", "data", "meta", "fieldFormat", "isPlainObject", "title", "subtitle", "fieldEntries", "value", "key", "formatValue", "children", "el", "fieldValue", "label", "labelFor", "image", "resolveImage", "display", "imageNode", "raw", "pattern", "text", "applyPattern", "linkOrText", "keysFromIds", "items", "keys", "seen", "item", "isPlainObject", "id", "key", "renderTable", "payload", "rows", "fieldFormat", "isPlainObject", "records", "row", "hintColumns", "columns", "column", "seen", "record", "key", "rowKeys", "keysFromIds", "chrome", "title", "subtitle", "parts", "el", "formatValue", "labelFor", "index", "value", "image", "resolveImage", "display", "imageNode", "raw", "pattern", "text", "applyPattern", "linkOrText", "renderTree", "payload", "depthHint", "expandDepth", "roots", "list", "el", "renderList", "title", "formatValue", "nodeLabel", "node", "isPlainObject", "_children", "_icon", "rest", "iconNode", "icon", "image", "resolveImage", "imageNode", "labelChildren", "label", "MAX_TREE_DEPTH", "childrenOf", "nodes", "depth", "keys", "keysFromIds", "index", "renderNode", "key", "childNodes", "isOpen", "GROUP_MAX_ITEMS", "GROUP_LAYOUTS", "GROUP_GAPS", "GROUP_MAX_COLUMNS", "checkGroupEnvelope", "data", "isPlainObject", "items", "checked", "i", "item", "entry", "renderGroupContainer", "hints", "children", "h", "layout", "known", "gap", "classes", "raw", "columns", "el", "stampActionLocation", "node", "location", "raw", "attrs", "descriptor", "children", "child", "DuplicateKindError", "kind", "createCatalog", "renderers", "descriptors", "catalog", "renderer", "payload", "options", "validated", "validateWidgetPayload", "schema", "schemaError", "validateDataAgainstSchema", "envelope", "checkGroupEnvelope", "i", "item", "sub", "subPath", "renderGroupContainer", "thrown", "renderCard", "BUILTIN_DESCRIPTORS", "renderTable", "renderTree", "result", "isPlainObject", "value", "isNewline", "char", "scan", "text", "out", "depth", "quote", "isBracket", "isBalanced", "open", "i", "splitTopLevel", "separator", "pieces", "current", "quoted", "piece", "topLevelText", "indexOfTopLevel", "test", "pseudoArguments", "names", "chars", "args", "entry", "before", "name", "end", "closer", "UNSAFE", "PROPERTY_NAME", "isStyleMap", "value", "isPlainObject", "declarations", "v", "UNSAFE_FUNCTIONS", "COMMENT", "callsUnsafeFunction", "text", "call", "FORWARDING_PSEUDOS", "COMBINATOR", "char", "isConstrainedList", "selector", "depth", "parts", "splitTopLevel", "part", "isConstrainedPart", "MAX_FORWARDING_DEPTH", "compound", "topLevelText", "pseudoArguments", "argument", "isSafeSelector", "isBalanced", "isSafeValue", "scopePart", "scope", "found", "indexOfTopLevel", "end", "widgetStylesToCss", "styles", "guardedStylesToCss", "rules", "lines", "property", "scoped", "SAFE_IDENTIFIER", "STYLE_RULES", "UNSAFE", "UNSAFE_FUNCTIONS", "PROPERTY_NAME", "FORMAT_TYPES", "isFormatType", "value", "type", "FORMAT_DECIMALS_MIN", "FORMAT_DECIMALS_MAX", "CURRENCY_DISPLAYS", "isCurrencyDisplay", "display", "CURRENCY_CODE", "DATE_TOKENS", "DATE_PATTERN_SEPARATORS", "DATE_PATTERN_MAX", "DATE_PATTERN_ALLOWED", "EPOCH_SECONDS_BELOW", "LOCALE_TAG", "DEFAULT_FORMAT_LOCALE", "tokenizeDatePattern", "pattern", "parts", "literal", "tokens", "outer", "token", "char", "isKnownLocale", "tag", "toFiniteNumber", "trimmed", "parsed", "toEpochMillis", "iso", "date", "time", "fraction", "zone", "millis", "clock", "pad", "width", "formatDate", "at", "field", "part", "UNICODE_SPACES", "plain", "formatValue", "parseFormatSpec", "spec", "isPlainObject", "decimals", "locale", "common", "buildFormatter", "digits", "intl", "numeric", "compiled", "compileFormat", "cached", "formatter", "formatBoundValue", "TOKEN_SPECS", "TOKEN_DEFAULTS", "name", "spec", "THEME_TOKENS", "TOKEN_VALUE_UNSAFE", "isSafeTokenValue", "value", "isBalanced", "UNSAFE_FUNCTIONS", "call", "TOKEN_VALUE_RULE", "v", "token", "TOKEN_DEFAULTS", "tokenDefaultsBlock", "THEME_TOKENS", "ICON_BOX", "baseStylesheet", "STYLE_MARKER", "injectBaseStyles", "doc", "style", "isPlainObject", "value", "KNOWN_TOKENS", "THEME_TOKENS", "CUSTOM_VARIABLE", "customKeys", "theme", "key", "propertyName", "validateTheme", "input", "token", "isSafeTokenValue", "withFallbacks", "source", "filled", "fallback", "TOKEN_SPECS", "inherited", "applyTheme", "container", "style", "i", "property", "keys", "darkTheme", "DuplicateThemeError", "name", "InvalidThemeEntryError", "code", "message", "copyStyles", "styles", "copy", "selector", "declarations", "createThemeRegistry", "entries", "defaultNames", "registry", "entry", "validated", "validateTheme", "isStyleMap", "stored", "mode", "darkTheme", "themeStylesToCss", "styles", "scope", "guardedStylesToCss", "FORBIDDEN_ATTR", "FORBIDDEN_TAGS", "RESERVED_ATTR", "URL_ATTRS", "MAX_TEMPLATE_DEPTH", "RESERVED", "parsePath", "value", "tokens", "i", "base", "up", "rest", "segment", "SECRET_NAME", "ACTION_NAME", "OUTPUT_MODES", "HTTP_METHODS", "join", "path", "segment", "fail", "message", "HEADER_TOKEN", "RESERVED_HEADERS", "FORBIDDEN_SEGMENTS", "isDataPath", "value", "checkHeaderValue", "isPlainObject", "SECRET_NAME", "containsSecretRef", "checkUrl", "url", "parsed", "validateActionDefinition", "input", "options", "literal", "HTTP_METHODS", "m", "urlError", "field", "map", "name", "namePath", "error", "definitionOf", "binding", "validateActionBinding", "definitionError", "definition", "declared", "fieldPath", "outPath", "mode", "target", "OUTPUT_MODES", "entries", "key", "entryPath", "validateLoadBinding", "join", "path", "segment", "nodeError", "message", "checkFormat", "spec", "label", "bad", "isPlainObject", "isFormatType", "FORMAT_TYPES", "DATE_PATTERN_MAX", "DATE_PATTERN_ALLOWED", "tokenizeDatePattern", "DATE_TOKENS", "FORMAT_DECIMALS_MIN", "FORMAT_DECIMALS_MAX", "LOCALE_TAG", "isKnownLocale", "CURRENCY_CODE", "isCurrencyDisplay", "CURRENCY_DISPLAYS", "parseFormatSpec", "TRANSFORM_KEYS", "activeTransform", "value", "present", "key", "checkPathSyntax", "parsePath", "check", "node", "depth", "MAX_TEMPLATE_DEPTH", "pathError", "entry", "keyError", "templateError", "FORBIDDEN_TAGS", "name", "attrPath", "FORBIDDEN_ATTR", "RESERVED_ATTR", "transform", "hasMap", "hasPrefix", "hasFormat", "formatError", "actionError", "validateActionBinding", "i", "childError", "validateTemplate", "input", "error", "eachBinding", "template", "load", "onBinding", "visit", "node", "isPlainObject", "key", "child", "collectActionRefs", "refs", "binding", "join", "path", "segment", "resolvePath", "frames", "meta", "parsed", "parsePath", "current", "depth", "frame", "index", "isPlainObject", "keyOf", "value", "DEFAULT_MAX_NODES", "buildDescriptor", "binding", "id", "ctx", "definition", "unresolved", "text", "segments", "formatValue", "prompt", "args", "field", "resolved", "descriptor", "interpretNode", "node", "budget", "tpath", "key", "hit", "formatBoundValue", "items", "out", "itemPath", "keyPath", "i", "rendered", "only", "truthy", "branch", "FORBIDDEN_TAGS", "attrs", "name", "raw", "FORBIDDEN_ATTR", "RESERVED_ATTR", "lower", "URL_ATTRS", "imageContext", "isSafeUrl", "isSafeImageSrc", "children", "child", "element", "compileTemplate", "template", "options", "maxNodes", "DEFAULT_MAX_NODES", "ctx", "payload", "budget", "frames", "nodes", "interpretNode", "only", "attrs", "buildDom", "node", "doc", "element", "name", "value", "child", "patchNode", "prev", "next", "dom", "patchElement", "doc", "replacement", "buildDom", "element", "prevAttrs", "nextAttrs", "name", "value", "patchChildren", "keyIndex", "list", "index", "i", "node", "patchKeyed", "prevIndex", "domChildren", "kept", "placed", "child", "prevChild", "at", "elements", "shared", "nextChild", "childDom", "extra", "surplus", "mountWidget", "payload", "container", "options", "catalog", "createCatalog", "current", "root", "disposed", "mountedPayload", "onAction", "parseDescriptor", "el", "parsed", "activation", "event", "key", "descriptor", "update", "nextPayload", "rendered", "built", "buildDom", "patchNode", "dispose", "CHROME_TOKENS", "TYPOGRAPHY", "CHROME_DEFAULTS", "declarations", "scheme", "prefix", "indent", "token", "chromeCss", "palette", "options", "selector", "darkMediaSelector", "blocks", "requireChild", "parent", "selector", "found", "h", "tag", "attrs", "children", "element", "name", "value", "child", "textField", "label", "onInput", "input", "textArea", "rows", "area", "section", "title", "open", "select", "options", "className", "onChange", "el", "option", "fitSelect", "fit", "menuButton", "onPick", "wrap", "toggle", "menu", "close", "onOutside", "onKey", "event", "item", "diagnosticLine", "text", "CHROME_TOKEN_SET", "CHROME_TOKENS", "CSS_WIDE_KEYWORD", "applyChrome", "root", "chrome", "token", "parseChromeAttribute", "parsed", "STYLE_MARKER", "injectDesignerStyles", "doc", "style", "chromeCss", "CHROME_DEFAULTS", "tabs", "entries", "buttons", "entry", "index", "button", "other", "i", "clone", "value", "errorMessage", "error", "effectiveDataSchema", "draft", "schemas", "ref", "entry", "inline", "isPlainObject", "BASE_KINDS", "createCatalog", "kindProblem", "kind", "SAFE_IDENTIFIER", "auditStyles", "styles", "issues", "selector", "declarations", "widgetStylesToCss", "STYLE_RULES", "property", "value", "PROPERTY_NAME", "deriveDiagnostics", "options", "diagnostics", "problem", "dataShape", "inlineSchema", "warnings", "auditDataSchema", "template", "validateTemplate", "issue", "path", "schema", "error", "validateDataAgainstSchema", "validateLoadBinding", "parsePath", "known", "action", "unknown", "collectActionRefs", "theme", "validateTheme", "JSON_TOKENS", "tokenizeJson", "text", "out", "last", "match", "paint", "layer", "nodes", "token", "span", "attachJsonHighlight", "textarea", "parent", "wrap", "sync", "syncScroll", "onTab", "event", "selectionStart", "selectionEnd", "value", "repaintHighlight", "checkDefinition", "definition", "currentKind", "errors", "isPlainObject", "problem", "kindProblem", "template", "validateTemplate", "dataSchema", "dataSchemaRef", "SAFE_IDENTIFIER", "validateLoadBinding", "value", "parsePath", "exportWidgetJson", "draft", "importWidgetJson", "text", "currentKind", "parsed", "error", "errorMessage", "errors", "checkDefinition", "applyDefinition", "store", "definition", "theme", "themeStyles", "previewTheme", "camelCase", "kind", "part", "i", "toTypeScriptModule", "draft", "mountIoPanel", "output", "h", "button", "label", "produce", "el", "repaintHighlight", "importError", "diagnosticLine", "importField", "textArea", "importArea", "requireChild", "attachJsonHighlight", "importButton", "result", "importSection", "section", "exportSection", "exportWidgetJson", "element", "TYPE_OPTIONS", "typeOf", "value", "defaultFor", "type", "previous", "parsed", "setAt", "root", "path", "remove", "step", "rest", "copy", "renameKey", "from", "to", "holder", "node", "entries", "k", "v", "createJsonTreeEditor", "initial", "onChange", "current", "element", "h", "commit", "next", "render", "commitText", "text", "typeSelect", "select", "option", "valueControl", "box", "input", "entryRow", "keyLabel", "removable", "row", "wrap", "renderContainer", "body", "item", "index", "add", "key", "keyInput", "name", "i", "TYPES", "ENUM_TYPES", "createSchemaBuilder", "initial", "onChange", "current", "element", "h", "commit", "next", "rerender", "render", "withKey", "node", "key", "value", "copy", "renderNode", "apply", "depth", "lead", "trail", "rows", "typeSelect", "t", "rawType", "typeList", "nullable", "currentType", "type", "fitSelect", "nullBox", "typeValue", "selected", "allowNull", "constraints", "pattern", "enumError", "diagnosticLine", "enumInput", "parsed", "error", "errorMessage", "properties", "isPlainObject", "required", "k", "cards", "name", "sub", "nameInput", "entries", "v", "nextRequired", "requiredBox", "removeProp", "_gone", "rest", "nextSub", "addProp", "i", "nextItems", "start", "clear", "schema", "createRecordEditor", "initial", "placeholders", "onChange", "current", "element", "h", "commit", "next", "render", "changeInput", "value", "placeholder", "className", "onCommit", "input", "record", "rows", "key", "keyInput", "entries", "k", "v", "valueInput", "remove", "_gone", "rest", "add", "i", "firstType", "schema", "type", "primary", "t", "seedFor", "seed", "isPlainObject", "key", "createSchemaForm", "initial", "onChange", "current", "element", "h", "setAt", "root", "path", "value", "remove", "step", "rest", "copy", "holder", "commit", "rerender", "render", "control", "node", "label", "select", "option", "field", "box", "input", "parsed", "body", "properties", "required", "name", "sub", "isRequired", "itemsSchema", "items", "item", "index", "row", "add", "controlEl", "createStylesEditor", "initial", "onChange", "current", "element", "h", "commit", "next", "render", "changeInput", "value", "placeholder", "className", "onCommit", "input", "renderSelector", "selector", "declarations", "styles", "rename", "entries", "k", "v", "addDecl", "removeSelector", "_gone", "rest", "declRows", "property", "propInput", "valueInput", "removeDecl", "addSelector", "name", "i", "isPlainObject", "createStylesPanel", "initial", "onChange", "tree", "createStylesEditor", "styles", "showJson", "parseError", "diagnosticLine", "field", "textArea", "text", "value", "isStyleMap", "next", "error", "errorMessage", "area", "requireChild", "attachJsonHighlight", "repaintHighlight", "issues", "h", "section", "tabs", "list", "issue", "MAX_SCHEMA_DEPTH", "schemaType", "schema", "isPlainObject", "type", "primary", "t", "collectPaths", "prefix", "out", "depth", "name", "sub", "path", "itemSchema", "schemaAt", "current", "segment", "typesConflict", "a", "b", "norm", "schemaMismatch", "source", "target", "sourceType", "targetType", "allPaths", "entries", "entry", "CUSTOM_PATH", "starterPromptDefinition", "starterHttpDefinition", "isRefBinding", "binding", "textInput", "value", "className", "onCommit", "placeholder", "el", "h", "label", "text", "removeButton", "onClick", "button", "pathSelect", "options", "sel", "known", "listed", "option", "fitSelect", "custom", "headerMapEditor", "initial", "secretNames", "labels", "onChange", "current", "clone", "pending", "element", "duplicate", "diagnosticLine", "commit", "next", "render", "flagDuplicate", "name", "valueControl", "onValue", "isSecret", "isPlainObject", "mode", "select", "names", "picker", "n", "nameInput", "entries", "k", "v", "controls", "remove", "_gone", "rest", "row", "index", "add", "segmentsEditor", "segment", "isBind", "copy", "_", "i", "addText", "addBind", "createDefinitionEditor", "ctx", "headEl", "schemasEl", "mapsEl", "http", "rerender", "renderSchemas", "schemaSection", "title", "which", "builder", "createSchemaBuilder", "schema", "parts", "shared", "copyFrom", "s", "entry", "renderHead", "kind", "method", "HTTP_METHODS", "m", "url", "renderMaps", "headers", "_h", "query", "_q", "definition", "createBindingEditor", "inputEl", "outputEl", "definitionOf", "a", "inputOf", "outputOf", "renderInput", "renderOutput", "withMapping", "input", "output", "helperPaths", "allPaths", "p", "modeSelect", "ref", "refSelect", "editor", "properties", "scopePaths", "pathOptions", "mapping", "rows", "field", "isConst", "kindSelect", "nextMapping", "literal", "valueInput", "modeSel", "OUTPUT_MODES", "nextOutput", "outputRow", "outputMapEditor", "map", "onMap", "container", "widgetSchema", "base", "targetSide", "schemaAt", "targetRoot", "itemSchema", "targetOptions", "selectedSchema", "perItemResponse", "schemaType", "sourceRoot", "selectOptions", "mismatch", "commitMap", "flag", "targetControl", "target", "onTarget", "control", "problems", "mapped", "key", "sourceOptions", "source", "conflict", "schemaMismatch", "targetInput", "sourceInput", "pathOptions", "scope", "use", "schemaType", "entries", "collectPaths", "scalars", "paths", "schema", "type", "entry", "itemScope", "eachPath", "target", "schemaAt", "itemSchema", "REMOVE", "pathString", "path", "out", "step", "segment", "setNode", "node", "next", "rest", "isPlainObject", "children", "_removed", "remaining", "swapChildren", "root", "parent", "a", "b", "holder", "getNode", "x", "y", "swapped", "current", "NODE_PRESETS", "mountTemplatePanel", "store", "refreshers", "options", "actionContext", "unknownRefs", "treeHost", "h", "jsonError", "diagnosticLine", "jsonArea", "jsonWrap", "attachJsonHighlight", "treeTab", "jsonTab", "templateDiag", "element", "commit", "draft", "commitAt", "parsed", "error", "errorMessage", "changeInput", "value", "onCommit", "className", "input", "formatEditor", "spec", "active", "isFormatType", "typeSelect", "select", "FORMAT_TYPES", "decimalsInput", "_gone", "FORMAT_DECIMALS_MIN", "FORMAT_DECIMALS_MAX", "code", "display", "CURRENCY_DISPLAYS", "isCurrencyDisplay", "pattern", "DATE_TOKENS", "collapsedPaths", "nodeShell", "badge", "inline", "body", "errorText", "removable", "moves", "extras", "key", "collapsible", "isCollapsed", "chevron", "renderTree", "header", "icons", "up", "down", "remove", "TAG_OPTIONS", "pathControl", "known", "option", "fitSelect", "custom", "marker", "keyControl", "title", "tagControl", "tag", "slotEditor", "label", "parentPath", "slot", "required", "errorPath", "slotPath", "menu", "menuButton", "name", "preset", "renderNode", "here", "errorHere", "currentError", "bind", "transform", "activeTransform", "bindFormat", "bindMap", "withBind", "extra", "addMap", "mapEditor", "createRecordEditor", "nextMap", "defaultInput", "each", "_each", "_key", "attrs", "binding", "attrRows", "bound", "isBind", "bindValue", "rebuild", "fields", "setAttr", "nextValue", "nameInput", "nextName", "k", "v", "mode", "literalInput", "valueInput", "removeAttr", "row", "attrFormat", "showFormat", "showPrefix", "showAddMap", "prefixInput", "attrRow", "parts", "childNodes", "addMenu", "choice", "first", "scopePaths", "bindingEditor", "createBindingEditor", "effectiveDataSchema", "actionParts", "ref", "child", "index", "summaryParts", "lastDraft", "lastErrorPath", "refresh", "diagnostics", "action", "collectActionRefs", "templateMessage", "repaintHighlight", "mountThemePanel", "store", "refreshers", "themes", "themeDiag", "diagnosticLine", "themeSelect", "h", "entry", "showChoice", "draft", "candidate", "_theme", "_styles", "_name", "rest", "tokenList", "renderTokenReference", "theme", "name", "spec", "TOKEN_SPECS", "value", "row", "rows", "element", "section", "message", "jsonField", "label", "read", "write", "clear", "store", "refreshers", "rows", "parseError", "diagnosticLine", "initial", "field", "textArea", "text", "draft", "value", "error", "errorMessage", "area", "requireChild", "attachJsonHighlight", "repaintHighlight", "h", "mountPanels", "columns", "themes", "schemas", "actionContext", "disposers", "bindText", "textField", "input", "kindDiag", "hintsEditor", "createRecordEditor", "hints", "d", "_h", "rest", "dataShapeDiag", "generalPanel", "section", "v", "tabs", "isPlainObject", "k", "doc", "_hints", "schemaBuilder", "createSchemaBuilder", "schema", "_s", "inlineEditors", "modeSelect", "sharedOption", "refSelect", "entry", "sharedView", "schemaRefDiag", "schemaAuditDiag", "sharedWrap", "name", "resolved", "effectiveDataSchema", "_r", "refreshSchemaMode", "ref", "shared", "schemaPanel", "adaptiveDataEditor", "hostEl", "schemaKey", "editor", "rebuild", "key", "onChange", "createSchemaForm", "createJsonTreeEditor", "exampleDiag", "samplePanel", "_e", "sampleDiag", "previewDataPanel", "stylesPanel", "createStylesPanel", "styles", "templatePanel", "mountTemplatePanel", "themePanel", "mountThemePanel", "loadDiag", "loadEditor", "createBindingEditor", "binding", "_l", "loadPanel", "ioPanel", "mountIoPanel", "applyDiagnostics", "diagnostics", "deriveDiagnostics", "refresh", "off", "dispose", "PREVIEW_KIND", "previewCount", "previewSalt", "createPreview", "options", "injectBaseStyles", "banner", "h", "themeStyles", "kindStyles", "scope", "mountRoot", "scoped", "styles", "themeStylesToCss", "pane", "catalog", "createCatalog", "renderer", "payload", "customStyles", "widget", "validated", "validateTemplate", "compiled", "compileTemplate", "descriptor", "isPlainObject", "kinds", "kind", "mount", "update", "draft", "diagnostics", "previewKind", "renderingDraft", "issue", "shared", "ref", "action", "applyTheme", "sampleFor", "mountWidget", "bound", "cloneDraft", "draft", "starterDraft", "createDraftStore", "initial", "current", "history", "listeners", "notify", "listener", "updater", "previous", "createDesigner", "container", "options", "injectDesignerStyles", "base", "cloneDraft", "starterDraft", "preselected", "entry", "initial", "store", "createDraftStore", "listeners", "preview", "createPreview", "leftColumn", "h", "rightSections", "rightColumn", "root", "applyChrome", "actionContext", "panels", "mountPanels", "diagnose", "draft", "deriveDiagnostics", "refresh", "diagnostics", "listener", "unsubscribe", "setReadOnly", "readOnly", "bodies", "body", "definition", "errors", "checkDefinition", "applyDefinition", "kind", "template", "descriptor", "load", "theme", "validated", "validateTheme", "_previous", "rest", "chosen", "starterEntry", "checkSchemaEntry", "entry", "errors", "isPlainObject", "SAFE_IDENTIFIER", "createSchemaDesigner", "container", "options", "injectDesignerStyles", "listeners", "panels", "h", "root", "applyChrome", "getEntry", "schemaDiag", "diagnosticLine", "showSchemaWarnings", "warnings", "auditDataSchema", "notify", "listener", "identityRefreshers", "nameDiag", "identityField", "label", "read", "write", "field", "textField", "input", "requireChild", "identity", "section", "value", "bad", "builder", "createSchemaBuilder", "schema", "syncJson", "jsonError", "jsonArea", "jsonWrap", "parsed", "error", "errorMessage", "repaintHighlight", "builderTab", "jsonTab", "definition", "importError", "importArea", "importButton", "result", "loadSchema", "importSection", "output", "exportButton", "exportSection", "attachJsonHighlight", "refresh", "setReadOnly", "readOnly", "bodies", "body", "BASE_KINDS", "createCatalog", "HEX", "CUSTOM_NAME", "toHexInput", "value", "r", "g", "b", "starterEntry", "BUILT_IN_THEMES", "createThemeRegistry", "nameProblem", "name", "SAFE_IDENTIFIER", "takeEntry", "input", "_retired", "entry", "checkThemeEntry", "currentName", "errors", "candidate", "problem", "validated", "validateTheme", "isStyleMap", "createThemeDesigner", "container", "options", "injectDesignerStyles", "listeners", "preview", "createPreview", "previewKinds", "previewKind", "panels", "h", "side", "root", "applyChrome", "previewDraft", "draft", "starterDraft", "refresh", "listener", "getEntry", "setToken", "key", "tokens", "identityRefreshers", "identityField", "label", "read", "write", "field", "textField", "requireChild", "nameDiag", "diagnosticLine", "showNameProblem", "identity", "section", "kindSelect", "kind", "tokenRefreshers", "tokenRows", "token", "THEME_TOKENS", "TOKEN_DEFAULTS", "issue", "swatch", "TOKEN_SPECS", "paint", "effective", "hex", "isSafeTokenValue", "unsafe", "TOKEN_VALUE_RULE", "tokenPanel", "customHost", "customError", "customEntries", "renderCustom", "rows", "nameInput", "next", "valueInput", "remove", "add", "i", "customPanel", "output", "exportButton", "importArea", "importError", "importButton", "parsed", "error", "errorMessage", "result", "loadTheme", "importPanel", "exportPanel", "stylesPanel", "createStylesPanel", "styles", "_previous", "rest", "auditStyles", "refreshIdentity", "refreshToken", "setReadOnly", "readOnly", "bodies", "body", "starterEntry", "checkActionEntry", "entry", "errors", "isPlainObject", "ACTION_NAME", "field", "problem", "validateActionDefinition", "normalizeEntry", "input", "clone", "withText", "current", "value", "_gone", "rest", "createActionDesigner", "container", "options", "injectDesignerStyles", "testCall", "listeners", "panels", "h", "root", "applyChrome", "getEntry", "notify", "listener", "identityRefreshers", "nameDiag", "diagnosticLine", "identityField", "label", "read", "write", "textField", "inputEl", "requireChild", "identity", "section", "bad", "definitionDiag", "editor", "createDefinitionEditor", "definition", "syncJson", "refreshDefinitionDiag", "refreshTest", "jsonError", "jsonArea", "jsonWrap", "parsed", "error", "errorMessage", "repaintHighlight", "builderTab", "jsonTab", "testHost", "testSection", "testArgs", "testInputJson", "definitionNow", "inputJson", "form", "createSchemaForm", "output", "run", "result", "importError", "importArea", "importButton", "loadAction", "importSection", "exportButton", "exportSection", "attachJsonHighlight", "refresh", "setReadOnly", "readOnly", "bodies", "body", "MODES", "checkSettings", "settings", "isPlainObject", "errors", "domains", "entry", "themes", "mode", "name", "known", "createSettingsDesigner", "container", "options", "injectDesignerStyles", "record", "clone", "listeners", "panels", "h", "root", "applyChrome", "getSettings", "notify", "listener", "selects", "fillSelect", "select", "builtIn", "current", "theme", "rows", "label", "next", "defaultsPanel", "section", "domainRows", "addInput", "addButton", "recorded", "typed", "parsed", "parseResourceDomain", "setDomains", "renderDomains", "index", "input", "remove", "_entry", "at", "mark", "error", "diagnosticLine", "full", "addDomain", "event", "domainsPanel", "loadSettings", "setReadOnly", "readOnly", "body", "setThemes", "elementOptions", "element", "appearance", "chrome", "parseChromeAttribute", "DEFAULT_TAG", "DEFAULT_THEME_TAG", "DEFAULT_SCHEMA_TAG", "DEFAULT_ACTION_TAG", "DEFAULT_SETTINGS_TAG", "defineDesignerElement", "tagName", "WidgenticDesignerElement", "#handle", "#unsubscribe", "createDesigner", "draft", "diagnostics", "defineThemeDesignerElement", "WidgenticThemeDesignerElement", "createThemeDesigner", "entry", "defineSchemaDesignerElement", "WidgenticSchemaDesignerElement", "createSchemaDesigner", "defineActionDesignerElement", "WidgenticActionDesignerElement", "createActionDesigner", "upgradeProperty", "name", "own", "value", "defineSettingsDesignerElement", "WidgenticSettingsDesignerElement", "#themes", "themes", "createSettingsDesigner", "settings", "defineActionDesignerElement", "defineDesignerElement", "defineSchemaDesignerElement", "defineThemeDesignerElement", "defineSettingsDesignerElement"]
3
+ "sources": ["../../../core/src/contract/validate.ts", "../../../core/src/contract/urls.ts", "../../../core/src/contract/domains.ts", "../../../core/src/catalog/node.ts", "../../../core/src/catalog/descriptors.ts", "../../../core/src/catalog/schema.ts", "../../../core/src/catalog/widgets/format.ts", "../../../core/src/catalog/widgets/images.ts", "../../../core/src/catalog/widgets/card.ts", "../../../core/src/catalog/widgets/keys.ts", "../../../core/src/catalog/widgets/table.ts", "../../../core/src/catalog/widgets/tree.ts", "../../../core/src/catalog/widgets/group.ts", "../../../core/src/catalog/registry.ts", "../../../core/src/shared/plain-object.ts", "../../../core/src/shared/css-scan.ts", "../../../core/src/catalog/styles.ts", "../../../core/src/catalog/identifiers.ts", "../../../core/src/catalog/style-rules.ts", "../../../core/src/catalog/widgets/value-format.ts", "../../../core/src/theming/tokens.ts", "../../../core/src/theming/stylesheet.ts", "../../../core/src/theming/apply.ts", "../../../core/src/theming/registry.ts", "../../../core/src/theming/styles.ts", "../../../core/src/templates/guards.ts", "../../../core/src/templates/paths.ts", "../../../core/src/actions/types.ts", "../../../core/src/actions/validate.ts", "../../../core/src/templates/validate.ts", "../../../core/src/templates/locate.ts", "../../../core/src/templates/markdown.ts", "../../../core/src/templates/compile.ts", "../../../core/src/reactive/build.ts", "../../../core/src/reactive/diff.ts", "../../../core/src/reactive/mount.ts", "../../src/chrome-defaults.ts", "../../src/dom.ts", "../../src/internal.ts", "../../src/validate.ts", "../../src/highlight.ts", "../../src/io.ts", "../../src/json-tree-editor.ts", "../../src/schema-builder.ts", "../../src/record-editor.ts", "../../src/schema-form.ts", "../../src/styles-editor.ts", "../../src/styles-panel.ts", "../../src/schema-paths.ts", "../../src/action-editor.ts", "../../src/template-panel.ts", "../../src/theme-panel.ts", "../../src/panels.ts", "../../src/preview.ts", "../../src/store.ts", "../../src/shell.ts", "../../src/schema-designer.ts", "../../src/theme-designer.ts", "../../src/action-designer.ts", "../../src/settings-designer.ts", "../../src/element.ts", "../../src/browser.ts"],
4
+ "sourcesContent": ["import type { WidgetPayload } from \"./types.js\";\nimport type { WidgetContractError } from \"./errors.js\";\n\nexport interface ValidateOptions {\n /**\n * If provided and non-empty, payloads whose `kind` is not in the set fail\n * with `UNKNOWN_KIND`. When omitted or empty, kind membership is not\n * checked (kind format is still validated).\n */\n knownKinds?: ReadonlySet<string>;\n}\n\nexport type ValidateResult =\n | { ok: true; payload: WidgetPayload }\n | { ok: false; error: WidgetContractError };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Validate an unknown input against the widget contract.\n *\n * Returns a discriminated result. The `payload` returned on success is the\n * original input (unknown top-level fields are preserved for forward\n * compatibility).\n */\nexport function validateWidgetPayload(\n input: unknown,\n options: ValidateOptions = {}\n): ValidateResult {\n if (!isPlainObject(input)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"\",\n message: \"Payload must be a plain object.\"\n }\n };\n }\n\n if (!(\"kind\" in input)) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"kind\",\n message: \"Payload is missing required field 'kind'.\"\n }\n };\n }\n\n const kind = input.kind;\n if (typeof kind !== \"string\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"kind\",\n message: \"Field 'kind' must be a string.\"\n }\n };\n }\n if (kind.length === 0) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"kind\",\n message: \"Field 'kind' must be a non-empty string.\"\n }\n };\n }\n\n if (!(\"data\" in input)) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"data\",\n message: \"Payload is missing required field 'data'.\"\n }\n };\n }\n\n if (\"hints\" in input && input.hints !== undefined && !isPlainObject(input.hints)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"hints\",\n message: \"Field 'hints' must be an object when present.\"\n }\n };\n }\n\n if (\"meta\" in input && input.meta !== undefined && !isPlainObject(input.meta)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"meta\",\n message: \"Field 'meta' must be an object when present.\"\n }\n };\n }\n\n const { knownKinds } = options;\n if (knownKinds && knownKinds.size > 0 && !knownKinds.has(kind)) {\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_KIND\",\n path: \"kind\",\n message: `Unknown widget kind '${kind}'.`\n }\n };\n }\n\n // Preserve unknown top-level fields by returning the original input.\n return { ok: true, payload: input as WidgetPayload };\n}\n", "/**\n * URL safety primitives shared by the template DSL and the catalog's image\n * rendering. They live in the contract layer \u2014 the zero-dependency base\n * both consumers sit on \u2014 so the strict and lenient layers can never drift\n * (`templates` imports from `catalog`, so `catalog` cannot import back).\n */\n\n/** Schemes allowed in URL-bearing attributes (plus relative references). */\nexport const ALLOWED_SCHEMES = new Set([\"http\", \"https\", \"mailto\", \"tel\"]);\n\n/**\n * Strip control characters and whitespace before scheme inspection,\n * mirroring how browsers parse URLs (defeats `java\\nscript:` obfuscation).\n */\nfunction cleanUrl(value: string): string {\n return value.replace(/[\\u0000-\\u0020]+/g, \"\");\n}\n\n/**\n * True when a URL value is safe for a URL-bearing attribute: an allowed\n * scheme or a relative reference.\n */\nexport function isSafeUrl(value: string): boolean {\n const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleanUrl(value));\n if (match === null) return true;\n const scheme = match[1];\n return scheme !== undefined && ALLOWED_SCHEMES.has(scheme.toLowerCase());\n}\n\n/**\n * True only for an EXPLICITLY-schemed allowed URL \u2014 unlike {@link isSafeUrl},\n * relative references do not qualify: as anchor targets they are dead\n * clicks inside the app frame and junk navigation on served pages.\n */\nexport function isLinkableUrl(value: string): boolean {\n const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleanUrl(value));\n if (match === null) return false;\n const scheme = match[1];\n return scheme !== undefined && ALLOWED_SCHEMES.has(scheme.toLowerCase());\n}\n\n/** `data:image/<subtype>;base64,<payload>` \u2014 the only `data:` form images accept. */\nconst DATA_IMAGE = /^data:image\\/[a-z0-9.+-]+;base64,[a-z0-9+/=]*$/i;\n\n/** Absolute http(s) \u2014 image sources are fetched, so relative refs are useless. */\nconst HTTP_URL = /^https?:\\/\\//i;\n\n/**\n * True when a value is acceptable as an image source: an absolute http(s)\n * URL or a base64 `data:image/*` URI. Broader `data:` stays banned here and\n * everywhere else \u2014 data-URI navigation is an XSS vector; data-URI images\n * are not.\n */\nexport function isSafeImageSrc(value: string): boolean {\n const cleaned = cleanUrl(value);\n return DATA_IMAGE.test(cleaned) || HTTP_URL.test(cleaned);\n}\n\nconst IMAGE_EXTENSION = /\\.(png|jpe?g|gif|webp|avif|svg)$/i;\n\n/**\n * Auto-detection predicate for the built-in renderers: a safe image source\n * that self-identifies as an image \u2014 `data:image/*`, or an http(s) URL\n * whose pathname ends in an image extension (query strings tolerated).\n * Extensionless image URLs need a `hints.images` entry instead.\n */\nexport function looksLikeImageUrl(value: string): boolean {\n const cleaned = cleanUrl(value);\n if (!isSafeImageSrc(cleaned)) return false;\n if (cleaned.toLowerCase().startsWith(\"data:image/\")) return true;\n try {\n return IMAGE_EXTENSION.test(new URL(cleaned).pathname);\n } catch {\n return false;\n }\n}\n", "/**\n * Resource domains: the origins an MCP Apps frame may load assets from\n * directly, declared as the app resource's `_meta.ui.csp.resourceDomains`.\n * One rule for every door \u2014 the store, the settings designer, the server\n * assembly and the host bundle \u2014 narrower than CSP's own grammar: https\n * only, a host of two or more DNS labels with an optional leading `*.`\n * wildcard, and no port, path, userinfo or IP literal. Hosts build their\n * frame CSP by joining the entries, so nothing that could end a source\n * expression (whitespace, `;`, `,`, quotes) ever passes. Checked label by\n * label over ASCII, never through `URL`, so every runtime reads an entry\n * alike.\n */\n\n/** The most domains one list may declare. */\nexport const RESOURCE_DOMAIN_LIMIT = 20;\n\nexport interface ResourceDomain {\n /** The canonical origin: `https://cdn.example.com` or `https://*.example.com`. */\n origin: string;\n /** The host without its wildcard label: `cdn.example.com`, `example.com`. */\n host: string;\n /** `*.host`: every subdomain of `host`, at any depth, never `host` itself. */\n wildcard: boolean;\n}\n\n/** An accepted entry, or why it is refused (a short clause a person can read). */\nexport type ResourceDomainResult = ResourceDomain | { error: string };\n\nconst LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction hostProblem(host: string, wildcard: boolean): string | undefined {\n if (host.length > 253) return \"the host is longer than 253 characters\";\n const labels = host.split(\".\");\n if (labels.some((label) => label.length === 0)) return \"the host has an empty label\";\n if (labels.every((label) => /^\\d+$/.test(label))) return \"an IP address cannot be declared, only a domain name\";\n if (labels.length < 2) {\n return wildcard\n ? \"a wildcard needs at least two labels after it, as in *.example.com\"\n : \"a single-label host such as localhost cannot be declared\";\n }\n if (labels[labels.length - 1] === \"localhost\") return \"a localhost name cannot be declared\";\n if (/^\\d+$/.test(labels[labels.length - 1] ?? \"\")) return \"the last label is a number, so this is not a domain name\";\n const bad = labels.find((label) => !LABEL.test(label));\n if (bad !== undefined) {\n return `the label '${bad}' is not 1-63 letters, digits or hyphens that start and end with a letter or digit`;\n }\n return undefined;\n}\n\n/**\n * Read one entry: `host`, `*.host`, or either behind `https://`, with at\n * most one trailing `/`. Case and surrounding whitespace are ignored.\n */\nexport function parseResourceDomain(input: string): ResourceDomainResult {\n const trimmed = input.trim();\n if (trimmed.length === 0) return { error: \"it is empty\" };\n if (/[\\s;,'\"`]/.test(trimmed)) return { error: \"it contains a space, ';', ',' or a quote, which no domain holds\" };\n if (/[^\\x21-\\x7e]/.test(trimmed)) return { error: \"it has a non-ASCII character: enter the punycode (xn--) form\" };\n const lower = trimmed.toLowerCase();\n\n let rest = lower;\n if (lower.startsWith(\"https://\")) {\n rest = lower.slice(\"https://\".length);\n } else if (/^[a-z][a-z0-9+.-]*:(?!\\d+\\/?$)/.test(lower)) {\n // A scheme other than https (`http://`, `data:`, `javascript:`); a\n // `host:8443` falls through to the port check instead.\n return { error: \"only https:// domains can be declared\" };\n }\n if (rest.endsWith(\"/\")) rest = rest.slice(0, -1);\n if (rest.includes(\"@\")) return { error: \"it carries a user name, which a domain cannot\" };\n if (rest.includes(\"/\")) return { error: \"it is a page, not a domain: drop the path\" };\n if (rest.includes(\"?\") || rest.includes(\"#\")) return { error: \"it carries a query or fragment, which a domain cannot\" };\n if (rest.startsWith(\"[\")) return { error: \"an IP address cannot be declared, only a domain name\" };\n if (rest.includes(\":\")) return { error: \"it names a port, which a domain cannot\" };\n\n const wildcard = rest.startsWith(\"*.\");\n const host = wildcard ? rest.slice(2) : rest;\n if (host.includes(\"*\")) return { error: \"a wildcard may only be the whole first label, as in *.example.com\" };\n const problem = hostProblem(host, wildcard);\n if (problem !== undefined) return { error: problem };\n return { origin: `https://${wildcard ? \"*.\" : \"\"}${host}`, host, wildcard };\n}\n\n/**\n * Read a list: the accepted domains, deduplicated by canonical origin in\n * first-seen order, and each refused entry with its reason.\n */\nexport function parseResourceDomains(entries: readonly string[]): {\n domains: ResourceDomain[];\n refused: { entry: string; error: string }[];\n} {\n const domains: ResourceDomain[] = [];\n const refused: { entry: string; error: string }[] = [];\n for (const entry of entries) {\n const parsed = parseResourceDomain(entry);\n if (\"error\" in parsed) refused.push({ entry, error: parsed.error });\n else if (!domains.some((domain) => domain.origin === parsed.origin)) domains.push(parsed);\n }\n return { domains, refused };\n}\n\n/** Whether `hostname` falls under `domain`, as a CSP host source matches it. */\nexport function matchesResourceDomain(hostname: string, domain: ResourceDomain): boolean {\n const host = hostname.toLowerCase();\n return domain.wildcard ? host.endsWith(`.${domain.host}`) : host === domain.host;\n}\n", "/**\n * Pure render tree produced by widget renderers.\n *\n * Plain, JSON-serializable data \u2014 no DOM or framework types \u2014 so renderers\n * are testable anywhere and the output layers (`renderToHtml`, `mountNode`)\n * stay thin and swappable. There is deliberately no raw-HTML node type: all\n * text is escaped at the output boundary. An element's optional `key` names\n * it among its siblings for keyed in-place patching; it is render-tree data\n * only, and no output layer emits it.\n */\nimport type { WidgetPayload } from \"../contract/types.js\";\n\n/** Attribute map. Values are plain strings (escaped by output layers). */\nexport type WidgetNodeAttrs = Record<string, string>;\n\n/** A tagged element in the render tree. */\nexport interface WidgetElementNode {\n tag: string;\n attrs?: WidgetNodeAttrs;\n children?: WidgetNode[];\n /** Identity among siblings for keyed patching; never serialized. */\n key?: string;\n}\n\n/** An element in the render tree: a text node or a tagged element. */\nexport type WidgetNode = string | WidgetElementNode;\n\n/** A widget renderer: pure function from payload to render tree. */\nexport type WidgetRenderer = (payload: WidgetPayload) => WidgetNode;\n\n/** Convenience node constructor (omits empty attrs/children and an absent key). */\nexport function el(\n tag: string,\n attrs?: WidgetNodeAttrs,\n children?: WidgetNode[],\n key?: string\n): WidgetElementNode {\n const node: WidgetElementNode = { tag };\n if (attrs && Object.keys(attrs).length > 0) node.attrs = attrs;\n if (children && children.length > 0) node.children = children;\n if (key !== undefined) node.key = key;\n return node;\n}\n", "import type { WidgetKind } from \"../contract/types.js\";\nimport type { DataSchema } from \"./schema.js\";\nimport type { WidgetStyles } from \"./styles.js\";\n\n/**\n * Agent-facing documentation for a widget kind. Descriptors make the\n * catalog reflectable: tooling (e.g. the widgentic MCP server's\n * `list_widgets`) lists them so agents can pick a widget and shape their\n * `data` without reading source.\n */\nexport interface WidgetDescriptor {\n kind: WidgetKind;\n /** What the widget is for. */\n description: string;\n /** Human-readable description of the expected `data` input. */\n dataShape: string;\n /** Small example `data` value an agent can imitate. */\n dataExample?: unknown;\n /** Supported hint keys and what they do. */\n hints?: Record<string, string>;\n /**\n * Optional JSON-Schema subset for `data` (see schema.ts). When present,\n * `catalog.render` validates data against it before rendering; kinds\n * without one keep their lenient fallback behavior.\n */\n dataSchema?: DataSchema;\n /**\n * Optional CSS-as-data for the kind's `.wg-` classes (see styles.ts).\n * Included in `page` output and exposable by hosts; guarded like themes.\n */\n styles?: WidgetStyles;\n}\n\n/** Descriptor as supplied at registration; `kind` is filled by the catalog. */\nexport type WidgetDescriptorInput = Omit<WidgetDescriptor, \"kind\">;\n\n/**\n * How agents should write the labels a reader sees \u2014 the `labels` hint of\n * the built-in card and table, and the literals a template writes. One\n * text, derived by every surface that steers agents.\n */\nexport const LABEL_STYLE_RULE =\n 'Labels are what the reader sees: write them in Title Case (\"First Name\", \"Order Total\") ' +\n \"unless the user asks for another style or language, and keep the data's keys as they are.\";\n\n/**\n * Honest documentation of the built-ins' actual (lenient) behavior. Every\n * `dataExample` is asserted by tests to render successfully.\n */\nexport const BUILTIN_DESCRIPTORS: Record<\n \"card\" | \"table\" | \"tree\" | \"group\",\n WidgetDescriptorInput\n> = {\n card: {\n description:\n \"Key/value details for a single entity, with optional title and subtitle.\",\n dataShape:\n \"A plain object. `title`, `subtitle`, and `fields` are used when present; \" +\n \"other entries become field key/value pairs. Primitives render as a single \" +\n \"value line. `meta.title`/`meta.subtitle` fill in missing chrome. Send \" +\n \"field values typed (e.g. price: 9.99, not '$9.99') and use \" +\n \"hints.fieldFormat for display formatting \u2014 the payload keeps the \" +\n \"typed value while the render gets its unit. Field values that are \" +\n \"image URLs render as images (see hints.images). Each field is labelled \" +\n \"by its key unless hints.labels names it.\",\n dataExample: {\n title: \"Essence Mascara\",\n subtitle: \"beauty\",\n fields: { price: 9.99, rating: 2.56, stock: 99 }\n },\n hints: {\n fieldFormat:\n \"Record<fieldKey, pattern> \u2014 formats matching field values by \" +\n \"substituting {value} in the pattern (e.g. { price: '${value}', \" +\n \"rating: '{value} / 5' }); a pattern without {value} is prefixed \" +\n \"to the value. Output is escaped like any text.\",\n images:\n \"Record<fieldKey, 'avatar' | 'thumb' | 'hero' | true | false> \u2014 \" +\n \"field values that are https image URLs (image extension) or \" +\n \"data:image/* URIs auto-render as images (default shape: thumb); \" +\n \"a shape forces image treatment (use for extensionless URLs), \" +\n \"true forces the default shape, false keeps the URL as text. \" +\n \"Unsafe sources always render as text; image treatment wins over \" +\n \"fieldFormat for the same key.\",\n labels:\n \"Record<fieldKey, string> \u2014 the label shown for a field instead of \" +\n \"its key (also an image field's alt text); every other hint still \" +\n \"names the key. \" +\n LABEL_STYLE_RULE,\n links:\n \"Record<fieldKey, boolean | prefix> \u2014 true links a field whose \" +\n \"value already IS an http(s)/mailto/tel URL; a prefix string \" +\n \"composes the href while the display stays the clean value \" +\n \"(e.g. { email: 'mailto:', phone: 'tel:' } shows a@b.c but links \" +\n \"mailto:a@b.c). Unsafe compositions and non-strings stay plain \" +\n \"text; image treatment wins for the same key. Links are never \" +\n \"automatic \u2014 opt in per field.\"\n }\n },\n table: {\n description: \"Rows and columns for arrays of records.\",\n dataShape:\n \"An array of records (plain objects). Columns are the union of record keys \" +\n \"in first-seen order; missing cells render empty; non-array data becomes a \" +\n \"single row. Cell values that are image URLs render as avatars (see \" +\n \"hints.images). meta.title/meta.subtitle render as the table's caption. \" +\n \"Send cell values typed (e.g. total: 11471334.78, not '11,471,334.78') \" +\n \"and use hints.fieldFormat for display formatting \u2014 the payload keeps \" +\n \"the typed value while the render gets its unit.\",\n dataExample: [\n { name: \"Ada\", role: \"eng\", avatar: \"https://picsum.photos/id/64/64/64.jpg\" },\n { name: \"Lin\", role: \"ops\", avatar: \"https://picsum.photos/id/65/64/64.jpg\" }\n ],\n hints: {\n columns: \"string[] \u2014 overrides column selection and order\",\n labels:\n \"Record<columnKey, string> \u2014 the header shown for a column instead \" +\n \"of its key (also its images' alt text); every other hint, \" +\n \"columns included, still names the key. \" +\n LABEL_STYLE_RULE,\n fieldFormat:\n \"Record<columnKey, pattern> \u2014 formats matching cell values by \" +\n \"substituting {value} in the pattern (e.g. { total: '${value}' }); \" +\n \"a pattern without {value} is prefixed to the value. Output is \" +\n \"escaped like any text; image treatment wins for the same column.\",\n links:\n \"Record<columnKey, boolean | prefix> \u2014 true links cells whose \" +\n \"value already IS an http(s)/mailto/tel URL; a prefix string \" +\n \"composes the href while the display stays the clean value \" +\n \"(e.g. { email: 'mailto:', phone: 'tel:' } shows a@b.c but links \" +\n \"mailto:a@b.c). Unsafe compositions and non-strings stay plain \" +\n \"text; image treatment wins for the same column. Links are never \" +\n \"automatic \u2014 opt in per column.\",\n images:\n \"Record<columnKey, 'avatar' | 'thumb' | 'hero' | true | false> \u2014 \" +\n \"cell values that are https image URLs (image extension) or \" +\n \"data:image/* URIs auto-render as images (default shape: avatar); \" +\n \"a shape forces image treatment (use for extensionless URLs), \" +\n \"true forces the default shape, false keeps the URL as text. \" +\n \"Unsafe sources always render as text.\"\n }\n },\n tree: {\n description:\n \"Collapsible hierarchy of labeled nodes \u2014 a person can expand and \" +\n \"collapse branches by click or keyboard.\",\n dataShape:\n \"Nested `{ label, icon?, children[] }` nodes \u2014 a single root object or an \" +\n \"array of them. A node with children renders as a native disclosure that \" +\n \"opens and closes; leaves are plain labels. Optional `icon` is ONE string \" +\n \"per node, shown before the label: a data:image/* URI or an https URL \" +\n \"ending in an image extension (.png, .jpg, .svg, ...) renders as a small \" +\n \"decorative image; any other string \u2014 an emoji, a glyph, an extensionless \" +\n \"URL \u2014 renders as text. Nodes without a usable `label` get a JSON fallback label (which \" +\n \"excludes `children` and `icon`). meta.title renders as a title line above \" +\n \"the tree.\",\n dataExample: {\n label: \"src\",\n icon: \"\\u{1F4C1}\",\n children: [{ label: \"index.ts\", icon: \"\\u{1F4C4}\", children: [] }]\n },\n hints: {\n expandDepth:\n \"number \u2014 branches at depth < value START expanded (default: \" +\n \"unlimited). Presentational only: the full subtree is always in the \" +\n \"markup, and collapsing is the disclosure's own behavior. The value \" +\n \"selects only the INITIAL state (the `open` attribute on branches); \" +\n \"a visitor's own expand/collapse survives later re-renders.\"\n }\n },\n group: {\n description:\n \"Several widgets in one response \u2014 mixed kinds in a single layout \" +\n \"container. Use ONE group render instead of repeated render calls \" +\n \"when showing multiple widgets together.\",\n dataShape:\n \"{ items: [{ kind, data, hints?, meta? }, ...] } \u2014 each item is a \" +\n \"full sub-widget rendered exactly as a top-level call would be \" +\n \"(any listed kind except 'group'; groups do not nest). At most 20 \" +\n \"items per group.\",\n dataExample: {\n items: [\n { kind: \"card\", data: { title: \"Ada\", fields: { role: \"eng\" } } },\n { kind: \"card\", data: { title: \"Lin\", fields: { role: \"ops\" } } }\n ]\n },\n hints: {\n layout:\n \"'stack' | 'row' | 'grid' \u2014 how items sit together (default: \" +\n \"stack). 'row' wraps; 'grid' uses equal columns.\",\n gap: \"'none' | 'sm' | 'md' | 'lg' \u2014 spacing between items (default: md).\",\n columns: \"number 1-4 \u2014 column count for layout: 'grid' (default: 2).\"\n }\n }\n};\n", "import type { WidgetContractError } from \"../contract/errors.js\";\n\n/**\n * A JSON-Schema *subset* for widget `data`: `type`, `properties`,\n * `required`, `items`, `enum`, `pattern`. Unknown keywords are ignored\n * (forward compatible), never misinterpreted \u2014 and that policy extends to\n * `pattern` values this module refuses to run (see the ReDoS bounds\n * below). Violations map to the existing contract vocabulary with dotted\n * paths into the data.\n */\nexport type DataSchema = Record<string, unknown>;\n\n// `pattern` bounds: schemas arrive from descriptor authors, but the strings\n// they test arrive from agents \u2014 an exponential-backtracking pattern over\n// attacker-lengthened input is a denial of service. Overlong patterns,\n// nested-quantifier shapes, and RegExp-invalid sources are IGNORED (never\n// misinterpreted as passing or failing); tested strings are capped.\n/** Longest `pattern` the validator will compile. */\nexport const PATTERN_MAX_LENGTH = 256;\nconst TESTED_STRING_MAX = 10_000;\nconst NESTED_QUANTIFIER = /(\\([^)]*[+*][^)]*\\)|\\[[^\\]]*\\][+*])[+*{]/;\n\nfunction compileSafePattern(pattern: unknown): RegExp | undefined {\n if (typeof pattern !== \"string\" || pattern.length > PATTERN_MAX_LENGTH) {\n return undefined;\n }\n if (NESTED_QUANTIFIER.test(pattern)) return undefined;\n try {\n return new RegExp(pattern);\n } catch {\n return undefined;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The `type` names the validator checks; any other name constrains nothing. */\nexport const DATA_SCHEMA_TYPES: readonly string[] = [\n \"object\",\n \"array\",\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"null\"\n];\n\nfunction matchesSingleType(type: string, data: unknown): boolean {\n switch (type) {\n case \"object\":\n return isPlainObject(data);\n case \"array\":\n return Array.isArray(data);\n case \"string\":\n return typeof data === \"string\";\n case \"number\":\n return typeof data === \"number\";\n case \"integer\":\n return typeof data === \"number\" && Number.isInteger(data);\n case \"boolean\":\n return typeof data === \"boolean\";\n case \"null\":\n return data === null;\n default:\n // Unknown type keyword: ignore rather than reject.\n return true;\n }\n}\n\nfunction matchesType(type: unknown, data: unknown): boolean {\n if (typeof type === \"string\") return matchesSingleType(type, data);\n if (Array.isArray(type)) {\n return type.some(\n (candidate) =>\n typeof candidate === \"string\" && matchesSingleType(candidate, data)\n );\n }\n return true;\n}\n\nfunction enumMatches(allowed: unknown[], data: unknown): boolean {\n return allowed.some((value) => {\n if (value === data) return true;\n try {\n return JSON.stringify(value) === JSON.stringify(data);\n } catch {\n return false;\n }\n });\n}\n\nfunction formatType(type: unknown): string {\n return Array.isArray(type) ? type.join(\" | \") : String(type);\n}\n\n/**\n * Validate `data` against a subset schema. Returns the first violation as a\n * contract-vocabulary error (`MISSING_FIELD` for required, `INVALID_TYPE`\n * for type/enum) with a dotted path, or `undefined` when valid. Never\n * throws.\n */\nexport function validateDataAgainstSchema(\n schema: DataSchema,\n data: unknown,\n path = \"data\"\n): WidgetContractError | undefined {\n if (Array.isArray(schema.enum) && !enumMatches(schema.enum, data)) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must be one of the enumerated options.`\n };\n }\n\n if (schema.type !== undefined && !matchesType(schema.type, data)) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must have type ${formatType(schema.type)}.`\n };\n }\n\n // Pattern applies to string data only \u2014 type mismatches are `type`'s job.\n if (typeof data === \"string\" && schema.pattern !== undefined) {\n const regex = compileSafePattern(schema.pattern);\n if (regex !== undefined && !regex.test(data.slice(0, TESTED_STRING_MAX))) {\n return {\n code: \"INVALID_TYPE\",\n path,\n message: `Value at '${path}' must match pattern ${String(schema.pattern)}.`\n };\n }\n }\n\n if (isPlainObject(data)) {\n if (Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (typeof key === \"string\" && !(key in data)) {\n return {\n code: \"MISSING_FIELD\",\n path: `${path}.${key}`,\n message: `Missing required property '${key}'.`\n };\n }\n }\n }\n if (isPlainObject(schema.properties)) {\n for (const [key, subschema] of Object.entries(schema.properties)) {\n if (key in data && isPlainObject(subschema)) {\n const error = validateDataAgainstSchema(\n subschema,\n data[key],\n `${path}.${key}`\n );\n if (error) return error;\n }\n }\n }\n }\n\n if (Array.isArray(data) && isPlainObject(schema.items)) {\n for (let i = 0; i < data.length; i++) {\n const error = validateDataAgainstSchema(\n schema.items as DataSchema,\n data[i],\n `${path}.${i}`\n );\n if (error) return error;\n }\n }\n\n return undefined;\n}\n\n/**\n * What the validator would silently ignore in a schema: an unknown `type`\n * name, a `pattern` it refuses to run, or a subset keyword of the wrong\n * shape. Warnings, never refusals \u2014 stores accept these (unknown input is\n * ignored, not misread), but an author meant something by them. Paths are\n * dotted from `path`. Never throws.\n */\nexport function auditDataSchema(schema: DataSchema, path = \"schema\"): string[] {\n const warnings: string[] = [];\n const type = schema.type;\n if (type !== undefined) {\n const names = typeof type === \"string\" ? [type] : Array.isArray(type) ? type : undefined;\n if (names === undefined) {\n warnings.push(`${path}.type: must be a type name or a list of them; it is ignored.`);\n } else {\n for (const name of names) {\n if (typeof name !== \"string\" || !DATA_SCHEMA_TYPES.includes(name)) {\n warnings.push(\n `${path}.type: '${String(name)}' is not one of ${DATA_SCHEMA_TYPES.join(\", \")}; it constrains nothing.`\n );\n }\n }\n }\n }\n if (schema.pattern !== undefined && compileSafePattern(schema.pattern) === undefined) {\n warnings.push(\n `${path}.pattern: not run \u2014 it must be a valid regular expression of at most ${PATTERN_MAX_LENGTH} characters without nested quantifiers.`\n );\n }\n if (schema.enum !== undefined && !Array.isArray(schema.enum)) {\n warnings.push(`${path}.enum: must be a list of values; it is ignored.`);\n }\n if (\n schema.required !== undefined &&\n !(Array.isArray(schema.required) && schema.required.every((key) => typeof key === \"string\"))\n ) {\n warnings.push(`${path}.required: must be a list of property names; it is ignored.`);\n }\n if (schema.properties !== undefined) {\n if (!isPlainObject(schema.properties)) {\n warnings.push(`${path}.properties: must be an object of schemas; it is ignored.`);\n } else {\n for (const [key, subschema] of Object.entries(schema.properties)) {\n if (isPlainObject(subschema)) warnings.push(...auditDataSchema(subschema, `${path}.properties.${key}`));\n else warnings.push(`${path}.properties.${key}: must be a schema object; it is ignored.`);\n }\n }\n }\n if (schema.items !== undefined) {\n if (isPlainObject(schema.items)) warnings.push(...auditDataSchema(schema.items, `${path}.items`));\n else warnings.push(`${path}.items: must be a schema object; it is ignored.`);\n }\n return warnings;\n}\n", "/** Shared helpers for the built-in renderers. */\nimport { isLinkableUrl } from \"../../contract/urls.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\n\n/** Same plain-object definition as the contract validator. */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Render any value as display text. Strings pass through; primitives\n * stringify; structured values fall back to compact JSON. Never throws.\n */\nexport function formatValue(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined) return \"\";\n if (\n value === null ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\"\n ) {\n return String(value);\n }\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * The label a reader sees for a card field or table column: its\n * `hints.labels` entry when that is a non-blank string, else the key.\n */\nexport function labelFor(key: string, hints: unknown): string {\n const labels = isPlainObject(hints) && isPlainObject(hints.labels) ? hints.labels : undefined;\n const label = labels?.[key];\n return typeof label === \"string\" && label.trim() !== \"\" ? label : key;\n}\n\n/** Apply a `fieldFormat` pattern: substitute `{value}`, or append when absent. */\nexport function applyPattern(pattern: string, value: string): string {\n return pattern.includes(\"{value}\")\n ? pattern.split(\"{value}\").join(value)\n : pattern + value;\n}\n\n/**\n * Wrap display text in an anchor when the caller opted this key into\n * `hints.links` AND the raw value is an explicitly-schemed safe URL.\n * Built-ins construct nodes directly (they never pass the template\n * compiler's URL guard), so the scheme check lives here \u2014 mirroring\n * `isSafeImageSrc` in the image path. Everything else stays plain text.\n */\nexport function linkOrText(\n key: string,\n raw: unknown,\n hints: unknown,\n display: string\n): WidgetNode {\n const links =\n isPlainObject(hints) && isPlainObject(hints.links) ? hints.links : undefined;\n const hint = links?.[key];\n if (typeof raw !== \"string\" || raw === \"\") return display;\n // true: the value IS the URL. String: an author-supplied prefix composed\n // with the value (e.g. \"mailto:\") \u2014 the display stays the clean value,\n // and the COMPOSED href faces the guard, so a hostile value can never\n // smuggle a scheme past an author prefix.\n const href =\n hint === true ? raw : typeof hint === \"string\" ? hint + raw : undefined;\n if (href === undefined || !isLinkableUrl(href)) return display;\n return el(\n \"a\",\n { class: \"wg-link\", href, rel: \"noopener noreferrer\" },\n [display]\n );\n}\n", "import { isSafeImageSrc, looksLikeImageUrl } from \"../../contract/urls.js\";\nimport type { WidgetElementNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { isPlainObject } from \"./format.js\";\n\n/** Image presentation variants; each maps to a `wg-img-<shape>` class. */\nexport type ImageShape = \"avatar\" | \"thumb\" | \"hero\";\n\n/**\n * Render-only shapes extend the hintable ones: `icon` is the tree's\n * per-node anchor and is deliberately not accepted by `hints.images`.\n */\nexport type RenderImageShape = ImageShape | \"icon\";\n\nconst HINTABLE_SHAPES: readonly ImageShape[] = [\"avatar\", \"thumb\", \"hero\"];\nconst SHAPES = new Set<string>(HINTABLE_SHAPES);\n\n/**\n * Decide whether a card-field / table-cell value renders as an image.\n * `hints.images` (keyed by field/column name) overrides auto-detection:\n * a shape string forces that shape, `true` forces the context default,\n * `false` suppresses. Hints never bypass safety \u2014 an unsafe source always\n * renders as text (`null` here). Auto-detection requires the value to\n * self-identify as an image (`looksLikeImageUrl`).\n */\nexport function resolveImage(\n key: string,\n value: unknown,\n hints: Record<string, unknown> | undefined,\n defaultShape: RenderImageShape\n): { src: string; shape: RenderImageShape } | null {\n if (typeof value !== \"string\") return null;\n const images = isPlainObject(hints?.images) ? hints.images : undefined;\n const hint = images?.[key];\n if (hint === false) return null;\n if (typeof hint === \"string\" && SHAPES.has(hint)) {\n return isSafeImageSrc(value)\n ? { src: value, shape: hint as ImageShape }\n : null;\n }\n if (hint === true) {\n return isSafeImageSrc(value) ? { src: value, shape: defaultShape } : null;\n }\n return looksLikeImageUrl(value) ? { src: value, shape: defaultShape } : null;\n}\n\n/**\n * The standard image element: stable classes, the field's label (its key\n * when unlabelled) as alt, lazy loading. An empty `alt` marks decorative\n * images whose meaning the neighbouring text already carries.\n */\nexport function imageNode(\n alt: string,\n src: string,\n shape: RenderImageShape\n): WidgetElementNode {\n return el(\"img\", {\n class: `wg-img wg-img-${shape}`,\n src,\n alt,\n loading: \"lazy\",\n decoding: \"async\"\n });\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { applyPattern, formatValue, isPlainObject, labelFor, linkOrText } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\n\n/**\n * `card` renderer.\n *\n * Uses `data.title`/`data.subtitle`/`data.fields` when present; other\n * plain-object entries become field key/value pairs; primitives and `null`\n * render as a single value line. `meta.title`/`meta.subtitle` fill in when\n * `data` does not provide them. A field shows its `hints.labels` entry, or\n * its key; every other hint still addresses it by key. Total: never throws.\n */\nexport function renderCard(payload: WidgetPayload): WidgetNode {\n const { data, meta } = payload;\n const fieldFormat = isPlainObject(payload.hints?.fieldFormat)\n ? payload.hints.fieldFormat\n : undefined;\n\n let title: unknown;\n let subtitle: unknown;\n let fieldEntries: [string, unknown][] = [];\n let value: string | undefined;\n\n if (isPlainObject(data)) {\n title = data.title;\n subtitle = data.subtitle;\n if (isPlainObject(data.fields)) {\n fieldEntries = Object.entries(data.fields);\n } else {\n fieldEntries = Object.entries(data).filter(\n ([key]) => key !== \"title\" && key !== \"subtitle\"\n );\n }\n } else {\n value = formatValue(data);\n }\n\n if (title === undefined) title = meta?.title;\n if (subtitle === undefined) subtitle = meta?.subtitle;\n\n const children: WidgetNode[] = [];\n if (title !== undefined) {\n children.push(el(\"div\", { class: \"wg-card-title\" }, [formatValue(title)]));\n }\n if (subtitle !== undefined) {\n children.push(\n el(\"div\", { class: \"wg-card-subtitle\" }, [formatValue(subtitle)])\n );\n }\n if (value !== undefined) {\n children.push(el(\"div\", { class: \"wg-card-value\" }, [value]));\n }\n if (fieldEntries.length > 0) {\n children.push(\n el(\n \"dl\",\n { class: \"wg-card-fields\" },\n fieldEntries.map(([key, fieldValue]) => {\n const label = labelFor(key, payload.hints);\n // Image treatment wins over fieldFormat for the same key.\n const image = resolveImage(key, fieldValue, payload.hints, \"thumb\");\n let display: WidgetNode;\n if (image) {\n display = imageNode(label, image.src, image.shape);\n } else {\n const raw = formatValue(fieldValue);\n const pattern = fieldFormat?.[key];\n const text =\n typeof pattern === \"string\" ? applyPattern(pattern, raw) : raw;\n display = linkOrText(key, fieldValue, payload.hints, text);\n }\n return el(\"div\", { class: \"wg-card-field\" }, [\n el(\"dt\", { class: \"wg-card-field-key\" }, [label]),\n el(\"dd\", { class: \"wg-card-field-value\" }, [display])\n ]);\n })\n )\n );\n }\n return el(\"div\", { class: \"wg-card\" }, children);\n}\n", "import { isPlainObject } from \"./format.js\";\n\n/**\n * Keys for a sibling list from record identity: every item must be an\n * object whose `id` is a string or a finite number, and the ids must be\n * distinct as strings (`1` and `\"1\"` collide). Otherwise the list stays\n * unkeyed and the patchers pair it by position.\n */\nexport function keysFromIds(items: readonly unknown[]): string[] | undefined {\n const keys: string[] = [];\n const seen = new Set<string>();\n for (const item of items) {\n if (!isPlainObject(item)) return undefined;\n const id = item.id;\n let key: string;\n if (typeof id === \"string\") key = id;\n else if (typeof id === \"number\" && Number.isFinite(id)) key = String(id);\n else return undefined;\n if (seen.has(key)) return undefined;\n seen.add(key);\n keys.push(key);\n }\n return keys;\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { applyPattern, formatValue, isPlainObject, labelFor, linkOrText } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\nimport { keysFromIds } from \"./keys.js\";\n\n/**\n * `table` renderer.\n *\n * One row per record; columns are the union of record keys in first-seen\n * order, overridable via `hints.columns`. Non-array data becomes a\n * single-record array; non-object rows are wrapped as `{ value }`. A\n * header shows its column's `hints.labels` entry, or its key. Missing\n * cells render empty. Body rows are keyed by record `id` when every record\n * carries a distinct one, so a reordering re-render moves rows instead of\n * re-pairing them. Total: never throws.\n */\nexport function renderTable(payload: WidgetPayload): WidgetNode {\n const rows = Array.isArray(payload.data) ? payload.data : [payload.data];\n const fieldFormat = isPlainObject(payload.hints?.fieldFormat)\n ? payload.hints.fieldFormat\n : undefined;\n const records: Record<string, unknown>[] = rows.map((row) =>\n isPlainObject(row) ? row : { value: row }\n );\n\n const hintColumns = payload.hints?.columns;\n let columns: string[];\n if (\n Array.isArray(hintColumns) &&\n hintColumns.every((column): column is string => typeof column === \"string\")\n ) {\n columns = hintColumns;\n } else {\n columns = [];\n const seen = new Set<string>();\n for (const record of records) {\n for (const key of Object.keys(record)) {\n if (!seen.has(key)) {\n seen.add(key);\n columns.push(key);\n }\n }\n }\n }\n\n const rowKeys = keysFromIds(records);\n\n // Caption chrome from meta \u2014 a table's data has no title slot, so meta\n // is the only source; absence means no caption. <caption> must be the\n // table's first child per the HTML content model.\n const chrome: WidgetNode[] = [];\n const title = payload.meta?.title;\n const subtitle = payload.meta?.subtitle;\n if (title !== undefined || subtitle !== undefined) {\n const parts: WidgetNode[] = [];\n if (title !== undefined) {\n parts.push(el(\"span\", { class: \"wg-table-title\" }, [formatValue(title)]));\n }\n if (subtitle !== undefined) {\n parts.push(\n el(\"span\", { class: \"wg-table-subtitle\" }, [formatValue(subtitle)])\n );\n }\n chrome.push(el(\"caption\", { class: \"wg-table-caption\" }, parts));\n }\n\n return el(\"table\", { class: \"wg-table\" }, [\n ...chrome,\n el(\"thead\", { class: \"wg-table-head\" }, [\n el(\n \"tr\",\n undefined,\n columns.map((column) =>\n el(\"th\", { class: \"wg-table-header\" }, [labelFor(column, payload.hints)])\n )\n )\n ]),\n el(\n \"tbody\",\n { class: \"wg-table-body\" },\n records.map((record, index) =>\n el(\n \"tr\",\n { class: \"wg-table-row\" },\n columns.map((column) => {\n if (!(column in record)) {\n return el(\"td\", { class: \"wg-table-cell\" }, [\"\"]);\n }\n const value = record[column];\n // Precedence per column: image > link > formatted text.\n const image = resolveImage(column, value, payload.hints, \"avatar\");\n let display: WidgetNode;\n if (image) {\n display = imageNode(labelFor(column, payload.hints), image.src, image.shape);\n } else {\n const raw = formatValue(value);\n const pattern = fieldFormat?.[column];\n const text =\n typeof pattern === \"string\" ? applyPattern(pattern, raw) : raw;\n display = linkOrText(column, value, payload.hints, text);\n }\n return el(\"td\", { class: \"wg-table-cell\" }, [display]);\n }),\n rowKeys?.[index]\n )\n )\n )\n ]);\n}\n", "import type { WidgetPayload } from \"../../contract/types.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { formatValue, isPlainObject } from \"./format.js\";\nimport { imageNode, resolveImage } from \"./images.js\";\nimport { keysFromIds } from \"./keys.js\";\n\n/**\n * `tree` renderer.\n *\n * Renders nested `{ label, icon?, children[] }` nodes; nodes without a\n * usable `label` get a JSON-snippet fallback (excluding `children` and\n * `icon`). Recurses only into array-valued `children`. A node with children\n * renders as a native `details`/`summary` disclosure, so branches expand and\n * collapse with no script in every context the HTML reaches;\n * `hints.expandDepth` (default unlimited) selects the INITIAL state by\n * marking nodes at depth < value `open`. Leaves carry no disclosure. Each\n * sibling list is keyed by node `id` when all its nodes carry distinct ones,\n * so a visitor's open branch follows its node through a reorder.\n * Total: never throws.\n */\nexport function renderTree(payload: WidgetPayload): WidgetNode {\n const depthHint = payload.hints?.expandDepth;\n // Negative depths clamp to 0 (everything collapsed): `depth < value` must\n // hold monotonically, or -1 would flip a fully-collapsed tree fully open.\n const expandDepth =\n typeof depthHint === \"number\" && !Number.isNaN(depthHint)\n ? Math.max(0, depthHint)\n : Infinity;\n const roots = Array.isArray(payload.data) ? payload.data : [payload.data];\n const list = el(\"ul\", { class: \"wg-tree\" }, renderList(roots, 0, expandDepth));\n // Title chrome from meta \u2014 tree data has no title slot, so meta is the\n // only source; absence means no title line.\n const title = payload.meta?.title;\n if (title === undefined) return list;\n return el(\"div\", { class: \"wg-tree-titled\" }, [\n el(\"div\", { class: \"wg-tree-title\" }, [formatValue(title)]),\n list\n ]);\n}\n\nfunction nodeLabel(node: unknown): string {\n if (isPlainObject(node)) {\n if (node.label !== undefined) return formatValue(node.label);\n // The fallback snippet always excludes `children` and `icon` \u2014 a node\n // carrying only those must not print its own subtree as its label.\n const { children: _children, icon: _icon, ...rest } = node;\n return formatValue(rest);\n }\n return formatValue(node);\n}\n\n/**\n * The node's optional visual anchor, before the label. The same gate card\n * and table use decides image treatment \u2014 one rule to audit \u2014 and anything\n * else (an emoji, a glyph, an unsafe URL) stays text. Decorative: the alt is\n * empty because the label already carries the meaning.\n */\nfunction iconNode(icon: unknown): WidgetNode | undefined {\n if (typeof icon !== \"string\") return undefined;\n const image = resolveImage(\"\", icon, undefined, \"icon\");\n if (image !== null) return imageNode(\"\", image.src, image.shape);\n return el(\"span\", { class: \"wg-tree-icon\" }, [icon]);\n}\n\nfunction labelChildren(node: unknown): WidgetNode[] {\n const icon = isPlainObject(node) ? iconNode(node.icon) : undefined;\n const label = nodeLabel(node);\n return icon === undefined ? [label] : [icon, label];\n}\n\n// Deeper trees than any honest payload; past it nodes render as leaves so a\n// hostile nesting cannot overflow the recursive renderer or the serializers.\nconst MAX_TREE_DEPTH = 64;\n\nconst childrenOf = (node: unknown): unknown[] | undefined =>\n isPlainObject(node) && Array.isArray(node.children) && node.children.length > 0\n ? node.children\n : undefined;\n\nfunction renderList(nodes: unknown[], depth: number, expandDepth: number): WidgetNode[] {\n const keys = keysFromIds(nodes);\n return nodes.map((node, index) => renderNode(node, depth, expandDepth, keys?.[index]));\n}\n\nfunction renderNode(\n node: unknown,\n depth: number,\n expandDepth: number,\n key: string | undefined\n): WidgetNode {\n const childNodes = depth < MAX_TREE_DEPTH ? childrenOf(node) : undefined;\n\n // Leaves are plain labels: the presence of the disclosure is what marks a\n // branch, so a leaf must not offer a toggle affordance.\n if (childNodes === undefined) {\n return el(\n \"li\",\n { class: \"wg-tree-node\" },\n [el(\"span\", { class: \"wg-tree-label\" }, labelChildren(node))],\n key\n );\n }\n // `open` is a pure function of data + hints, so an unchanged branch\n // re-emits the same attributes and the in-place patchers leave a\n // visitor's own toggle alone.\n const isOpen = depth < expandDepth;\n return el(\n \"li\",\n { class: \"wg-tree-node\" },\n [\n el(\n \"details\",\n { class: \"wg-tree-branch\", ...(isOpen ? { open: \"\" } : {}) },\n [\n el(\"summary\", { class: \"wg-tree-label\" }, labelChildren(node)),\n el(\n \"ul\",\n { class: \"wg-tree-children\" },\n renderList(childNodes, depth + 1, expandDepth)\n )\n ]\n )\n ],\n key\n );\n}\n", "/**\n * `group` built-in \u2014 several widgets in one render.\n *\n * The renderer here only builds the layout container; item rendering is\n * the catalog dispatch's job (items re-enter `catalog.render`, so\n * registered and composed kinds participate and per-item errors keep\n * their structured codes with `data.items[<i>]`-prefixed paths).\n */\nimport type { WidgetContractError } from \"../../contract/errors.js\";\nimport type { WidgetNode } from \"../node.js\";\nimport { el } from \"../node.js\";\nimport { isPlainObject } from \"./format.js\";\n\n/** Hard cap on `data.items` \u2014 bounds total render work per call. */\nexport const GROUP_MAX_ITEMS = 20;\n\nexport const GROUP_LAYOUTS = [\"stack\", \"row\", \"grid\"] as const;\nexport const GROUP_GAPS = [\"none\", \"sm\", \"md\", \"lg\"] as const;\n/** `columns` is clamped into this range (grid only). */\nexport const GROUP_MAX_COLUMNS = 4;\n\nexport interface GroupItem {\n kind: string;\n data: unknown;\n hints?: unknown;\n meta?: unknown;\n}\n\nexport type GroupEnvelopeResult =\n | { ok: true; items: GroupItem[] }\n | { ok: false; error: WidgetContractError };\n\n/**\n * Validate the group envelope: `data.items` is an array of sub-widget\n * objects with string kinds, no nested groups, within the item cap.\n * Item *content* is not judged here \u2014 each item faces the full contract\n * and schema validation when it re-enters the catalog.\n */\nexport function checkGroupEnvelope(data: unknown): GroupEnvelopeResult {\n if (!isPlainObject(data) || data.items === undefined) {\n return {\n ok: false,\n error: {\n code: \"MISSING_FIELD\",\n path: \"data.items\",\n message: \"'group' data must be an object with an 'items' array.\"\n }\n };\n }\n const items = data.items;\n if (!Array.isArray(items)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"data.items\",\n message: \"'items' must be an array of sub-widgets.\"\n }\n };\n }\n if (items.length > GROUP_MAX_ITEMS) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: \"data.items\",\n message: `'items' holds ${items.length} sub-widgets; a group renders at most ${GROUP_MAX_ITEMS}.`\n }\n };\n }\n const checked: GroupItem[] = [];\n for (let i = 0; i < items.length; i++) {\n const item: unknown = items[i];\n if (!isPlainObject(item)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}]`,\n message: \"each item must be an object: { kind, data, hints?, meta? }.\"\n }\n };\n }\n if (typeof item.kind !== \"string\" || item.kind === \"\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}].kind`,\n message: \"each item needs a widget kind (non-empty string).\"\n }\n };\n }\n if (item.kind === \"group\") {\n return {\n ok: false,\n error: {\n code: \"INVALID_TYPE\",\n path: `data.items[${i}].kind`,\n message: \"a 'group' cannot contain another 'group'.\"\n }\n };\n }\n const entry: GroupItem = { kind: item.kind, data: item.data };\n if (item.hints !== undefined) entry.hints = item.hints;\n if (item.meta !== undefined) entry.meta = item.meta;\n checked.push(entry);\n }\n return { ok: true, items: checked };\n}\n\n/**\n * Build the layout container. Hints only ever SELECT from the fixed\n * class names below \u2014 no hint or data value contributes characters to\n * the class list. Unknown values fall back to the defaults (hint\n * diagnostics, not renderers, tell the caller).\n */\nexport function renderGroupContainer(\n hints: unknown,\n children: WidgetNode[]\n): WidgetNode {\n const h = isPlainObject(hints) ? hints : {};\n const layout = GROUP_LAYOUTS.some((known) => known === h.layout)\n ? (h.layout as string)\n : \"stack\";\n const gap = GROUP_GAPS.some((known) => known === h.gap)\n ? (h.gap as string)\n : \"md\";\n const classes = [`wg-group`, `wg-group-${layout}`, `wg-gap-${gap}`];\n if (layout === \"grid\") {\n const raw = typeof h.columns === \"number\" && Number.isFinite(h.columns) ? h.columns : 2;\n const columns = Math.min(GROUP_MAX_COLUMNS, Math.max(1, Math.trunc(raw)));\n classes.push(`wg-cols-${columns}`);\n }\n return el(\"div\", { class: classes.join(\" \") }, children);\n}\n", "import { validateWidgetPayload } from \"../contract/validate.js\";\nimport type { WidgetContractError } from \"../contract/errors.js\";\nimport type { WidgetKind } from \"../contract/types.js\";\nimport type { WidgetNode, WidgetRenderer } from \"./node.js\";\nimport type { WidgetDescriptor, WidgetDescriptorInput } from \"./descriptors.js\";\nimport { BUILTIN_DESCRIPTORS } from \"./descriptors.js\";\nimport { validateDataAgainstSchema } from \"./schema.js\";\nimport { renderCard } from \"./widgets/card.js\";\nimport { renderTable } from \"./widgets/table.js\";\nimport { renderTree } from \"./widgets/tree.js\";\nimport { checkGroupEnvelope, renderGroupContainer } from \"./widgets/group.js\";\n\n/**\n * Group composition: an item's action descriptors were compiled against\n * the ITEM's template, so they name the item's kind (`widget`) but not\n * where the item sits in the group payload. Stamping `at` lets the server\n * fold an action's result back into the right item and re-render the whole\n * group. Returns a NEW tree \u2014 renderers may hand back cached nodes, and\n * composition must not mutate what a pure renderer returned. Groups do not\n * nest, so the location is always one level: `data.items.<i>`.\n */\nfunction stampActionLocation(node: WidgetNode, location: string): WidgetNode {\n if (typeof node === \"string\") return node;\n const raw = node.attrs?.[\"data-wg-action\"];\n let attrs = node.attrs;\n if (typeof raw === \"string\") {\n try {\n const descriptor = JSON.parse(raw) as Record<string, unknown>;\n if (typeof descriptor === \"object\" && descriptor !== null) {\n attrs = { ...node.attrs, \"data-wg-action\": JSON.stringify({ ...descriptor, at: location }) };\n }\n } catch {\n /* not a descriptor */\n }\n }\n const children = node.children?.map((child) => stampActionLocation(child, location));\n return {\n tag: node.tag,\n ...(attrs !== undefined ? { attrs } : {}),\n ...(children !== undefined ? { children } : {})\n };\n}\n\n/**\n * Thrown when a widget kind is registered twice on the same catalog.\n * Double registration is a host programming error, surfaced loudly at\n * setup time \u2014 unlike render-time errors, which are structured results.\n */\nexport class DuplicateKindError extends Error {\n readonly code: \"DUPLICATE_KIND\" = \"DUPLICATE_KIND\";\n readonly kind: string;\n\n constructor(kind: string) {\n super(`Widget kind '${kind}' is already registered.`);\n this.name = \"DuplicateKindError\";\n this.kind = kind;\n }\n}\n\n/** Discriminated result of `catalog.render` (mirrors the contract pattern). */\nexport type RenderResult =\n | { ok: true; node: WidgetNode }\n | { ok: false; error: WidgetContractError };\n\n/** Options for one `catalog.render` call. */\nexport interface RenderOptions {\n /**\n * The data may still be arriving (a streaming preview): skip the\n * descriptor data-schema check for the payload and every group item. The\n * payload contract and interpretation bounds still apply.\n */\n partialData?: boolean;\n}\n\nexport interface WidgetCatalog {\n /**\n * Register a renderer for a new kind, optionally with agent-facing\n * documentation. Throws {@link DuplicateKindError} on duplicates\n * (built-ins included). Without a descriptor, a minimal one is generated\n * so every renderable kind stays listable.\n */\n register(\n kind: WidgetKind,\n renderer: WidgetRenderer,\n descriptor?: WidgetDescriptorInput\n ): void;\n has(kind: WidgetKind): boolean;\n resolve(kind: WidgetKind): WidgetRenderer | undefined;\n /** Currently registered kinds, as a fresh array. */\n kinds(): WidgetKind[];\n /** Descriptor for a kind, or undefined when the kind is unknown. */\n describe(kind: WidgetKind): WidgetDescriptor | undefined;\n /** All descriptors, as a fresh array. */\n list(): WidgetDescriptor[];\n /** Validate a payload against the contract (with this catalog's kinds) and render it. Never throws. */\n render(payload: unknown, options?: RenderOptions): RenderResult;\n}\n\n/**\n * Create an independent catalog instance with the built-ins (`card`,\n * `table`, `tree`, `group`) pre-registered.\n */\nexport function createCatalog(): WidgetCatalog {\n const renderers = new Map<WidgetKind, WidgetRenderer>();\n const descriptors = new Map<WidgetKind, WidgetDescriptor>();\n\n const catalog: WidgetCatalog = {\n register(kind, renderer, descriptor) {\n if (renderers.has(kind)) throw new DuplicateKindError(kind);\n renderers.set(kind, renderer);\n descriptors.set(kind, {\n kind,\n description: descriptor?.description ?? `Custom widget kind '${kind}'.`,\n dataShape: descriptor?.dataShape ?? \"Defined by the registered renderer.\",\n ...(descriptor?.dataExample !== undefined\n ? { dataExample: descriptor.dataExample }\n : {}),\n ...(descriptor?.hints ? { hints: descriptor.hints } : {}),\n ...(descriptor?.dataSchema ? { dataSchema: descriptor.dataSchema } : {}),\n ...(descriptor?.styles ? { styles: descriptor.styles } : {})\n });\n },\n has: (kind) => renderers.has(kind),\n resolve: (kind) => renderers.get(kind),\n kinds: () => [...renderers.keys()],\n describe: (kind) => descriptors.get(kind),\n list: () => [...descriptors.values()],\n render(payload, options = {}) {\n const validated = validateWidgetPayload(payload, {\n knownKinds: new Set(renderers.keys())\n });\n if (!validated.ok) return validated;\n // Opt-in structural validation: kinds with a dataSchema fail fast\n // with a dotted data path instead of rendering a lenient fallback.\n const schema = options.partialData === true\n ? undefined\n : descriptors.get(validated.payload.kind)?.dataSchema;\n if (schema) {\n const schemaError = validateDataAgainstSchema(\n schema,\n validated.payload.data\n );\n if (schemaError) return { ok: false, error: schemaError };\n }\n // `group` recurses through this same entry so registered and\n // composed kinds participate and per-item failures keep their\n // structured codes, re-pathed under `data.items[<i>]`. Renderers\n // stay pure `(payload) => WidgetNode`; composition is dispatch work.\n if (validated.payload.kind === \"group\") {\n const envelope = checkGroupEnvelope(validated.payload.data);\n if (!envelope.ok) return envelope;\n const children: WidgetNode[] = [];\n for (let i = 0; i < envelope.items.length; i++) {\n const item = envelope.items[i]!;\n const sub = catalog.render(\n {\n kind: item.kind,\n data: item.data,\n ...(item.hints !== undefined ? { hints: item.hints } : {}),\n ...(item.meta !== undefined ? { meta: item.meta } : {})\n },\n options\n );\n if (!sub.ok) {\n const subPath = sub.error.path;\n return {\n ok: false,\n error: {\n ...sub.error,\n path: `data.items[${i}]${subPath ? `.${subPath}` : \"\"}`\n }\n };\n }\n children.push(stampActionLocation(sub.node, `data.items.${i}`));\n }\n return {\n ok: true,\n node: renderGroupContainer(validated.payload.hints, children)\n };\n }\n const renderer = renderers.get(validated.payload.kind);\n if (renderer === undefined) {\n // Unreachable while knownKinds is non-empty; kept for totality.\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_KIND\",\n path: \"kind\",\n message: `Unknown widget kind '${validated.payload.kind}'.`\n }\n };\n }\n // Built-ins are total by construction; this guards the extension\n // point \u2014 a registered renderer that throws must surface as a\n // structured error, never a propagated exception.\n try {\n return { ok: true, node: renderer(validated.payload) };\n } catch (thrown) {\n return {\n ok: false,\n error: {\n code: \"RENDER_FAILED\",\n path: \"widget\",\n message: `Renderer for kind '${validated.payload.kind}' threw: ${\n thrown instanceof Error ? thrown.message : String(thrown)\n }`\n }\n };\n }\n }\n };\n\n // Built-ins go through register() so they get the same duplicate\n // protection and hosts cannot silently override them.\n catalog.register(\"card\", renderCard, BUILTIN_DESCRIPTORS.card);\n catalog.register(\"table\", renderTable, BUILTIN_DESCRIPTORS.table);\n catalog.register(\"tree\", renderTree, BUILTIN_DESCRIPTORS.tree);\n // `render()` intercepts 'group' before renderer lookup, so this renderer\n // only serves direct `resolve()` callers (e.g. designer previews); it\n // delegates back through the dispatch so items render for them too.\n catalog.register(\n \"group\",\n (payload) => {\n const result = catalog.render(payload);\n if (result.ok) return result.node;\n throw new Error(result.error.message);\n },\n BUILTIN_DESCRIPTORS.group\n );\n\n return catalog;\n}\n", "/**\n * The one `isPlainObject`. Every entry imports it relatively, so the\n * zero-dependency entries stay zero-dependency and the source-scan tests\n * keep passing.\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "/**\n * Bracket-aware reading of the CSS text the style and token guards inspect.\n * Depth counts `(` and `[` only outside quoted strings, so a parenthesis\n * inside an attribute value can neither hide a comma nor close a\n * pseudo-class early. Strings carry no escapes here: every guard bans `\\`.\n * As in CSS, a newline ends a string unclosed (a bad string), so a string\n * broken across lines never counts as closed.\n */\n\n/** A line break that ends a CSS string: LF, CR or FF. */\nconst isNewline = (char: string) => char === \"\\n\" || char === \"\\r\" || char === \"\\f\";\n\ninterface ScannedChar {\n char: string;\n /** Bracket depth around the character; a bracket itself sits at the outer depth. */\n depth: number;\n /** Part of a quoted string, quotes included. */\n quoted: boolean;\n}\n\nfunction scan(text: string): ScannedChar[] {\n const out: ScannedChar[] = [];\n let depth = 0;\n let quote: string | undefined;\n // UTF-16 units, so indices match `String.slice`; brackets and quotes are\n // never surrogate halves.\n for (let i = 0; i < text.length; i++) {\n const char = text.charAt(i);\n if (quote !== undefined) {\n out.push({ char, depth, quoted: true });\n if (char === quote || isNewline(char)) quote = undefined;\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n out.push({ char, depth, quoted: true });\n } else if (char === \"(\" || char === \"[\") {\n out.push({ char, depth, quoted: false });\n depth++;\n } else if (char === \")\" || char === \"]\") {\n depth = Math.max(0, depth - 1);\n out.push({ char, depth, quoted: false });\n } else {\n out.push({ char, depth, quoted: false });\n }\n }\n return out;\n}\n\nconst isBracket = (char: string) => char === \"(\" || char === \")\" || char === \"[\" || char === \"]\";\n\n/**\n * Every `(` and `[` closed in order and every string closed. An unclosed\n * bracket or string runs on through the rest of the stylesheet, swallowing\n * every rule after it.\n */\nexport function isBalanced(text: string): boolean {\n const open: string[] = [];\n let quote: string | undefined;\n for (let i = 0; i < text.length; i++) {\n const char = text.charAt(i);\n if (quote !== undefined) {\n if (isNewline(char)) return false;\n if (char === quote) quote = undefined;\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \"(\" || char === \"[\") {\n open.push(char === \"(\" ? \")\" : \"]\");\n } else if (char === \")\" || char === \"]\") {\n if (open.pop() !== char) return false;\n }\n }\n return open.length === 0 && quote === undefined;\n}\n\n/** Split on `separator` characters outside every bracket and string; empty pieces dropped. */\nexport function splitTopLevel(text: string, separator: (char: string) => boolean): string[] {\n const pieces: string[] = [];\n let current = \"\";\n for (const { char, depth, quoted } of scan(text)) {\n if (depth === 0 && !quoted && separator(char)) {\n pieces.push(current.trim());\n current = \"\";\n } else {\n current += char;\n }\n }\n pieces.push(current.trim());\n return pieces.filter((piece) => piece.length > 0);\n}\n\n/** The text outside every bracket and string: what a selector says at its own level. */\nexport function topLevelText(text: string): string {\n return scan(text)\n .filter(({ char, depth, quoted }) => depth === 0 && !quoted && !isBracket(char))\n .map(({ char }) => char)\n .join(\"\");\n}\n\n/** Index of the first character outside every bracket and string that passes `test`, or -1. */\nexport function indexOfTopLevel(text: string, test: (char: string) => boolean): number {\n return scan(text).findIndex(({ char, depth, quoted }) => depth === 0 && !quoted && test(char));\n}\n\n/**\n * The argument of each top-level functional pseudo-class named in `names`\n * (`:is(\u2026)` \u2192 `\u2026`), so a guard can look inside the ones that pass their\n * argument's matches through.\n */\nexport function pseudoArguments(text: string, names: readonly string[]): string[] {\n const chars = scan(text);\n const args: string[] = [];\n for (let i = 0; i < chars.length; i++) {\n const entry = chars[i];\n if (entry === undefined || entry.char !== \"(\" || entry.depth !== 0 || entry.quoted) continue;\n const before = text.slice(0, i).toLowerCase();\n if (!names.some((name) => before.endsWith(`:${name}`))) continue;\n let end = i + 1;\n while (end < chars.length) {\n const closer = chars[end];\n if (closer !== undefined && closer.char === \")\" && closer.depth === 0 && !closer.quoted) break;\n end++;\n }\n args.push(text.slice(i + 1, end));\n }\n return args;\n}\n", "/**\n * Registered widget styles: custom kinds ship their look as data alongside\n * their template/renderer, and themes ship shared classes the same way.\n * Same trust model as theme tokens \u2014 designer-authored \u2014 so selectors,\n * properties, and values are all guarded, and unsafe entries are skipped\n * rather than emitted.\n */\nimport { isPlainObject } from \"../shared/plain-object.js\";\nimport { indexOfTopLevel, isBalanced, pseudoArguments, splitTopLevel, topLevelText } from \"../shared/css-scan.js\";\n\nexport type WidgetStyles = Record<string, Record<string, string>>;\n\n/** Substrings that disqualify a selector, property or value. Exported\n * so the authoring guide derives the rule instead of restating it. */\nexport const UNSAFE = /[;{}<>@\\\\]/;\n/** The property-name allowlist: not merely \"no banned characters\". */\nexport const PROPERTY_NAME = /^-?[a-zA-Z][a-zA-Z-]*$/;\n\n/**\n * The shape both widget and theme styles must have: selectors mapping to\n * property/value strings. Shape only \u2014 unsafe entries pass here and are\n * dropped by the generator, so one rule decides what reaches CSS.\n */\nexport function isStyleMap(value: unknown): value is WidgetStyles {\n if (!isPlainObject(value)) return false;\n return Object.values(value).every(\n (declarations) =>\n isPlainObject(declarations) &&\n Object.values(declarations).every((v) => typeof v === \"string\")\n );\n}\n\n/**\n * CSS functions that fetch or execute, refused in values wherever they\n * appear \u2014 `image-set()` and `src()` carry URLs without spelling `url(`.\n * Exported so the guides derive the rule instead of restating it.\n */\nexport const UNSAFE_FUNCTIONS: readonly string[] = [\"url(\", \"expression(\", \"image-set(\", \"src(\"];\n\n/** A comment opener or closer: one can swallow every rule after it. */\nconst COMMENT = /\\/\\*|\\*\\//;\n\nfunction callsUnsafeFunction(text: string): boolean {\n return UNSAFE_FUNCTIONS.some((call) => new RegExp(`${call.slice(0, -1)}\\\\s*\\\\(`, \"i\").test(text));\n}\n\n/**\n * Pseudo-classes that pass their argument's matches through: `:is(.wg-a,\n * .wg-b)` matches only what its arguments match. `:not()` and `:has()` do\n * not \u2014 `body:not(.wg-x)` and `body:has(.wg-x)` match `body`.\n */\nconst FORWARDING_PSEUDOS = [\"is\", \"where\", \"matches\", \"-webkit-any\", \"-moz-any\"] as const;\n\n/** Combinators between compounds, read outside brackets and strings. */\nconst COMBINATOR = (char: string) => /[\\s>+~]/.test(char);\n\n/**\n * A selector list every one of whose parts is held to `.wg-` classes: some\n * compound of each part names a `.wg-` class at its own level, or forwards\n * through `:is()`/`:where()` to a list that does. A `.wg-` hidden in\n * `:not()`, `:has()`, an attribute test or a string constrains nothing.\n */\nfunction isConstrainedList(selector: string, depth: number): boolean {\n const parts = splitTopLevel(selector, (char) => char === \",\");\n return parts.length > 0 && parts.every((part) => isConstrainedPart(part, depth));\n}\n\n/**\n * How deep `:is()`/`:where()` may nest before a selector is refused: the\n * check recurses per level, and a generator that runs on every render must\n * never throw. Real selectors nest two or three levels.\n */\nconst MAX_FORWARDING_DEPTH = 16;\n\nfunction isConstrainedPart(part: string, depth = 0): boolean {\n if (depth > MAX_FORWARDING_DEPTH) return false;\n return splitTopLevel(part, COMBINATOR).some(\n (compound) =>\n topLevelText(compound).includes(\".wg-\") ||\n pseudoArguments(compound, FORWARDING_PSEUDOS).some((argument) => isConstrainedList(argument, depth + 1))\n );\n}\n\n/**\n * Every top-level selector part must be held to `.wg-` classes, and no\n * part may open with a combinator (`~ .wg-b` is invalid alone and would\n * only become valid once scoped). Brackets and strings must close, and\n * no comments: either would run on and swallow the rules after it.\n */\nfunction isSafeSelector(selector: string): boolean {\n if (UNSAFE.test(selector) || COMMENT.test(selector) || !isBalanced(selector)) return false;\n const parts = splitTopLevel(selector, (char) => char === \",\");\n return parts.length > 0 && parts.every((part) => !/^[>+~]/.test(part) && isConstrainedPart(part));\n}\n\nfunction isSafeValue(value: string): boolean {\n return !UNSAFE.test(value) && !COMMENT.test(value) && isBalanced(value) && !callsUnsafeFunction(value);\n}\n\n/**\n * One part under a scope that targets the root element. A part already\n * anchored at the root (`:root[data-theme=\"dark\"] .wg-x`, `html .wg-x`)\n * takes the scope as an extra condition on that root compound \u2014 prefixing\n * would demand a root inside the root and never match; any other part is\n * prefixed with `:where(<scope>) `.\n */\nfunction scopePart(part: string, scope: string): string {\n if (!/^(:root|html)(?![\\w-])/i.test(part)) return `:where(${scope}) ${part}`;\n const found = indexOfTopLevel(part, COMBINATOR);\n const end = found === -1 ? part.length : found;\n return `${part.slice(0, end)}:where(${scope})${part.slice(end)}`;\n}\n\n/**\n * Generate CSS from a styles map, emitting only guarded entries. Values may\n * reference theme tokens via `var(--wg-*)`. Never throws.\n */\nexport function widgetStylesToCss(styles: WidgetStyles): string {\n return guardedStylesToCss(styles, undefined);\n}\n\n/**\n * The one generator behind widget and theme styles. A `scope` (always a\n * caller constant, never style data) prefixes every selector part with\n * `:where(<scope>) `, so the rule applies inside the scope at the weight\n * its author wrote.\n */\nexport function guardedStylesToCss(styles: WidgetStyles, scope: string | undefined): string {\n const rules: string[] = [];\n for (const [selector, declarations] of Object.entries(styles)) {\n if (!isSafeSelector(selector)) continue;\n if (typeof declarations !== \"object\" || declarations === null) continue;\n const lines: string[] = [];\n for (const [property, value] of Object.entries(declarations)) {\n if (!PROPERTY_NAME.test(property)) continue;\n if (typeof value !== \"string\" || !isSafeValue(value)) continue;\n lines.push(` ${property}: ${value};`);\n }\n if (lines.length > 0) {\n const scoped = scope === undefined\n ? selector\n : splitTopLevel(selector, (char) => char === \",\").map((part) => scopePart(part, scope)).join(\", \");\n rules.push(`${scoped} {\\n${lines.join(\"\\n\")}\\n}`);\n }\n }\n return rules.join(\"\\n\");\n}\n", "/**\n * The identifier rule for widget kinds and theme, schema and principal\n * names: one charset every store adapter accepts identically (the file\n * store uses it as a path guard; Cosmos embeds it in document ids). Kept\n * here so the store, the designers and the guides read the same rule.\n */\nexport const SAFE_IDENTIFIER = /^[a-zA-Z0-9._-]+$/;\n", "/**\n * The style rules as text, built from the constants the guards enforce.\n * Both authoring guides, the tool descriptions and the designers' messages\n * read them from here, so none can drift from the guards or from another.\n */\nimport { PROPERTY_NAME, UNSAFE, UNSAFE_FUNCTIONS } from \"./styles.js\";\n\nexport const STYLE_RULES = {\n selectors:\n \"Every selector part (split on top-level commas) must be held to .wg- classes: \" +\n \"one of its compounds names a .wg- class itself, or through :is() or :where() \" +\n \"whose every argument does. A .wg- class only inside :not(), :has(), an \" +\n \"attribute test or a string does not count, and no part may open with a \" +\n \"combinator \u2014 e.g. '.wg-card .wg-xcard-head', '.wg-row:has(.wg-ok, .wg-warn)' \" +\n \"or ':is(.wg-btn, .wg-link):hover'.\",\n banned:\n `Selectors, properties, or values matching ${UNSAFE.source}, holding a ` +\n \"comment marker (/* or */) or an unclosed bracket or string, or calling \" +\n `${UNSAFE_FUNCTIONS.join(\", \")} are dropped.`,\n // An ALLOWLIST, not merely \"no banned characters\": a property with a\n // digit or underscore is dropped even though it contains nothing banned.\n propertyNames:\n `Property names must match ${PROPERTY_NAME.source} (letters and ` +\n \"hyphens, optionally leading '-'); anything else is dropped.\"\n} as const;\n", "/**\n * The bind format engine: a CLOSED, data-only presentation vocabulary.\n *\n * Formatting is render-time, never fold-time \u2014 the payload keeps the typed\n * value while the render gets its unit, so an initial render, a preview and\n * an action's re-render all present the same data the same way and a second\n * fold never formats an already-formatted string.\n *\n * Determinism is a hard requirement: server render, designer preview and\n * in-frame re-render must agree byte for byte, or the patcher would see\n * phantom text changes. Hence a fixed default locale, UTC throughout (an\n * unzoned ISO value is read as UTC \u2014 ECMAScript would read it as LOCAL\n * time), and ordinary spaces in numeric output (ICU builds differ in the\n * no-break spaces they emit).\n *\n * Total by construction: a value the format cannot parse renders as its\n * plain `formatValue` text. A format never hides data and never throws.\n */\nimport { isPlainObject } from \"../../shared/plain-object.js\";\nimport { formatValue } from \"./format.js\";\n\n/**\n * Format kinds. Closed \u2014 an unknown `type` fails validation. The first\n * three present one value; the text formats present a list or a text.\n */\nexport const FORMAT_TYPES = [\"number\", \"currency\", \"date\", \"count\", \"join\", \"truncate\", \"pluralize\"] as const;\n\nexport type FormatType = (typeof FORMAT_TYPES)[number];\n\n/** The formats that read a list: count and join, and pluralize, which also reads a number. */\nexport const LIST_FORMAT_TYPES = [\"count\", \"join\", \"pluralize\"] as const;\n\nexport const isFormatType = (value: unknown): value is FormatType =>\n FORMAT_TYPES.some((type) => type === value);\n\n/** Bounds on `decimals` (inclusive), shared by the validator and the guide. */\nexport const FORMAT_DECIMALS_MIN = 0;\nexport const FORMAT_DECIMALS_MAX = 8;\n\n/** How a currency names itself. `narrowSymbol` is the default: `$3,207`. */\nexport const CURRENCY_DISPLAYS = [\"narrowSymbol\", \"symbol\", \"code\"] as const;\n\nexport type CurrencyDisplay = (typeof CURRENCY_DISPLAYS)[number];\n\nexport const isCurrencyDisplay = (value: unknown): value is CurrencyDisplay =>\n CURRENCY_DISPLAYS.some((display) => display === value);\n\n/** ISO-4217: three uppercase letters. */\nexport const CURRENCY_CODE = /^[A-Z]{3}$/;\n\n/**\n * The date pattern's tokens, longest first \u2014 the tokenizer scans in this\n * order so `mm` cannot eat the tail of `MM`.\n */\nexport const DATE_TOKENS = [\"yyyy\", \"MM\", \"dd\", \"HH\", \"mm\", \"ss\"] as const;\n\n/** Characters a pattern may carry outside its tokens. */\nexport const DATE_PATTERN_SEPARATORS = \" -/:.,T\";\n\n/** Bound on a date pattern's length \u2014 a pattern is a format, not a document. */\nexport const DATE_PATTERN_MAX = 40;\n\n/** Every character a date pattern may contain (tokens + separators). */\nexport const DATE_PATTERN_ALLOWED = new RegExp(\n `^[${DATE_PATTERN_SEPARATORS.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")}yMdHms]*$`\n);\n\n/**\n * Epoch numbers below this are SECONDS, above it MILLISECONDS \u2014 the two\n * shapes APIs emit. 1e11 s is the year 5138, 1e11 ms is 1973, so no real\n * timestamp is ambiguous under the split.\n */\nexport const EPOCH_SECONDS_BELOW = 1e11;\n\n/**\n * A locale is an author literal, shape-bounded here; the validator also asks\n * the runtime whether it knows the tag, so a typo cannot reach a render.\n */\nexport const LOCALE_TAG = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\n/** The default locale \u2014 fixed so every surface formats identically. */\nexport const DEFAULT_FORMAT_LOCALE = \"en-US\";\n\n/** Bound on a `join` separator or last separator, in characters. */\nexport const JOIN_SEPARATOR_MAX = 16;\n\n/** The separator a `join` uses when the author gives none. */\nexport const JOIN_DEFAULT_SEPARATOR = \", \";\n\n/** Bounds on a `truncate` length (inclusive), in code points. */\nexport const TRUNCATE_LENGTH_MIN = 1;\nexport const TRUNCATE_LENGTH_MAX = 1000;\n\n/** Bound on a `truncate` ellipsis, in characters. */\nexport const TRUNCATE_ELLIPSIS_MAX = 8;\n\n/** The ellipsis a `truncate` appends when the author gives none. */\nexport const TRUNCATE_DEFAULT_ELLIPSIS = \"\u2026\";\n\n/** The CLDR plural categories a `pluralize` form may be keyed by; `other` is required. */\nexport const PLURAL_CATEGORIES = [\"zero\", \"one\", \"two\", \"few\", \"many\", \"other\"] as const;\n\nexport type PluralCategory = (typeof PLURAL_CATEGORIES)[number];\n\nexport const isPluralCategory = (value: unknown): value is PluralCategory =>\n PLURAL_CATEGORIES.some((category) => category === value);\n\n/** Bound on one `pluralize` form, in characters. */\nexport const PLURAL_FORM_MAX = 80;\n\n/** Replaced in a `pluralize` form by the grouped number. */\nexport const PLURAL_COUNT_PLACEHOLDER = \"{count}\";\n\n/**\n * A `join` field: dot segments read in the item's own scope, none of them\n * empty or `$`-prefixed \u2014 no scope tokens, since an item has no `each`\n * chain of its own.\n */\nexport const isPlainDottedPath = (value: unknown): value is string =>\n typeof value === \"string\" &&\n value.split(\".\").every((segment) => segment !== \"\" && !segment.startsWith(\"$\"));\n\nexport interface NumberFormatSpec {\n type: \"number\";\n decimals?: number;\n locale?: string;\n}\n\nexport interface CurrencyFormatSpec {\n type: \"currency\";\n currency: string;\n decimals?: number;\n currencyDisplay?: CurrencyDisplay;\n locale?: string;\n}\n\nexport interface DateFormatSpec {\n type: \"date\";\n pattern: string;\n}\n\nexport interface CountFormatSpec {\n type: \"count\";\n locale?: string;\n}\n\nexport interface JoinFormatSpec {\n type: \"join\";\n separator?: string;\n last?: string;\n field?: string;\n}\n\nexport interface TruncateFormatSpec {\n type: \"truncate\";\n length: number;\n ellipsis?: string;\n}\n\nexport interface PluralizeFormatSpec {\n type: \"pluralize\";\n forms: Partial<Record<PluralCategory, string>> & { other: string };\n locale?: string;\n}\n\n/** A bind's presentation transform. */\nexport type FormatSpec =\n | NumberFormatSpec\n | CurrencyFormatSpec\n | DateFormatSpec\n | CountFormatSpec\n | JoinFormatSpec\n | TruncateFormatSpec\n | PluralizeFormatSpec;\n\n/** A tokenized pattern: literal runs and the tokens between them. */\nexport type DatePatternPart = { token: (typeof DATE_TOKENS)[number] } | { literal: string };\n\n/**\n * Split a pattern into tokens and literals. Every letter must belong to a\n * token \u2014 a stray `d` or `yy` would render as itself for every value, a\n * constant that hides the data \u2014 so a pattern with leftover letters or no\n * token at all tokenizes to `undefined`.\n */\nexport function tokenizeDatePattern(pattern: string): DatePatternPart[] | undefined {\n const parts: DatePatternPart[] = [];\n let literal = \"\";\n let tokens = 0;\n let i = 0;\n outer: while (i < pattern.length) {\n for (const token of DATE_TOKENS) {\n if (pattern.startsWith(token, i)) {\n if (literal !== \"\") parts.push({ literal });\n literal = \"\";\n parts.push({ token });\n tokens += 1;\n i += token.length;\n continue outer;\n }\n }\n const char = pattern[i] as string;\n if (/[A-Za-z]/.test(char)) return undefined;\n literal += char;\n i += 1;\n }\n if (literal !== \"\") parts.push({ literal });\n return tokens === 0 ? undefined : parts;\n}\n\n/** Whether the runtime knows a locale tag (a malformed tag throws \u2192 false). */\nexport function isKnownLocale(tag: string): boolean {\n try {\n return Intl.NumberFormat.supportedLocalesOf([tag]).length > 0;\n } catch {\n return false;\n }\n}\n\n/**\n * A finite number from a number or a numeric STRING \u2014 the shape every JSON\n * API that fears float precision returns.\n */\nfunction toFiniteNumber(value: unknown): number | undefined {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\n/**\n * Epoch milliseconds from an ISO-8601 string or an epoch number (seconds\n * below {@link EPOCH_SECONDS_BELOW}, milliseconds above). An unzoned value\n * is read as UTC; fractional seconds beyond three digits are truncated,\n * since `Date.parse` is not required to accept them.\n */\nfunction toEpochMillis(value: unknown): number | undefined {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) return undefined;\n return Math.abs(value) < EPOCH_SECONDS_BELOW ? value * 1000 : value;\n }\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const iso =\n /^(\\d{4}-\\d{2}-\\d{2})(?:[T ](\\d{2}:\\d{2}(?::\\d{2})?)(?:\\.(\\d+))?(Z|[+-]\\d{2}:?\\d{2})?)?$/.exec(\n trimmed\n );\n if (iso === null) return undefined;\n const [, date, time, fraction, zone] = iso;\n const millis = fraction === undefined ? \"\" : `.${fraction.slice(0, 3)}`;\n const clock = time === undefined ? \"00:00:00\" : time.length === 5 ? `${time}:00` : time;\n const parsed = Date.parse(`${date}T${clock}${millis}${zone ?? \"Z\"}`);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nconst pad = (value: number, width: number): string => String(value).padStart(width, \"0\");\n\n/** Substitute the tokens from the UTC fields of `millis`. */\nfunction formatDate(millis: number, parts: readonly DatePatternPart[]): string {\n const at = new Date(millis);\n const field = (token: (typeof DATE_TOKENS)[number]): string => {\n switch (token) {\n case \"yyyy\": return pad(at.getUTCFullYear(), 4);\n case \"MM\": return pad(at.getUTCMonth() + 1, 2);\n case \"dd\": return pad(at.getUTCDate(), 2);\n case \"HH\": return pad(at.getUTCHours(), 2);\n case \"mm\": return pad(at.getUTCMinutes(), 2);\n case \"ss\": return pad(at.getUTCSeconds(), 2);\n }\n };\n return parts.map((part) => (\"token\" in part ? field(part.token) : part.literal)).join(\"\");\n}\n\n/** ICU emits U+00A0 / U+202F / U+2009 where locales space digits and symbols. */\nconst UNICODE_SPACES = /[\\u00A0\\u202F\\u2009]/g;\n\n/** Every parse failure or malformed spec formats as the plain value. */\nconst plain = (value: unknown): string => formatValue(value);\n\ntype Formatter = (value: unknown) => string;\n\n/**\n * Narrow an author spec to the engine's typed shape, defaults applied. The\n * validator refuses everything this returns `undefined` for; it stays here\n * so a spec reaching the engine unvalidated degrades to plain text.\n */\nexport function parseFormatSpec(spec: unknown): FormatSpec | undefined {\n if (!isPlainObject(spec) || !isFormatType(spec.type)) return undefined;\n if (spec.type === \"date\") {\n return typeof spec.pattern === \"string\" ? { type: \"date\", pattern: spec.pattern } : undefined;\n }\n const locale =\n typeof spec.locale === \"string\" && LOCALE_TAG.test(spec.locale) ? spec.locale : undefined;\n const withLocale = locale === undefined ? {} : { locale };\n if (spec.type === \"count\") return { type: \"count\", ...withLocale };\n if (spec.type === \"join\") {\n const bounded = (value: unknown): value is string =>\n typeof value === \"string\" && value.length <= JOIN_SEPARATOR_MAX;\n return {\n type: \"join\",\n ...(bounded(spec.separator) ? { separator: spec.separator } : {}),\n ...(bounded(spec.last) ? { last: spec.last } : {}),\n ...(isPlainDottedPath(spec.field) ? { field: spec.field } : {})\n };\n }\n if (spec.type === \"truncate\") {\n if (\n typeof spec.length !== \"number\" ||\n !Number.isInteger(spec.length) ||\n spec.length < TRUNCATE_LENGTH_MIN ||\n spec.length > TRUNCATE_LENGTH_MAX\n ) {\n return undefined;\n }\n const ellipsis =\n typeof spec.ellipsis === \"string\" && spec.ellipsis.length <= TRUNCATE_ELLIPSIS_MAX\n ? spec.ellipsis\n : undefined;\n return { type: \"truncate\", length: spec.length, ...(ellipsis === undefined ? {} : { ellipsis }) };\n }\n if (spec.type === \"pluralize\") {\n if (!isPlainObject(spec.forms)) return undefined;\n const forms: Partial<Record<PluralCategory, string>> = {};\n for (const category of PLURAL_CATEGORIES) {\n const form = spec.forms[category];\n if (typeof form === \"string\" && form.length <= PLURAL_FORM_MAX) forms[category] = form;\n }\n const other = forms.other;\n if (other === undefined) return undefined;\n return { type: \"pluralize\", forms: { ...forms, other }, ...withLocale };\n }\n const decimals =\n typeof spec.decimals === \"number\" &&\n Number.isInteger(spec.decimals) &&\n spec.decimals >= FORMAT_DECIMALS_MIN &&\n spec.decimals <= FORMAT_DECIMALS_MAX\n ? spec.decimals\n : undefined;\n const common = {\n ...(decimals === undefined ? {} : { decimals }),\n ...(locale === undefined ? {} : { locale })\n };\n if (spec.type === \"number\") return { type: \"number\", ...common };\n if (typeof spec.currency !== \"string\" || !CURRENCY_CODE.test(spec.currency)) return undefined;\n return {\n type: \"currency\",\n currency: spec.currency,\n ...(isCurrencyDisplay(spec.currencyDisplay) ? { currencyDisplay: spec.currencyDisplay } : {}),\n ...common\n };\n}\n\n/**\n * Build the formatter for one spec: the `Intl.NumberFormat` instance and the\n * tokenized pattern are created here, once, not per value \u2014 a table over a\n * list formats thousands of cells through one instance.\n */\nfunction buildFormatter(spec: FormatSpec): Formatter {\n if (spec.type === \"join\") return joinFormatter(spec);\n if (spec.type === \"truncate\") return truncateFormatter(spec);\n if (spec.type === \"count\" || spec.type === \"pluralize\") {\n const grouped = groupedNumber(spec.locale ?? DEFAULT_FORMAT_LOCALE);\n if (grouped === undefined) return plain;\n if (spec.type === \"count\") {\n return (value) => (Array.isArray(value) ? grouped(value.length) : plain(value));\n }\n return pluralizeFormatter(spec, grouped);\n }\n if (spec.type === \"date\") {\n const parts = tokenizeDatePattern(spec.pattern);\n if (parts === undefined) return plain;\n return (value) => {\n const millis = toEpochMillis(value);\n return millis === undefined ? plain(value) : formatDate(millis, parts);\n };\n }\n const locale = spec.locale ?? DEFAULT_FORMAT_LOCALE;\n const digits: Intl.NumberFormatOptions =\n spec.decimals === undefined\n ? {}\n : { minimumFractionDigits: spec.decimals, maximumFractionDigits: spec.decimals };\n let intl: Intl.NumberFormat;\n try {\n intl =\n spec.type === \"number\"\n ? new Intl.NumberFormat(locale, digits)\n : new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: spec.currency,\n currencyDisplay: spec.currencyDisplay ?? \"narrowSymbol\",\n ...digits\n });\n } catch {\n // An engine that rejects an author literal must not break the render.\n return plain;\n }\n return (value) => {\n const numeric = toFiniteNumber(value);\n return numeric === undefined ? plain(value) : intl.format(numeric).replace(UNICODE_SPACES, \" \");\n };\n}\n\n/** A number grouped in `locale` with ordinary spaces, or `undefined` when the engine refuses the locale. */\nfunction groupedNumber(locale: string): ((value: number) => string) | undefined {\n try {\n const intl = new Intl.NumberFormat(locale);\n return (value) => intl.format(value).replace(UNICODE_SPACES, \" \");\n } catch {\n return undefined;\n }\n}\n\n/** The plain text at `field`'s segments inside `item`, or of the item itself. */\nfunction itemText(item: unknown, segments: readonly string[] | undefined): string {\n let current = item;\n if (segments !== undefined && isPlainObject(item)) {\n for (const segment of segments) {\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = current[segment];\n } else {\n current = undefined;\n }\n }\n }\n // An absent or null item is no item: sparse data never reads \", ,\".\n return current === null || current === undefined ? \"\" : formatValue(current);\n}\n\nfunction joinFormatter(spec: JoinFormatSpec): Formatter {\n const separator = spec.separator ?? JOIN_DEFAULT_SEPARATOR;\n const segments = spec.field === undefined ? undefined : spec.field.split(\".\");\n return (value) => {\n if (!Array.isArray(value)) return plain(value);\n const texts = value.map((item) => itemText(item, segments)).filter((text) => text !== \"\");\n if (spec.last === undefined || texts.length < 2) return texts.join(separator);\n return texts.slice(0, -1).join(separator) + spec.last + (texts[texts.length - 1] as string);\n };\n}\n\nfunction truncateFormatter(spec: TruncateFormatSpec): Formatter {\n const ellipsis = spec.ellipsis ?? TRUNCATE_DEFAULT_ELLIPSIS;\n return (value) => {\n const text = formatValue(value);\n // Code points, so a surrogate pair is never split.\n const points = Array.from(text);\n if (points.length <= spec.length) return text;\n return points.slice(0, spec.length).join(\"\").trimEnd() + ellipsis;\n };\n}\n\nfunction pluralizeFormatter(spec: PluralizeFormatSpec, grouped: (value: number) => string): Formatter {\n let rules: Intl.PluralRules;\n try {\n rules = new Intl.PluralRules(spec.locale ?? DEFAULT_FORMAT_LOCALE);\n } catch {\n return plain;\n }\n return (value) => {\n const count = Array.isArray(value) ? value.length : toFiniteNumber(value);\n if (count === undefined) return plain(value);\n // An author's `zero` form reads \"No items\" in every locale; the locale's\n // own rules choose otherwise.\n const category = count === 0 && spec.forms.zero !== undefined ? \"zero\" : rules.select(count);\n const form = (isPluralCategory(category) ? spec.forms[category] : undefined) ?? spec.forms.other;\n return form.split(PLURAL_COUNT_PLACEHOLDER).join(grouped(count));\n };\n}\n\n/**\n * Formatters keyed by the spec OBJECT, which lives as long as the compiled\n * template that carries it. Holds author literals and locale/currency configuration only \u2014\n * never tenant data \u2014 so the per-request no-cache rule is untouched.\n */\nconst compiled = new WeakMap<object, Formatter>();\n\n/** The formatter for `spec`, built once per spec object. */\nexport function compileFormat(spec: unknown): Formatter {\n if (!isPlainObject(spec)) return plain;\n const cached = compiled.get(spec);\n if (cached !== undefined) return cached;\n const parsed = parseFormatSpec(spec);\n const formatter = parsed === undefined ? plain : buildFormatter(parsed);\n compiled.set(spec, formatter);\n return formatter;\n}\n\n/** Render `value` through `spec`, or as plain text when it cannot be parsed. */\nexport function formatBoundValue(value: unknown, spec: unknown): string {\n return compileFormat(spec)(value);\n}\n", "/**\n * Theme token registry. Tokens are the only theming surface: the base\n * stylesheet reads them via `var(--wg-<token>, <default>)` and themes are\n * plain maps of bare token names to values. The defaults table is the\n * single source of truth for the light look.\n */\nimport { UNSAFE_FUNCTIONS } from \"../catalog/styles.js\";\nimport { isBalanced } from \"../shared/css-scan.js\";\n\n/**\n * The token table: every token's default, its VALUE TYPE, and what it is\n * for. Type metadata is not decoration \u2014 tooling reads it (the theme\n * designer picks a color picker vs a text field from `type`, never by\n * guessing at the default's shape) and `list_theme_tokens` tells agents\n * what kind of value each token expects. `use` doubles as the\n * documentation that earns a token its place when the base stylesheet\n * cannot consume it.\n */\nexport type TokenType =\n | \"color\"\n | \"dimension\"\n | \"number\"\n | \"font-family\"\n | \"font-weight\"\n | \"shadow\";\n\nexport interface TokenSpec {\n default: string;\n type: TokenType;\n use: string;\n /**\n * Token this one inherits from when a theme leaves it unset. Declared\n * here rather than special-cased in the stylesheet because a literal\n * default at `:root` would sever that inheritance: a `var()` fallback\n * applies only when the property is UNSET, so defining\n * `--wg-surface: #ffffff` makes `var(--wg-surface, var(--wg-bg, \u2026))`\n * unreachable. The defaults block emits a chain for these instead.\n */\n fallback?: string;\n}\n\nexport const TOKEN_SPECS = {\n bg: { default: \"#ffffff\", type: \"color\", use: \"Page background behind widgets.\" },\n surface: {\n default: \"#ffffff\",\n type: \"color\",\n fallback: \"bg\",\n use: \"Widget panel background (cards, tables); falls back to bg when unset.\"\n },\n fg: { default: \"#1f2430\", type: \"color\", use: \"Primary text.\" },\n muted: { default: \"#6b7280\", type: \"color\", use: \"Secondary text: labels, captions, keys.\" },\n accent: { default: \"#2563eb\", type: \"color\", use: \"Emphasis: titles, links, filled badges.\" },\n \"accent-fg\": {\n default: \"#ffffff\",\n type: \"color\",\n use: \"Text drawn on an accent fill (filled badges and buttons).\"\n },\n border: { default: \"#e2e8f0\", type: \"color\", use: \"Hairlines: panel edges, row rules.\" },\n \"border-width\": { default: \"1px\", type: \"dimension\", use: \"Width of those hairlines.\" },\n radius: { default: \"6px\", type: \"dimension\", use: \"Default corner rounding.\" },\n \"radius-sm\": { default: \"3px\", type: \"dimension\", use: \"Tight rounding: pills, chips, inline marks.\" },\n \"radius-lg\": { default: \"12px\", type: \"dimension\", use: \"Generous rounding: hero media, large panels.\" },\n spacing: { default: \"8px\", type: \"dimension\", use: \"Base spacing step.\" },\n \"spacing-sm\": { default: \"4px\", type: \"dimension\", use: \"Half step: inline gaps inside a row.\" },\n \"spacing-lg\": { default: \"16px\", type: \"dimension\", use: \"Double step: section separation.\" },\n \"font-family\": {\n default: \"system-ui, -apple-system, 'Segoe UI', sans-serif\",\n type: \"font-family\",\n use: \"Body text family.\"\n },\n \"font-mono\": {\n default: \"ui-monospace, SFMono-Regular, Menlo, monospace\",\n type: \"font-family\",\n use: \"Monospace family for the wg-code block utility.\"\n },\n \"font-size\": { default: \"14px\", type: \"dimension\", use: \"Body text size.\" },\n \"font-size-sm\": { default: \"12px\", type: \"dimension\", use: \"Small text: captions, stats, pills.\" },\n \"font-size-lg\": { default: \"18px\", type: \"dimension\", use: \"Large text: widget titles.\" },\n \"font-weight-bold\": {\n default: \"600\",\n type: \"font-weight\",\n use: \"Weight for titles and emphasized labels.\"\n },\n \"line-height\": { default: \"1.45\", type: \"number\", use: \"Text density.\" },\n shadow: {\n default: \"0 1px 3px rgba(0, 0, 0, 0.12)\",\n type: \"shadow\",\n use: \"Panel elevation.\"\n },\n danger: { default: \"#b91c1c\", type: \"color\", use: \"Error status: fills and text (see .wg-status-danger).\" },\n \"danger-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a danger fill.\" },\n success: { default: \"#15803d\", type: \"color\", use: \"Success status (see .wg-status-success).\" },\n \"success-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a success fill.\" },\n warning: { default: \"#b45309\", type: \"color\", use: \"Warning status (see .wg-status-warning).\" },\n \"warning-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on a warning fill.\" },\n info: { default: \"#0369a1\", type: \"color\", use: \"Informational status (see .wg-status-info).\" },\n \"info-fg\": { default: \"#ffffff\", type: \"color\", use: \"Text on an info fill.\" },\n \"avatar-size\": { default: \"32px\", type: \"dimension\", use: \"Box of .wg-img-avatar images.\" },\n \"thumb-size\": { default: \"48px\", type: \"dimension\", use: \"Box of .wg-img-thumb images.\" }\n} as const satisfies Record<string, TokenSpec>;\n\n/** Default value per token \u2014 derived, so the table stays the one source. */\nexport const TOKEN_DEFAULTS = Object.fromEntries(\n Object.entries(TOKEN_SPECS).map(([name, spec]) => [name, spec.default])\n) as { [K in keyof typeof TOKEN_SPECS]: (typeof TOKEN_SPECS)[K][\"default\"] };\n\nexport type ThemeToken = keyof typeof TOKEN_SPECS;\n\n/** All theme token names, in defaults-table order. */\nexport const THEME_TOKENS: readonly ThemeToken[] = Object.keys(\n TOKEN_SPECS\n) as ThemeToken[];\n\n/**\n * A theme: bare token names to CSS values. Bare keys make unknown-token\n * validation trivial and structurally prevent setting arbitrary custom\n * properties \u2014 the `--wg-` prefix is always applied by this module.\n */\nexport type WidgetTheme = Partial<Record<ThemeToken, string>>;\n\n/**\n * A theme plus author-defined `x-*` variables (emitted as `--wg-x-<name>`).\n * Kept as a separate type on purpose: `WidgetTheme` has only optional\n * properties, which is what makes TypeScript reject `{ sneaky: \"red\" }` via\n * weak-type detection \u2014 an index signature here would silently disable that\n * protection for every consumer. Functions accept this wider input; the\n * runtime validator is the authority on which keys are legal.\n */\nexport type WidgetThemeInput = WidgetTheme &\n Partial<Record<`x-${string}`, string>>;\n\nexport type ThemeErrorCode =\n | \"INVALID_THEME\"\n | \"UNKNOWN_TOKEN\"\n | \"INVALID_TOKEN_VALUE\";\n\nexport interface ThemeError {\n code: ThemeErrorCode;\n message: string;\n /** Offending token name, when applicable. */\n token?: string;\n}\n\n/**\n * Characters a token value may not hold: declaration and HTML escapes, and\n * the backslash, whose escapes can spell any banned call (`u\\72 l(` is\n * `url(`). Exported so the guides derive the rule.\n */\nexport const TOKEN_VALUE_UNSAFE = /[;{}<>\\\\]/;\n\n/**\n * Value guard shared by validation (strict) and application (lenient\n * defense in depth). Rejects exfiltration and execution vectors \u2014 not\n * invalid CSS: declaration/HTML escapes, backslash escapes, comment markers\n * and unclosed brackets or strings (each swallows the rest of the sheet),\n * `url()`, `image-set()` and `src()`\n * (resource fetching), and `expression()` (legacy script execution in old\n * embedded webviews).\n */\nexport function isSafeTokenValue(value: string): boolean {\n return (\n !TOKEN_VALUE_UNSAFE.test(value) &&\n // An unclosed bracket or string runs on through the rest of the sheet.\n isBalanced(value) &&\n // A comment opener swallows every declaration after it in the sheet.\n !/\\/\\*|\\*\\//.test(value) &&\n // The style guard's calls: url(), expression(), and the URL carriers\n // that do not spell url(.\n !UNSAFE_FUNCTIONS.some((call) => new RegExp(`${call.slice(0, -1)}\\\\s*\\\\(`, \"i\").test(value))\n );\n}\n\n/** The token-value rule as text, built from the constants that enforce it. */\nexport const TOKEN_VALUE_RULE =\n `Token values are plain CSS values. Rejected: anything matching ${TOKEN_VALUE_UNSAFE.source}, ` +\n \"a comment marker (/* or */), an unclosed bracket or string, and calls to \" +\n `${UNSAFE_FUNCTIONS.join(\", \")} (case-insensitive, whitespace-tolerant). ` +\n \"Keep values to colors, lengths, and font stacks.\";\n", "import type { ThemeToken } from \"./tokens.js\";\nimport { THEME_TOKENS, TOKEN_DEFAULTS } from \"./tokens.js\";\n\n/** `var(--wg-<token>, <light default>)` \u2014 every themeable knob goes through this. */\nfunction v(token: ThemeToken): string {\n return `var(--wg-${token}, ${TOKEN_DEFAULTS[token]})`;\n}\n\n/**\n * Every registry token DEFINED at :root with its default, so custom\n * widget styles may reference bare `var(--wg-<token>)` and always\n * resolve. The built-in rules below carry their own fallbacks and never\n * needed this; custom authors write plain references (per the authoring\n * guide), and before this block an applied theme was the only thing that\n * defined tokens \u2014 every token it didn't set silently collapsed the\n * author's declaration (observed live: a valid widget rendered jammed\n * because `--wg-spacing-lg` was \"not defined\"). Themes override these\n * (later style elements and element-level applyTheme both win).\n *\n * Literals only \u2014 a chain here would NOT work: `--wg-surface:\n * var(--wg-bg, \u2026)` substitutes against `:root`'s own `--wg-bg` at\n * computed-value time and inherits that resolved value, so a descendant\n * overriding `--wg-bg` never reaches it. Tokens declaring a `fallback`\n * are resolved where the theme is applied instead (see `withFallbacks`\n * in apply.ts); this block only guarantees a bare `var(--wg-<token>)`\n * always resolves to something.\n */\nconst tokenDefaultsBlock = `:root {\n${THEME_TOKENS.map((token) => ` --wg-${token}: ${TOKEN_DEFAULTS[token]};`).join(\"\\n\")}\n}`;\n\n/**\n * Predefined styles for the built-in `wg-*` classes. Generated from the\n * token defaults table, so the light theme lives in exactly one place and\n * every visual knob is overridable by a theme.\n */\n// One em-box for both icon forms, so an emoji and an image align on the\n// same slot by construction rather than by two literals kept equal.\nconst ICON_BOX = \"1.25em\";\n\nexport const baseStylesheet = `\n${tokenDefaultsBlock}\n.wg-card, .wg-table, .wg-tree, .wg-code, .wg-template {\n font-family: ${v(\"font-family\")};\n font-size: ${v(\"font-size\")};\n line-height: ${v(\"line-height\")};\n color: ${v(\"fg\")};\n}\n.wg-card {\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius-lg\")};\n box-shadow: ${v(\"shadow\")};\n padding: ${v(\"spacing-lg\")};\n}\n.wg-card-title {\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-card-subtitle {\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-card-fields {\n margin: 0;\n}\n.wg-card-field {\n display: flex;\n gap: ${v(\"spacing\")};\n padding: ${v(\"spacing-sm\")} 0;\n}\n.wg-card-field-key {\n color: ${v(\"muted\")};\n}\n.wg-card-field-value {\n margin: 0;\n}\n.wg-table {\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius\")};\n border-collapse: collapse;\n}\n.wg-table-header {\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n font-weight: ${v(\"font-weight-bold\")};\n text-align: left;\n border-bottom: calc(${v(\"border-width\")} * 2) solid ${v(\"border\")};\n padding: ${v(\"spacing\")};\n}\n.wg-table-cell {\n border-bottom: ${v(\"border-width\")} solid ${v(\"border\")};\n padding: ${v(\"spacing\")};\n}\n.wg-tree {\n list-style: none;\n margin: 0;\n padding-left: 0;\n}\n.wg-tree-children {\n list-style: none;\n padding-left: ${v(\"spacing-lg\")};\n border-left: ${v(\"border-width\")} solid ${v(\"border\")};\n}\n.wg-tree-node {\n padding: ${v(\"spacing-sm\")} 0;\n}\n.wg-tree-label {\n display: flex;\n align-items: center;\n gap: ${v(\"spacing-sm\")};\n}\n.wg-tree-branch > .wg-tree-label {\n cursor: pointer;\n list-style: none;\n}\n.wg-tree-branch > .wg-tree-label::-webkit-details-marker {\n display: none;\n}\n.wg-tree-branch > .wg-tree-label::before {\n content: \"\";\n flex: 0 0 auto;\n width: 0;\n height: 0;\n border-left: 0.4em solid ${v(\"muted\")};\n border-top: 0.3em solid transparent;\n border-bottom: 0.3em solid transparent;\n}\n.wg-tree-branch[open] > .wg-tree-label::before {\n transform: rotate(90deg);\n}\n.wg-tree-icon {\n flex: 0 0 auto;\n width: ${ICON_BOX};\n text-align: center;\n}\n.wg-img-icon {\n flex: 0 0 auto;\n width: ${ICON_BOX};\n height: ${ICON_BOX};\n border-radius: ${v(\"radius-sm\")};\n}\n/* Monospace block utility. No built-in emits it: it is a styling surface\n template authors opt into, and what keeps the font-mono token consumed. */\n.wg-code {\n font-family: ${v(\"font-mono\")};\n background: var(--wg-surface, ${v(\"bg\")});\n border: ${v(\"border-width\")} solid ${v(\"border\")};\n border-radius: ${v(\"radius\")};\n padding: ${v(\"spacing\")};\n overflow: auto;\n}\n.wg-status {\n display: inline-block;\n padding: 0 ${v(\"spacing-sm\")};\n border-radius: ${v(\"radius-sm\")};\n font-size: ${v(\"font-size-sm\")};\n font-weight: ${v(\"font-weight-bold\")};\n}\n.wg-status-danger { background: ${v(\"danger\")}; color: ${v(\"danger-fg\")}; }\n.wg-status-success { background: ${v(\"success\")}; color: ${v(\"success-fg\")}; }\n.wg-status-warning { background: ${v(\"warning\")}; color: ${v(\"warning-fg\")}; }\n.wg-status-info { background: ${v(\"info\")}; color: ${v(\"info-fg\")}; }\n.wg-status-accent { background: ${v(\"accent\")}; color: ${v(\"accent-fg\")}; }\n.wg-img {\n object-fit: cover;\n vertical-align: middle;\n background: ${v(\"border\")};\n}\n.wg-img-avatar {\n width: ${v(\"avatar-size\")};\n height: ${v(\"avatar-size\")};\n border-radius: 50%;\n}\n.wg-img-thumb {\n width: ${v(\"thumb-size\")};\n height: ${v(\"thumb-size\")};\n border-radius: ${v(\"radius\")};\n}\n.wg-img-hero {\n display: block;\n width: 100%;\n max-width: 100%;\n height: auto;\n border-radius: ${v(\"radius\")};\n}\n.wg-table-caption {\n caption-side: top;\n text-align: left;\n padding-bottom: ${v(\"spacing\")};\n}\n.wg-table-title {\n display: block;\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing-sm\")};\n}\n.wg-table-subtitle {\n display: block;\n color: ${v(\"muted\")};\n font-size: ${v(\"font-size-sm\")};\n}\n.wg-tree-title {\n color: ${v(\"accent\")};\n font-size: ${v(\"font-size-lg\")};\n font-weight: ${v(\"font-weight-bold\")};\n margin-bottom: ${v(\"spacing\")};\n}\n.wg-link {\n color: ${v(\"accent\")};\n text-decoration: underline;\n}\n.wg-md p, .wg-md ul, .wg-md ol {\n margin: 0 0 ${v(\"spacing\")};\n}\n.wg-md > :last-child {\n margin-bottom: 0;\n}\n.wg-md ul, .wg-md ol {\n padding-left: 1.5em;\n}\n.wg-md code {\n font-family: ${v(\"font-mono\")};\n font-size: 0.9em;\n}\n.wg-md a {\n color: ${v(\"accent\")};\n text-decoration: underline;\n}\n.wg-group {\n display: flex;\n flex-direction: column;\n}\n.wg-group-row {\n flex-direction: row;\n flex-wrap: wrap;\n}\n.wg-group-row > * {\n flex: 1 1 240px;\n min-width: 0;\n}\n.wg-group-grid {\n display: grid;\n}\n.wg-group-grid > * {\n min-width: 0;\n}\n.wg-cols-1 { grid-template-columns: 1fr; }\n.wg-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }\n.wg-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }\n.wg-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }\n.wg-gap-none { gap: 0; }\n.wg-gap-sm { gap: ${v(\"spacing-sm\")}; }\n.wg-gap-md { gap: ${v(\"spacing\")}; }\n.wg-gap-lg { gap: ${v(\"spacing-lg\")}; }\n`.trim();\n\nconst STYLE_MARKER = \"data-widgentic\";\n\n/**\n * Append the base stylesheet to the document head as a marked `<style>`\n * element. Idempotent: repeated calls leave exactly one element.\n */\nexport function injectBaseStyles(doc: Document): void {\n if (doc.head.querySelector(`style[${STYLE_MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(STYLE_MARKER, \"base\");\n style.textContent = baseStylesheet;\n doc.head.appendChild(style);\n}\n", "import type { ThemeError, TokenSpec, WidgetTheme, WidgetThemeInput } from \"./tokens.js\";\nimport { THEME_TOKENS, TOKEN_SPECS, isSafeTokenValue } from \"./tokens.js\";\n\nexport type ValidateThemeResult =\n | { ok: true; theme: WidgetThemeInput }\n | { ok: false; error: ThemeError };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst KNOWN_TOKENS: ReadonlySet<string> = new Set(THEME_TOKENS);\n\n/**\n * Author-defined variables: `x-<name>` keys are accepted alongside registry\n * tokens and emitted as `--wg-x-<name>`. This is the sanctioned escape\n * hatch for custom widgets that need their own knobs, so the registry does\n * not have to grow for every one-off. Names are lowercase/kebab so the\n * generated custom property is always a valid CSS identifier. Exported so\n * tooling states this rule by reading it, never by restating it.\n */\nexport const CUSTOM_VARIABLE = /^x-[a-z0-9][a-z0-9-]*$/;\n\n/** Custom-variable keys carried by a theme, in declaration order. */\nfunction customKeys(theme: WidgetThemeInput): string[] {\n return Object.keys(theme).filter((key) => CUSTOM_VARIABLE.test(key));\n}\n\n/** The `--wg-*` property name a theme key maps to. */\nfunction propertyName(key: string): string {\n return `--wg-${key}`;\n}\n\n/** Validate an unknown value as a theme. Never throws. */\nexport function validateTheme(input: unknown): ValidateThemeResult {\n if (!isPlainObject(input)) {\n return {\n ok: false,\n error: { code: \"INVALID_THEME\", message: \"Theme must be a plain object.\" }\n };\n }\n for (const [token, value] of Object.entries(input)) {\n if (!KNOWN_TOKENS.has(token) && !CUSTOM_VARIABLE.test(token)) {\n return {\n ok: false,\n error: {\n code: \"UNKNOWN_TOKEN\",\n message:\n `Unknown theme token '${token}'. Use a registry token, or a ` +\n `custom variable named 'x-<lowercase-kebab>'.`,\n token\n }\n };\n }\n if (typeof value !== \"string\" || !isSafeTokenValue(value)) {\n return {\n ok: false,\n error: {\n code: \"INVALID_TOKEN_VALUE\",\n message: `Token '${token}' has an invalid or unsafe value.`,\n token\n }\n };\n }\n }\n return { ok: true, theme: input as WidgetThemeInput };\n}\n\n/**\n * Fill in tokens a theme left unset that declare a `fallback`, using the\n * fallback token's value FROM THIS THEME.\n *\n * This cannot live in the base stylesheet: a `:root` chain\n * (`--wg-surface: var(--wg-bg, \u2026)`) substitutes against `:root`'s own\n * `--wg-bg` at computed-value time and then inherits that resolved\n * value, so a descendant overriding `--wg-bg` never reaches it. Resolving\n * where the theme is applied puts both declarations on the same element,\n * which is the only place the relationship holds (observed live at v24: a\n * bg-only dark theme painted white cards).\n */\nfunction withFallbacks(theme: WidgetThemeInput): WidgetThemeInput {\n const source = theme as Record<string, unknown>;\n let filled: Record<string, unknown> | undefined;\n for (const token of THEME_TOKENS) {\n const { fallback } = TOKEN_SPECS[token] as TokenSpec;\n if (fallback === undefined) continue;\n if (typeof source[token] === \"string\") continue; // theme set it explicitly\n const inherited = source[fallback];\n if (typeof inherited !== \"string\") continue; // nothing to inherit from\n filled ??= { ...source };\n filled[token] = inherited;\n }\n return (filled ?? theme) as WidgetThemeInput;\n}\n\n/**\n * Apply a theme to a container as inline `--wg-*` custom properties\n * (scoped: descendants inherit them; siblings are unaffected). Replace\n * semantics \u2014 previously applied tokens are removed first, so\n * `applyTheme(el, {})` resets to the stylesheet defaults. Invalid entries\n * are skipped; the CSSOM path (`setProperty`) parses no stylesheet text,\n * so declaration escape is structurally impossible here.\n */\nexport function applyTheme(container: Element, input: WidgetThemeInput): void {\n const theme = withFallbacks(input);\n const style = (container as Partial<ElementCSSInlineStyle>).style;\n if (!style) return;\n // Replace semantics: clear every property this module could have set,\n // custom variables included (they are removed by name from the inline\n // style, which is the only place applyTheme writes).\n for (const token of THEME_TOKENS) {\n style.removeProperty(propertyName(token));\n }\n for (let i = style.length - 1; i >= 0; i--) {\n const property = style.item(i);\n if (property.startsWith(\"--wg-x-\")) style.removeProperty(property);\n }\n const keys: string[] = [...THEME_TOKENS, ...customKeys(theme)];\n for (const key of keys) {\n const value = (theme as Record<string, unknown>)[key];\n if (typeof value === \"string\" && isSafeTokenValue(value)) {\n style.setProperty(propertyName(key), value);\n }\n }\n}\n\n/**\n * Generate a CSS rule assigning the theme's tokens under `selector`\n * (default `:root`). Only entries passing the safety guard are emitted.\n */\nexport function themeToCss(input: WidgetThemeInput, selector = \":root\"): string {\n const theme = withFallbacks(input);\n const declarations: string[] = [];\n const keys: string[] = [...THEME_TOKENS, ...customKeys(theme)];\n for (const key of keys) {\n const value = (theme as Record<string, unknown>)[key];\n if (typeof value === \"string\" && isSafeTokenValue(value)) {\n declarations.push(` ${propertyName(key)}: ${value};`);\n }\n }\n return `${selector} {\\n${declarations.join(\"\\n\")}\\n}`;\n}\n\n/** Dark preset \u2014 ordinary theme data, a starting point for custom themes. */\nexport const darkTheme: WidgetTheme = {\n bg: \"#0f131c\",\n surface: \"#161b26\",\n fg: \"#e5e9f0\",\n muted: \"#8b93a7\",\n accent: \"#7aa2f7\",\n \"accent-fg\": \"#0f131c\",\n border: \"#2a3140\",\n shadow: \"0 1px 3px rgba(0, 0, 0, 0.6)\",\n danger: \"#f0a3a3\",\n success: \"#8fd19e\",\n warning: \"#e8b878\",\n info: \"#7cc4e8\"\n};\n", "/**\n * Named theme registry \u2014 themes as addressable entities rather than\n * anonymous token maps, mirroring the widget catalog's ergonomics. Each\n * entry is complete as registered: a host that derives one theme from\n * another merges the tokens and styles before registering. The registry\n * also knows which entry each mode falls back to when a render names no\n * theme \u2014 the built-ins until a caller's settings choose otherwise.\n */\nimport { isStyleMap } from \"../catalog/styles.js\";\nimport type { WidgetStyles } from \"../catalog/styles.js\";\nimport { darkTheme, validateTheme } from \"./apply.js\";\nimport type { WidgetThemeInput } from \"./tokens.js\";\n\n/** The host colour schemes a default theme is chosen for. */\nexport type ThemeMode = \"light\" | \"dark\";\n\n/** A registered theme: identity, optional prose, tokens and shared styles. */\nexport interface ThemeEntry {\n name: string;\n label?: string;\n description?: string;\n tokens: WidgetThemeInput;\n /** Shared `.wg-` classes for every widget the theme dresses. */\n styles?: WidgetStyles;\n}\n\n/** Entry as supplied to `register`. */\nexport type ThemeEntryInput = ThemeEntry;\n\nexport class DuplicateThemeError extends Error {\n readonly code: \"DUPLICATE_THEME\" = \"DUPLICATE_THEME\";\n readonly theme: string;\n\n constructor(name: string) {\n super(`Theme '${name}' is already registered.`);\n this.name = \"DuplicateThemeError\";\n this.theme = name;\n }\n}\n\nexport class InvalidThemeEntryError extends Error {\n readonly code: string;\n readonly theme: string;\n\n constructor(name: string, code: string, message: string) {\n super(`Theme '${name}' is invalid: ${message}`);\n this.name = \"InvalidThemeEntryError\";\n this.code = code;\n this.theme = name;\n }\n}\n\nexport interface ThemeRegistry {\n /** Register an entry. Throws on conflicts and invalid entries. */\n register(entry: ThemeEntryInput): void;\n get(name: string): ThemeEntry | undefined;\n list(): ThemeEntry[];\n names(): string[];\n /** Make a registered entry the mode's default. Throws for an unknown name. */\n setDefault(mode: ThemeMode, name: string): void;\n /** The mode's default entry: the built-in of that mode until set. */\n getDefault(mode: ThemeMode): ThemeEntry;\n /** The effective default name per mode. */\n defaults(): Record<ThemeMode, string>;\n}\n\n/** A copy of the styles, so later edits to the input never reach the registry. */\nfunction copyStyles(styles: WidgetStyles | undefined): WidgetStyles {\n const copy: WidgetStyles = {};\n for (const [selector, declarations] of Object.entries(styles ?? {})) copy[selector] = { ...declarations };\n return copy;\n}\n\n/**\n * A registry seeded with the built-ins: `light` (no tokens \u2014 the\n * stylesheet defaults) and `dark` (the shipped preset).\n */\nexport function createThemeRegistry(): ThemeRegistry {\n const entries = new Map<string, ThemeEntry>();\n const defaultNames: Record<ThemeMode, string> = { light: \"light\", dark: \"dark\" };\n\n const registry: ThemeRegistry = {\n register(entry) {\n if (\n typeof entry?.name !== \"string\" ||\n entry.name.trim() === \"\"\n ) {\n throw new InvalidThemeEntryError(\n String(entry?.name),\n \"INVALID_NAME\",\n \"name must be a non-empty string.\"\n );\n }\n if (entries.has(entry.name)) throw new DuplicateThemeError(entry.name);\n\n const validated = validateTheme(entry.tokens ?? {});\n if (!validated.ok) {\n throw new InvalidThemeEntryError(\n entry.name,\n validated.error.code,\n validated.error.message\n );\n }\n\n if (entry.styles !== undefined && !isStyleMap(entry.styles)) {\n throw new InvalidThemeEntryError(\n entry.name,\n \"INVALID_THEME\",\n \"styles must map selectors to objects of property/value strings.\"\n );\n }\n\n const styles = copyStyles(entry.styles);\n const stored: ThemeEntry = { name: entry.name, tokens: validated.theme };\n if (Object.keys(styles).length > 0) stored.styles = styles;\n if (entry.label !== undefined) stored.label = entry.label;\n if (entry.description !== undefined) stored.description = entry.description;\n entries.set(entry.name, stored);\n },\n get: (name) => entries.get(name),\n list: () => [...entries.values()],\n names: () => [...entries.keys()],\n setDefault(mode, name) {\n if (!entries.has(name)) {\n throw new InvalidThemeEntryError(name, \"UNKNOWN_THEME\", \"it is not registered, so it cannot be a default.\");\n }\n defaultNames[mode] = name;\n },\n getDefault(mode) {\n // Defaults only ever name registered entries and entries are never\n // removed, so this cannot miss; narrowed rather than asserted.\n const entry = entries.get(defaultNames[mode]);\n if (entry === undefined) throw new Error(`No ${mode} default theme is registered.`);\n return entry;\n },\n defaults: () => ({ ...defaultNames })\n };\n\n registry.register({\n name: \"light\",\n label: \"Light\",\n description: \"The built-in defaults \u2014 no tokens set.\",\n tokens: {}\n });\n registry.register({\n name: \"dark\",\n label: \"Dark\",\n description: \"Shipped dark preset with a lifted surface.\",\n tokens: darkTheme\n });\n\n return registry;\n}\n", "/**\n * Theme styles: the shared `.wg-` classes a theme defines for every widget\n * it dresses. Same shape and guards as a widget descriptor's styles \u2014 one\n * generator decides what reaches CSS for both.\n */\nimport { guardedStylesToCss } from \"../catalog/styles.js\";\nimport type { WidgetStyles } from \"../catalog/styles.js\";\n\n/**\n * Generate a theme's style CSS. With `scope` (a caller constant such as\n * `:root[data-theme=\"dark\"]`, never theme data) every selector part is\n * prefixed with `:where(<scope>) `, so the rule applies only inside the\n * scope and weighs what its author wrote. Never throws.\n */\nexport function themeStylesToCss(styles: WidgetStyles, scope?: string): string {\n return guardedStylesToCss(styles, scope);\n}\n", "/**\n * Safety constants shared by validation (strict) and interpretation\n * (lenient defense in depth). Both layers MUST consult these \u2014 keeping them\n * in one module is what prevents the two from drifting. URL safety itself\n * lives in the contract layer (`contract/urls.ts`) so the catalog's image\n * rendering shares the exact same rules; re-exported here to keep this\n * module the single import point for template safety.\n */\nexport {\n ALLOWED_SCHEMES,\n isSafeUrl,\n isSafeImageSrc\n} from \"../contract/urls.js\";\n\n/**\n * Attributes that are code or embedded documents: event handlers (`on*`)\n * and `srcdoc`, which smuggles a whole document past the tag policy.\n */\nexport const FORBIDDEN_ATTR = /^(?:on.*|srcdoc)$/i;\n\n/**\n * Tags that introduce active or foreign content into the frame. A template\n * is data, never a program: these fail validation and render as nothing\n * when validation was bypassed \u2014 the same two-layer stance as `on*`.\n */\nexport const FORBIDDEN_TAGS: ReadonlySet<string> = new Set([\n \"script\", \"iframe\", \"frame\", \"frameset\", \"object\", \"embed\", \"style\",\n \"link\", \"meta\", \"base\", \"template\", \"noscript\"\n]);\n\n/**\n * Renderer-owned attributes (`data-wg-*`): action descriptors and render\n * markers. Authors cannot write them \u2014 only a validated `action` binding\n * produces one \u2014 so a hand-written descriptor never reaches a tree.\n */\nexport const RESERVED_ATTR = /^data-wg-/i;\n\n/** Attributes whose values are URLs and can smuggle script schemes. */\nexport const URL_ATTRS = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"data\",\n \"poster\",\n \"ping\"\n]);\n\n/** Maximum template nesting depth accepted by validation. */\nexport const MAX_TEMPLATE_DEPTH = 64;\n", "/**\n * The template path grammar, shared by validation (strict) and\n * interpretation (lenient) so the two never drift:\n *\n * \".\" the current scope itself\n * \"$index\" zero-based position in the innermost `each`\n * \"$meta.<segments>\" reads payload.meta\n * \"$root[.<segments>]\" reads payload.data regardless of `each` nesting\n * \"$parent\"+ [.<rest>] steps out of one enclosing `each` per token;\n * <rest> is segments, \"$index\", or nothing\n * \"<segments>\" dot path against the current scope\n *\n * Reserved tokens (`$meta`, `$root`, `$parent`, `$index`) are only valid in\n * the positions above; anywhere else the path is invalid.\n */\nexport interface ParsedPath {\n base: \"scope\" | \"meta\" | \"root\";\n /** Enclosing-scope hops (`$parent` count). */\n up: number;\n /** The path names the current index rather than a value. */\n index: boolean;\n segments: string[];\n}\n\nconst RESERVED = new Set([\"$meta\", \"$root\", \"$parent\", \"$index\"]);\n\n/** Parse a path; `undefined` when the syntax is invalid. Never throws. */\nexport function parsePath(value: string): ParsedPath | undefined {\n if (value === \".\") return { base: \"scope\", up: 0, index: false, segments: [] };\n const tokens = value.split(\".\");\n let i = 0;\n let base: ParsedPath[\"base\"] = \"scope\";\n let up = 0;\n if (tokens[0] === \"$meta\") {\n base = \"meta\";\n i = 1;\n } else if (tokens[0] === \"$root\") {\n base = \"root\";\n i = 1;\n } else {\n while (tokens[i] === \"$parent\") {\n up++;\n i++;\n }\n }\n const rest = tokens.slice(i);\n if (rest.length === 1 && rest[0] === \"$index\") {\n if (base !== \"scope\") return undefined;\n return { base, up, index: true, segments: [] };\n }\n if (rest.length === 0) {\n if (base === \"meta\") return undefined;\n return { base, up, index: false, segments: [] };\n }\n if (rest.some((segment) => segment === \"\" || RESERVED.has(segment))) return undefined;\n return { base, up, index: false, segments: rest };\n}\n", "/**\n * The action model: what a widget can ask for when a person activates a\n * bound element. Two kinds \u2014 `prompt` proposes a user message through the\n * host, `http` performs a server-side request against an author-declared\n * URL \u2014 both plain JSON data, storable and validatable, never code.\n *\n * Zero-dependency by design: this module is shared by the template\n * compiler (which resolves bindings into descriptors at render time), the\n * store (which validates stored actions), the server (which executes) and\n * the designers (which edit).\n */\nimport type { DataSchema } from \"../catalog/index.js\";\n\n/** A prompt's text: literals and `{ bind }` segments resolved at render time. */\nexport type PromptSegment = string | { bind: string };\n\nexport interface PromptActionDefinition {\n kind: \"prompt\";\n text: PromptSegment[];\n}\n\n/** A by-name reference to one of the principal's secrets. */\nexport interface SecretRef {\n secret: string;\n}\n\n/** Header and query values: author literals or secret references. */\nexport type HeaderValue = string | SecretRef;\n\nexport type HttpMethod = \"GET\" | \"POST\";\n\nexport interface HttpActionDefinition {\n kind: \"http\";\n method: HttpMethod;\n /** Absolute https URL, fixed by the author \u2014 bindings never reach it. */\n url: string;\n /** JSON Schema (`type: \"object\"`) of the arguments. */\n input: DataSchema;\n /** JSON Schema the response body must satisfy. */\n output: DataSchema;\n headers?: Record<string, HeaderValue>;\n query?: Record<string, HeaderValue>;\n}\n\nexport type ActionDefinition = PromptActionDefinition | HttpActionDefinition;\n\n/** A shared, named action a principal owns. */\nexport interface StoredAction {\n name: string;\n label?: string;\n description?: string;\n definition: ActionDefinition;\n}\n\n/** Input mapping: input-schema field \u2192 template path or literal. */\nexport type InputMapping = Record<string, string | { const: unknown }>;\n\nexport type OutputMode = \"replace\" | \"merge\" | \"patch\";\n\nexport interface OutputBinding {\n /** Default `merge`. */\n mode?: OutputMode;\n /** Required for `patch`: the dotted data path the response is written at. */\n path?: string;\n /** Projection applied first: target data path \u2192 source response path. */\n map?: Record<string, string>;\n}\n\n/**\n * A binding names an action \u2014 a shared one by `ref`, or an inline one\n * under `definition` (nested so the definition's `input`/`output` schemas\n * never collide with the binding's `input` mapping and `output` mode) \u2014\n * plus how data flows.\n */\nexport type ActionBinding = ({ ref: string } | { definition: ActionDefinition }) & {\n input?: InputMapping;\n output?: OutputBinding;\n};\n\n/** Why an action renders unavailable. */\nexport type ActionDisabledReason = \"scope\" | \"unresolved\";\n\n/**\n * What a rendered element carries in `data-wg-action`: everything the\n * bridge needs, nothing it must evaluate.\n */\nexport interface ActionDescriptor {\n /** Binding identifier: the element's dotted template path, or \"load\". */\n id: string;\n kind?: ActionDefinition[\"kind\"];\n /** Resolved http arguments. */\n args?: Record<string, unknown>;\n /** Resolved prompt text. */\n text?: string;\n disabled?: ActionDisabledReason;\n /** The kind whose template declared the binding (set when registered). */\n widget?: string;\n /**\n * Inside a `group` render: the dotted path of the item payload within the\n * root payload (e.g. `data.items.2`), stamped by the group composition.\n */\n at?: string;\n}\n\n/** Structured validation error; `path` is dotted, relative to the caller's root. */\nexport interface ActionError {\n code: \"INVALID_ACTION\";\n message: string;\n path: string;\n}\n\n/** Upper bound on a resolved prompt message. */\nexport const PROMPT_TEXT_MAX = 2_000;\n\n/** Secret names: short, lowercase, URL- and header-safe. */\nexport const SECRET_NAME = /^[a-z][a-z0-9-]{0,63}$/;\n\n/** Action names share the secret-name discipline. */\nexport const ACTION_NAME = SECRET_NAME;\n\nexport const OUTPUT_MODES: readonly OutputMode[] = [\"replace\", \"merge\", \"patch\"];\n\nexport const HTTP_METHODS: readonly HttpMethod[] = [\"GET\", \"POST\"];\n", "import { isPlainObject } from \"../shared/plain-object.js\";\nimport type {\n ActionDefinition,\n ActionError\n} from \"./types.js\";\nimport {\n HTTP_METHODS,\n OUTPUT_MODES,\n PROMPT_TEXT_MAX,\n SECRET_NAME\n} from \"./types.js\";\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\nfunction fail(message: string, path: string): ActionError {\n return { code: \"INVALID_ACTION\", message, path };\n}\n\n/** RFC 7230 token: what a header or query parameter NAME may be. */\nconst HEADER_TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\n/** Header names the transport owns; an author must not set them. */\nconst RESERVED_HEADERS: ReadonlySet<string> = new Set([\n \"host\", \"content-length\", \"transfer-encoding\", \"connection\"\n]);\n\n/** Segments that would reach the prototype chain or the template grammar's reserved tokens. */\nconst FORBIDDEN_SEGMENTS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * The dotted-path grammar for output `path` and `map` entries: non-empty\n * segments, no `$`-tokens, nothing that addresses a prototype.\n */\nexport function isDataPath(value: string): boolean {\n if (value === \"\") return false;\n return value.split(\".\").every(\n (segment) => segment !== \"\" && !segment.startsWith(\"$\") && !FORBIDDEN_SEGMENTS.has(segment)\n );\n}\n\n/** A header/query value: literal string or `{ secret: name }`. */\nfunction checkHeaderValue(value: unknown, path: string): ActionError | undefined {\n if (typeof value === \"string\") return undefined;\n if (isPlainObject(value) && typeof value.secret === \"string\") {\n if (!SECRET_NAME.test(value.secret)) {\n return fail(`Secret reference '${value.secret}' is not a valid secret name.`, path);\n }\n if (Object.keys(value).length !== 1) {\n return fail(\"A secret reference carries only 'secret'.\", path);\n }\n return undefined;\n }\n return fail(\"Value must be a string or a { secret } reference.\", path);\n}\n\n/** Does any nested value look like a secret reference? */\nfunction containsSecretRef(value: unknown): boolean {\n if (!isPlainObject(value) && !Array.isArray(value)) return false;\n if (isPlainObject(value) && typeof value.secret === \"string\") return true;\n const entries = Array.isArray(value) ? value : Object.values(value);\n return entries.some(containsSecretRef);\n}\n\nfunction checkUrl(url: unknown, path: string): ActionError | undefined {\n if (typeof url !== \"string\" || url.length === 0) {\n return fail(\"'url' must be a non-empty string.\", path);\n }\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return fail(`'url' must be an absolute URL (got '${url}').`, path);\n }\n if (parsed.protocol !== \"https:\") return fail(\"'url' must use https.\", path);\n if (parsed.username !== \"\" || parsed.password !== \"\") {\n return fail(\"'url' must not carry userinfo.\", path);\n }\n if (parsed.hash !== \"\") return fail(\"'url' must not carry a fragment.\", path);\n return undefined;\n}\n\n/**\n * Validate an action definition. `path` locates it for the caller (an\n * element's `action`, a stored action's `definition`). Never throws.\n */\nexport interface DefinitionCheckOptions {\n /** Path-syntax check supplied by the template layer (owner of the grammar). */\n isPath?: (path: string) => boolean;\n}\n\nexport function validateActionDefinition(\n input: unknown,\n path = \"\",\n options: DefinitionCheckOptions = {}\n): ActionError | undefined {\n if (!isPlainObject(input)) return fail(\"Action definition must be an object.\", path);\n if (input.kind === \"prompt\") {\n if (!Array.isArray(input.text)) {\n return fail(\"'text' must be an array of literals and { bind } segments.\", join(path, \"text\"));\n }\n let literal = 0;\n for (let i = 0; i < input.text.length; i++) {\n const segment = input.text[i];\n if (typeof segment === \"string\") {\n literal += segment.length;\n continue;\n }\n if (isPlainObject(segment) && typeof segment.bind === \"string\" && Object.keys(segment).length === 1) {\n if (options.isPath && !options.isPath(segment.bind)) {\n return fail(`Invalid data path '${segment.bind}'.`, join(path, `text.${i}`));\n }\n continue;\n }\n return fail(\"Prompt segments are strings or { bind } objects.\", join(path, `text.${i}`));\n }\n if (literal > PROMPT_TEXT_MAX) {\n return fail(`Prompt text exceeds ${PROMPT_TEXT_MAX} characters.`, join(path, \"text\"));\n }\n return undefined;\n }\n if (input.kind === \"http\") {\n if (!HTTP_METHODS.some((m) => m === input.method)) {\n return fail(\"'method' must be GET or POST.\", join(path, \"method\"));\n }\n const urlError = checkUrl(input.url, join(path, \"url\"));\n if (urlError) return urlError;\n if (!isPlainObject(input.input) || input.input.type !== \"object\") {\n return fail(\"'input' must be a JSON Schema with type \\\"object\\\".\", join(path, \"input\"));\n }\n if (containsSecretRef(input.input)) {\n return fail(\"Secret references are allowed only in headers and query.\", join(path, \"input\"));\n }\n if (!isPlainObject(input.output)) {\n return fail(\"'output' must be a JSON Schema object.\", join(path, \"output\"));\n }\n for (const field of [\"headers\", \"query\"] as const) {\n const map = input[field];\n if (map === undefined) continue;\n if (!isPlainObject(map)) return fail(`'${field}' must be an object.`, join(path, field));\n for (const [name, value] of Object.entries(map)) {\n const namePath = join(path, `${field}.${name}`);\n if (!HEADER_TOKEN.test(name)) {\n return fail(`'${name}' is not a valid ${field === \"headers\" ? \"header\" : \"parameter\"} name.`, namePath);\n }\n if (field === \"headers\" && RESERVED_HEADERS.has(name.toLowerCase())) {\n return fail(`Header '${name}' is set by the transport and cannot be declared.`, namePath);\n }\n const error = checkHeaderValue(value, namePath);\n if (error) return error;\n }\n }\n return undefined;\n }\n return fail(\"'kind' must be \\\"prompt\\\" or \\\"http\\\".\", join(path, \"kind\"));\n}\n\nexport interface BindingCheckOptions {\n /** Path-syntax check supplied by the template layer (owner of the grammar). */\n isPath?: (path: string) => boolean;\n /** Resolve a `ref` to its definition when the caller knows the catalog. */\n resolve?: (ref: string) => ActionDefinition | undefined;\n /** `load` bindings: http GET only. */\n loadOnly?: boolean;\n}\n\nfunction definitionOf(\n binding: Record<string, unknown>,\n options: BindingCheckOptions\n): ActionDefinition | undefined {\n if (typeof binding.ref === \"string\") return options.resolve?.(binding.ref);\n return binding.definition as ActionDefinition | undefined;\n}\n\n/**\n * Validate a binding: `{ ref }` or an inline definition, plus `input` and\n * `output`. When the definition is known (inline, or resolved through\n * `options.resolve`), input keys are checked against its input schema and\n * `load` bindings are held to http GET. Never throws.\n */\nexport function validateActionBinding(\n input: unknown,\n path = \"\",\n options: BindingCheckOptions = {}\n): ActionError | undefined {\n if (!isPlainObject(input)) return fail(\"Action binding must be an object.\", path);\n const hasRef = \"ref\" in input;\n if (hasRef) {\n if (typeof input.ref !== \"string\" || input.ref.length === 0) {\n return fail(\"'ref' must name a shared action.\", join(path, \"ref\"));\n }\n if (\"definition\" in input) return fail(\"A binding is either a { ref } or a { definition }, not both.\", path);\n if (options.resolve && options.resolve(input.ref) === undefined) {\n return fail(`Unknown action '${input.ref}'.`, join(path, \"ref\"));\n }\n } else if (\"definition\" in input) {\n const definitionError = validateActionDefinition(input.definition, join(path, \"definition\"), {\n ...(options.isPath ? { isPath: options.isPath } : {})\n });\n if (definitionError) return definitionError;\n } else {\n return fail(\"A binding names a shared action ({ ref }) or carries an inline { definition }.\", path);\n }\n const definition = definitionOf(input, options);\n\n if (options.loadOnly && definition !== undefined) {\n if (definition.kind !== \"http\" || definition.method !== \"GET\") {\n return fail(\"'load' accepts only http GET actions.\", path);\n }\n }\n\n if (input.input !== undefined) {\n if (!isPlainObject(input.input)) return fail(\"'input' must be an object.\", join(path, \"input\"));\n if (definition?.kind === \"prompt\") {\n return fail(\"Prompt actions take no input mapping.\", join(path, \"input\"));\n }\n const declared = definition?.kind === \"http\" && isPlainObject(definition.input.properties)\n ? definition.input.properties\n : undefined;\n for (const [field, value] of Object.entries(input.input)) {\n const fieldPath = join(path, `input.${field}`);\n if (declared !== undefined && !(field in declared)) {\n return fail(`Input field '${field}' is not declared by the action's input schema.`, fieldPath);\n }\n if (typeof value === \"string\") {\n if (options.isPath && !options.isPath(value)) {\n return fail(`Invalid data path '${value}'.`, fieldPath);\n }\n continue;\n }\n if (isPlainObject(value) && \"const\" in value && Object.keys(value).length === 1) {\n if (containsSecretRef(value.const)) {\n return fail(\"Secret references are allowed only in headers and query.\", fieldPath);\n }\n continue;\n }\n return fail(\"Input values are data paths or { const } literals.\", fieldPath);\n }\n }\n\n if (input.output !== undefined) {\n const outPath = join(path, \"output\");\n if (!isPlainObject(input.output)) return fail(\"'output' must be an object.\", outPath);\n if (definition?.kind === \"prompt\") return fail(\"Prompt actions have no output.\", outPath);\n const { mode, path: target, map } = input.output;\n if (mode !== undefined && !OUTPUT_MODES.some((m) => m === mode)) {\n return fail(\"'mode' must be replace, merge or patch.\", join(outPath, \"mode\"));\n }\n if (mode === \"patch\") {\n if (typeof target !== \"string\" || !isDataPath(target)) {\n return fail(\"'patch' requires a valid data 'path'.\", join(outPath, \"path\"));\n }\n } else if (target !== undefined) {\n return fail(\"'path' is only meaningful with mode \\\"patch\\\".\", join(outPath, \"path\"));\n }\n if (map !== undefined) {\n if (!isPlainObject(map)) return fail(\"'map' must be an object of data paths.\", join(outPath, \"map\"));\n const entries = Object.entries(map);\n if (entries.length === 0) return fail(\"'map' must not be empty (omit it to take the whole response).\", join(outPath, \"map\"));\n for (const [key, value] of entries) {\n const entryPath = join(outPath, `map.${key}`);\n if (key !== \".\" && !isDataPath(key)) {\n return fail(`'${key}' is not a valid data path.`, entryPath);\n }\n if (typeof value !== \"string\" || (value !== \".\" && !isDataPath(value))) {\n return fail(\"Map values are data paths into the response ('.' for the whole response).\", entryPath);\n }\n }\n }\n }\n return undefined;\n}\n\n/** A widget's `load` binding: http GET only (see `BindingCheckOptions.loadOnly`). */\nexport function validateLoadBinding(\n input: unknown,\n path = \"load\",\n options: Omit<BindingCheckOptions, \"loadOnly\"> = {}\n): ActionError | undefined {\n return validateActionBinding(input, path, { ...options, loadOnly: true });\n}\n\n/** Secret names an http definition references in its headers and query. */\nexport function collectSecretRefs(definition: unknown): string[] {\n if (!isPlainObject(definition) || definition.kind !== \"http\") return [];\n const names = new Set<string>();\n for (const field of [\"headers\", \"query\"] as const) {\n const map = definition[field];\n if (!isPlainObject(map)) continue;\n for (const value of Object.values(map)) {\n if (isPlainObject(value) && typeof value.secret === \"string\") names.add(value.secret);\n }\n }\n return [...names];\n}\n", "import { isPlainObject } from \"../shared/plain-object.js\";\nimport type { TemplateError, WidgetTemplate } from \"./types.js\";\nimport { FORBIDDEN_ATTR, FORBIDDEN_TAGS, MAX_TEMPLATE_DEPTH, RESERVED_ATTR } from \"./guards.js\";\nimport { parsePath } from \"./paths.js\";\nimport { validateActionBinding } from \"../actions/validate.js\";\nimport {\n CURRENCY_CODE,\n CURRENCY_DISPLAYS,\n DATE_PATTERN_ALLOWED,\n DATE_PATTERN_MAX,\n DATE_TOKENS,\n FORMAT_DECIMALS_MAX,\n FORMAT_DECIMALS_MIN,\n FORMAT_TYPES,\n JOIN_SEPARATOR_MAX,\n LOCALE_TAG,\n PLURAL_CATEGORIES,\n PLURAL_FORM_MAX,\n TRUNCATE_ELLIPSIS_MAX,\n TRUNCATE_LENGTH_MAX,\n TRUNCATE_LENGTH_MIN,\n isCurrencyDisplay,\n isFormatType,\n isKnownLocale,\n isPlainDottedPath,\n isPluralCategory,\n parseFormatSpec,\n tokenizeDatePattern\n} from \"../catalog/widgets/value-format.js\";\n\nexport type ValidateTemplateResult =\n | { ok: true; template: WidgetTemplate }\n | { ok: false; error: TemplateError };\n\n/**\n * Thrown by `registerTemplate` when the template fails validation \u2014\n * registration is host setup, where failing loudly is the convention.\n * Carries the structured error for programmatic handling.\n */\nexport class InvalidTemplateError extends Error {\n readonly templateError: TemplateError;\n\n constructor(kind: string, error: TemplateError) {\n super(\n `Invalid widget template for kind '${kind}' at '${error.path}': ${error.message} (${error.code})`\n );\n this.name = \"InvalidTemplateError\";\n this.templateError = error;\n }\n}\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\nfunction nodeError(message: string, path: string): TemplateError {\n return { code: \"INVALID_TEMPLATE_NODE\", message, path };\n}\n\n/**\n * The `format` spec: a closed vocabulary of author literals. Every bound\n * comes from the engine's own exported constants, so a change to the\n * engine cannot leave the validator (or the guide) behind.\n */\nfunction checkFormat(\n spec: unknown,\n label: string,\n path: string\n): TemplateError | undefined {\n const bad = (message: string): TemplateError => nodeError(`${label}: ${message}`, path);\n if (!isPlainObject(spec)) return bad(\"'format' must be an object.\");\n if (!isFormatType(spec.type)) {\n return bad(`'format.type' must be one of ${FORMAT_TYPES.join(\", \")}.`);\n }\n if (spec.type === \"date\") {\n if (typeof spec.pattern !== \"string\") {\n return bad(\"'format.pattern' must be a string.\");\n }\n if (spec.pattern.length === 0 || spec.pattern.length > DATE_PATTERN_MAX) {\n return bad(`'format.pattern' must be 1-${DATE_PATTERN_MAX} characters.`);\n }\n if (!DATE_PATTERN_ALLOWED.test(spec.pattern)) {\n return bad(\"'format.pattern' may contain only the date tokens and separators.\");\n }\n if (tokenizeDatePattern(spec.pattern) === undefined) {\n return bad(\n `'format.pattern' must use at least one of ${DATE_TOKENS.join(\", \")} and no stray letters.`\n );\n }\n return undefined;\n }\n if (spec.type === \"join\") {\n for (const field of [\"separator\", \"last\"] as const) {\n const value = spec[field];\n if (value !== undefined && (typeof value !== \"string\" || value.length > JOIN_SEPARATOR_MAX)) {\n return bad(`'format.${field}' must be a string of at most ${JOIN_SEPARATOR_MAX} characters.`);\n }\n }\n if (spec.field !== undefined && !isPlainDottedPath(spec.field)) {\n return bad(\"'format.field' must be a plain dotted path read in each item, such as 'name' or 'owner.name'.\");\n }\n return undefined;\n }\n if (spec.type === \"truncate\") {\n if (\n typeof spec.length !== \"number\" ||\n !Number.isInteger(spec.length) ||\n spec.length < TRUNCATE_LENGTH_MIN ||\n spec.length > TRUNCATE_LENGTH_MAX\n ) {\n return bad(`'format.length' must be an integer ${TRUNCATE_LENGTH_MIN}-${TRUNCATE_LENGTH_MAX}.`);\n }\n if (\n spec.ellipsis !== undefined &&\n (typeof spec.ellipsis !== \"string\" || spec.ellipsis.length > TRUNCATE_ELLIPSIS_MAX)\n ) {\n return bad(`'format.ellipsis' must be a string of at most ${TRUNCATE_ELLIPSIS_MAX} characters.`);\n }\n return undefined;\n }\n if (spec.type === \"pluralize\") {\n if (!isPlainObject(spec.forms)) return bad(\"'format.forms' must be an object of plural forms.\");\n for (const [category, form] of Object.entries(spec.forms)) {\n if (!isPluralCategory(category)) {\n return bad(`'format.forms' keys must be plural categories: ${PLURAL_CATEGORIES.join(\", \")}.`);\n }\n if (typeof form !== \"string\" || form.length > PLURAL_FORM_MAX) {\n return bad(`'format.forms.${category}' must be a string of at most ${PLURAL_FORM_MAX} characters.`);\n }\n }\n if (spec.forms.other === undefined) return bad(\"'format.forms' must carry an 'other' form.\");\n }\n if (spec.decimals !== undefined) {\n if (\n typeof spec.decimals !== \"number\" ||\n !Number.isInteger(spec.decimals) ||\n spec.decimals < FORMAT_DECIMALS_MIN ||\n spec.decimals > FORMAT_DECIMALS_MAX\n ) {\n return bad(\n `'format.decimals' must be an integer ${FORMAT_DECIMALS_MIN}-${FORMAT_DECIMALS_MAX}.`\n );\n }\n }\n if (spec.locale !== undefined) {\n if (typeof spec.locale !== \"string\" || !LOCALE_TAG.test(spec.locale) || !isKnownLocale(spec.locale)) {\n return bad(\"'format.locale' must be a BCP-47 language tag this runtime knows.\");\n }\n }\n if (spec.type === \"currency\") {\n if (typeof spec.currency !== \"string\" || !CURRENCY_CODE.test(spec.currency)) {\n return bad(\"'format.currency' must be a three-letter uppercase ISO-4217 code.\");\n }\n if (spec.currencyDisplay !== undefined && !isCurrencyDisplay(spec.currencyDisplay)) {\n return bad(`'format.currencyDisplay' must be one of ${CURRENCY_DISPLAYS.join(\", \")}.`);\n }\n }\n // The engine narrows the same shape; a spec it would degrade never passes.\n return parseFormatSpec(spec) === undefined ? bad(\"'format' is not a spec the engine accepts.\") : undefined;\n}\n\n/** The value transforms a bind may carry \u2014 at most one of them per value. */\nexport const TRANSFORM_KEYS = [\"map\", \"prefix\", \"format\"] as const;\n\nexport type TransformKey = (typeof TRANSFORM_KEYS)[number];\n\n/** Which transform a bind value carries, or `undefined`; `\"conflict\"` when more than one. */\nexport function activeTransform(value: Record<string, unknown>): TransformKey | \"conflict\" | undefined {\n const present = TRANSFORM_KEYS.filter((key) => value[key] !== undefined);\n if (present.length > 1) return \"conflict\";\n return present[0];\n}\n\n/** Path syntax per paths.ts: \".\", \"$index\", \"$meta.\"/\"$root.\"/\"$parent.\"-prefixed, or dot segments. */\nfunction checkPathSyntax(value: string, path: string): TemplateError | undefined {\n if (parsePath(value) !== undefined) return undefined;\n return {\n code: \"INVALID_PATH\",\n message: `Invalid data path '${value}'.`,\n path\n };\n}\n\nfunction check(node: unknown, path: string, depth: number): TemplateError | undefined {\n if (depth > MAX_TEMPLATE_DEPTH) {\n return {\n code: \"TEMPLATE_TOO_DEEP\",\n message: `Template exceeds the maximum nesting depth of ${MAX_TEMPLATE_DEPTH}.`,\n path\n };\n }\n if (typeof node === \"string\") return undefined;\n if (!isPlainObject(node)) {\n return nodeError(\"Template node must be a string or a plain object.\", path);\n }\n\n if (\"bind\" in node) {\n if (typeof node.bind !== \"string\") {\n return nodeError(\"'bind' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.bind, path);\n if (pathError) return pathError;\n // A text bind takes one of `map` (value \u2192 authored label), `format` and\n // `markdown`. `prefix` is an attribute-value transform: ignored here and\n // kept valid, so no stored template is refused on read for carrying it.\n if (node.markdown !== undefined) {\n if (typeof node.markdown !== \"boolean\") {\n return nodeError(\"Bind: 'markdown' must be true or false.\", path);\n }\n if (node.markdown && (node.map !== undefined || node.format !== undefined)) {\n return nodeError(\"A text bind carries one of 'map', 'format' and 'markdown' \u2014 one transform per value.\", path);\n }\n }\n if (node.map !== undefined && node.format !== undefined) {\n return nodeError(\"A text bind carries either 'map' or 'format' \u2014 one transform per value.\", path);\n }\n if (node.map !== undefined) {\n if (!isPlainObject(node.map) || Object.values(node.map).some((entry) => typeof entry !== \"string\")) {\n return nodeError(\"Bind: 'map' must be an object of string values.\", path);\n }\n if (node.default !== undefined && typeof node.default !== \"string\") {\n return nodeError(\"Bind: 'default' must be a string.\", path);\n }\n return undefined;\n }\n if (node.default !== undefined) {\n return nodeError(\"Bind: 'default' requires 'map'.\", path);\n }\n if (node.format !== undefined) {\n return checkFormat(node.format, \"Bind\", path);\n }\n return undefined;\n }\n\n if (\"each\" in node) {\n if (typeof node.each !== \"string\") {\n return nodeError(\"'each' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.each, path);\n if (pathError) return pathError;\n if (\"key\" in node && node.key !== undefined) {\n if (typeof node.key !== \"string\") {\n return nodeError(\"'key' must be a string path.\", path);\n }\n const keyError = checkPathSyntax(node.key, path);\n if (keyError) return keyError;\n }\n if (!(\"template\" in node)) {\n return nodeError(\"'each' node requires a 'template'.\", path);\n }\n const templateError = check(node.template, join(path, \"template\"), depth + 1);\n if (templateError) return templateError;\n if (\"empty\" in node && node.empty !== undefined) {\n return check(node.empty, join(path, \"empty\"), depth + 1);\n }\n return undefined;\n }\n\n if (\"when\" in node) {\n if (typeof node.when !== \"string\") {\n return nodeError(\"'when' must be a string path.\", path);\n }\n const pathError = checkPathSyntax(node.when, path);\n if (pathError) return pathError;\n if (!(\"template\" in node)) {\n return nodeError(\"'when' node requires a 'template'.\", path);\n }\n const templateError = check(node.template, join(path, \"template\"), depth + 1);\n if (templateError) return templateError;\n if (\"else\" in node && node.else !== undefined) {\n return check(node.else, join(path, \"else\"), depth + 1);\n }\n return undefined;\n }\n\n if (\"tag\" in node) {\n if (typeof node.tag !== \"string\" || node.tag.length === 0) {\n return nodeError(\"'tag' must be a non-empty string.\", path);\n }\n if (FORBIDDEN_TAGS.has(node.tag.toLowerCase())) {\n return {\n code: \"FORBIDDEN_TAG\",\n message: `Element '${node.tag}' is not allowed in templates (active or foreign content).`,\n path\n };\n }\n if (\"attrs\" in node && node.attrs !== undefined) {\n if (!isPlainObject(node.attrs)) {\n return nodeError(\"'attrs' must be an object.\", path);\n }\n for (const [name, value] of Object.entries(node.attrs)) {\n const attrPath = join(path, `attrs.${name}`);\n if (FORBIDDEN_ATTR.test(name)) {\n return {\n code: \"FORBIDDEN_ATTRIBUTE\",\n message: `Attribute '${name}' is not allowed in templates (event handlers and srcdoc).`,\n path: attrPath\n };\n }\n if (RESERVED_ATTR.test(name)) {\n return {\n code: \"FORBIDDEN_ATTRIBUTE\",\n message: `Attribute '${name}' is reserved for the renderer (data-wg-*); use an 'action' binding.`,\n path: attrPath\n };\n }\n if (typeof value === \"string\") continue;\n if (isPlainObject(value) && typeof value.bind === \"string\") {\n const pathError = checkPathSyntax(value.bind, attrPath);\n if (pathError) return pathError;\n if (value.markdown !== undefined) {\n return nodeError(\n `Attribute '${name}': 'markdown' is a text-bind mode; an attribute value cannot carry it.`,\n attrPath\n );\n }\n // One transform per value: map selects an authored literal,\n // prefix glues one in front, format presents the value \u2014\n // combining them has no use case and every combination would\n // need teaching forever.\n const transform = activeTransform(value);\n const hasMap = transform === \"map\";\n const hasPrefix = transform === \"prefix\";\n const hasFormat = transform === \"format\";\n if (transform === \"conflict\") {\n return nodeError(\n `Attribute '${name}' carries more than one of 'map', 'prefix' and 'format' \u2014 one transform per value.`,\n attrPath\n );\n }\n if (hasMap) {\n if (\n !isPlainObject(value.map) ||\n Object.values(value.map).some((entry) => typeof entry !== \"string\")\n ) {\n return nodeError(\n `Attribute '${name}': 'map' must be an object of string values.`,\n attrPath\n );\n }\n if (value.default !== undefined && typeof value.default !== \"string\") {\n return nodeError(\n `Attribute '${name}': 'default' must be a string.`,\n attrPath\n );\n }\n } else if (value.default !== undefined) {\n return nodeError(\n `Attribute '${name}': 'default' requires 'map'.`,\n attrPath\n );\n }\n if (hasPrefix && typeof value.prefix !== \"string\") {\n return nodeError(\n `Attribute '${name}': 'prefix' must be a string.`,\n attrPath\n );\n }\n if (hasFormat) {\n const formatError = checkFormat(value.format, `Attribute '${name}'`, attrPath);\n if (formatError) return formatError;\n }\n continue;\n }\n return nodeError(\n `Attribute '${name}' must be a string, { bind }, { bind, map, default? }, { bind, prefix } or { bind, format } value.`,\n attrPath\n );\n }\n }\n if (\"action\" in node && node.action !== undefined) {\n // An element is a link OR an action \u2014 both would leave the bridge\n // guessing which the author meant.\n const hasHref =\n isPlainObject(node.attrs) &&\n Object.keys(node.attrs).some((name) => name.toLowerCase() === \"href\");\n if (hasHref) {\n return {\n code: \"CONFLICTING_ATTRIBUTES\",\n message: \"An element carries 'href' or an 'action' binding, never both.\",\n path\n };\n }\n const actionError = validateActionBinding(node.action, join(path, \"action\"), {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (actionError) {\n return { code: \"INVALID_ACTION\", message: actionError.message, path: actionError.path };\n }\n }\n if (\"children\" in node && node.children !== undefined) {\n if (!Array.isArray(node.children)) {\n return nodeError(\"'children' must be an array.\", path);\n }\n for (let i = 0; i < node.children.length; i++) {\n const childError = check(\n node.children[i],\n join(path, `children.${i}`),\n depth + 1\n );\n if (childError) return childError;\n }\n }\n return undefined;\n }\n\n return nodeError(\n \"Unknown template node form (expected text, bind, tag, each, or when).\",\n path\n );\n}\n\n/** Validate an unknown value as a widget template. Never throws. */\nexport function validateTemplate(input: unknown): ValidateTemplateResult {\n const error = check(input, \"\", 0);\n if (error) return { ok: false, error };\n return { ok: true, template: input as WidgetTemplate };\n}\n", "/**\n * Addressing nodes inside a template by the validator's dotted path\n * convention (`children.2.template`, `else`, \u2026) \u2014 the identifier an action\n * binding is known by \u2014 and enumerating the shared actions a template\n * references, so stores can enforce referential integrity without a\n * second grammar.\n */\nimport { isPlainObject } from \"../shared/plain-object.js\";\nimport type { ActionBinding } from \"../actions/types.js\";\n\n/** The template node at a dotted path (\"\" is the root); `undefined` when absent. */\nexport function findTemplateNode(template: unknown, path: string): unknown {\n if (path === \"\") return template;\n let current: unknown = template;\n for (const segment of path.split(\".\")) {\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = current[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/** The element's `action` binding at a dotted path, when that node is a bound element. */\nexport function findActionBinding(template: unknown, path: string): ActionBinding | undefined {\n const node = findTemplateNode(template, path);\n if (isPlainObject(node) && typeof node.tag === \"string\" && isPlainObject(node.action)) {\n return node.action as ActionBinding;\n }\n return undefined;\n}\n\n/** Visit every binding object a template (and an optional `load`) carries. */\nfunction eachBinding(template: unknown, load: unknown, onBinding: (binding: Record<string, unknown>) => void): void {\n const visit = (node: unknown): void => {\n if (!isPlainObject(node)) return;\n if (isPlainObject(node.action)) onBinding(node.action);\n for (const key of [\"template\", \"empty\", \"else\"] as const) {\n if (node[key] !== undefined) visit(node[key]);\n }\n if (Array.isArray(node.children)) for (const child of node.children) visit(child);\n };\n visit(template);\n if (isPlainObject(load)) onBinding(load);\n}\n\n/** Every shared-action name a template (and an optional `load`) references by `ref`. */\nexport function collectActionRefs(template: unknown, load?: unknown): string[] {\n const refs = new Set<string>();\n eachBinding(template, load, (binding) => {\n if (typeof binding.ref === \"string\") refs.add(binding.ref);\n });\n return [...refs];\n}\n\n/** Every inline action definition in a template (and `load`), for secret-reference scans. */\nexport function collectInlineActions(template: unknown, load?: unknown): unknown[] {\n const out: unknown[] = [];\n eachBinding(template, load, (binding) => {\n if (typeof binding.ref !== \"string\" && binding.definition !== undefined) out.push(binding.definition);\n });\n return out;\n}\n\n/** Does the template (or `load`) carry any action binding at all? */\nexport function hasActionBindings(template: unknown, load?: unknown): boolean {\n if (load !== undefined) return true;\n return collectActionRefs(template).length > 0 || collectInlineActions(template).length > 0;\n}\n", "/**\n * Markdown text binds: a small, fixed subset parsed into render-tree nodes.\n *\n * The parser, not the value, chooses tags: only `p`, `br`, `strong`, `em`,\n * `code`, `a`, `ul`, `ol` and `li` inside one `div.wg-md`, every character\n * of the value emitted as text, never parsed as HTML. Links face the same\n * URL guard as a bound `href`; a refused link renders as its text. Syntax\n * outside the subset (headings, fences, quotes, images, tables, raw HTML)\n * stays literal, so no data is hidden.\n *\n * Cost is bounded twice: a source over {@link MARKDOWN_SOURCE_MAX} renders\n * as one plain paragraph without parsing, and every emitted node spends the\n * render's node budget, so the parse is linear in a bounded source.\n */\nimport type { WidgetElementNode, WidgetNode } from \"../catalog/index.js\";\nimport { isSafeUrl } from \"./guards.js\";\n\n/** The longest source parsed; a longer value renders as one plain paragraph. */\nexport const MARKDOWN_SOURCE_MAX = 20_000;\n\n/** Every tag Markdown output can carry, its `div.wg-md` wrapper aside. */\nexport const MARKDOWN_TAGS = [\"p\", \"br\", \"strong\", \"em\", \"code\", \"a\", \"ul\", \"ol\", \"li\"] as const;\n\n/** The render's node budget, shared with the interpreter. */\nexport interface MarkdownBudget {\n remaining: number;\n truncated: boolean;\n}\n\ntype Block =\n | { kind: \"p\"; lines: string[] }\n | { kind: \"literal\"; lines: string[] }\n | { kind: \"ul\" | \"ol\"; start: number; items: string[][] };\n\nconst BULLET = /^\\s*[-*+][ \\t]+(.*)$/;\nconst ORDERED = /^\\s*(\\d{1,9})[.)][ \\t]+(.*)$/;\nconst FENCE = /^\\s*(`{3,}|~{3,})/;\n\n/**\n * Sort lines into paragraphs and flat lists; blank lines separate blocks.\n * A code fence is outside the subset: its lines, the fences included, form\n * one literal block that no inline syntax touches, through the closing\n * fence or the end of the value.\n */\nfunction blocksOf(text: string): Block[] {\n const blocks: Block[] = [];\n let current: Exclude<Block, { kind: \"literal\" }> | undefined;\n const lines = text.split(\"\\n\");\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index] as string;\n const fence = FENCE.exec(line)?.[1];\n if (fence !== undefined) {\n const closing = new RegExp(`^\\\\s*${fence[0] === \"`\" ? \"`\" : \"~\"}{${fence.length},}\\\\s*$`);\n const literal: string[] = [line];\n while (++index < lines.length) {\n literal.push(lines[index] as string);\n if (closing.test(lines[index] as string)) break;\n }\n blocks.push({ kind: \"literal\", lines: literal });\n current = undefined;\n continue;\n }\n if (line.trim() === \"\") {\n current = undefined;\n continue;\n }\n const bullet = BULLET.exec(line);\n const ordered = bullet === null ? ORDERED.exec(line) : null;\n if (bullet !== null || ordered !== null) {\n const kind = bullet !== null ? \"ul\" : \"ol\";\n const content = (bullet !== null ? bullet[1] : ordered?.[2]) ?? \"\";\n if (current === undefined || current.kind !== kind) {\n current = { kind, start: ordered === null ? 1 : Number(ordered[1]), items: [] };\n blocks.push(current);\n }\n current.items.push([content.trim()]);\n continue;\n }\n if (current === undefined) {\n current = { kind: \"p\", lines: [] };\n blocks.push(current);\n }\n // A line under an item continues it; any other line continues the paragraph.\n if (current.kind === \"p\") current.lines.push(line.trim());\n else current.items[current.items.length - 1]?.push(line.trim());\n }\n return blocks;\n}\n\n/** Characters a backslash makes literal. */\nconst ESCAPABLE = new Set(\"\\\\`*_[]()#+-.!{}<>|~\\\"'\");\n\nconst isWhitespace = (char: string | undefined): boolean => char === undefined || /\\s/.test(char);\nconst isPunctuation = (char: string | undefined): boolean =>\n char !== undefined && /[!-/:-@[-`{-~\\u2000-\\u206f\\u2e00-\\u2e7f]/.test(char);\n\ntype Entry =\n | { kind: \"text\"; value: string }\n | { kind: \"node\"; node: WidgetNode }\n | { kind: \"delim\"; char: \"*\" | \"_\"; count: number; canOpen: boolean; canClose: boolean; index: number };\n\n/** Entries as nodes: a delimiter left unmatched is literal text; adjacent texts merge. */\nfunction nodesOf(entries: readonly Entry[]): WidgetNode[] {\n const out: WidgetNode[] = [];\n for (const entry of entries) {\n const piece: WidgetNode =\n entry.kind === \"node\" ? entry.node : entry.kind === \"text\" ? entry.value : entry.char.repeat(entry.count);\n const last = out[out.length - 1];\n if (typeof piece === \"string\" && typeof last === \"string\") out[out.length - 1] = last + piece;\n else if (piece !== \"\") out.push(piece);\n }\n return out;\n}\n\n/**\n * Backtick runs by length, each list in source order, read through a\n * forward cursor: finding a closing run never rescans the text, so a value\n * of unmatched runs stays linear.\n */\nfunction tickRuns(text: string): (length: number, from: number) => number {\n const runs = new Map<number, number[]>();\n for (let i = 0; i < text.length; ) {\n if (text[i] !== \"`\") {\n i++;\n continue;\n }\n let end = i;\n while (text[end] === \"`\") end++;\n const list = runs.get(end - i) ?? [];\n list.push(i);\n runs.set(end - i, list);\n i = end;\n }\n const cursors = new Map<number, number>();\n return (length, from) => {\n const list = runs.get(length) ?? [];\n let cursor = cursors.get(length) ?? 0;\n while (cursor < list.length && (list[cursor] as number) < from) cursor++;\n cursors.set(length, cursor);\n return cursor < list.length ? (list[cursor] as number) : -1;\n };\n}\n\n/** How far a link's text and URL may reach, so a value of unmatched brackets stays linear. */\nconst LINK_LABEL_MAX = 1000;\nconst LINK_URL_MAX = 2048;\n\n/** `[text](url)` starting at `start`: the text, the url and the index after `)`. */\nfunction linkAt(text: string, start: number): { label: string; url: string; end: number } | undefined {\n let depth = 0;\n let i = start;\n const labelEnd = Math.min(text.length, start + LINK_LABEL_MAX);\n for (; i < labelEnd; i++) {\n const char = text[i];\n if (char === \"\\\\\") {\n i++;\n continue;\n }\n if (char === \"[\") depth++;\n else if (char === \"]\" && --depth === 0) break;\n }\n if (i >= labelEnd || text[i + 1] !== \"(\") return undefined;\n // The URL ends at the `)` that balances its own parentheses.\n const urlEnd = Math.min(text.length, i + 2 + LINK_URL_MAX);\n let close = i + 2;\n for (let parens = 0; close < urlEnd; close++) {\n if (text[close] === \"(\") parens++;\n else if (text[close] === \")\" && parens-- === 0) break;\n }\n if (close >= urlEnd) return undefined;\n const url = text.slice(i + 2, close);\n if (url === \"\" || /\\s/.test(url)) return undefined;\n return { label: text.slice(start + 1, i), url, end: close + 1 };\n}\n\n/**\n * Inline syntax in one left-to-right scan: code spans and escapes first,\n * then links (whose text is parsed again, without links), then emphasis\n * through a delimiter stack. Line breaks are `br`.\n */\nfunction inline(text: string, links: boolean): WidgetNode[] {\n const stack: Entry[] = [];\n // Open delimiters per character, so finding an opener never rescans the stack.\n const openers: Record<\"*\" | \"_\", Extract<Entry, { kind: \"delim\" }>[]> = { \"*\": [], _: [] };\n const pushText = (value: string) => {\n const last = stack[stack.length - 1];\n if (last?.kind === \"text\") last.value += value;\n else stack.push({ kind: \"text\", value });\n };\n const pushNode = (node: WidgetNode) => stack.push({ kind: \"node\", node });\n const closingTicks = tickRuns(text);\n\n let i = 0;\n while (i < text.length) {\n const char = text[i] as string;\n if (char === \"\\\\\" && i + 1 < text.length && ESCAPABLE.has(text[i + 1] as string)) {\n pushText(text[i + 1] as string);\n i += 2;\n continue;\n }\n if (char === \"\\n\") {\n pushNode({ tag: \"br\" });\n i++;\n continue;\n }\n if (char === \"`\") {\n let end = i;\n while (text[end] === \"`\") end++;\n const close = closingTicks(end - i, end);\n if (close === -1) {\n pushText(text.slice(i, end));\n i = end;\n continue;\n }\n let code = text.slice(end, close).replace(/\\n/g, \" \");\n if (code.length > 2 && code.startsWith(\" \") && code.endsWith(\" \") && code.trim() !== \"\") code = code.slice(1, -1);\n pushNode(code === \"\" ? { tag: \"code\" } : { tag: \"code\", children: [code] });\n i = close + (end - i);\n continue;\n }\n if (char === \"!\" && text[i + 1] === \"[\" && links) {\n // An image is outside the subset: its source stays literal text.\n const image = linkAt(text, i + 1);\n if (image !== undefined) {\n pushText(text.slice(i, image.end));\n i = image.end;\n continue;\n }\n }\n if (char === \"[\" && links) {\n const link = linkAt(text, i);\n if (link !== undefined) {\n const label = inline(link.label, false);\n const href = link.url.trim();\n if (isSafeUrl(href)) {\n const anchor: WidgetElementNode = { tag: \"a\", attrs: { href, rel: \"noopener noreferrer\" } };\n if (label.length > 0) anchor.children = label;\n pushNode(anchor);\n } else {\n for (const piece of label) {\n if (typeof piece === \"string\") pushText(piece);\n else pushNode(piece);\n }\n }\n i = link.end;\n continue;\n }\n }\n if (char === \"*\" || char === \"_\") {\n const delim: \"*\" | \"_\" = char;\n let end = i;\n while (text[end] === delim) end++;\n const before = text[i - 1];\n const after = text[end];\n const left = !isWhitespace(after) && (!isPunctuation(after) || isWhitespace(before) || isPunctuation(before));\n const right = !isWhitespace(before) && (!isPunctuation(before) || isWhitespace(after) || isPunctuation(after));\n // An underscore inside a word is literal, so snake_case stays text.\n const canOpen = delim === \"*\" ? left : left && (!right || isPunctuation(before));\n const canClose = delim === \"*\" ? right : right && (!left || isPunctuation(after));\n let remaining = end - i;\n if (canClose) {\n const mine = openers[delim];\n while (remaining > 0) {\n while (mine.length > 0 && (mine[mine.length - 1] as { count: number }).count === 0) mine.pop();\n const opener = mine[mine.length - 1];\n if (opener === undefined) break;\n const use = opener.count >= 2 && remaining >= 2 ? 2 : 1;\n const inner = stack.splice(opener.index + 1);\n // Delimiters of the other character inside the span stay literal.\n const theirs = openers[delim === \"*\" ? \"_\" : \"*\"];\n while (theirs.length > 0 && (theirs[theirs.length - 1] as { index: number }).index > opener.index) theirs.pop();\n const children = nodesOf(inner);\n opener.count -= use;\n remaining -= use;\n if (opener.count === 0) {\n stack.pop();\n mine.pop();\n }\n const element: WidgetElementNode = { tag: use === 2 ? \"strong\" : \"em\" };\n if (children.length > 0) element.children = children;\n pushNode(element);\n }\n }\n if (remaining > 0) {\n if (canOpen) {\n const entry = { kind: \"delim\" as const, char: delim, count: remaining, canOpen, canClose, index: stack.length };\n stack.push(entry);\n openers[delim].push(entry);\n } else {\n pushText(delim.repeat(remaining));\n }\n }\n i = end;\n continue;\n }\n pushText(char);\n i++;\n }\n return nodesOf(stack);\n}\n\n/** Copy `node` in document order while the budget lasts; one unit per element or text. */\nfunction spend(node: WidgetNode, budget: MarkdownBudget): WidgetNode | undefined {\n if (budget.remaining <= 0) {\n budget.truncated = true;\n return undefined;\n }\n budget.remaining--;\n if (typeof node === \"string\" || node.children === undefined) return node;\n const children: WidgetNode[] = [];\n for (const child of node.children) {\n const kept = spend(child, budget);\n if (kept === undefined) break;\n children.push(kept);\n }\n const copy: WidgetElementNode = { ...node };\n if (children.length > 0) copy.children = children;\n else delete copy.children;\n return copy;\n}\n\nconst element = (tag: string, children: WidgetNode[], attrs?: Record<string, string>): WidgetElementNode => {\n const node: WidgetElementNode = { tag };\n if (attrs !== undefined) node.attrs = attrs;\n if (children.length > 0) node.children = children;\n return node;\n};\n\n/**\n * Parse `source` into one `div.wg-md`, spending `budget` \u2014 or nothing for\n * an empty or whitespace-only value. Never throws.\n */\nexport function parseMarkdown(source: string, budget: MarkdownBudget): WidgetNode[] {\n const text = source.replace(/\\r\\n?/g, \"\\n\");\n if (text.trim() === \"\") return [];\n let children: WidgetNode[];\n if (text.length > MARKDOWN_SOURCE_MAX) {\n children = [element(\"p\", [text])];\n } else {\n children = blocksOf(text).map((block) => {\n if (block.kind === \"p\") return element(\"p\", inline(block.lines.join(\"\\n\"), true));\n if (block.kind === \"literal\") {\n return element(\"p\", block.lines.flatMap((line, i): WidgetNode[] => [\n ...(i === 0 ? [] : [{ tag: \"br\" }]),\n ...(line === \"\" ? [] : [line])\n ]));\n }\n const items = block.items.map((lines) => element(\"li\", inline(lines.join(\"\\n\"), true)));\n return element(block.kind, items, block.kind === \"ol\" && block.start !== 1 ? { start: String(block.start) } : undefined);\n });\n }\n const root = spend(element(\"div\", children, { class: \"wg-md\" }), budget);\n return root === undefined ? [] : [root];\n}\n", "import type { WidgetPayload } from \"../contract/types.js\";\nimport type {\n WidgetCatalog,\n WidgetDescriptorInput,\n WidgetElementNode,\n WidgetNode,\n WidgetNodeAttrs,\n WidgetRenderer\n} from \"../catalog/index.js\";\nimport type {\n ActionBinding,\n ActionDefinition,\n ActionDescriptor,\n ActionDisabledReason\n} from \"../actions/types.js\";\nimport { PROMPT_TEXT_MAX } from \"../actions/types.js\";\nimport type { WidgetTemplate } from \"./types.js\";\nimport {\n FORBIDDEN_ATTR,\n FORBIDDEN_TAGS,\n RESERVED_ATTR,\n URL_ATTRS,\n isSafeImageSrc,\n isSafeUrl\n} from \"./guards.js\";\nimport { parsePath } from \"./paths.js\";\nimport { InvalidTemplateError, validateTemplate } from \"./validate.js\";\nimport { formatValue } from \"../catalog/widgets/format.js\";\nimport { formatBoundValue } from \"../catalog/widgets/value-format.js\";\nimport { parseMarkdown } from \"./markdown.js\";\nimport { isPlainObject } from \"../shared/plain-object.js\";\n\nfunction join(path: string, segment: string): string {\n return path === \"\" ? segment : `${path}.${segment}`;\n}\n\n/**\n * One scope frame: the root frame holds `payload.data`; every `each`\n * pushes the current item with its position. `$parent` walks the stack,\n * `$root` reads the bottom, `$index` reads the top's position.\n */\ninterface Frame {\n scope: unknown;\n index?: number;\n}\n\n/**\n * Resolve a path against the scope chain (see paths.ts for the grammar).\n * Missing, non-traversable or malformed paths resolve to `undefined` \u2014\n * never throws.\n */\nfunction resolvePath(path: string, frames: Frame[], meta: unknown): unknown {\n const parsed = parsePath(path);\n if (parsed === undefined) return undefined;\n let current: unknown;\n if (parsed.base === \"meta\") {\n current = meta;\n } else if (parsed.base === \"root\") {\n current = frames[0]?.scope;\n } else {\n const depth = frames.length - 1 - parsed.up;\n if (depth < 0) return undefined;\n const frame = frames[depth];\n if (frame === undefined) return undefined;\n if (parsed.index) return frame.index;\n current = frame.scope;\n }\n for (const segment of parsed.segments) {\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = current[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/** A key's string form: strings and finite numbers only. */\nfunction keyOf(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return undefined;\n}\n\n/**\n * Interpretation budget. `each` multiplies template nodes by the length of\n * AGENT-supplied data, so template size bounds nothing on its own \u2014 a\n * stored template driven by a large payload could otherwise spend the\n * process. Counting work (nodes emitted, plus one unit per `each`\n * iteration so empty iterations are not free) rather than watching a\n * clock keeps the bound reproducible: the same template and data always\n * truncate at the same place.\n */\nexport const DEFAULT_MAX_NODES = 50_000;\n\ninterface Budget {\n remaining: number;\n truncated: boolean;\n}\n\n/** Render-time knowledge about actions the caller supplies. */\n/** The compile options the action layer reads; the options object itself serves. */\ntype ActionContext = Pick<CompileOptions, \"actions\" | \"httpDisabled\" | \"kind\">;\n\n/**\n * Resolve a binding into the descriptor an element carries. Everything the\n * bridge needs is decided here, in scope, at render time: the prompt's\n * text, the http arguments, and whether the action is available at all.\n */\nfunction buildDescriptor(\n binding: ActionBinding,\n id: string,\n frames: Frame[],\n meta: unknown,\n ctx: ActionContext\n): ActionDescriptor {\n const definition: ActionDefinition | undefined =\n \"ref\" in binding && typeof binding.ref === \"string\"\n ? ctx.actions?.(binding.ref)\n : \"definition\" in binding && isPlainObject(binding.definition)\n ? (binding.definition as ActionDefinition)\n : undefined;\n if (definition === undefined || (definition.kind !== \"prompt\" && definition.kind !== \"http\")) {\n const unresolved: ActionDescriptor = { id, disabled: \"unresolved\" };\n if (ctx.kind !== undefined) unresolved.widget = ctx.kind;\n return unresolved;\n }\n if (definition.kind === \"prompt\") {\n let text = \"\";\n const segments = Array.isArray(definition.text) ? definition.text : [];\n for (const segment of segments) {\n if (typeof segment === \"string\") text += segment;\n else if (isPlainObject(segment) && typeof segment.bind === \"string\") {\n text += formatValue(resolvePath(segment.bind, frames, meta));\n }\n if (text.length >= PROMPT_TEXT_MAX) break;\n }\n // Cap by code point so a surrogate pair is never split.\n const prompt: ActionDescriptor = { id, kind: \"prompt\", text: Array.from(text).slice(0, PROMPT_TEXT_MAX).join(\"\") };\n if (ctx.kind !== undefined) prompt.widget = ctx.kind;\n return prompt;\n }\n const args: Record<string, unknown> = {};\n if (isPlainObject(binding.input)) {\n for (const [field, value] of Object.entries(binding.input)) {\n let resolved: unknown;\n if (typeof value === \"string\") resolved = resolvePath(value, frames, meta);\n else if (isPlainObject(value) && \"const\" in value) resolved = value.const;\n if (resolved !== undefined) args[field] = resolved;\n }\n }\n const descriptor: ActionDescriptor = { id, kind: \"http\", args };\n if (ctx.httpDisabled !== undefined) descriptor.disabled = ctx.httpDisabled;\n if (ctx.kind !== undefined) descriptor.widget = ctx.kind;\n return descriptor;\n}\n\n/**\n * Interpret a template node into zero or more render-tree nodes.\n * Lenient by design: validation is the strict layer, so unknown or\n * malformed forms render as nothing rather than throwing (defense in\n * depth for templates that bypassed validation). `tpath` is the node's\n * dotted position in the TEMPLATE (the validator's path convention) \u2014 the\n * identifier an action binding is known by.\n */\nfunction interpretNode(\n node: unknown,\n frames: Frame[],\n meta: unknown,\n budget: Budget,\n tpath: string,\n ctx: ActionContext\n): WidgetNode[] {\n if (budget.remaining <= 0) {\n budget.truncated = true;\n return [];\n }\n if (typeof node === \"string\") {\n budget.remaining--;\n return [node];\n }\n if (!isPlainObject(node)) return [];\n\n if (typeof node.bind === \"string\") {\n if (node.markdown === true) {\n // The parser chooses the tags and spends the budget per node it emits.\n return parseMarkdown(formatValue(resolvePath(node.bind, frames, meta)), budget);\n }\n budget.remaining--;\n const resolved = resolvePath(node.bind, frames, meta);\n if (isPlainObject(node.map)) {\n // The value, as a string, SELECTS an authored label: a hit emits that\n // literal, a miss falls to `default` or empty text \u2014 data chooses\n // among the author's words and never contributes characters.\n const key = formatValue(resolved);\n const hit = Object.prototype.hasOwnProperty.call(node.map, key) ? node.map[key] : undefined;\n return [typeof hit === \"string\" ? hit : typeof node.default === \"string\" ? node.default : \"\"];\n }\n // The payload keeps the typed value; only the render gets the unit.\n // (`prefix` is an attribute-value transform and is ignored here.)\n return [formatBoundValue(resolved, node.format)];\n }\n\n if (typeof node.each === \"string\") {\n const value = resolvePath(node.each, frames, meta);\n const items = Array.isArray(value) ? value : [];\n if (items.length === 0) {\n return node.empty === undefined\n ? []\n : interpretNode(node.empty, frames, meta, budget, join(tpath, \"empty\"), ctx);\n }\n const out: WidgetNode[] = [];\n const itemPath = join(tpath, \"template\");\n const keyPath = typeof node.key === \"string\" ? node.key : undefined;\n for (let i = 0; i < items.length; i++) {\n if (budget.remaining <= 0) {\n budget.truncated = true;\n break;\n }\n budget.remaining--; // the iteration itself costs, even when it renders nothing\n frames.push({ scope: items[i], index: i });\n const rendered = interpretNode(node.template, frames, meta, budget, itemPath, ctx);\n const only = rendered.length === 1 ? rendered[0] : undefined;\n if (keyPath !== undefined && only !== undefined && typeof only !== \"string\") {\n const key = keyOf(resolvePath(keyPath, frames, meta));\n if (key !== undefined) rendered[0] = { ...only, key };\n }\n out.push(...rendered);\n frames.pop();\n }\n return out;\n }\n\n if (typeof node.when === \"string\") {\n const truthy = Boolean(resolvePath(node.when, frames, meta));\n const branch = truthy ? node.template : node.else;\n return branch === undefined\n ? []\n : interpretNode(branch, frames, meta, budget, join(tpath, truthy ? \"template\" : \"else\"), ctx);\n }\n\n if (typeof node.tag === \"string\" && node.tag.length > 0) {\n if (FORBIDDEN_TAGS.has(node.tag.toLowerCase())) return []; // active content never reaches a tree\n budget.remaining--;\n const attrs: WidgetNodeAttrs = {};\n if (isPlainObject(node.attrs)) {\n for (const [name, raw] of Object.entries(node.attrs)) {\n // Handlers are code; data-wg-* is the renderer's own vocabulary.\n if (FORBIDDEN_ATTR.test(name) || RESERVED_ATTR.test(name)) continue;\n let value: string | undefined;\n if (typeof raw === \"string\") {\n value = raw;\n } else if (isPlainObject(raw) && typeof raw.bind === \"string\") {\n const resolved = resolvePath(raw.bind, frames, meta);\n if (isPlainObject(raw.map)) {\n // The resolved value SELECTS a key; every emitted character\n // is an author-written literal. A miss falls to `default`,\n // or empty \u2014 an unanticipated status degrades, never breaks.\n const key = formatValue(resolved);\n const hit = Object.prototype.hasOwnProperty.call(raw.map, key)\n ? raw.map[key]\n : undefined;\n value =\n typeof hit === \"string\"\n ? hit\n : typeof raw.default === \"string\"\n ? raw.default\n : \"\";\n } else if (typeof raw.prefix === \"string\") {\n // The prefix is never emitted alone: no dead mailto: hrefs.\n // The composed value still faces the URL guard below.\n const text = formatValue(resolved);\n value = text === \"\" ? \"\" : raw.prefix + text;\n } else if (raw.format !== undefined) {\n // Formats produce TEXT; a URL attribute's scheme guard still\n // runs below, so a format can never build a scheme.\n value = formatBoundValue(resolved, raw.format);\n } else {\n value = formatValue(resolved);\n }\n }\n if (value === undefined) continue;\n const lower = name.toLowerCase();\n if (URL_ATTRS.has(lower)) {\n // Image sources additionally accept data:image/*; every other\n // URL attribute keeps the strict scheme set (data-URI\n // navigation is an XSS vector; data-URI images are not).\n const imageContext = lower === \"src\" && node.tag.toLowerCase() === \"img\";\n const allowed =\n isSafeUrl(value) || (imageContext && isSafeImageSrc(value));\n if (!allowed) continue;\n }\n attrs[name] = value;\n }\n }\n if (isPlainObject(node.action)) {\n attrs[\"data-wg-action\"] = JSON.stringify(\n buildDescriptor(node.action as ActionBinding, tpath, frames, meta, ctx)\n );\n }\n const children = Array.isArray(node.children)\n ? node.children.flatMap((child, i) =>\n interpretNode(child, frames, meta, budget, join(tpath, `children.${i}`), ctx)\n )\n : [];\n const element: WidgetElementNode = { tag: node.tag };\n if (Object.keys(attrs).length > 0) element.attrs = attrs;\n if (children.length > 0) element.children = children;\n return [element];\n }\n\n return [];\n}\n\n/** Count the nodes a template's STRUCTURE contains (not its output). */\nexport function countTemplateNodes(template: unknown): number {\n if (typeof template === \"string\") return 1;\n if (!isPlainObject(template)) return 0;\n if (typeof template.bind === \"string\") return 1;\n let total = 1;\n for (const key of [\"template\", \"empty\", \"else\"] as const) {\n if (template[key] !== undefined) total += countTemplateNodes(template[key]);\n }\n if (Array.isArray(template.children)) {\n for (const child of template.children) total += countTemplateNodes(child);\n }\n return total;\n}\n\nexport interface CompileOptions {\n /** Node budget for one render (default {@link DEFAULT_MAX_NODES}). */\n maxNodes?: number;\n /**\n * Resolve `{ ref }` action bindings to their definitions (the\n * principal's shared actions). Unresolvable refs render disabled.\n */\n actions?: (ref: string) => ActionDefinition | undefined;\n /**\n * Render every http action disabled with this reason \u2014 the server sets\n * `\"scope\"` when the caller's key cannot execute.\n */\n httpDisabled?: ActionDisabledReason;\n /** The kind this template is registered as \u2014 stamped into descriptors. */\n kind?: string;\n}\n\n/**\n * Compile a template into an ordinary widget renderer. The renderer is pure\n * and total; when the root interprets to anything other than exactly one\n * node, the output is wrapped in a `div.wg-template`. Renders are bounded\n * by a node budget \u2014 an exhausted budget stops interpretation and marks\n * the output with `data-truncated`, so the outcome is visible rather than\n * silently short.\n */\nexport function compileTemplate(\n template: WidgetTemplate,\n options: CompileOptions = {}\n): WidgetRenderer {\n const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;\n const ctx: ActionContext = options;\n return (payload: WidgetPayload): WidgetNode => {\n const budget: Budget = { remaining: maxNodes, truncated: false };\n const frames: Frame[] = [{ scope: payload.data }];\n const nodes = interpretNode(template, frames, payload.meta, budget, \"\", ctx);\n if (!budget.truncated && nodes.length === 1) {\n const only = nodes[0];\n if (only !== undefined) return only;\n }\n const attrs: WidgetNodeAttrs = { class: \"wg-template\" };\n if (budget.truncated) attrs[\"data-truncated\"] = \"true\";\n return { tag: \"div\", attrs, children: nodes };\n };\n}\n\n/**\n * Resolve a binding outside the tree \u2014 the widget-level `load` binding,\n * whose descriptor rides `structuredContent.load` rather than an element.\n * Resolved against the payload's root scope.\n */\nexport function resolveActionDescriptor(\n binding: ActionBinding,\n id: string,\n payload: WidgetPayload,\n options: Pick<CompileOptions, \"actions\" | \"httpDisabled\" | \"kind\"> = {}\n): ActionDescriptor {\n const ctx: ActionContext = options;\n return buildDescriptor(binding, id, [{ scope: payload.data }], payload.meta, ctx);\n}\n\n/**\n * Validate, compile, and register a template as a widget kind. Throws\n * {@link InvalidTemplateError} on invalid templates and the catalog's\n * `DuplicateKindError` on duplicate kinds \u2014 registration is host setup.\n */\nexport function registerTemplate(\n catalog: WidgetCatalog,\n kind: string,\n template: unknown,\n descriptor?: WidgetDescriptorInput,\n options?: CompileOptions\n): void {\n const validated = validateTemplate(template);\n if (!validated.ok) {\n throw new InvalidTemplateError(kind, validated.error);\n }\n catalog.register(kind, compileTemplate(validated.template, { ...options, kind }), descriptor);\n}\n", "import type { WidgetNode } from \"../catalog/index.js\";\n\n/**\n * Materialize a render tree as fresh DOM. Text becomes text nodes (no HTML\n * parsing), matching the catalog DOM layer's safety discipline. Private to\n * the reactive module \u2014 the catalog's builder stays private to its own.\n */\nexport function buildDom(node: WidgetNode, doc: Document): Node {\n if (typeof node === \"string\") return doc.createTextNode(node);\n const element = doc.createElement(node.tag);\n if (node.attrs) {\n for (const [name, value] of Object.entries(node.attrs)) {\n element.setAttribute(name, value);\n }\n }\n if (node.children) {\n for (const child of node.children) {\n element.appendChild(buildDom(child, doc));\n }\n }\n return element;\n}\n", "import type { WidgetElementNode, WidgetNode } from \"../catalog/index.js\";\nimport { buildDom } from \"./build.js\";\n\n/**\n * Patch `dom` in place so it reflects `next`, given that it currently\n * reflects `prev`. Returns the node now representing `next` \u2014 the same node\n * when patched in place, a freshly built replacement when the shape (tag or\n * node type) changed. Identity is preserved wherever shape matches. Sibling\n * lists pair by `key` when every child of both lists is a uniquely keyed\n * element \u2014 existing nodes MOVE with their record \u2014 and by position\n * otherwise. The app template's inline patcher implements the same rule.\n */\nexport function patchNode(prev: WidgetNode, next: WidgetNode, dom: Node): Node {\n if (typeof prev === \"string\" && typeof next === \"string\") {\n if (prev !== next) dom.nodeValue = next;\n return dom;\n }\n if (\n typeof prev !== \"string\" &&\n typeof next !== \"string\" &&\n prev.tag === next.tag &&\n dom.nodeType === 1\n ) {\n patchElement(prev, next, dom as Element);\n return dom;\n }\n // Shape changed: replace only this subtree.\n const doc = dom.ownerDocument;\n if (!doc || !dom.parentNode) return dom;\n const replacement = buildDom(next, doc);\n dom.parentNode.replaceChild(replacement, dom);\n return replacement;\n}\n\nfunction patchElement(\n prev: WidgetElementNode,\n next: WidgetElementNode,\n element: Element\n): void {\n const prevAttrs = prev.attrs ?? {};\n const nextAttrs = next.attrs ?? {};\n for (const [name, value] of Object.entries(nextAttrs)) {\n if (prevAttrs[name] !== value) element.setAttribute(name, value);\n }\n for (const name of Object.keys(prevAttrs)) {\n if (!(name in nextAttrs)) element.removeAttribute(name);\n }\n patchChildren(prev.children ?? [], next.children ?? [], element);\n}\n\n/**\n * Key \u2192 index for a list in which every child is an element with a unique\n * key; `undefined` for any other list (text child, unkeyed element,\n * duplicate key), which then pairs by position.\n */\nfunction keyIndex(list: readonly WidgetNode[]): Map<string, number> | undefined {\n const index = new Map<string, number>();\n for (let i = 0; i < list.length; i++) {\n const node = list[i];\n if (node === undefined || typeof node === \"string\" || typeof node.key !== \"string\") {\n return undefined;\n }\n if (index.has(node.key)) return undefined;\n index.set(node.key, i);\n }\n return index;\n}\n\nfunction patchKeyed(\n prev: readonly WidgetNode[],\n next: readonly WidgetElementNode[],\n prevIndex: Map<string, number>,\n domChildren: readonly Node[],\n element: Element\n): void {\n const doc = element.ownerDocument;\n const kept = new Set<number>();\n const placed = next.map((child) => {\n const i = child.key === undefined ? undefined : prevIndex.get(child.key);\n const prevChild = i === undefined ? undefined : prev[i];\n const dom = i === undefined ? undefined : domChildren[i];\n if (i === undefined || prevChild === undefined || dom === undefined) {\n return buildDom(child, doc);\n }\n kept.add(i);\n return patchNode(prevChild, child, dom);\n });\n domChildren.forEach((dom, i) => {\n if (!kept.has(i) && dom.parentNode === element) element.removeChild(dom);\n });\n // Moving a node keeps its state (a visitor's `open`); only misplaced\n // nodes are touched.\n placed.forEach((dom, i) => {\n const at = element.childNodes[i] ?? null;\n if (dom !== at) element.insertBefore(dom, at);\n });\n}\n\nfunction patchChildren(\n prev: readonly WidgetNode[],\n next: readonly WidgetNode[],\n element: Element\n): void {\n const doc = element.ownerDocument;\n // Snapshot: childNodes is live and patchNode may replace entries.\n const domChildren: Node[] = [];\n for (let i = 0; i < element.childNodes.length; i++) {\n const child = element.childNodes[i];\n if (child) domChildren.push(child);\n }\n\n const prevIndex = keyIndex(prev);\n if (prevIndex !== undefined && keyIndex(next) !== undefined) {\n const elements = next.filter((child): child is WidgetElementNode => typeof child !== \"string\");\n patchKeyed(prev, elements, prevIndex, domChildren, element);\n return;\n }\n\n const shared = Math.min(prev.length, next.length);\n for (let i = 0; i < shared; i++) {\n const prevChild = prev[i];\n const nextChild = next[i];\n const childDom = domChildren[i];\n if (prevChild === undefined || nextChild === undefined) continue;\n if (childDom) {\n patchNode(prevChild, nextChild, childDom);\n } else {\n element.appendChild(buildDom(nextChild, doc));\n }\n }\n for (let i = shared; i < next.length; i++) {\n const extra = next[i];\n if (extra !== undefined) element.appendChild(buildDom(extra, doc));\n }\n for (let i = prev.length - 1; i >= shared; i--) {\n const surplus = domChildren[i];\n if (surplus) element.removeChild(surplus);\n }\n}\n", "import type { WidgetCatalog, WidgetNode } from \"../catalog/index.js\";\nimport { createCatalog } from \"../catalog/index.js\";\nimport type { WidgetContractError } from \"../contract/index.js\";\nimport type { ActionDescriptor } from \"../actions/index.js\";\nimport { buildDom } from \"./build.js\";\nimport { patchNode } from \"./diff.js\";\n\n/** Outcome of a mount or update. Failures leave the DOM untouched. */\nexport type UpdateResult =\n | { ok: true }\n | { ok: false; error: WidgetContractError };\n\n/** An activated element's descriptor, handed to the host untouched. */\nexport type ActionActivation = ActionDescriptor;\n\nexport interface MountOptions {\n /**\n * Catalog used for validation and rendering. Defaults to a fresh\n * `createCatalog()` per mount; pass a shared instance to render custom\n * registered kinds.\n */\n catalog?: WidgetCatalog;\n /**\n * Receives activations of mounted `[data-wg-action]` elements (click, or\n * Enter/Space on non-button hosts) with the parsed descriptor and the\n * currently mounted payload; the default action is prevented. Without\n * it, action elements are inert \u2014 the mount never executes anything.\n */\n onAction?: (activation: ActionActivation, payload: unknown) => void;\n}\n\nexport interface WidgetMount {\n /** Outcome of the initial render performed by `mountWidget`. */\n readonly initial: UpdateResult;\n /**\n * Re-render with a new payload, patching the DOM in place. Returns a\n * structured error (DOM untouched) for invalid payloads. Throws if the\n * mount was disposed \u2014 that is a host programming error.\n */\n update(payload: unknown): UpdateResult;\n /** Currently rendered tree (`undefined` before the first successful render). */\n node(): WidgetNode | undefined;\n /** Empty the container and end this mount. Idempotent. */\n dispose(): void;\n}\n\n/**\n * Mount a widget payload into `container` and keep updating it in place.\n * The first render is just an internal `update`; its outcome is exposed as\n * `initial`, so a failed first payload does not cost the caller the handle.\n */\nexport function mountWidget(\n payload: unknown,\n container: Element,\n options: MountOptions = {}\n): WidgetMount {\n const catalog = options.catalog ?? createCatalog();\n let current: WidgetNode | undefined;\n let root: Node | undefined;\n let disposed = false;\n let mountedPayload: unknown;\n\n // Delegated on the container: descriptors are data the host decides\n // about \u2014 this layer only parses and forwards them.\n const onAction = options.onAction;\n function parseDescriptor(el: Element): ActionDescriptor | undefined {\n try {\n const parsed = JSON.parse(el.getAttribute(\"data-wg-action\") ?? \"\") as unknown;\n if (typeof parsed === \"object\" && parsed !== null && typeof (parsed as { id?: unknown }).id === \"string\") {\n return parsed as ActionDescriptor;\n }\n } catch {\n /* malformed descriptor: inert */\n }\n return undefined;\n }\n function activation(event: Event): void {\n const target = event.target as Element | null;\n const el = target?.closest?.(\"[data-wg-action]\");\n if (!el || !container.contains(el)) return;\n if (event.type === \"keydown\") {\n const key = (event as KeyboardEvent).key;\n if (key !== \"Enter\" && key !== \" \") return;\n if (el.tagName === \"BUTTON\" || el.tagName === \"A\") return; // native keyboard \u2192 click\n }\n event.preventDefault();\n if (onAction === undefined) return;\n const descriptor = parseDescriptor(el);\n if (descriptor !== undefined) onAction(descriptor, mountedPayload);\n }\n container.addEventListener(\"click\", activation);\n container.addEventListener(\"keydown\", activation);\n\n function update(nextPayload: unknown): UpdateResult {\n if (disposed) {\n throw new Error(\n \"Widget mount is disposed; create a new mount instead of updating.\"\n );\n }\n const rendered = catalog.render(nextPayload);\n if (!rendered.ok) return rendered;\n\n if (current === undefined || root === undefined) {\n const built = buildDom(rendered.node, container.ownerDocument);\n container.replaceChildren(built);\n root = built;\n } else {\n root = patchNode(current, rendered.node, root);\n }\n current = rendered.node;\n mountedPayload = nextPayload;\n return { ok: true };\n }\n\n function dispose(): void {\n if (disposed) return;\n disposed = true;\n container.removeEventListener(\"click\", activation);\n container.removeEventListener(\"keydown\", activation);\n container.replaceChildren();\n current = undefined;\n root = undefined;\n mountedPayload = undefined;\n }\n\n return {\n initial: update(payload),\n update,\n node: () => current,\n dispose\n };\n}\n", "/**\n * The chrome tokens and the palettes painted through them.\n *\n * `CHROME_DEFAULTS` is not a description of the defaults \u2014 it IS them: the\n * injected stylesheet's token blocks are generated from this object, so a host\n * that paints its own surfaces from the export cannot drift from the\n * designers. There is deliberately no second palette to fall back to: a host\n * that wants a different look passes its own values through `chrome`, and\n * `chromeCss` renders whatever palette it hands back.\n *\n * Colours and shape carry the product's identity. Typography does not: a\n * library must never default to a webfont it cannot serve, so `font`,\n * `font-mono` and the three sizes stay system values in both palettes and a\n * host with its own typeface passes it through `chrome`.\n */\n\n/**\n * The chrome tokens \u2014 every `--wgd-<token>` the stylesheet paints with.\n * Colours (18) differ between the schemes; typography, shape and shadow are\n * declared per scheme too so each palette stands alone. Public API: a rename\n * is a spec change.\n */\nexport const CHROME_TOKENS = [\n \"bg\", \"panel\", \"border\", \"line\", \"text\", \"muted\",\n \"accent\", \"accent-bg\", \"accent-line\",\n \"danger\", \"danger-bg\", \"danger-line\", \"hover\",\n \"hl-key\", \"hl-str\", \"hl-num\", \"hl-bool\", \"hl-punct\",\n \"font\", \"font-mono\", \"font-size\", \"font-size-sm\", \"font-size-xs\",\n \"radius-sm\", \"radius\", \"radius-lg\", \"gap\", \"shadow\"\n] as const;\n\nexport type ChromeToken = (typeof CHROME_TOKENS)[number];\n\n/** A host's partial chrome: token \u2192 CSS value (`var()` references welcome). */\nexport type ChromeOptions = Partial<Record<ChromeToken, string>>;\n\n/** Every token valued \u2014 what a palette is. */\nexport type ChromeScheme = Record<ChromeToken, string>;\n\n/** A complete palette: both schemes, every token. */\nexport interface ChromePalette {\n light: ChromeScheme;\n dark: ChromeScheme;\n}\n\n/** Shared by both palettes: see the module header on why typography is not branded. */\nconst TYPOGRAPHY = {\n font: \"system-ui, sans-serif\",\n \"font-mono\": \"ui-monospace, monospace\",\n \"font-size\": \"13px\",\n \"font-size-sm\": \"12px\",\n \"font-size-xs\": \"11px\"\n} as const;\n\n/**\n * The widgentic palette \u2014 what the designers render with when a host passes\n * no `chrome`, and what a host paints its own page with to match them.\n *\n * Every colour sits on the logo mark's own hue (197.6deg, from `#40a0c8`).\n * Surfaces, text and accents come from the product's existing palette;\n * `border`, `accent-line` and `danger-line` are DERIVED, not chosen: each is\n * the lightest value on that hue which still clears 3:1 against the surface\n * it sits on, because those edges are what identifies a control, a focused tag\n * and a banner. Minimum weight that complies, so nothing is heavier than\n * accessibility requires. See chrome-contrast.test.ts for the gate.\n */\nexport const CHROME_DEFAULTS: ChromePalette = {\n light: {\n bg: \"#f6fafc\", panel: \"#ffffff\", border: \"#6e95a6\",\n line: \"#e4ecf2\", text: \"#0b1b26\", muted: \"#56707f\",\n accent: \"#1e6f92\", \"accent-bg\": \"#e3f1f7\", \"accent-line\": \"#4b91ae\",\n danger: \"#b42318\", \"danger-bg\": \"#fdf2f2\", \"danger-line\": \"#c97572\",\n hover: \"#eef5f9\",\n \"hl-key\": \"#1e6f92\", \"hl-str\": \"#2e7d5b\", \"hl-num\": \"#96620f\",\n \"hl-bool\": \"#7a4fbf\", \"hl-punct\": \"#56707f\",\n ...TYPOGRAPHY,\n \"radius-sm\": \"4px\", radius: \"6px\", \"radius-lg\": \"8px\", gap: \"16px\",\n shadow: \"0 8px 24px -12px rgba(11, 27, 38, 0.35)\"\n },\n dark: {\n bg: \"#0b141b\", panel: \"#10202a\", border: \"#437082\",\n line: \"#1b2f3d\", text: \"#e6f0f5\", muted: \"#93a9b6\",\n accent: \"#8acbe6\", \"accent-bg\": \"#14303d\", \"accent-line\": \"#3e7e98\",\n danger: \"#f0a3a3\", \"danger-bg\": \"#2a1a1c\", \"danger-line\": \"#a3524f\",\n hover: \"#152a36\",\n \"hl-key\": \"#8acbe6\", \"hl-str\": \"#6cc79a\", \"hl-num\": \"#e0b25a\",\n \"hl-bool\": \"#bb9af7\", \"hl-punct\": \"#93a9b6\",\n ...TYPOGRAPHY,\n \"radius-sm\": \"4px\", radius: \"6px\", \"radius-lg\": \"8px\", gap: \"16px\",\n shadow: \"0 8px 24px -12px rgba(0, 0, 0, 0.7)\"\n }\n};\n\nexport interface ChromeCssOptions {\n /** Custom-property prefix, dashes included. Default `--wgd`. */\n prefix?: string;\n /** Selector the light block is written under. Default `:root`. */\n selector?: string;\n /** Selector for the dark block inside `prefers-color-scheme: dark`; defaults to `selector`. */\n darkMediaSelector?: string;\n /** Optional selector for an unconditional dark block \u2014 an explicit host toggle. */\n darkSelector?: string;\n}\n\nfunction declarations(scheme: ChromeScheme, prefix: string, indent: string): string {\n return CHROME_TOKENS.map((token) => `${indent}${prefix}-${token}: ${scheme[token]};`).join(\"\\n\");\n}\n\n/**\n * Render a palette as CSS declaration blocks \u2014 the light values under\n * `selector`, the dark values under `prefers-color-scheme: dark`, and\n * optionally under an explicit selector a host toggles. Every token is\n * declared in every block, so nothing falls back to a browser value.\n *\n * A string builder, deliberately: no injection, no runtime, no dependency.\n * The designers' own stylesheet is built with it, and so is a host page that\n * wants its surfaces to match them.\n */\nexport function chromeCss(palette: ChromePalette, options: ChromeCssOptions = {}): string {\n const prefix = options.prefix ?? \"--wgd\";\n const selector = options.selector ?? \":root\";\n const darkMediaSelector = options.darkMediaSelector ?? selector;\n const blocks = [\n `${selector} {\\n${declarations(palette.light, prefix, \" \")}\\n}`,\n `@media (prefers-color-scheme: dark) {\\n ${darkMediaSelector} {\\n${declarations(palette.dark, prefix, \" \")}\\n }\\n}`\n ];\n if (options.darkSelector !== undefined) {\n blocks.push(`${options.darkSelector} {\\n${declarations(palette.dark, prefix, \" \")}\\n}`);\n }\n return blocks.join(\"\\n\");\n}\n\n/**\n * The full `chrome` map of `var()` references to a host page's own\n * properties under `prefix` \u2014 the other half of `chromeCss`: paint the page\n * with the derived palette, hand the designers these references, and the\n * two match by construction. Because inline `var()` resolves at the host,\n * the page's scheme handling (an explicit toggle included) reaches MOUNTED\n * designers through the cascade \u2014 no remount, no event, no API.\n *\n * A reference to a property the page never defines is invalid at\n * computed-value time; it does NOT fall back to the built-in defaults, so\n * always pair this map with `chromeCss` under the same prefix. Override\n * individual entries by spreading: `{ ...chromeReferences(), font: \"...\" }`.\n */\nexport function chromeReferences(prefix = \"--host\"): Record<ChromeToken, string> {\n return Object.fromEntries(\n CHROME_TOKENS.map((token) => [token, `var(${prefix}-${token})`])\n ) as Record<ChromeToken, string>;\n}\n\n", "/**\n * Tiny DOM helpers for the designer chrome \u2014 the same hand-rolled\n * discipline as the rest of the project, sized for form-heavy panels.\n * Designer chrome classes are prefixed `wgd-` (widget content inside the\n * preview keeps the normal `wg-` classes).\n */\nimport { CHROME_DEFAULTS, CHROME_TOKENS, chromeCss } from \"./chrome-defaults.js\";\nimport type { ChromeOptions } from \"./chrome-defaults.js\";\n\nexport type Child = Node | string;\n\n/** The first `<selector>` under `parent`, which the caller's own markup guarantees exists. */\nexport function requireChild<K extends keyof HTMLElementTagNameMap>(\n parent: ParentNode,\n selector: K\n): HTMLElementTagNameMap[K] {\n const found = parent.querySelector(selector);\n if (found === null) throw new Error(`Designer chrome is missing a <${selector}> element.`);\n return found;\n}\n\nexport function h<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attrs?: Record<string, string>,\n children?: Child[]\n): HTMLElementTagNameMap[K];\nexport function h(tag: string, attrs?: Record<string, string>, children?: Child[]): HTMLElement;\nexport function h(tag: string, attrs?: Record<string, string>, children?: Child[]): HTMLElement {\n const element = document.createElement(tag);\n if (attrs) {\n for (const [name, value] of Object.entries(attrs)) {\n element.setAttribute(name, value);\n }\n }\n if (children) {\n for (const child of children) {\n element.append(child);\n }\n }\n return element;\n}\n\n/** Labeled single-line input bound through a callback. */\nexport function textField(\n label: string,\n value: string,\n onInput: (value: string) => void\n): HTMLElement {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n input.value = value;\n input.addEventListener(\"input\", () => onInput(input.value));\n return h(\"label\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [label]),\n input\n ]);\n}\n\n/** Labeled multi-line textarea bound through a callback. */\nexport function textArea(\n label: string,\n value: string,\n onInput: (value: string) => void,\n rows = 6\n): HTMLElement {\n const area = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: String(rows),\n spellcheck: \"false\"\n });\n area.value = value;\n area.addEventListener(\"input\", () => onInput(area.value));\n // An empty label means the surrounding chrome already names the field \u2014\n // no legend row.\n return h(\"label\", { class: \"wgd-field\" }, [\n ...(label === \"\" ? [] : [h(\"span\", { class: \"wgd-field-label\" }, [label])]),\n area\n ]);\n}\n\n/** Collapsible titled section (open by default). */\nexport function section(title: string, children: Child[], open = true): HTMLElement {\n const attrs: Record<string, string> = { class: \"wgd-section\" };\n if (open) attrs.open = \"\";\n return h(\"details\", attrs, [\n h(\"summary\", { class: \"wgd-section-title\" }, [title]),\n h(\"div\", { class: \"wgd-section-body\" }, children)\n ]);\n}\n\n/**\n * Size a select to its SELECTED label (a bare <select> sizes to its\n * widest option, or to whatever flex hands it), so the caret sits beside\n * the text instead of drifting with leftover row width. ch tracks\n * monospace text exactly; the em term scales with padding, and the px\n * term covers the UA's caret region, which does NOT scale with font size\n * (11px selects clip under a pure em term). Re-fits on change.\n */\n/** A fitted select over `options`: value set, width fitted, `onChange` on change. */\nexport function select(\n options: { value: string; label?: string }[],\n value: string,\n className: string,\n onChange: (value: string) => void,\n title?: string\n): HTMLSelectElement {\n const el = h(\"select\", { class: className, ...(title === undefined ? {} : { title }) });\n for (const option of options) el.append(h(\"option\", { value: option.value }, [option.label ?? option.value]));\n el.value = value;\n fitSelect(el);\n el.addEventListener(\"change\", () => onChange(el.value));\n return el;\n}\n\nexport function fitSelect(select: HTMLSelectElement): void {\n const fit = (): void => {\n const label = select.options[select.selectedIndex]?.text ?? select.value;\n select.style.width = `calc(${Math.max(label.length, 1)}ch + 1.2em + 18px)`;\n };\n fit();\n select.addEventListener(\"change\", fit);\n}\n\n/**\n * Compact add-menu: one toggle button revealing the options on demand \u2014\n * the tree stays calm instead of carrying a button per option at every\n * level. Closes on pick, outside pointer-down, or Escape.\n */\nexport function menuButton(\n label: string,\n title: string,\n options: string[],\n onPick: (option: string) => void\n): HTMLElement {\n const wrap = h(\"span\", { class: \"wgd-menuwrap\" });\n const toggle = h(\n \"button\",\n { class: \"wgd-icon wgd-menu-toggle\", type: \"button\", title },\n [label]\n );\n const menu = h(\"div\", { class: \"wgd-menu\" });\n menu.hidden = true;\n\n const close = (): void => {\n menu.hidden = true;\n document.removeEventListener(\"pointerdown\", onOutside, true);\n document.removeEventListener(\"keydown\", onKey, true);\n };\n const onOutside = (event: Event): void => {\n if (!wrap.contains(event.target as Node)) close();\n };\n const onKey = (event: KeyboardEvent): void => {\n if (event.key === \"Escape\") close();\n };\n\n toggle.addEventListener(\"click\", () => {\n if (!menu.hidden) {\n close();\n return;\n }\n menu.hidden = false;\n document.addEventListener(\"pointerdown\", onOutside, true);\n document.addEventListener(\"keydown\", onKey, true);\n });\n for (const option of options) {\n const item = h(\n \"button\",\n { class: \"wgd-menu-item\", type: \"button\" },\n [option]\n );\n item.addEventListener(\"click\", () => {\n close();\n onPick(option);\n });\n menu.append(item);\n }\n wrap.append(toggle, menu);\n return wrap;\n}\n\n/** Inline diagnostic line (empty text removes it from the flow). */\nexport function diagnosticLine(text: string | undefined): HTMLElement {\n const el = h(\"div\", { class: \"wgd-diagnostic\" }, text === undefined ? [] : [text]);\n if (text === undefined) el.setAttribute(\"hidden\", \"\");\n return el;\n}\n\n// The token list and the palettes live in chrome-defaults.ts, which the\n// stylesheet below is generated from; re-exported here so the modules that\n// already import chrome types from this one keep working.\nexport { CHROME_TOKENS } from \"./chrome-defaults.js\";\nexport type { ChromeOptions, ChromeToken } from \"./chrome-defaults.js\";\n\nconst CHROME_TOKEN_SET: ReadonlySet<string> = new Set<string>(CHROME_TOKENS);\n\n// On a custom property a CSS-wide keyword acts on the property itself (it\n// inherits/resets the TOKEN, not the consumer), so it never expresses what\n// a host means by it; hosts pass `var(--their-token, fallback)` instead.\nconst CSS_WIDE_KEYWORD = /^(inherit|initial|unset|revert|revert-layer)$/i;\n\n/**\n * Apply a host's chrome on a designer root as inline custom properties \u2014\n * the style attribute outranks every rule in the injected stylesheet, so\n * the host's values win over the light/dark defaults. Unknown tokens,\n * non-string values and CSS-wide keywords are ignored at the door.\n */\nexport function applyChrome(root: HTMLElement, chrome: ChromeOptions | undefined): void {\n if (chrome === undefined) return;\n for (const [token, value] of Object.entries(chrome)) {\n if (!CHROME_TOKEN_SET.has(token)) continue;\n if (typeof value !== \"string\" || CSS_WIDE_KEYWORD.test(value.trim())) continue;\n root.style.setProperty(`--wgd-${token}`, value);\n }\n}\n\n/** The element form of the option: a `chrome` attribute holding JSON; anything else \u2192 nothing. */\nexport function parseChromeAttribute(value: string | null): ChromeOptions | undefined {\n if (value === null) return undefined;\n try {\n const parsed: unknown = JSON.parse(value);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return parsed as ChromeOptions;\n } catch {\n return undefined;\n }\n}\n\nconst STYLE_MARKER = \"data-widgentic-designer\";\n\n/** Designer chrome stylesheet \u2014 injected once per document. */\nexport function injectDesignerStyles(doc: Document): void {\n if (doc.head.querySelector(`style[${STYLE_MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(STYLE_MARKER, \"chrome\");\n style.textContent = `\n/* Chrome tokens (CHROME_TOKENS), generated from CHROME_DEFAULTS so the\n exported palette IS the applied one. A host overrides any of them through\n options.chrome (inline on the root, which outranks these rules). Widget\n content inside the preview keeps its own --wg-* theme tokens. */\n${chromeCss(CHROME_DEFAULTS, {\n selector: \".wgd-root\",\n darkMediaSelector: '.wgd-root:not([data-wgd-theme=\"light\"])',\n darkSelector: '.wgd-root[data-wgd-theme=\"dark\"]'\n})}\n.wgd-root { display: flex; gap: var(--wgd-gap); font-family: var(--wgd-font); font-size: var(--wgd-font-size); align-items: flex-start; color: var(--wgd-text); background: var(--wgd-bg); }\n/* Any chrome class that sets display would silently defeat the hidden\n attribute (learned live twice: the add menu, then the styles tree as a\n tab pane). hidden always wins \u2014 scoped to the designer's own tree. */\n.wgd-root [hidden] { display: none !important; }\n/* Read-only: editing surfaces are inert (visible, inoperable) and read\n de-emphasized; the preview and its selectors stay full-strength. The\n controls flatten into plain values \u2014 a form that cannot be typed in\n should not look like a form (opacity alone was invisible on dark). */\n.wgd-readonly .wgd-section-body[inert] { opacity: 0.75; }\n/* Empty preview state \u2014 shown only when there has never been a valid\n render to freeze on; a blank pane is the one state the contract bans. */\n.wgd-preview-empty { color: var(--wgd-muted); font-style: italic; font-size: var(--wgd-font-size-sm); }\n.wgd-readonly [inert] .wgd-input,\n.wgd-readonly [inert] .wgd-select,\n.wgd-readonly [inert] .wgd-textarea,\n.wgd-readonly [inert] textarea.wgd-hl-input {\n border-color: transparent; background: transparent; box-shadow: none;\n}\n.wgd-readonly [inert] .wgd-hl { background: transparent; }\n/* Controls that only exist to mutate carry no meaning here. */\n.wgd-readonly [inert] .wgd-button,\n.wgd-readonly [inert] .wgd-icon,\n.wgd-readonly [inert] .wgd-add,\n.wgd-readonly [inert] input[type=\"checkbox\"] { opacity: 0.4; }\n.wgd-panels { flex: 1 1 460px; min-width: 340px; display: flex; flex-direction: column; gap: 8px; }\n.wgd-side { flex: 1 1 420px; min-width: 320px; display: flex; flex-direction: column; gap: 8px; position: sticky; top: 8px; }\n.wgd-preview-pane { display: flex; flex-direction: column; gap: 8px; }\n.wgd-section { border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-lg); padding: 6px 10px; background: var(--wgd-panel); }\n.wgd-section-title { cursor: pointer; font-weight: 600; }\n.wgd-section-body { display: flex; flex-direction: column; gap: 8px; padding-top: 8px; }\n.wgd-field { display: flex; flex-direction: column; gap: 2px; }\n.wgd-field-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-sm); }\n.wgd-input, .wgd-textarea, .wgd-select { font: inherit; padding: 4px 6px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: var(--wgd-bg); color: var(--wgd-text); }\n/* Textareas fill their panel regardless of the intrinsic cols width. */\n.wgd-textarea { font-family: var(--wgd-font-mono); white-space: pre; width: 100%; box-sizing: border-box; min-width: 0; resize: vertical; }\n.wgd-preview .wg-designer-action { position: relative; outline: 1px dashed var(--wgd-muted); outline-offset: 2px; }\n.wgd-preview .wg-designer-action::after { content: \"\u26A1 action\"; position: absolute; top: -0.9em; right: 0; font: calc(var(--wgd-font-size-xs) - 1px) var(--wgd-font); color: var(--wgd-muted); background: var(--wgd-panel); padding: 0 4px; border-radius: var(--wgd-radius-sm); pointer-events: none; }\n.wgd-binding { display: flex; flex-direction: column; gap: 6px; padding: 6px 8px; border: 1px dashed var(--wgd-border); border-radius: var(--wgd-radius); margin: 4px 0; }\n.wgd-binding-field { min-width: 8ch; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-sm); }\n.wgd-action-definition { display: flex; flex-direction: column; gap: 6px; }\n.wgd-action-schema { display: flex; flex-direction: column; gap: 4px; padding: 4px 0; }\n.wgd-test-output { font: var(--wgd-font-size-sm) var(--wgd-font-mono); white-space: pre-wrap; word-break: break-all; max-height: 240px; overflow: auto; margin: 6px 0 0; }\n.wgd-diagnostic { color: var(--wgd-danger); font-size: var(--wgd-font-size-sm); white-space: pre-wrap; }\n.wgd-banner { border: 1px solid var(--wgd-danger-line); background: var(--wgd-danger-bg); color: var(--wgd-danger); border-radius: var(--wgd-radius-lg); padding: 8px 10px; margin-bottom: 8px; }\n/* The preview is the WIDGET's surface, not chrome: it establishes the\n --wg-* context (like composePage does for page output) so widget content\n \u2014 including custom kinds the base stylesheet doesn't color \u2014 never\n inherits the designer's own text/background. */\n.wgd-preview { border: 1px dashed var(--wgd-border); border-radius: var(--wgd-radius-lg); padding: 16px; background: var(--wg-bg); color: var(--wg-fg); }\n.wgd-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }\n.wgd-button { font: inherit; padding: 4px 10px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: var(--wgd-bg); color: var(--wgd-text); cursor: pointer; }\n.wgd-button:hover { background: var(--wgd-hover); }\n.wgd-tab-active { background: var(--wgd-accent-bg); border-color: var(--wgd-accent); }\n/* Shared tree/editor chrome (JSON tree, schema builder/form, template tree) */\n.wgd-jt-children, .wgd-children { margin-left: 10px; padding-left: 10px; border-left: 2px solid var(--wgd-line); display: flex; flex-direction: column; gap: 4px; }\n.wgd-jt-row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }\n.wgd-jt-entry { padding: 2px 0; }\n.wgd-jt-key { font-family: var(--wgd-font-mono); color: var(--wgd-muted); min-width: 2ch; }\n.wgd-jt-keyinput, .wgd-jt-type { max-width: 12ch; }\n.wgd-jt-summary { cursor: pointer; color: var(--wgd-muted); font-size: var(--wgd-font-size-sm); }\n.wgd-sf-object { border: 1px solid var(--wgd-line); border-radius: var(--wgd-radius-lg); padding: 6px 10px; margin: 4px 0; }\n/* Schema builder: property name + type + required on one row. */\n.wgd-sb-node { margin-left: 8px; padding: 1px 0 1px 8px; border-left: 2px solid var(--wgd-line); }\n.wgd-sb-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 1px 0; }\n.wgd-sb-constraints { padding-left: 12px; }\n.wgd-sb-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n.wgd-sb-prop { flex: 1 1 auto; min-width: 6ch; font-family: var(--wgd-font-mono); }\n.wgd-sb-type { flex: 0 0 auto; max-width: 11ch; font-size: var(--wgd-font-size-sm); }\n.wgd-sb-req { display: flex; gap: 2px; align-items: center; color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n.wgd-sb-constraint { flex: 1 1 auto; min-width: 6ch; font-size: var(--wgd-font-size-sm); }\n.wgd-sb-root { padding: 2px 0 2px 8px; border-left: 2px solid transparent; }\n/* Schema builder: the template tree's flat discipline \u2014 chrome on\n hover/focus only, removal revealed by the row, fitted type selects. */\n.wgd-schemabuilder .wgd-input, .wgd-schemabuilder .wgd-select { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-schemabuilder .wgd-input:hover, .wgd-schemabuilder .wgd-select:hover,\n.wgd-schemabuilder .wgd-input:focus, .wgd-schemabuilder .wgd-select:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-schemabuilder .wgd-sb-type { flex: 0 0 auto; box-sizing: border-box; max-width: none; color: var(--wgd-accent); }\n.wgd-schemabuilder .wgd-sb-prop { font-size: var(--wgd-font-size-sm); color: var(--wgd-hl-key); }\n.wgd-sb-row { border-radius: var(--wgd-radius-sm); }\n.wgd-sb-row:hover { background: var(--wgd-hover); }\n.wgd-sb-row > .wgd-icon { visibility: hidden; }\n.wgd-sb-row:hover > .wgd-icon, .wgd-sb-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-schemabuilder .wgd-button { font-size: var(--wgd-font-size-xs); padding: 0 6px; border-color: transparent; color: var(--wgd-accent); background: none; }\n.wgd-schemabuilder .wgd-button:hover { border-color: var(--wgd-border); background: var(--wgd-hover); }\n.wgd-remove { color: var(--wgd-danger); }\n/* Breathing room between a tab strip and its active pane. */\n.wgd-tabs > .wgd-row { margin-bottom: 6px; }\n/* Template tree: one node = one slim row; sub-structure indents below.\n Controls stay flat (chrome appears on hover/focus) so a deep template\n reads like the JSON it projects, not like a form. */\n.wgd-node { padding: 0 0 0 4px; }\n.wgd-node-row { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; padding: 1px 0; border-radius: var(--wgd-radius-sm); }\n.wgd-node-row:hover { background: var(--wgd-hover); }\n.wgd-node-badge { font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-xs); color: var(--wgd-accent); background: var(--wgd-accent-bg); border-radius: var(--wgd-radius-sm); padding: 0 5px; flex: 0 0 auto; }\n.wgd-node-icons { display: flex; gap: 2px; margin-left: auto; flex: 0 0 auto; visibility: hidden; }\n/* One reveal rule for every row type that hosts the icon group: a row that\n is not listed here would carry present-but-invisible controls. */\n:is(.wgd-node-row, .wgd-st-row, .wgd-attr-row):is(:hover, :focus-within) > .wgd-node-icons { visibility: visible; }\n.wgd-node-value { flex: 1 1 auto; min-width: 4ch; }\n.wgd-icon { font: inherit; font-size: var(--wgd-font-size-xs); line-height: 1.4; padding: 0 5px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-sm); background: var(--wgd-bg); cursor: pointer; color: var(--wgd-muted); }\n.wgd-icon:hover { background: var(--wgd-hover); }\n/* Compact controls: inside tree nodes, and wherever a section opts in with\n .wgd-compact (the Load action editor mirrors an element's binding editor). */\n.wgd-node .wgd-input, .wgd-node .wgd-select,\n.wgd-compact .wgd-input, .wgd-compact .wgd-select { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-node .wgd-input:hover, .wgd-node .wgd-select:hover, .wgd-compact .wgd-input:hover, .wgd-compact .wgd-select:hover,\n.wgd-node .wgd-input:focus, .wgd-node .wgd-select:focus, .wgd-compact .wgd-input:focus, .wgd-compact .wgd-select:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-compact .wgd-binding { border: none; padding: 0; }\n/* Busy controls (the host-supplied Test call): disabled, with a spinner. */\n.wgd-button.wgd-busy { opacity: 0.7; cursor: progress; }\n.wgd-button.wgd-busy::after { content: \"\"; display: inline-block; width: 10px; height: 10px; margin-left: 6px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; vertical-align: -1px; animation: wgd-spin 0.8s linear infinite; }\n@keyframes wgd-spin { to { transform: rotate(360deg); } }\n.wgd-tagwrap, .wgd-pathwrap { display: contents; }\n/* Collapse chevron: every tree row reserves the column so values align. */\n.wgd-chevron { flex: 0 0 auto; width: 16px; padding: 0; border: none; background: none; color: var(--wgd-muted); font-size: calc(var(--wgd-font-size-xs) - 1px); cursor: pointer; }\n.wgd-chevron-none { visibility: hidden; }\n.wgd-node-summary { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); flex: 0 0 auto; }\n/* Attrs vs children: attributes group under a dotted muted rail with\n key-colored names; children keep the solid accent rail. */\n.wgd-attrs { margin-left: 14px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-attr-row { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; padding: 0; }\n.wgd-attr-row > .wgd-icon { visibility: hidden; }\n.wgd-attr-row:is(:hover, :focus-within) > .wgd-icon { visibility: visible; }\n.wgd-attr-name { font-family: var(--wgd-font-mono); color: var(--wgd-hl-key); flex: 0 1 auto; min-width: 5ch; }\n.wgd-attr-prefix { flex: 0 1 auto; min-width: 6ch; max-width: 10ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-str); }\n.wgd-attr { display: flex; flex-direction: column; gap: 1px; }\n/* Transform block under a bind attr: one more dotted level in. */\n.wgd-attr-map { margin-left: 24px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-attr-map-default { flex: 1 1 auto; min-width: 8ch; }\n.wgd-attr-mode, .wgd-format-type, .wgd-format-display { flex: 0 0 auto; color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); }\n.wgd-format-decimals { flex: 0 0 auto; width: 4ch; min-width: 4ch; text-align: right; font-family: var(--wgd-font-mono); }\n.wgd-format-currency { flex: 0 0 auto; width: 5ch; min-width: 5ch; text-transform: uppercase; font-family: var(--wgd-font-mono); }\n.wgd-format-pattern { flex: 0 1 auto; min-width: 8ch; max-width: 16ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-str); }\n.wgd-format-separator, .wgd-format-last, .wgd-format-ellipsis { flex: 0 0 auto; width: 6ch; min-width: 6ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-str); }\n.wgd-format-length { flex: 0 0 auto; width: 5ch; min-width: 5ch; text-align: right; font-family: var(--wgd-font-mono); }\n.wgd-format-field { flex: 0 1 auto; min-width: 6ch; max-width: 12ch; font-family: var(--wgd-font-mono); }\n.wgd-format-form { flex: 0 1 auto; min-width: 7ch; max-width: 14ch; color: var(--wgd-hl-str); }\n.wgd-md-toggle { flex: 0 0 auto; font-size: var(--wgd-font-size-xs); color: var(--wgd-accent); background: none; border: 1px solid currentColor; border-radius: var(--wgd-radius); padding: 0 6px; cursor: pointer; }\n.wgd-children { margin-left: 14px; padding-left: 8px; border-left: 2px solid var(--wgd-accent-line); gap: 1px; }\n.wgd-slot { display: flex; flex-direction: column; gap: 1px; }\n.wgd-slot-label { color: var(--wgd-muted); font-size: var(--wgd-font-size-xs); font-style: italic; padding-left: 4px; }\n/* Add menu: one toggle, options in a popover. */\n.wgd-menuwrap { position: relative; display: inline-flex; }\n.wgd-menu-toggle { color: var(--wgd-accent); }\n.wgd-menu { position: absolute; top: 100%; left: 0; z-index: 10; min-width: 9ch; display: flex; flex-direction: column; background: var(--wgd-panel); border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); box-shadow: var(--wgd-shadow); padding: 2px; }\n/* An OPEN menu must not inherit the icons' hover-gated visibility:\n visibility (unlike display) lets a child re-assert visible. */\n.wgd-menu:not([hidden]) { visibility: visible; }\n.wgd-menuwrap:has(> .wgd-menu:not([hidden])) { visibility: visible; }\n/* Menus in the right-aligned icons area hang leftward, not off-panel. */\n.wgd-node-icons .wgd-menu { left: auto; right: 0; }\n.wgd-menu-item { font: inherit; font-size: var(--wgd-font-size-sm); text-align: left; padding: 3px 8px; border: none; border-radius: var(--wgd-radius-sm); background: none; color: var(--wgd-text); cursor: pointer; white-space: nowrap; }\n.wgd-menu-item:hover { background: var(--wgd-accent-bg); color: var(--wgd-accent); }\n/* Styles tree: selector rows with declaration rows \u2014 the same flat\n template-tree discipline (flat inputs, hover-revealed icons). */\n.wgd-styles { display: flex; flex-direction: column; gap: 2px; }\n.wgd-st-row { display: flex; gap: 4px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-st-row:hover { background: var(--wgd-hover); }\n.wgd-styles .wgd-input { padding: 1px 4px; font-size: var(--wgd-font-size-sm); font-family: var(--wgd-font-mono); border-color: transparent; background: transparent; }\n.wgd-styles .wgd-input:hover, .wgd-styles .wgd-input:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-st-selector { flex: 1 1 auto; min-width: 8ch; color: var(--wgd-accent); }\n.wgd-st-decls { margin-left: 14px; padding-left: 8px; border-left: 2px dotted var(--wgd-border); display: flex; flex-direction: column; gap: 1px; }\n.wgd-st-decl { display: flex; gap: 2px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-st-decl:hover { background: var(--wgd-hover); }\n.wgd-st-decl > .wgd-icon { visibility: hidden; }\n.wgd-st-decl:hover > .wgd-icon, .wgd-st-decl:focus-within > .wgd-icon { visibility: visible; }\n.wgd-st-prop { flex: 0 1 auto; min-width: 8ch; color: var(--wgd-hl-key); }\n.wgd-st-value { flex: 1 1 auto; min-width: 8ch; }\n.wgd-st-colon { color: var(--wgd-muted); flex: 0 0 auto; }\n.wgd-st-add { font-size: var(--wgd-font-size-xs); padding: 0 6px; border-color: transparent; color: var(--wgd-accent); background: none; }\n.wgd-st-add:hover { border-color: var(--wgd-border); background: var(--wgd-hover); }\n/* Import and export stack as sibling sections with the column's rhythm. */\n.wgd-io { display: flex; flex-direction: column; gap: 8px; }\n/* Flat string\u2192string record rows (hints): mono keys, prose values. */\n.wgd-record { display: flex; flex-direction: column; gap: 1px; }\n.wgd-rec-row { display: flex; gap: 2px; align-items: center; border-radius: var(--wgd-radius-sm); }\n.wgd-rec-row:hover { background: var(--wgd-hover); }\n.wgd-rec-row > .wgd-icon { visibility: hidden; }\n.wgd-rec-row:hover > .wgd-icon, .wgd-rec-row:focus-within > .wgd-icon { visibility: visible; }\n.wgd-record .wgd-input { padding: 1px 4px; font-size: var(--wgd-font-size-sm); border-color: transparent; background: transparent; }\n.wgd-record .wgd-input:hover, .wgd-record .wgd-input:focus { border-color: var(--wgd-border); background: var(--wgd-bg); }\n.wgd-rec-key { flex: 0 1 auto; min-width: 8ch; font-family: var(--wgd-font-mono); color: var(--wgd-hl-key); }\n.wgd-rec-value { flex: 1 1 auto; min-width: 8ch; }\n/* The tag select IS the element node's label: flat, accent, monospace.\n Tag and path selects are width-fitted to their SELECTED value by the\n panel (fitSelect), so carets hug the text \u2014 no flex stretching here. */\n.wgd-node .wgd-tag { flex: 0 0 auto; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-xs); color: var(--wgd-accent); background: var(--wgd-accent-bg); border: 1px solid transparent; border-radius: var(--wgd-radius-sm); padding: 0 4px; }\n.wgd-node .wgd-tag:hover, .wgd-node .wgd-tag:focus { border-color: var(--wgd-accent-line); }\n.wgd-node .wgd-path, .wgd-node .wgd-each-key { flex: 0 1 auto; min-width: 6ch; max-width: 100%; font-family: var(--wgd-font-mono); }\n.wgd-node .wgd-select { box-sizing: border-box; }\n/* Theme panel: swatch beside each color token. */\n/* Syntax coloring: <pre> layer behind a transparent-text textarea. Every\n metric here must mirror .wgd-textarea or the glyphs drift apart. */\n.wgd-hlwrap { position: relative; }\n.wgd-hl, .wgd-hl-input {\n font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size); line-height: 1.45;\n padding: 4px 6px; border: 1px solid transparent; border-radius: var(--wgd-radius);\n box-sizing: border-box; white-space: pre; tab-size: 2; letter-spacing: normal;\n}\n.wgd-hl {\n position: absolute; inset: 0; margin: 0; overflow: hidden;\n pointer-events: none; z-index: 0; background: var(--wgd-bg);\n color: var(--wgd-text);\n}\ntextarea.wgd-hl-input {\n position: relative; z-index: 1; background: transparent; color: transparent;\n caret-color: var(--wgd-text); border-color: var(--wgd-border);\n}\n.wgd-hl-k { color: var(--wgd-hl-key); }\n.wgd-hl-s { color: var(--wgd-hl-str); }\n.wgd-hl-n { color: var(--wgd-hl-num); }\n.wgd-hl-b { color: var(--wgd-hl-bool); }\n.wgd-hl-p { color: var(--wgd-hl-punct); }\n.wgd-swatch { flex: 0 0 auto; width: 26px; height: 22px; padding: 0; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius); background: none; cursor: pointer; }\n.wgd-token-row { display: flex; gap: 6px; align-items: center; }\n.wgd-token-row .wgd-input { flex: 1 1 auto; min-width: 6ch; font-family: var(--wgd-font-mono); font-size: var(--wgd-font-size-sm); }\n.wgd-token-ref { display: flex; flex-direction: column; gap: 2px; max-height: 220px; overflow-y: auto; margin-top: 4px; }\n.wgd-token-ref-row { display: flex; gap: 6px; align-items: center; font-size: var(--wgd-font-size-xs); }\n.wgd-token-ref-swatch { flex: 0 0 auto; width: 14px; height: 14px; border: 1px solid var(--wgd-border); border-radius: var(--wgd-radius-sm); }\n.wgd-token-ref-noswatch { border-style: dashed; opacity: 0.35; }\n.wgd-token-ref-name { font-family: var(--wgd-font-mono); color: var(--wgd-accent); }\n.wgd-token-ref-value { color: var(--wgd-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.wgd-token-ref-details summary { cursor: pointer; }\n`;\n doc.head.appendChild(style);\n}\n\n/** Tabbed container: first tab visible, buttons switch panes. */\nexport function tabs(entries: { label: string; element: HTMLElement }[]): HTMLElement {\n const buttons = entries.map((entry, index) => {\n const button = h(\n \"button\",\n { class: `wgd-button wgd-tab${index === 0 ? \" wgd-tab-active\" : \"\"}`, type: \"button\" },\n [entry.label]\n );\n button.addEventListener(\"click\", () => {\n entries.forEach((other, i) => {\n other.element.hidden = i !== index;\n buttons[i]?.classList.toggle(\"wgd-tab-active\", i === index);\n });\n });\n entry.element.hidden = index !== 0;\n return button;\n });\n return h(\"div\", { class: \"wgd-tabs\" }, [\n h(\"div\", { class: \"wgd-row\" }, buttons),\n ...entries.map((entry) => entry.element)\n ]);\n}\n", "/** Package-local helpers (kept here rather than exported from core \u2014 see design D4). */\n\n/** Structural copy of JSON-shaped data; the designers hand out copies, never their state. */\nexport function clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** A caught value's message without asserting it is an Error. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n", "/**\n * The designer's derive step: run widgentic's pure validators over the\n * draft and shape their structured errors into per-panel diagnostics.\n * Everything here goes through public package entries \u2014 the designer owns\n * no validation logic of its own.\n */\nimport { auditDataSchema, isPlainObject, PROPERTY_NAME, SAFE_IDENTIFIER, STYLE_RULES } from \"@widgentic/core\";\nimport {\n createCatalog,\n validateDataAgainstSchema,\n widgetStylesToCss\n} from \"@widgentic/core\";\nimport type { WidgetStyles } from \"@widgentic/core\";\nimport type { WidgetContractError } from \"@widgentic/core\";\nimport { collectActionRefs, parsePath, validateTemplate } from \"@widgentic/core\";\nimport { validateLoadBinding } from \"@widgentic/core\";\nimport { validateTheme } from \"@widgentic/core\";\nimport type { ThemeError } from \"@widgentic/core\";\nimport type { WidgetDraft } from \"./store.js\";\n\nexport interface TemplateIssue {\n code: string;\n message: string;\n /** Node path when the validator reports one. */\n path?: string;\n}\n\nexport interface StyleIssue {\n selector: string;\n property?: string;\n message: string;\n}\n\nexport interface DesignerDiagnostics {\n /** Problem with the kind id itself (empty, or colliding with a base kind). */\n kind?: string;\n template?: TemplateIssue;\n /** `descriptor.dataExample` vs `descriptor.dataSchema`. */\n example?: WidgetContractError;\n /** `sampleData` vs `descriptor.dataSchema`. */\n sample?: WidgetContractError;\n /** Entries the renderer's safety filters would skip. */\n styles: StyleIssue[];\n theme?: ThemeError;\n /** Shared-schema reference problems (unknown ref, or ref + inline). */\n schemaRef?: string;\n /** The widget-level `load` binding failed validation. */\n load?: string;\n /** Shared actions referenced by the template or `load` that are not among the supplied ones. */\n actionRefs?: string;\n /**\n * A warning, never blocking: without `descriptor.dataShape` agents that\n * list the widget see a placeholder instead of the data it expects.\n */\n dataShape?: string;\n /** Warnings, never blocking: what the validator would ignore in the inline `dataSchema`. */\n dataSchema?: string[];\n /** True when the draft can be registered and previewed. */\n previewable: boolean;\n}\n\n/** Host-supplied shared schemas the draft may reference by name. */\nexport interface DeriveOptions {\n schemas?: { name: string; schema: Record<string, unknown> }[];\n /** Host-supplied shared actions the draft may bind by name. */\n actions?: { name: string }[];\n}\n\n/**\n * The schema validation actually runs against: the inline one, or the\n * referenced shared one resolved from the supplied list \u2014 the same join\n * the server's composition performs.\n */\nexport function effectiveDataSchema(\n draft: WidgetDraft,\n schemas: { name: string; schema: Record<string, unknown> }[] = []\n): Record<string, unknown> | undefined {\n const ref = draft.descriptor?.dataSchemaRef;\n if (typeof ref === \"string\") {\n return schemas.find((entry) => entry.name === ref)?.schema;\n }\n const inline = draft.descriptor?.dataSchema;\n return isPlainObject(inline) ? inline : undefined;\n}\n\nconst BASE_KINDS = new Set(createCatalog().kinds());\n\n/** What saving would refuse about a kind, in the store's terms; `undefined` when acceptable. */\nexport function kindProblem(kind: string): string | undefined {\n if (!SAFE_IDENTIFIER.test(kind)) {\n return `INVALID_IDENTIFIER \u2014 '${kind}' may use letters, digits, '.', '_' or '-' only.`;\n }\n if (BASE_KINDS.has(kind)) {\n return `RESERVED_KIND \u2014 '${kind}' is a built-in kind; give the widget its own kind.`;\n }\n return undefined;\n}\n\n/**\n * Detect style entries the renderer would skip, using only the public\n * generator: a probe that produces no CSS was filtered by the safety\n * guards. Selector and per-declaration issues are reported separately.\n */\nexport function auditStyles(styles: WidgetStyles | undefined): StyleIssue[] {\n if (!isPlainObject(styles)) return [];\n const issues: StyleIssue[] = [];\n for (const [selector, declarations] of Object.entries(styles)) {\n if (widgetStylesToCss({ [selector]: { color: \"red\" } }) === \"\") {\n issues.push({\n selector,\n message: `Selector would be skipped. ${STYLE_RULES.selectors} ${STYLE_RULES.banned}`\n });\n continue;\n }\n if (!isPlainObject(declarations)) {\n issues.push({ selector, message: \"Declarations must be a property \u2192 value map.\" });\n continue;\n }\n for (const [property, value] of Object.entries(declarations)) {\n if (\n typeof value !== \"string\" ||\n widgetStylesToCss({ \".wg-probe\": { [property]: value } }) === \"\"\n ) {\n // Name the part at fault: the property name, or else the value.\n issues.push({\n selector,\n property,\n message: !PROPERTY_NAME.test(property)\n ? `Property would be skipped. ${STYLE_RULES.propertyNames}`\n : typeof value !== \"string\"\n ? \"Value would be skipped: it must be a string.\"\n : `Value would be skipped. ${STYLE_RULES.banned}`\n });\n }\n }\n }\n return issues;\n}\n\n/** Run every validator; total \u2014 never throws on any draft shape. */\nexport function deriveDiagnostics(\n draft: WidgetDraft,\n options: DeriveOptions = {}\n): DesignerDiagnostics {\n const diagnostics: DesignerDiagnostics = { styles: [], previewable: false };\n\n if (typeof draft.kind !== \"string\" || draft.kind.trim().length === 0) {\n diagnostics.kind = \"Kind must be a non-empty id.\";\n } else {\n const problem = kindProblem(draft.kind);\n if (problem !== undefined) diagnostics.kind = problem;\n }\n\n const dataShape = draft.descriptor?.dataShape;\n if (typeof dataShape !== \"string\" || dataShape.trim() === \"\") {\n diagnostics.dataShape =\n \"Data shape is empty \u2014 agents listing this widget will see a placeholder instead of the data it expects.\";\n }\n\n const inlineSchema = draft.descriptor?.dataSchema;\n if (isPlainObject(inlineSchema)) {\n const warnings = auditDataSchema(inlineSchema, \"dataSchema\");\n if (warnings.length > 0) diagnostics.dataSchema = warnings;\n }\n\n const template = validateTemplate(draft.template);\n if (!template.ok) {\n const issue: TemplateIssue = {\n code: template.error.code,\n message: template.error.message\n };\n const path = (template.error as { path?: unknown }).path;\n if (typeof path === \"string\") issue.path = path;\n diagnostics.template = issue;\n }\n\n // Shared-schema refs resolve here exactly as the server's composition\n // resolves them, so diagnostics match what the store will enforce.\n const ref = draft.descriptor?.dataSchemaRef;\n if (typeof ref === \"string\") {\n if (draft.descriptor?.dataSchema !== undefined) {\n diagnostics.schemaRef =\n \"A descriptor carries 'dataSchema' OR 'dataSchemaRef', never both.\";\n } else if (\n // Unverifiable without the host's schemas: never a false \"unknown\".\n options.schemas !== undefined &&\n options.schemas.every((entry) => entry.name !== ref)\n ) {\n diagnostics.schemaRef = `References unknown schema '${ref}' \u2014 it is not among the supplied shared schemas.`;\n }\n }\n const schema = effectiveDataSchema(draft, options.schemas ?? []);\n if (isPlainObject(schema)) {\n if (draft.descriptor.dataExample !== undefined) {\n const error = validateDataAgainstSchema(schema, draft.descriptor.dataExample);\n if (error) diagnostics.example = error;\n }\n if (draft.sampleData !== undefined) {\n const error = validateDataAgainstSchema(schema, draft.sampleData);\n if (error) diagnostics.sample = error;\n }\n }\n\n diagnostics.styles = auditStyles(draft.descriptor?.styles);\n\n if (draft.load !== undefined) {\n const problem = validateLoadBinding(draft.load, \"load\", {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (problem) diagnostics.load = `${problem.message} (at ${problem.path})`;\n }\n if (options.actions !== undefined) {\n const known = new Set(options.actions.map((action) => action.name));\n const unknown = collectActionRefs(draft.template, draft.load).filter((ref) => !known.has(ref));\n if (unknown.length > 0) {\n diagnostics.actionRefs = `References unknown shared action${unknown.length === 1 ? \"\" : \"s\"} ${unknown\n .map((ref) => `'${ref}'`)\n .join(\", \")} \u2014 bound elements will render disabled.`;\n }\n }\n\n if (draft.theme !== undefined) {\n const theme = validateTheme(draft.theme);\n if (!theme.ok) diagnostics.theme = theme.error;\n }\n\n diagnostics.previewable =\n diagnostics.kind === undefined && diagnostics.template === undefined;\n return diagnostics;\n}\n", "/**\n * Cheap syntax coloring for the JSON textareas: a highlighted <pre> layer\n * sits exactly behind a transparent-text <textarea>, so the browser keeps\n * doing all the real work (typing, selection, undo, IME) and we only paint\n * colors. No editor library, no parsing beyond a tokenizer \u2014 invalid JSON\n * still colors sensibly because the tokenizer is regex-based, never a\n * parser.\n *\n * The two layers must agree on every metric that affects glyph position\n * (font, size, line-height, padding, border width, white-space); the\n * stylesheet keeps them in lockstep.\n */\n\ninterface Token {\n /** Token class suffix: k(ey) s(tring) n(umber) b(oolean/null) p(unctuation). */\n cls: string;\n text: string;\n}\n\nconst JSON_TOKENS =\n /(\"(?:[^\"\\\\]|\\\\.)*\")(\\s*:)?|(-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)|\\b(true|false|null)\\b|([{}[\\],:])/g;\n\nexport function tokenizeJson(text: string): Token[] {\n const out: Token[] = [];\n let last = 0;\n let match: RegExpExecArray | null;\n JSON_TOKENS.lastIndex = 0;\n while ((match = JSON_TOKENS.exec(text)) !== null) {\n if (match.index > last) out.push({ cls: \"\", text: text.slice(last, match.index) });\n if (match[1] !== undefined) {\n // A string followed by ':' is an object key.\n if (match[2] !== undefined) {\n out.push({ cls: \"k\", text: match[1] });\n out.push({ cls: \"p\", text: match[2] });\n } else {\n out.push({ cls: \"s\", text: match[1] });\n }\n } else if (match[3] !== undefined) {\n out.push({ cls: \"n\", text: match[3] });\n } else if (match[4] !== undefined) {\n out.push({ cls: \"b\", text: match[4] });\n } else if (match[5] !== undefined) {\n out.push({ cls: \"p\", text: match[5] });\n }\n last = JSON_TOKENS.lastIndex;\n }\n if (last < text.length) out.push({ cls: \"\", text: text.slice(last) });\n return out;\n}\n\n/** Paint tokens into the layer as DOM nodes (never innerHTML). */\nfunction paint(layer: HTMLElement, text: string): void {\n const nodes: Node[] = [];\n for (const token of tokenizeJson(text)) {\n if (token.cls === \"\") {\n nodes.push(document.createTextNode(token.text));\n continue;\n }\n const span = document.createElement(\"span\");\n span.className = `wgd-hl-${token.cls}`;\n span.textContent = token.text;\n nodes.push(span);\n }\n // A trailing newline needs a following glyph box to render as a line.\n nodes.push(document.createTextNode(\"\\n\"));\n layer.replaceChildren(...nodes);\n}\n\n/**\n * Wrap a textarea in the highlight layer. Returns a disposer that restores\n * the original DOM shape.\n */\nexport function attachJsonHighlight(textarea: HTMLTextAreaElement): () => void {\n const parent = textarea.parentNode;\n if (parent === null) return () => undefined;\n\n const wrap = document.createElement(\"div\");\n wrap.className = \"wgd-hlwrap\";\n const layer = document.createElement(\"pre\");\n layer.className = \"wgd-hl\";\n layer.setAttribute(\"aria-hidden\", \"true\");\n\n parent.insertBefore(wrap, textarea);\n wrap.append(layer, textarea);\n textarea.classList.add(\"wgd-hl-input\");\n\n const sync = (): void => {\n paint(layer, textarea.value);\n layer.scrollTop = textarea.scrollTop;\n layer.scrollLeft = textarea.scrollLeft;\n };\n const syncScroll = (): void => {\n layer.scrollTop = textarea.scrollTop;\n layer.scrollLeft = textarea.scrollLeft;\n };\n // Tab indents instead of moving focus \u2014 these panes hold indented JSON.\n // Shift+Tab keeps its focus-moving default as the keyboard escape.\n const onTab = (event: KeyboardEvent): void => {\n if (event.key !== \"Tab\" || event.shiftKey || textarea.readOnly) return;\n event.preventDefault();\n const { selectionStart, selectionEnd, value } = textarea;\n textarea.value = `${value.slice(0, selectionStart)} ${value.slice(selectionEnd)}`;\n textarea.selectionStart = textarea.selectionEnd = selectionStart + 2;\n // The commit path listens for input; a synthetic one keeps the store\n // and the paint layer in step with the inserted spaces.\n textarea.dispatchEvent(new Event(\"input\", { bubbles: true }));\n };\n\n textarea.addEventListener(\"input\", sync);\n textarea.addEventListener(\"scroll\", syncScroll);\n textarea.addEventListener(\"keydown\", onTab);\n sync();\n\n return () => {\n textarea.removeEventListener(\"input\", sync);\n textarea.removeEventListener(\"scroll\", syncScroll);\n textarea.removeEventListener(\"keydown\", onTab);\n textarea.classList.remove(\"wgd-hl-input\");\n wrap.replaceWith(textarea);\n };\n}\n\n/**\n * Repaint after a programmatic value change (store refresh), which fires\n * no input event.\n */\nexport function repaintHighlight(textarea: HTMLTextAreaElement): void {\n const layer = textarea.parentElement?.querySelector(\".wgd-hl\");\n if (layer instanceof HTMLElement) paint(layer, textarea.value);\n}\n", "/**\n * Import/export in the server's shapes: widget JSON is exactly the\n * `CustomWidget` definition (`{ kind, template, descriptor }`) that\n * `examples/mcp-server/widgets/` registers; themes are bare token maps.\n * Imports are untrusted \u2014 everything re-validates, and a failed import\n * never touches the current draft.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject, SAFE_IDENTIFIER } from \"@widgentic/core\";\nimport { parsePath, validateTemplate } from \"@widgentic/core\";\nimport { validateLoadBinding } from \"@widgentic/core\";\nimport type { ActionBinding } from \"@widgentic/core\";\nimport { kindProblem } from \"./validate.js\";\nimport { diagnosticLine, h, section, textArea, requireChild } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\n\nexport interface WidgetDefinition {\n kind: WidgetDraft[\"kind\"];\n template: WidgetDraft[\"template\"];\n descriptor: WidgetDraft[\"descriptor\"];\n load?: ActionBinding;\n}\n\n/**\n * Validate an untrusted definition; errors instead of throws. The kind is\n * held to what saving accepts only when it differs from `currentKind`: a\n * kind the draft already has is the person's to fix (the diagnostics flag\n * it), and reloading the same draft with new data must not fail on it.\n */\nexport function checkDefinition(definition: unknown, currentKind?: string): string[] {\n const errors: string[] = [];\n if (!isPlainObject(definition)) return [\"Definition must be an object.\"];\n if (typeof definition.kind !== \"string\" || definition.kind.trim() === \"\") {\n errors.push(\"'kind' must be a non-empty string.\");\n } else if (definition.kind !== currentKind) {\n // What saving would refuse is refused here too, in the store's terms.\n const problem = kindProblem(definition.kind);\n if (problem !== undefined) errors.push(`kind: ${problem}`);\n }\n const template = validateTemplate(definition.template);\n if (!template.ok) {\n errors.push(`template: ${template.error.code} \u2014 ${template.error.message}`);\n }\n if (!isPlainObject(definition.descriptor)) {\n errors.push(\"'descriptor' must be an object.\");\n } else if (typeof definition.descriptor.description !== \"string\") {\n errors.push(\"'descriptor.description' must be a string.\");\n } else {\n // Refused at the door in the store's terms where Save refuses them; a\n // non-object `dataSchema` is refused because the designer cannot open it.\n const { dataSchema, dataSchemaRef } = definition.descriptor;\n if (dataSchema !== undefined && dataSchemaRef !== undefined) {\n errors.push(\"descriptor: INVALID_SHAPE \u2014 carries 'dataSchema' and 'dataSchemaRef'; keep one.\");\n } else if (dataSchema !== undefined && !isPlainObject(dataSchema)) {\n errors.push(\"descriptor: INVALID_SHAPE \u2014 'dataSchema' must be a schema object.\");\n } else if (dataSchemaRef !== undefined && (typeof dataSchemaRef !== \"string\" || !SAFE_IDENTIFIER.test(dataSchemaRef))) {\n errors.push(\"descriptor: INVALID_SHAPE \u2014 'dataSchemaRef' must be a valid schema name: letters, digits, '.', '_' or '-'.\");\n }\n }\n if (definition.load !== undefined) {\n const problem = validateLoadBinding(definition.load, \"load\", {\n isPath: (value) => parsePath(value) !== undefined\n });\n if (problem) errors.push(`load: ${problem.message} (at ${problem.path})`);\n }\n return errors;\n}\n\nexport function exportWidgetJson(draft: WidgetDraft): string {\n const definition: WidgetDefinition = {\n kind: draft.kind,\n template: draft.template,\n descriptor: draft.descriptor,\n ...(draft.load !== undefined ? { load: draft.load } : {})\n };\n return JSON.stringify(definition, null, 2);\n}\n\nexport function exportThemeJson(draft: WidgetDraft): string {\n return JSON.stringify(draft.theme ?? {}, null, 2);\n}\n\nexport type ImportResult =\n | { ok: true; definition: WidgetDefinition }\n | { ok: false; errors: string[] };\n\nexport function importWidgetJson(text: string, currentKind?: string): ImportResult {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n return { ok: false, errors: [`Invalid JSON: ${errorMessage(error)}`] };\n }\n const errors = checkDefinition(parsed, currentKind);\n if (errors.length > 0) return { ok: false, errors };\n return { ok: true, definition: parsed as unknown as WidgetDefinition };\n}\n\n/** Apply a validated definition to the store, preserving the session theme. */\nexport function applyDefinition(store: DraftStore, definition: WidgetDefinition): void {\n // The preview theme is the designer's state, not the definition's: a load\n // keeps it whole, tokens and shared styles alike.\n const { theme, themeStyles, previewTheme } = store.get();\n store.replace({\n kind: definition.kind,\n template: definition.template,\n descriptor: definition.descriptor,\n ...(definition.load !== undefined ? { load: definition.load } : {}),\n ...(theme !== undefined ? { theme } : {}),\n ...(themeStyles !== undefined ? { themeStyles } : {}),\n ...(previewTheme !== undefined ? { previewTheme } : {})\n });\n}\n\nfunction camelCase(kind: string): string {\n return kind\n .split(/[^a-zA-Z0-9]+/)\n .filter((part) => part.length > 0)\n .map((part, i) => (i === 0 ? part : part[0]?.toUpperCase() + part.slice(1)))\n .join(\"\");\n}\n\n/**\n * Emit a module body compatible with `examples/mcp-server/widgets/` \u2014\n * the manual-registration bridge until wire registration exists.\n */\nexport function toTypeScriptModule(draft: WidgetDraft): string {\n const name = camelCase(draft.kind) || \"custom\";\n return (\n `import type { CustomWidget } from \"./index.js\";\\n\\n` +\n `export const ${name}Widget: CustomWidget = ${JSON.stringify(\n {\n kind: draft.kind,\n template: draft.template,\n descriptor: draft.descriptor,\n ...(draft.load !== undefined ? { load: draft.load } : {})\n },\n null,\n 2\n )};\\n`\n );\n}\n\nexport function mountIoPanel(store: DraftStore): {\n element: HTMLElement;\n dispose(): void;\n} {\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n\n function button(label: string, produce: () => string): HTMLElement {\n const el = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [label]);\n el.addEventListener(\"click\", () => {\n output.value = produce();\n repaintHighlight(output);\n });\n return el;\n }\n\n const importError = diagnosticLine(undefined);\n const importField = textArea(\"Import widget JSON\", \"\", () => undefined, 5);\n const importArea = requireChild(importField, \"textarea\");\n attachJsonHighlight(importArea);\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\n \"Import\"\n ]);\n importButton.addEventListener(\"click\", () => {\n const result = importWidgetJson(importArea.value, store.get().kind);\n if (!result.ok) {\n importError.hidden = false;\n importError.textContent = result.errors.join(\"\\n\");\n return; // current draft untouched\n }\n importError.hidden = true;\n importError.textContent = \"\";\n applyDefinition(store, result.definition);\n });\n\n // Import and export are independent flows \u2014 two sections, import first\n // (bringing a drafted definition in is the more common entry point).\n const importSection = section(\"Import\", [\n importField,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n // Export copies out what is already on screen, so read-only leaves it\n // operable: the mode restricts editing, not looking.\n const exportSection = section(\"Export\", [\n h(\"div\", { class: \"wgd-row\" }, [\n // The entry the store persists \u2014 named like the other designers'\n // export buttons. Themes export from the theme designer.\n button(\"Export widget entry\", () => exportWidgetJson(store.get())),\n button(\"Copy as TypeScript\", () => toTypeScriptModule(store.get()))\n ]),\n output\n ]);\n exportSection.classList.add(\"wgd-view-only\");\n const element = h(\"div\", { class: \"wgd-io\" }, [importSection, exportSection]);\n // After assembly: the layer wraps the textarea in place, so the element\n // must already have its parent.\n attachJsonHighlight(output);\n\n return { element, dispose: () => element.remove() };\n}\n", "/**\n * Generic JSON value editor: collapsible tree with in-place key/value\n * editing, type switching, and add/remove \u2014 the NanoJSON/JSONTree\n * interaction pattern, built in-house because the general libraries carry\n * far more (and weigh far more) than the designer needs.\n *\n * Structural operations re-render the tree; text edits commit on change\n * (blur/Enter) so typing is never interrupted.\n */\nimport { h } from \"./dom.js\";\n\ntype Path = (string | number)[];\n\nconst TYPE_OPTIONS = [\"string\", \"number\", \"boolean\", \"null\", \"object\", \"array\"] as const;\ntype TypeName = (typeof TYPE_OPTIONS)[number];\n\nfunction typeOf(value: unknown): TypeName {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return (typeof value) as TypeName;\n}\n\nfunction defaultFor(type: TypeName, previous: unknown): unknown {\n switch (type) {\n case \"string\":\n return typeof previous === \"number\" || typeof previous === \"boolean\"\n ? String(previous)\n : \"\";\n case \"number\": {\n const parsed = Number(previous);\n return Number.isFinite(parsed) ? parsed : 0;\n }\n case \"boolean\":\n return previous === \"true\" ? true : Boolean(previous) && previous !== \"false\";\n case \"null\":\n return null;\n case \"object\":\n return {};\n case \"array\":\n return [];\n }\n}\n\nfunction setAt(root: unknown, path: Path, value: unknown, remove = false): unknown {\n if (path.length === 0) return value;\n const [step, ...rest] = path as [string | number, ...Path];\n if (Array.isArray(root)) {\n const copy = [...root];\n if (rest.length === 0 && remove) copy.splice(step as number, 1);\n else copy[step as number] = setAt(copy[step as number], rest, value, remove);\n return copy;\n }\n if (typeof root === \"object\" && root !== null) {\n const copy = { ...(root as Record<string, unknown>) };\n if (rest.length === 0 && remove) delete copy[step as string];\n else copy[step as string] = setAt(copy[step as string], rest, value, remove);\n return copy;\n }\n return root;\n}\n\nfunction renameKey(root: unknown, path: Path, from: string, to: string): unknown {\n const holder = path.reduce<unknown>(\n (node, step) =>\n typeof node === \"object\" && node !== null\n ? (node as Record<string, unknown>)[step as string]\n : undefined,\n root\n );\n if (typeof holder !== \"object\" || holder === null || Array.isArray(holder)) return root;\n const entries = Object.entries(holder).map(([k, v]) =>\n k === from ? ([to, v] as const) : ([k, v] as const)\n );\n return setAt(root, path, Object.fromEntries(entries));\n}\n\nexport interface JsonTreeEditor {\n element: HTMLElement;\n getValue(): unknown;\n /** External update (skipped while the user is editing inside the tree). */\n setValue(value: unknown): void;\n}\n\nexport function createJsonTreeEditor(\n initial: unknown,\n onChange: (value: unknown) => void\n): JsonTreeEditor {\n let current: unknown = initial;\n const element = h(\"div\", { class: \"wgd-jsontree\" });\n\n function commit(next: unknown): void {\n current = next;\n render();\n onChange(current);\n }\n\n function commitText(path: Path, type: TypeName, text: string): void {\n const value =\n type === \"number\"\n ? Number.isFinite(Number(text))\n ? Number(text)\n : 0\n : text;\n current = setAt(current, path, value);\n onChange(current); // no re-render: in-place text edit\n }\n\n function typeSelect(value: unknown, path: Path): HTMLSelectElement {\n const select = h(\"select\", { class: \"wgd-select wgd-jt-type\" });\n for (const option of TYPE_OPTIONS) {\n select.append(h(\"option\", { value: option }, [option]));\n }\n select.value = typeOf(value);\n select.addEventListener(\"change\", () =>\n commit(setAt(current, path, defaultFor(select.value as TypeName, value)))\n );\n return select;\n }\n\n function valueControl(value: unknown, path: Path): Node {\n const type = typeOf(value);\n if (type === \"boolean\") {\n const box = h(\"input\", { type: \"checkbox\" });\n box.checked = value as boolean;\n box.addEventListener(\"change\", () => commit(setAt(current, path, box.checked)));\n return box;\n }\n if (type === \"null\") return h(\"code\", undefined, [\"null\"]);\n if (type === \"string\" || type === \"number\") {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n input.value = String(value);\n input.addEventListener(\"change\", () => commitText(path, type, input.value));\n return input;\n }\n return h(\"span\");\n }\n\n function entryRow(\n keyLabel: Node,\n value: unknown,\n path: Path,\n removable: boolean\n ): HTMLElement {\n const row = h(\"div\", { class: \"wgd-jt-row\" }, [keyLabel, typeSelect(value, path)]);\n const type = typeOf(value);\n if (type !== \"object\" && type !== \"array\") {\n row.append(valueControl(value, path));\n }\n if (removable) {\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => commit(setAt(current, path, undefined, true)));\n row.append(remove);\n }\n const wrap = h(\"div\", { class: \"wgd-jt-entry\" }, [row]);\n if (type === \"object\" || type === \"array\") {\n wrap.append(renderContainer(value, path));\n }\n return wrap;\n }\n\n function renderContainer(value: unknown, path: Path): HTMLElement {\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n body.append(\n entryRow(h(\"span\", { class: \"wgd-jt-key\" }, [String(index)]), item, [...path, index], true)\n );\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ item\"]);\n add.addEventListener(\"click\", () =>\n commit(setAt(current, [...path, value.length], \"\"))\n );\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n } else if (typeof value === \"object\" && value !== null) {\n for (const [key, item] of Object.entries(value)) {\n const keyInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-jt-keyinput\"\n });\n keyInput.value = key;\n keyInput.addEventListener(\"change\", () =>\n commit(renameKey(current, path, key, keyInput.value))\n );\n body.append(entryRow(keyInput, item, [...path, key], true));\n }\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ property\"]);\n add.addEventListener(\"click\", () => {\n const holder = value as Record<string, unknown>;\n let name = \"key\";\n for (let i = 1; name in holder; i++) name = `key${i}`;\n commit(setAt(current, [...path, name], \"\"));\n });\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n const details = h(\"details\", { class: \"wgd-jt-branch\", open: \"\" }, [\n h(\"summary\", { class: \"wgd-jt-summary\" }, [\n Array.isArray(value)\n ? `[ ${value.length} item${value.length === 1 ? \"\" : \"s\"} ]`\n : `{ ${Object.keys(value as object).length} propert${Object.keys(value as object).length === 1 ? \"y\" : \"ies\"} }`\n ]),\n body\n ]);\n return details;\n }\n\n function render(): void {\n element.replaceChildren(\n entryRow(h(\"span\", { class: \"wgd-jt-key\" }, [\"value\"]), current, [], false)\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(value) {\n if (element.contains(document.activeElement)) return;\n current = value;\n render();\n }\n };\n}\n", "/**\n * Structured editor for the dataSchema subset \u2014 the property-card pattern\n * from the React schema-builder ecosystem, sized to widgentic's six\n * keywords (type/properties/required/items/enum/pattern) so it stays a\n * dependency-free couple hundred lines.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { diagnosticLine, fitSelect, h } from \"./dom.js\";\n\nconst TYPES = [\"object\", \"array\", \"string\", \"number\", \"integer\", \"boolean\", \"null\", \"any\"] as const;\n\n/**\n * Types the builder offers `enum` for. The validator accepts `enum` on any\n * type (deep JSON comparison, per JSON Schema), but enumerating whole\n * objects/arrays belongs in the JSON tab, not a form.\n */\nconst ENUM_TYPES = new Set([\"string\", \"number\", \"integer\", \"any\"]);\n\nexport interface SchemaBuilder {\n element: HTMLElement;\n getValue(): DataSchema | undefined;\n setValue(schema: DataSchema | undefined): void;\n}\n\nexport function createSchemaBuilder(\n initial: DataSchema | undefined,\n onChange: (schema: DataSchema | undefined) => void\n): SchemaBuilder {\n let current: DataSchema | undefined = initial;\n const element = h(\"div\", { class: \"wgd-schemabuilder\" });\n\n function commit(next: DataSchema | undefined, rerender = true): void {\n current = next;\n onChange(current);\n if (rerender) render();\n }\n\n /** Rebuild a node with one key changed/removed (undefined removes). */\n function withKey(node: DataSchema, key: string, value: unknown): DataSchema {\n const copy: DataSchema = { ...node };\n if (value === undefined) delete copy[key];\n else copy[key] = value;\n return copy;\n }\n\n /**\n * One schema node. `lead`/`trail` let a parent put the property name and\n * its required/remove controls on the SAME row as the type select.\n */\n function renderNode(\n node: DataSchema,\n apply: (next: DataSchema) => void,\n depth: number,\n lead: (Node | string)[] = [],\n trail: (Node | string)[] = []\n ): HTMLElement {\n const rows: (Node | string)[] = [];\n\n const typeSelect = h(\"select\", { class: \"wgd-select wgd-sb-type\" });\n for (const t of TYPES) typeSelect.append(h(\"option\", { value: t }, [t]));\n // Nullable type arrays ([<type>, \"null\"], either order) present as the\n // PRIMARY type + a nullable toggle \u2014 never collapsing to \"any\", which\n // silently hid pattern/enum for agent-authored nullable fields.\n const rawType = node.type;\n const typeList = Array.isArray(rawType)\n ? rawType.filter((t): t is string => typeof t === \"string\")\n : undefined;\n const nullable = typeList?.includes(\"null\") ?? false;\n const currentType =\n typeof rawType === \"string\"\n ? rawType\n : (typeList?.find((t) => t !== \"null\") ?? (nullable ? \"null\" : \"any\"));\n typeSelect.value = TYPES.some((type) => type === currentType)\n ? currentType\n : \"any\";\n fitSelect(typeSelect);\n const nullBox = h(\"input\", {\n type: \"checkbox\",\n title: \"Also allows null\"\n });\n nullBox.checked = nullable;\n nullBox.disabled = typeSelect.value === \"any\" || typeSelect.value === \"null\";\n /** The `type` value the current controls describe. */\n function typeValue(selected: string, allowNull: boolean): unknown {\n if (selected === \"any\") return undefined;\n return allowNull && selected !== \"null\" ? [selected, \"null\"] : selected;\n }\n nullBox.addEventListener(\"change\", () => {\n apply(withKey(node, \"type\", typeValue(typeSelect.value, nullBox.checked)));\n });\n typeSelect.addEventListener(\"change\", () => {\n let next = withKey(node, \"type\", typeValue(typeSelect.value, nullBox.checked));\n if (typeSelect.value !== \"object\") {\n next = withKey(withKey(next, \"properties\", undefined), \"required\", undefined);\n }\n if (typeSelect.value !== \"array\") next = withKey(next, \"items\", undefined);\n if (typeSelect.value !== \"string\") next = withKey(next, \"pattern\", undefined);\n if (!ENUM_TYPES.has(typeSelect.value)) next = withKey(next, \"enum\", undefined);\n apply(next);\n });\n // Header row: [name?] [type] [nullable] [required?] [remove?]\n rows.push(\n h(\"div\", { class: \"wgd-sb-row\" }, [\n ...lead,\n typeSelect,\n h(\"label\", { class: \"wgd-sb-req wgd-sb-null\", title: \"Also allows null\" }, [\n nullBox,\n \"null\"\n ]),\n ...trail\n ])\n );\n\n // Constraints row \u2014 only the ones this type can actually use.\n const constraints: (Node | string)[] = [];\n if (typeSelect.value === \"string\") {\n const pattern = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-constraint\",\n placeholder: \"pattern (regex, optional)\"\n });\n pattern.value = typeof node.pattern === \"string\" ? node.pattern : \"\";\n pattern.addEventListener(\"change\", () =>\n apply(withKey(node, \"pattern\", pattern.value === \"\" ? undefined : pattern.value))\n );\n constraints.push(h(\"span\", { class: \"wgd-sb-label\" }, [\"pattern\"]), pattern);\n }\n const enumError = diagnosticLine(undefined);\n // `enum` is type-agnostic in the validator, but enumerating whole\n // objects/arrays is a JSON-tab affair \u2014 the builder offers it where\n // it is actually useful.\n if (ENUM_TYPES.has(typeSelect.value)) {\n const enumInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-constraint\",\n placeholder: 'enum [\"a\",\"b\"] (optional)'\n });\n enumInput.value = Array.isArray(node.enum) ? JSON.stringify(node.enum) : \"\";\n enumInput.addEventListener(\"change\", () => {\n if (enumInput.value.trim() === \"\") {\n enumError.hidden = true;\n apply(withKey(node, \"enum\", undefined));\n return;\n }\n try {\n const parsed: unknown = JSON.parse(enumInput.value);\n if (!Array.isArray(parsed)) throw new Error(\"must be a JSON array\");\n enumError.hidden = true;\n apply(withKey(node, \"enum\", parsed));\n } catch (error) {\n enumError.hidden = false;\n enumError.textContent = `enum ignored: ${errorMessage(error)}`;\n }\n });\n constraints.push(h(\"span\", { class: \"wgd-sb-label\" }, [\"enum\"]), enumInput);\n }\n if (constraints.length > 0) {\n rows.push(h(\"div\", { class: \"wgd-sb-row wgd-sb-constraints\" }, constraints), enumError);\n }\n\n // Object: property cards + required toggles\n if (typeSelect.value === \"object\") {\n const properties = isPlainObject(node.properties) ? node.properties : {};\n const required = Array.isArray(node.required)\n ? node.required.filter((k): k is string => typeof k === \"string\")\n : [];\n const cards = h(\"div\", { class: \"wgd-jt-children\" });\n for (const [name, sub] of Object.entries(properties)) {\n const nameInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-sb-prop\",\n placeholder: \"property name\"\n });\n nameInput.value = name;\n nameInput.addEventListener(\"change\", () => {\n const entries = Object.entries(properties).map(([k, v]) =>\n k === name ? ([nameInput.value, v] as const) : ([k, v] as const)\n );\n const nextRequired = required.map((k) => (k === name ? nameInput.value : k));\n apply(\n withKey(\n withKey(node, \"properties\", Object.fromEntries(entries)),\n \"required\",\n nextRequired.length > 0 ? nextRequired : undefined\n )\n );\n });\n const requiredBox = h(\"input\", { type: \"checkbox\", title: \"required\" });\n requiredBox.checked = required.includes(name);\n requiredBox.addEventListener(\"change\", () => {\n const nextRequired = requiredBox.checked\n ? [...required, name]\n : required.filter((k) => k !== name);\n apply(withKey(node, \"required\", nextRequired.length > 0 ? nextRequired : undefined));\n });\n const removeProp = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove property\" }, [\"\u2715\"]);\n removeProp.addEventListener(\"click\", () => {\n const { [name]: _gone, ...rest } = properties;\n apply(\n withKey(\n withKey(node, \"properties\", Object.keys(rest).length > 0 ? rest : undefined),\n \"required\",\n required.filter((k) => k !== name).length > 0\n ? required.filter((k) => k !== name)\n : undefined\n )\n );\n });\n // Name, type, required and remove all share the property's first row.\n cards.append(\n renderNode(\n isPlainObject(sub) ? (sub as DataSchema) : {},\n (nextSub) =>\n apply(withKey(node, \"properties\", { ...properties, [name]: nextSub })),\n depth + 1,\n [nameInput],\n [\n h(\"label\", { class: \"wgd-sb-req\", title: \"required\" }, [requiredBox, \"req\"]),\n removeProp\n ]\n )\n );\n }\n const addProp = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ property\"\n ]);\n addProp.addEventListener(\"click\", () => {\n let name = \"field\";\n for (let i = 1; name in properties; i++) name = `field${i}`;\n apply(withKey(node, \"properties\", { ...properties, [name]: { type: \"string\" } }));\n });\n cards.append(h(\"div\", { class: \"wgd-toolbar\" }, [addProp]));\n rows.push(cards);\n }\n\n // Array: items node\n if (typeSelect.value === \"array\") {\n rows.push(\n h(\"div\", { class: \"wgd-slot\" }, [\n renderNode(\n isPlainObject(node.items) ? (node.items as DataSchema) : {},\n (nextItems) => apply(withKey(node, \"items\", nextItems)),\n depth + 1,\n [h(\"span\", { class: \"wgd-sb-label\" }, [\"items\"])]\n )\n ])\n );\n }\n\n return h(\"div\", { class: depth === 0 ? \"wgd-sb-root\" : \"wgd-sb-node\" }, rows);\n }\n\n function render(): void {\n if (current === undefined) {\n const start = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ add a data schema\"\n ]);\n start.addEventListener(\"click\", () => commit({ type: \"object\" }));\n element.replaceChildren(\n h(\"div\", undefined, [\n h(\"span\", { class: \"wgd-sb-label\" }, [\n \"No schema \u2014 data is accepted leniently.\"\n ]),\n h(\"div\", { class: \"wgd-toolbar\" }, [start])\n ])\n );\n return;\n }\n const clear = h(\"button\", { class: \"wgd-button wgd-add wgd-remove\", type: \"button\" }, [\n \"remove schema\"\n ]);\n clear.addEventListener(\"click\", () => commit(undefined));\n element.replaceChildren(\n renderNode(current, (next) => commit(next), 0),\n h(\"div\", { class: \"wgd-toolbar\" }, [clear])\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(schema) {\n if (element.contains(document.activeElement)) return;\n current = schema;\n render();\n }\n };\n}\n", "/**\n * Flat editor for a string\u2192string record (hints: name \u2192 doc), under the\n * same flat discipline as the styles tree \u2014 one slim row per entry,\n * removal revealed by the row. Values are strings by construction, so\n * the tree enforces the exact shape; anything looser is a JSON-tab\n * affair.\n */\nimport { h } from \"./dom.js\";\n\nexport interface RecordEditor {\n element: HTMLElement;\n getValue(): Record<string, string> | undefined;\n setValue(record: Record<string, string> | undefined): void;\n}\n\nexport function createRecordEditor(\n initial: Record<string, string> | undefined,\n placeholders: { key: string; value: string; add: string },\n onChange: (record: Record<string, string> | undefined) => void\n): RecordEditor {\n let current: Record<string, string> | undefined = initial;\n const element = h(\"div\", { class: \"wgd-record\" });\n\n function commit(next: Record<string, string>): void {\n // An emptied record means \"none\" \u2014 the owning key drops entirely.\n current = Object.keys(next).length > 0 ? next : undefined;\n onChange(current);\n render();\n }\n\n function changeInput(\n value: string,\n placeholder: string,\n className: string,\n onCommit: (value: string) => void\n ): HTMLInputElement {\n const input = h(\"input\", {\n type: \"text\",\n class: className,\n placeholder,\n spellcheck: \"false\"\n });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n function render(): void {\n const record = current ?? {};\n const rows = Object.entries(record).map(([key, value]) => {\n const keyInput = changeInput(\n key,\n placeholders.key,\n \"wgd-input wgd-rec-key\",\n (next) => {\n const entries = Object.entries(record).map(([k, v]) =>\n k === key ? ([next, v] as const) : ([k, v] as const)\n );\n commit(Object.fromEntries(entries));\n }\n );\n const valueInput = changeInput(\n value,\n placeholders.value,\n \"wgd-input wgd-rec-value\",\n (next) => commit({ ...record, [key]: next })\n );\n const remove = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove entry\" },\n [\"\u2715\"]\n );\n remove.addEventListener(\"click\", () => {\n const { [key]: _gone, ...rest } = record;\n commit(rest);\n });\n return h(\"div\", { class: \"wgd-rec-row\" }, [\n keyInput,\n h(\"span\", { class: \"wgd-st-colon\" }, [\":\"]),\n valueInput,\n remove\n ]);\n });\n const add = h(\n \"button\",\n { class: \"wgd-button wgd-add wgd-st-add\", type: \"button\" },\n [placeholders.add]\n );\n add.addEventListener(\"click\", () => {\n let key = \"\";\n for (let i = 1; key in record; i++) key = `key${i}`;\n commit({ ...record, [key]: \"\" });\n });\n element.replaceChildren(...rows, h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(record) {\n if (element.contains(document.activeElement)) return;\n current = record;\n render();\n }\n };\n}\n", "/**\n * Schema-driven data form: generates controls from widgentic's dataSchema\n * subset (type/properties/required/items/enum/pattern). This is the\n * @json-editor/json-editor interaction model, sized to the six keywords\n * the subset actually has \u2014 which is what makes an in-house generator a\n * few hundred lines instead of a 150 KB dependency.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\n\nfunction firstType(schema: DataSchema): string | undefined {\n const type = schema.type;\n if (typeof type === \"string\") return type;\n if (Array.isArray(type)) {\n // Nullable arrays pick the PRIMARY type regardless of order.\n const primary = type.find((t) => typeof t === \"string\" && t !== \"null\");\n if (typeof primary === \"string\") return primary;\n if (type.includes(\"null\")) return \"null\";\n }\n return undefined;\n}\n\nfunction seedFor(schema: DataSchema): unknown {\n if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];\n switch (firstType(schema)) {\n case \"object\": {\n const seed: Record<string, unknown> = {};\n if (isPlainObject(schema.properties) && Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (typeof key === \"string\" && isPlainObject(schema.properties[key])) {\n seed[key] = seedFor(schema.properties[key] as DataSchema);\n }\n }\n }\n return seed;\n }\n case \"array\":\n return [];\n case \"number\":\n case \"integer\":\n return 0;\n case \"boolean\":\n return false;\n case \"null\":\n return null;\n default:\n return \"\";\n }\n}\n\nexport interface SchemaForm {\n element: HTMLElement;\n getValue(): unknown;\n setValue(value: unknown): void;\n}\n\nexport function createSchemaForm(\n schema: DataSchema,\n initial: unknown,\n onChange: (value: unknown) => void\n): SchemaForm {\n let current: unknown = initial ?? seedFor(schema);\n const element = h(\"div\", { class: \"wgd-schemaform\" });\n\n type Path = (string | number)[];\n\n function setAt(root: unknown, path: Path, value: unknown, remove = false): unknown {\n if (path.length === 0) return value;\n const [step, ...rest] = path as [string | number, ...Path];\n if (Array.isArray(root)) {\n const copy = [...root];\n if (rest.length === 0 && remove) copy.splice(step as number, 1);\n else copy[step as number] = setAt(copy[step as number], rest, value, remove);\n return copy;\n }\n const holder = isPlainObject(root) ? { ...root } : {};\n if (rest.length === 0 && remove) delete holder[step as string];\n else holder[step as string] = setAt(holder[step as string], rest, value, remove);\n return holder;\n }\n\n function commit(path: Path, value: unknown, rerender = false): void {\n current = setAt(current, path, value);\n onChange(current);\n if (rerender) render();\n }\n\n function control(node: DataSchema, value: unknown, path: Path, label: string): HTMLElement {\n if (Array.isArray(node.enum)) {\n const select = h(\"select\", { class: \"wgd-select\" });\n for (const option of node.enum) {\n select.append(h(\"option\", { value: JSON.stringify(option) }, [JSON.stringify(option)]));\n }\n select.value = JSON.stringify(value ?? node.enum[0]);\n select.addEventListener(\"change\", () =>\n commit(path, JSON.parse(select.value) as unknown)\n );\n return field(label, select);\n }\n switch (firstType(node)) {\n case \"boolean\": {\n const box = h(\"input\", { type: \"checkbox\" });\n box.checked = value === true;\n box.addEventListener(\"change\", () => commit(path, box.checked));\n return field(label, box);\n }\n case \"number\":\n case \"integer\": {\n const input = h(\"input\", { type: \"number\", class: \"wgd-input\" });\n input.value = typeof value === \"number\" ? String(value) : \"0\";\n input.addEventListener(\"change\", () => {\n const parsed = Number(input.value);\n commit(path, Number.isFinite(parsed) ? parsed : 0);\n });\n return field(label, input);\n }\n case \"object\": {\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n const properties = isPlainObject(node.properties) ? node.properties : {};\n const required = Array.isArray(node.required) ? node.required : [];\n const holder = isPlainObject(value) ? value : {};\n for (const [name, sub] of Object.entries(properties)) {\n if (!isPlainObject(sub)) continue;\n const isRequired = required.includes(name);\n body.append(\n control(\n sub as DataSchema,\n holder[name] ?? (isRequired ? seedFor(sub as DataSchema) : undefined),\n [...path, name],\n isRequired ? `${name} *` : name\n )\n );\n }\n return h(\"fieldset\", { class: \"wgd-sf-object\" }, [\n h(\"legend\", { class: \"wgd-field-label\" }, [label]),\n body\n ]);\n }\n case \"array\": {\n const itemsSchema = isPlainObject(node.items) ? (node.items as DataSchema) : {};\n const items = Array.isArray(value) ? value : [];\n const body = h(\"div\", { class: \"wgd-jt-children\" });\n items.forEach((item, index) => {\n const row = h(\"div\", { class: \"wgd-jt-entry\" }, [\n control(itemsSchema, item, [...path, index], `#${index}`)\n ]);\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove item\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => {\n current = setAt(current, [...path, index], undefined, true);\n onChange(current);\n render();\n });\n row.append(remove);\n body.append(row);\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ item\"]);\n add.addEventListener(\"click\", () =>\n commit([...path, items.length], seedFor(itemsSchema), true)\n );\n body.append(h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n return h(\"fieldset\", { class: \"wgd-sf-object\" }, [\n h(\"legend\", { class: \"wgd-field-label\" }, [label]),\n body\n ]);\n }\n default: {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input\" });\n if (typeof node.pattern === \"string\") {\n input.setAttribute(\"placeholder\", `pattern: ${node.pattern}`);\n input.setAttribute(\"title\", `Must match ${node.pattern}`);\n }\n input.value = typeof value === \"string\" ? value : value === undefined ? \"\" : String(value);\n input.addEventListener(\"change\", () => commit(path, input.value));\n return field(label, input);\n }\n }\n }\n\n function field(label: string, controlEl: Node): HTMLElement {\n return h(\"label\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [label]),\n controlEl\n ]);\n }\n\n function render(): void {\n element.replaceChildren(control(schema, current, [], \"data\"));\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(value) {\n if (element.contains(document.activeElement)) return;\n current = value ?? seedFor(schema);\n render();\n }\n };\n}\n", "/**\n * Structured editor for the descriptor's styles \u2014 selector rows with\n * their declaration rows, under the template tree's flat discipline.\n * The value is `Record<selector, Record<property, value>>` (strings\n * only), so the tree enforces the exact shape the server's style guards\n * expect; anything looser belongs in the JSON tab.\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\n\nexport type WidgetStylesValue = Record<string, Record<string, string>>;\n\nexport interface StylesEditor {\n element: HTMLElement;\n getValue(): WidgetStylesValue | undefined;\n setValue(styles: WidgetStylesValue | undefined): void;\n}\n\nexport function createStylesEditor(\n initial: WidgetStylesValue | undefined,\n onChange: (styles: WidgetStylesValue | undefined) => void\n): StylesEditor {\n let current: WidgetStylesValue | undefined = initial;\n const element = h(\"div\", { class: \"wgd-styles\" });\n\n function commit(next: WidgetStylesValue): void {\n // An emptied record means \"no styles\" \u2014 the descriptor drops the key.\n current = Object.keys(next).length > 0 ? next : undefined;\n onChange(current);\n render();\n }\n\n function changeInput(\n value: string,\n placeholder: string,\n className: string,\n onCommit: (value: string) => void\n ): HTMLInputElement {\n const input = h(\"input\", {\n type: \"text\",\n class: className,\n placeholder,\n spellcheck: \"false\"\n });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n function renderSelector(\n selector: string,\n declarations: Record<string, string>,\n styles: WidgetStylesValue\n ): HTMLElement {\n const rename = changeInput(\n selector,\n \".wg-selector\",\n \"wgd-input wgd-st-selector\",\n (next) => {\n const entries = Object.entries(styles).map(([k, v]) =>\n k === selector ? ([next, v] as const) : ([k, v] as const)\n );\n commit(Object.fromEntries(entries));\n }\n );\n const addDecl = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Add declaration\" },\n [\"+\"]\n );\n addDecl.addEventListener(\"click\", () => {\n commit({ ...styles, [selector]: { ...declarations, \"\": \"\" } });\n });\n const removeSelector = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove selector\" },\n [\"\u2715\"]\n );\n removeSelector.addEventListener(\"click\", () => {\n const { [selector]: _gone, ...rest } = styles;\n commit(rest);\n });\n const declRows = Object.entries(declarations).map(([property, value]) => {\n const propInput = changeInput(\n property,\n \"property\",\n \"wgd-input wgd-st-prop\",\n (next) => {\n const entries = Object.entries(declarations).map(([k, v]) =>\n k === property ? ([next, v] as const) : ([k, v] as const)\n );\n commit({ ...styles, [selector]: Object.fromEntries(entries) });\n }\n );\n const valueInput = changeInput(\n value,\n \"value (no url(...), no ;)\",\n \"wgd-input wgd-st-value\",\n (next) => {\n commit({\n ...styles,\n [selector]: { ...declarations, [property]: next }\n });\n }\n );\n const removeDecl = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Remove declaration\" },\n [\"\u2715\"]\n );\n removeDecl.addEventListener(\"click\", () => {\n const { [property]: _gone, ...rest } = declarations;\n commit({ ...styles, [selector]: rest });\n });\n return h(\"div\", { class: \"wgd-st-decl\" }, [\n propInput,\n h(\"span\", { class: \"wgd-st-colon\" }, [\":\"]),\n valueInput,\n removeDecl\n ]);\n });\n return h(\"div\", { class: \"wgd-st-rule\" }, [\n h(\"div\", { class: \"wgd-st-row\" }, [\n rename,\n h(\"span\", { class: \"wgd-node-icons\" }, [addDecl, removeSelector])\n ]),\n h(\"div\", { class: \"wgd-st-decls\" }, declRows)\n ]);\n }\n\n function render(): void {\n const styles = current ?? {};\n const addSelector = h(\n \"button\",\n { class: \"wgd-button wgd-add wgd-st-add\", type: \"button\" },\n [\"+ selector\"]\n );\n addSelector.addEventListener(\"click\", () => {\n let name = \".wg-\";\n for (let i = 1; name in styles; i++) name = `.wg-${i}`;\n commit({ ...styles, [name]: {} });\n });\n element.replaceChildren(\n ...Object.entries(styles).map(([selector, declarations]) =>\n renderSelector(\n selector,\n isPlainObject(declarations)\n ? (declarations as Record<string, string>)\n : {},\n styles\n )\n ),\n h(\"div\", { class: \"wgd-toolbar\" }, [addSelector])\n );\n }\n\n render();\n\n return {\n element,\n getValue: () => current,\n setValue(styles) {\n if (element.contains(document.activeElement)) return;\n current = styles;\n render();\n }\n };\n}\n", "/**\n * The styles panel both designers mount \u2014 a widget's descriptor styles and\n * a theme's shared styles are one shape under one rule set, so they get one\n * editor: the structured Tree and a parse-gated JSON view over the same\n * value, plus the audit's list of entries the renderer would drop.\n */\nimport { isStyleMap } from \"@widgentic/core\";\nimport type { WidgetStyles } from \"@widgentic/core\";\nimport { diagnosticLine, h, requireChild, section, tabs, textArea } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { errorMessage } from \"./internal.js\";\nimport { createStylesEditor } from \"./styles-editor.js\";\nimport type { StyleIssue } from \"./validate.js\";\n\nexport interface StylesPanel {\n element: HTMLElement;\n /** Reflect a value set elsewhere; the JSON view keeps a focused edit. */\n setValue(styles: WidgetStyles | undefined): void;\n setIssues(issues: StyleIssue[]): void;\n}\n\nexport function createStylesPanel(\n initial: WidgetStyles | undefined,\n onChange: (styles: WidgetStyles | undefined) => void\n): StylesPanel {\n // The two views keep each other in step: an edit in one reaches the\n // other before the host hears of it, whatever the host refreshes.\n const tree = createStylesEditor(initial, (styles) => {\n showJson(styles);\n onChange(styles);\n });\n const parseError = diagnosticLine(undefined);\n // No legend \u2014 the section title already names the shape.\n const field = textArea(\"\", initial === undefined ? \"\" : JSON.stringify(initial, null, 2), (text) => {\n if (text.trim() === \"\") {\n parseError.hidden = true;\n tree.setValue(undefined);\n onChange(undefined);\n return;\n }\n try {\n const value: unknown = JSON.parse(text);\n parseError.hidden = true;\n parseError.textContent = \"\";\n // Last valid wins: only the styles shape reaches the value, and an\n // empty map is no styles, as the Tree view has it.\n if (!isStyleMap(value)) {\n parseError.hidden = false;\n parseError.textContent =\n \"Styles must map selectors to objects of property/value strings (the last valid value is kept).\";\n return;\n }\n const next = Object.keys(value).length > 0 ? value : undefined;\n tree.setValue(next);\n onChange(next);\n } catch (error) {\n parseError.hidden = false;\n parseError.textContent = `Invalid JSON (the last valid value is kept): ${errorMessage(error)}`;\n }\n });\n const area = requireChild(field, \"textarea\");\n attachJsonHighlight(area);\n\n function showJson(styles: WidgetStyles | undefined): void {\n if (document.activeElement === area) return;\n area.value = styles === undefined ? \"\" : JSON.stringify(styles, null, 2);\n repaintHighlight(area); // programmatic writes fire no input event\n // The text now shown is valid: an earlier parse error no longer applies.\n parseError.hidden = true;\n parseError.textContent = \"\";\n }\n\n const issues = h(\"div\");\n const element = section(\"Styles (.wg- selectors only)\", [\n tabs([\n { label: \"Tree\", element: tree.element },\n { label: \"JSON\", element: h(\"div\", undefined, [field, parseError]) }\n ]),\n issues\n ]);\n return {\n element,\n setValue(styles) {\n tree.setValue(styles);\n showJson(styles);\n },\n setIssues(list) {\n issues.replaceChildren(\n ...list.map((issue) =>\n diagnosticLine(`${issue.selector}${issue.property ? ` \u2192 ${issue.property}` : \"\"}: ${issue.message}`)\n )\n );\n }\n };\n}\n", "/**\n * Path helpers over widgentic's dataSchema subset, shared by the template\n * panel (bind/each/when completions) and the binding editor (input and\n * output mapping completions, type checks). Nullable type arrays pick the\n * PRIMARY type; `any` (no type) is treated as unknown, never mismatched.\n */\nimport { isPlainObject } from \"@widgentic/core\";\n/** The primary type a schema declares, if any. */\n/** How deep completions and type checks descend; schemas are JSON, but bounded anyway. */\nconst MAX_SCHEMA_DEPTH = 3;\n\nexport function schemaType(schema: unknown): string | undefined {\n if (!isPlainObject(schema)) return undefined;\n const type = schema.type;\n if (typeof type === \"string\") return type;\n if (Array.isArray(type)) {\n const primary = type.find((t) => typeof t === \"string\" && t !== \"null\");\n if (typeof primary === \"string\") return primary;\n }\n return undefined;\n}\n\n/**\n * Enumerate the paths a scope offers. Context-free on purpose: an array is\n * offered as ITSELF and never descended, because neither the template\n * resolver nor the projection steps into an array by name (`lines.qty`\n * resolves to nothing; `lines.0.qty` does). A caller whose scope IS the\n * item \u2014 a template inside an each, a projection over a list response \u2014\n * passes the item schema (`itemSchema`) instead.\n */\nexport function collectPaths(\n schema: unknown,\n prefix: string,\n out: { path: string; schema: unknown }[],\n depth = 0\n): void {\n if (!isPlainObject(schema) || depth > MAX_SCHEMA_DEPTH) return;\n if (schemaType(schema) !== \"object\" || !isPlainObject(schema.properties)) return;\n for (const [name, sub] of Object.entries(schema.properties)) {\n const path = prefix === \"\" ? name : `${prefix}.${name}`;\n out.push({ path, schema: sub });\n collectPaths(sub, path, out, depth + 1);\n }\n}\n\n/** The item schema of an array, or the schema itself when it is not one. */\nexport function itemSchema(schema: unknown): unknown {\n return isPlainObject(schema) && schemaType(schema) === \"array\"\n ? schema.items\n : schema;\n}\n\n/** The sub-schema at a dotted path (\"\" or \".\" is the schema itself). */\nexport function schemaAt(schema: unknown, path: string): unknown {\n if (path === \"\" || path === \".\") return schema;\n let current: unknown = schema;\n for (const segment of path.split(\".\")) {\n if (!isPlainObject(current)) return undefined;\n if (schemaType(current) === \"array\") {\n // Arrays are stepped into by INDEX only \u2014 the resolvers' own rule.\n if (!/^\\d+$/.test(segment)) return undefined;\n current = itemSchema(current);\n continue;\n }\n if (!isPlainObject(current.properties)) return undefined;\n current = current.properties[segment];\n }\n return current;\n}\n\n/** Numeric types agree with each other; unknown never mismatches. */\nexport function typesConflict(a: string | undefined, b: string | undefined): boolean {\n if (a === undefined || b === undefined) return false;\n const norm = (t: string) => (t === \"integer\" ? \"number\" : t);\n return norm(a) !== norm(b);\n}\n\n/**\n * Compare a source and a target schema for the projection editor,\n * descending MATCHED array sides so two lists are judged by their ITEM\n * types \u2014 the shape a per-item projection has. Returns the conflicting\n * type labels, or `undefined` when the two agree.\n */\nexport function schemaMismatch(\n source: unknown,\n target: unknown\n): { source: string | undefined; target: string | undefined } | undefined {\n let a = source;\n let b = target;\n for (let depth = 0; depth < MAX_SCHEMA_DEPTH; depth++) {\n if (schemaType(a) !== \"array\" || schemaType(b) !== \"array\") break;\n a = itemSchema(a);\n b = itemSchema(b);\n }\n const sourceType = schemaType(a);\n const targetType = schemaType(b);\n return typesConflict(sourceType, targetType)\n ? { source: sourceType, target: targetType }\n : undefined;\n}\n\n/** All dotted paths under a schema (leaves and branches), for completions. */\nexport function allPaths(schema: unknown): string[] {\n const entries: { path: string; schema: unknown }[] = [];\n collectPaths(schema, \"\", entries);\n return entries.map((entry) => entry.path);\n}\n", "/**\n * Shared editors for the action model: an action DEFINITION (prompt or\n * http) and a BINDING (shared ref or inline definition, plus the input\n * mapping and output mode). The standalone action designer edits\n * definitions; the widget designer binds them to elements and to the\n * widget's `load`. Everything is plain DOM over immutable values, and no\n * network I/O happens here \u2014 testing an action is the host's job.\n *\n * Handlers read the editor's live state at event time and a commit\n * re-renders only its own section, so two edits in a row never lose each\n * other and focus survives a commit. Rows without a name (a new header,\n * query parameter or projection) live in editor-local state until they are\n * named; only named rows reach `onChange`.\n */\nimport type { DataSchema } from \"@widgentic/core\";\nimport type {\n ActionBinding,\n ActionDefinition,\n HttpActionDefinition,\n InputMapping,\n OutputBinding,\n OutputMode,\n PromptSegment,\n StoredAction\n} from \"@widgentic/core\";\nimport { HTTP_METHODS, OUTPUT_MODES } from \"@widgentic/core\";\nimport { clone } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport { diagnosticLine, fitSelect, h, select } from \"./dom.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { allPaths, itemSchema, schemaAt, schemaMismatch, schemaType } from \"./schema-paths.js\";\n\n/** The path select's escape hatch to free text. */\nconst CUSTOM_PATH = \"__custom__\";\n\ntype HeaderValue = string | { secret: string };\ntype HeaderMap = Record<string, HeaderValue>;\ntype RefBinding = { ref: string } & Pick<ActionBinding, \"input\" | \"output\">;\n\nexport interface ActionEditorContext {\n /** Shared schemas offered as \"copy from\" sources for input/output. */\n schemas?: SchemaEntry[];\n /** Secret names offered for header/query values. */\n secretNames?: string[];\n}\n\nexport function starterPromptDefinition(): ActionDefinition {\n return { kind: \"prompt\", text: [\"Tell me more about \", { bind: \"title\" }] };\n}\n\nexport function starterHttpDefinition(): HttpActionDefinition {\n return {\n kind: \"http\",\n method: \"GET\",\n url: \"https://api.example.com/resource\",\n input: { type: \"object\", properties: {} },\n output: { type: \"object\" }\n };\n}\n\nfunction isRefBinding(binding: ActionBinding): binding is RefBinding {\n return \"ref\" in binding && typeof binding.ref === \"string\";\n}\n\nfunction textInput(value: string, className: string, onCommit: (value: string) => void, placeholder = \"\"): HTMLInputElement {\n const el = h(\"input\", { type: \"text\", class: className, placeholder });\n el.value = value;\n el.addEventListener(\"change\", () => onCommit(el.value));\n return el;\n}\n\n\nfunction label(text: string): HTMLElement {\n return h(\"span\", { class: \"wgd-field-label\" }, [text]);\n}\n\nfunction removeButton(onClick: () => void): HTMLElement {\n const button = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n button.addEventListener(\"click\", onClick);\n return button;\n}\n\n/**\n * Path picker: a select over the known paths (plus the current value when\n * it is off-schema) with a \"custom\u2026\" escape to free text \u2014 the template\n * panel's pathControl, for mappings. The placeholder option clears the\n * value. With no known paths it is a text input.\n */\nfunction pathSelect(\n value: string,\n options: string[],\n onCommit: (path: string) => void,\n placeholder: string,\n className = \"wgd-input wgd-rec-value\"\n): HTMLElement {\n if (options.length === 0) return textInput(value, className, onCommit, placeholder);\n const sel = h(\"select\", { class: \"wgd-select wgd-path\" });\n const known = options.includes(value);\n const listed = known || value === \"\" ? options : [value, ...options];\n sel.append(h(\"option\", { value: \"\" }, [placeholder]));\n for (const option of listed) {\n sel.append(h(\"option\", { value: option }, [option === value && !known ? `${option} (off-schema)` : option]));\n }\n sel.append(h(\"option\", { value: CUSTOM_PATH }, [\"custom\u2026\"]));\n sel.value = value;\n fitSelect(sel);\n const custom = textInput(value, className, onCommit, placeholder);\n custom.hidden = true;\n sel.addEventListener(\"change\", () => {\n if (sel.value === CUSTOM_PATH) {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(sel.value);\n });\n return h(\"span\", { class: \"wgd-pathwrap\" }, [sel, custom]);\n}\n\n/**\n * Header/query map rows: name, literal-or-secret mode, value. Unnamed rows\n * are editor-local; a rename onto an existing name is flagged, not applied.\n */\nfunction headerMapEditor(\n initial: HeaderMap | undefined,\n secretNames: string[],\n labels: { add: string; name: string },\n onChange: (next: HeaderMap | undefined) => void\n): HTMLElement {\n let current: HeaderMap = clone(initial ?? {});\n const pending: { value: HeaderValue }[] = [];\n const element = h(\"div\", { class: \"wgd-record wgd-headers\" });\n const duplicate = diagnosticLine(undefined);\n\n function commit(next: HeaderMap): void {\n current = next;\n onChange(Object.keys(current).length > 0 ? current : undefined);\n render();\n }\n function flagDuplicate(name: string): void {\n duplicate.hidden = false;\n duplicate.textContent = `'${name}' is already used; pick another ${labels.name} name.`;\n }\n function valueControl(value: HeaderValue, onValue: (next: HeaderValue) => void): HTMLElement[] {\n const isSecret = isPlainObject(value);\n const mode = select(\n [{ value: \"literal\" }, { value: \"secret\" }],\n isSecret ? \"secret\" : \"literal\",\n \"wgd-select wgd-attr-mode\",\n (next) => onValue(next === \"secret\" ? { secret: secretNames[0] ?? \"\" } : \"\")\n );\n if (isSecret) {\n const names = secretNames.includes(value.secret) ? secretNames : [value.secret, ...secretNames];\n const picker = select(\n names.map((n) => ({ value: n, label: n === \"\" ? \"(pick a secret)\" : n })),\n value.secret,\n \"wgd-select wgd-secret\",\n (next) => onValue({ secret: next })\n );\n return [mode, picker];\n }\n return [mode, textInput(value, \"wgd-input wgd-rec-value\", onValue, \"value\")];\n }\n function render(): void {\n element.replaceChildren();\n duplicate.hidden = true;\n for (const [name, value] of Object.entries(current)) {\n const nameInput = textInput(name, \"wgd-input wgd-rec-key\", (next) => {\n if (next === name) return;\n if (next === \"\" || Object.hasOwn(current, next)) { flagDuplicate(next || \"(empty)\"); return; }\n const entries = Object.entries(current).map(([k, v]) => (k === name ? [next, v] : [k, v]));\n commit(Object.fromEntries(entries));\n }, labels.name);\n const controls = valueControl(value, (next) => commit({ ...current, [name]: next }));\n const remove = removeButton(() => {\n const { [name]: _gone, ...rest } = current;\n commit(rest);\n });\n element.append(h(\"div\", { class: \"wgd-rec-row\" }, [nameInput, ...controls, remove]));\n }\n pending.forEach((row, index) => {\n const nameInput = textInput(\"\", \"wgd-input wgd-rec-key\", (next) => {\n if (next === \"\") return;\n if (Object.hasOwn(current, next)) { flagDuplicate(next); return; }\n pending.splice(index, 1);\n commit({ ...current, [next]: row.value });\n }, labels.name);\n const controls = valueControl(row.value, (next) => { row.value = next; render(); });\n const remove = removeButton(() => { pending.splice(index, 1); render(); });\n element.append(h(\"div\", { class: \"wgd-rec-row wgd-rec-pending\" }, [nameInput, ...controls, remove]));\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [labels.add]);\n add.addEventListener(\"click\", () => { pending.push({ value: \"\" }); render(); });\n element.append(h(\"div\", { class: \"wgd-row\" }, [add]), duplicate);\n }\n render();\n return element;\n}\n\n/** Prompt text: ordered literal/bind segments. */\nfunction segmentsEditor(initial: PromptSegment[], onChange: (next: PromptSegment[]) => void): HTMLElement {\n let current = clone(initial);\n const element = h(\"div\", { class: \"wgd-record wgd-segments\" });\n function commit(next: PromptSegment[]): void {\n current = next;\n onChange(current);\n render();\n }\n function render(): void {\n element.replaceChildren();\n current.forEach((segment, index) => {\n const isBind = typeof segment !== \"string\";\n const mode = select([{ value: \"text\" }, { value: \"bind\" }], isBind ? \"bind\" : \"text\", \"wgd-select wgd-attr-mode\", (next) => {\n const copy = [...current];\n copy[index] = next === \"bind\" ? { bind: \".\" } : \"\";\n commit(copy);\n });\n const value = textInput(\n isBind ? segment.bind : segment,\n \"wgd-input wgd-rec-value\",\n (next) => {\n const copy = [...current];\n copy[index] = isBind ? { bind: next } : next;\n commit(copy);\n },\n isBind ? \"data path\" : \"text\"\n );\n const remove = removeButton(() => commit(current.filter((_, i) => i !== index)));\n element.append(h(\"div\", { class: \"wgd-rec-row\" }, [mode, value, remove]));\n });\n const addText = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ text\"]);\n addText.addEventListener(\"click\", () => commit([...current, \"\"]));\n const addBind = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ bind\"]);\n addBind.addEventListener(\"click\", () => commit([...current, { bind: \".\" }]));\n element.append(h(\"div\", { class: \"wgd-row\" }, [addText, addBind]));\n }\n render();\n return element;\n}\n\nexport interface DefinitionEditor {\n element: HTMLElement;\n getValue(): ActionDefinition;\n setValue(definition: ActionDefinition): void;\n}\n\n/** Editor for one action definition, either kind. */\nexport function createDefinitionEditor(\n initial: ActionDefinition | undefined,\n ctx: ActionEditorContext,\n onChange: (definition: ActionDefinition) => void\n): DefinitionEditor {\n let current: ActionDefinition = clone(initial ?? starterPromptDefinition());\n const headEl = h(\"div\", { class: \"wgd-action-head\" });\n const schemasEl = h(\"div\", { class: \"wgd-action-schemas\" });\n const mapsEl = h(\"div\", { class: \"wgd-action-maps\" });\n const element = h(\"div\", { class: \"wgd-action-definition\" }, [headEl, schemasEl, mapsEl]);\n\n /** The live http definition; handlers call this at event time, never a render-time copy. */\n function http(): HttpActionDefinition {\n return current as HttpActionDefinition;\n }\n\n function commit(next: ActionDefinition, rerender: \"all\" | \"schemas\" | \"none\"): void {\n current = next;\n onChange(clone(current));\n if (rerender === \"all\") render();\n else if (rerender === \"schemas\") renderSchemas();\n }\n\n function schemaSection(title: string, which: \"input\" | \"output\"): HTMLElement {\n const builder = createSchemaBuilder(http()[which] as DataSchema, (schema) => {\n commit({ ...http(), [which]: schema ?? { type: \"object\" } }, \"none\");\n });\n const parts: (Node | string)[] = [label(title), builder.element];\n const shared = ctx.schemas ?? [];\n if (shared.length > 0) {\n // Actions store their schemas INLINE (a contract must not drift when a\n // shared schema is edited), so this is a copy \u2014 and says so.\n const copyFrom = select(\n [{ value: \"\", label: \"copy a shared schema into this action\u2026\" }, ...shared.map((s) => ({ value: s.name }))],\n \"\",\n \"wgd-select\",\n (name) => {\n const entry = shared.find((s) => s.name === name);\n if (entry) commit({ ...http(), [which]: clone(entry.schema) }, \"schemas\");\n }\n );\n parts.push(h(\"div\", { class: \"wgd-row\" }, [copyFrom, label(\"(a copy \u2014 later edits to the shared schema do not follow)\")]));\n }\n return h(\"div\", { class: \"wgd-action-schema\" }, parts);\n }\n\n function renderHead(): void {\n headEl.replaceChildren();\n const kind = select(\n [{ value: \"prompt\", label: \"prompt \u2014 propose a message\" }, { value: \"http\", label: \"http \u2014 call an API\" }],\n current.kind,\n \"wgd-select wgd-action-kind\",\n (next) => commit(next === \"http\" ? starterHttpDefinition() : starterPromptDefinition(), \"all\")\n );\n if (current.kind === \"prompt\") {\n headEl.append(\n h(\"div\", { class: \"wgd-row\" }, [label(\"Kind\"), kind]),\n label(\"Message (literals and bound values; the user reviews and sends it)\"),\n segmentsEditor(current.text, (text) => commit({ kind: \"prompt\", text }, \"none\"))\n );\n return;\n }\n const method = select(HTTP_METHODS.map((m) => ({ value: m })), current.method, \"wgd-select\", (next) =>\n commit({ ...http(), method: next as HttpActionDefinition[\"method\"] }, \"none\")\n );\n // Kind and method describe one thing \u2014 what call this is \u2014 so they share a row.\n const url = textInput(current.url, \"wgd-input wgd-action-url\", (next) => commit({ ...http(), url: next }, \"none\"), \"https://\u2026\");\n headEl.append(\n h(\"div\", { class: \"wgd-row\" }, [label(\"Kind\"), kind, label(\"Method\"), method]),\n h(\"label\", { class: \"wgd-field\" }, [label(\"URL (https, fixed)\"), url])\n );\n }\n\n function renderSchemas(): void {\n schemasEl.replaceChildren();\n if (current.kind !== \"http\") return;\n schemasEl.append(\n schemaSection(\"Input schema (arguments; GET \u2192 query, POST \u2192 JSON body)\", \"input\"),\n schemaSection(\"Output schema (the response must satisfy it)\", \"output\")\n );\n }\n\n function renderMaps(): void {\n mapsEl.replaceChildren();\n if (current.kind !== \"http\") return;\n const secretNames = ctx.secretNames ?? [];\n mapsEl.append(\n label(\"Headers\"),\n headerMapEditor(current.headers, secretNames, { add: \"+ header\", name: \"header\" }, (headers) => {\n const { headers: _h, ...rest } = http();\n commit(headers === undefined ? rest : { ...rest, headers }, \"none\");\n }),\n label(\"Fixed query parameters\"),\n headerMapEditor(current.query, secretNames, { add: \"+ parameter\", name: \"parameter\" }, (query) => {\n const { query: _q, ...rest } = http();\n commit(query === undefined ? rest : { ...rest, query }, \"none\");\n })\n );\n }\n\n function render(): void {\n renderHead();\n renderSchemas();\n renderMaps();\n }\n render();\n return {\n element,\n getValue: () => clone(current),\n setValue(definition) {\n current = clone(definition);\n render();\n }\n };\n}\n\nexport interface BindingEditorContext extends ActionEditorContext {\n /** Shared actions offered by name. */\n actions?: StoredAction[];\n /** Data paths in scope at the bound element, offered as completions. */\n scopePaths?: string[];\n /** The widget's effective data schema (inline or resolved ref) \u2014 drives output-map targets and type checks. */\n getDataSchema?: () => DataSchema | undefined;\n /** `load` bindings: http GET only, no prompt. */\n loadOnly?: boolean;\n}\n\nexport interface BindingEditor {\n element: HTMLElement;\n setValue(binding: ActionBinding | undefined): void;\n}\n\n/** Editor for a binding: none / shared / inline, input mapping, output mode. */\nexport function createBindingEditor(\n initial: ActionBinding | undefined,\n ctx: BindingEditorContext,\n onChange: (binding: ActionBinding | undefined) => void\n): BindingEditor {\n let current: ActionBinding | undefined = initial === undefined ? undefined : clone(initial);\n const headEl = h(\"div\", { class: \"wgd-binding-head\" });\n const inputEl = h(\"div\", { class: \"wgd-binding-input\" });\n const outputEl = h(\"div\", { class: \"wgd-binding-output\" });\n const element = h(\"div\", { class: \"wgd-binding\" }, [headEl, inputEl, outputEl]);\n\n function definitionOf(binding: ActionBinding | undefined): ActionDefinition | undefined {\n if (binding === undefined) return undefined;\n if (isRefBinding(binding)) return (ctx.actions ?? []).find((a) => a.name === binding.ref)?.definition;\n return binding.definition;\n }\n const inputOf = (): InputMapping => clone(current?.input ?? {});\n const outputOf = (): OutputBinding => clone(current?.output ?? {});\n\n function commit(next: ActionBinding | undefined, rerender: \"all\" | \"io\" | \"input\" | \"output\" | \"none\"): void {\n current = next;\n onChange(next === undefined ? undefined : clone(next));\n if (rerender === \"all\") render();\n else if (rerender === \"io\") { renderInput(); renderOutput(); }\n else if (rerender === \"input\") renderInput();\n else if (rerender === \"output\") renderOutput();\n }\n\n function withMapping(binding: ActionBinding, input: InputMapping | undefined, output: OutputBinding | undefined): ActionBinding {\n const head: { ref: string } | { definition: ActionDefinition } = isRefBinding(binding)\n ? { ref: binding.ref }\n : { definition: binding.definition };\n return {\n ...head,\n ...(input !== undefined && Object.keys(input).length > 0 ? { input } : {}),\n ...(output !== undefined && Object.keys(output).length > 0 ? { output } : {})\n };\n }\n\n /** Helper completions are complete paths: the scope markers alone, plus every root path. */\n function helperPaths(): string[] {\n const root = allPaths(ctx.getDataSchema?.()).map((p) => `$root.${p}`);\n return [\"$index\", \"$parent\", \"$root\", ...root];\n }\n\n function renderHead(): void {\n headEl.replaceChildren();\n const shared = (ctx.actions ?? []).filter((a) => !ctx.loadOnly || (a.definition.kind === \"http\" && a.definition.method === \"GET\"));\n const mode = current === undefined ? \"none\" : isRefBinding(current) ? \"shared\" : \"inline\";\n const modeSelect = select(\n [{ value: \"none\", label: ctx.loadOnly ? \"no load action\" : \"no action\" }, { value: \"shared\", label: \"shared action\" }, { value: \"inline\", label: \"inline definition\" }],\n mode,\n \"wgd-select wgd-binding-mode\",\n (next) => {\n if (next === \"none\") commit(undefined, \"all\");\n else if (next === \"shared\") commit({ ref: shared[0]?.name ?? \"\" }, \"all\");\n else commit({ definition: starterHttpDefinition() }, \"all\");\n }\n );\n headEl.append(h(\"div\", { class: \"wgd-row\" }, [modeSelect]));\n if (current === undefined) return;\n if (isRefBinding(current)) {\n const ref = current.ref;\n const names = shared.map((a) => a.name);\n const options = (names.includes(ref) ? names : [ref, ...names]).map((n) => ({ value: n, label: n === \"\" ? \"(pick an action)\" : names.includes(n) ? n : `${n} (unknown)` }));\n const refSelect = select(options, ref, \"wgd-select wgd-binding-ref\", (next) =>\n commit(withMapping({ ref: next }, inputOf(), outputOf()), \"io\")\n );\n headEl.append(h(\"div\", { class: \"wgd-row\" }, [label(\"Action\"), refSelect]));\n return;\n }\n const editor = createDefinitionEditor(current.definition, ctx, (definition) => {\n // The definition's schemas drive the mapping rows; the head keeps focus.\n commit(withMapping({ definition }, inputOf(), outputOf()), \"io\");\n });\n headEl.append(editor.element);\n }\n\n function renderInput(): void {\n inputEl.replaceChildren();\n const definition = definitionOf(current);\n if (current === undefined || definition?.kind !== \"http\") return;\n const binding = current;\n // Input mapping: one row per declared field, each a data path or a constant.\n const properties = isPlainObject(definition.input.properties) ? Object.keys(definition.input.properties) : [];\n // No element scope supplied (the widget-level `load`): the root data paths ARE the scope.\n const scopePaths = ctx.scopePaths ?? allPaths(ctx.getDataSchema?.());\n const pathOptions = [...new Set([...scopePaths, ...helperPaths()])];\n const mapping = inputOf();\n const rows = properties.map((field) => {\n const value = mapping[field];\n const isConst = isPlainObject(value) && \"const\" in value;\n const kindSelect = select([{ value: \"path\" }, { value: \"const\" }], isConst ? \"const\" : \"path\", \"wgd-select wgd-attr-mode\", (next) => {\n commit(withMapping(binding, { ...inputOf(), [field]: next === \"const\" ? { const: \"\" } : field }, outputOf()), \"input\");\n });\n const onValue = (next: string): void => {\n const nextMapping = inputOf();\n if (isConst) {\n let literal: unknown;\n try { literal = JSON.parse(next); } catch { literal = next; }\n nextMapping[field] = { const: literal };\n } else if (next === \"\") {\n delete nextMapping[field];\n } else {\n nextMapping[field] = next;\n }\n commit(withMapping(binding, nextMapping, outputOf()), \"none\");\n };\n const valueInput = isConst\n ? textInput(JSON.stringify(value.const), \"wgd-input wgd-rec-value\", onValue, \"JSON literal\")\n : pathSelect(typeof value === \"string\" ? value : \"\", pathOptions, onValue, \"data path\");\n return h(\"div\", { class: \"wgd-rec-row\" }, [h(\"span\", { class: \"wgd-rec-key wgd-binding-field\" }, [field]), kindSelect, valueInput]);\n });\n inputEl.append(\n label(\"Input mapping (field \u2190 data path or constant)\"),\n properties.length > 0 ? h(\"div\", { class: \"wgd-record\" }, rows) : h(\"div\", { class: \"wgd-diagnostic\" }, [\"The input schema declares no properties.\"])\n );\n }\n\n function renderOutput(): void {\n outputEl.replaceChildren();\n const definition = definitionOf(current);\n if (current === undefined || definition?.kind !== \"http\") return;\n const binding = current;\n const output = outputOf();\n const mode = output.mode ?? \"merge\";\n const modeSel = select(OUTPUT_MODES.map((m) => ({ value: m })), mode, \"wgd-select\", (next) => {\n const nextOutput: OutputBinding = { ...outputOf(), mode: next as OutputMode };\n if (next !== \"patch\") delete nextOutput.path;\n commit(withMapping(binding, inputOf(), nextOutput), \"output\");\n });\n const outputRow: (Node | string)[] = [label(\"Output\"), modeSel];\n if (mode === \"patch\") {\n outputRow.push(textInput(output.path ?? \"\", \"wgd-input\", (next) => {\n commit(withMapping(binding, inputOf(), { ...outputOf(), path: next }), \"output\");\n }, \"data path to write at\"));\n }\n outputEl.append(h(\"div\", { class: \"wgd-row\" }, outputRow));\n outputEl.append(outputMapEditor(definition, output, (map) => {\n const nextOutput = outputOf();\n if (map === undefined) delete nextOutput.map; else nextOutput.map = map;\n commit(withMapping(binding, inputOf(), nextOutput), \"none\");\n }));\n }\n\n /**\n * Output projection rows: target (a widget data path, relative to the\n * patch path when that mode is on) \u2190 source (a response path). Both\n * inputs complete from the respective schemas, and a type mismatch is\n * flagged here \u2014 at execution it would only surface as INVALID_TYPE.\n * Unnamed rows are editor-local until they get a target.\n */\n function outputMapEditor(\n definition: HttpActionDefinition,\n output: OutputBinding,\n onMap: (map: Record<string, string> | undefined) => void\n ): HTMLElement {\n const container = h(\"div\", { class: \"wgd-record wgd-output-map\" });\n let map: Record<string, string> = clone(output.map ?? {});\n const pending: { source: string }[] = [];\n const widgetSchema = ctx.getDataSchema?.();\n const mode = output.mode ?? \"merge\";\n const base = mode === \"patch\" && output.path ? output.path : \"\";\n // A list on either side is spoken to per ITEM: the projection maps each\n // element of a list response, and lands each in a list target \u2014 so the\n // columns and the type check work over the item schemas.\n const targetSide = base === \"\" ? widgetSchema : schemaAt(widgetSchema, base);\n const targetRoot = itemSchema(targetSide);\n // \".\" is always a valid target \u2014 the selection row \u2014 whatever the widget's shape.\n const targetOptions = [\".\", ...allPaths(targetRoot)];\n // A \".\" row SELECTS a sub-value the other rows then map (an enveloped\n // list: { \".\": \"data\", ask: \"ask\" }); the source column and the type\n // check follow that selection.\n const selectedSchema = (): unknown =>\n map[\".\"] === undefined ? definition.output : schemaAt(definition.output, map[\".\"]);\n const perItemResponse = (): boolean => schemaType(selectedSchema()) === \"array\";\n const sourceRoot = (): unknown => itemSchema(selectedSchema());\n const selectOptions = [\".\", ...allPaths(definition.output)];\n const mismatch = diagnosticLine(undefined);\n mismatch.classList.add(\"wgd-type-mismatch\");\n\n function commitMap(next: Record<string, string>): void {\n map = next;\n onMap(Object.keys(map).length > 0 ? map : undefined);\n render();\n }\n function flag(text: string): void {\n mismatch.hidden = false;\n mismatch.textContent = text;\n }\n function targetControl(target: string, onTarget: (next: string) => void): HTMLElement {\n const control = pathSelect(target, targetOptions, onTarget, \"target data path\", \"wgd-input wgd-rec-key\");\n control.classList.add(\"wgd-map-target\");\n return control;\n }\n function render(): void {\n container.replaceChildren();\n const problems: string[] = [];\n // A per-item projection yields a LIST; merge needs an object on both\n // sides and would only fail at execution.\n const mapped = Object.keys(map).filter((key) => key !== \".\");\n if (perItemResponse() && mode === \"merge\" && mapped.length > 0) {\n problems.push(\"a list projects per item \u2014 use replace or patch; merge needs an object.\");\n }\n const sourceOptions = [\".\", ...allPaths(sourceRoot())];\n for (const [target, source] of Object.entries(map)) {\n // The \".\" row selects against the response root; other rows map the selection.\n const options = target === \".\" ? selectOptions : sourceOptions;\n const conflict =\n target === \".\"\n ? undefined\n : schemaMismatch(schemaAt(sourceRoot(), source), schemaAt(targetRoot, target));\n if (conflict) {\n problems.push(`'${source}' is ${conflict.source} in the response but '${base ? `${base}.` : \"\"}${target}' is ${conflict.target} in the widget schema`);\n }\n const targetInput = targetControl(target, (next) => {\n if (next === target) return;\n if (next === \"\" || Object.hasOwn(map, next)) { flag(`'${next || \"(empty)\"}' is already a projection target.`); return; }\n const entries = Object.entries(map).map(([k, v]) => (k === target ? [next, v] : [k, v]));\n commitMap(Object.fromEntries(entries));\n });\n const sourceInput = pathSelect(source, options, (next) => commitMap({ ...map, [target]: next }), \"response path\");\n sourceInput.classList.add(\"wgd-map-source\");\n const remove = removeButton(() => {\n const { [target]: _gone, ...rest } = map;\n commitMap(rest);\n });\n container.append(h(\"div\", { class: \"wgd-rec-row\" }, [targetInput, h(\"span\", { class: \"wgd-st-colon\" }, [\"\u2190\"]), sourceInput, remove]));\n }\n pending.forEach((row, index) => {\n const targetInput = targetControl(\"\", (next) => {\n if (next === \"\") return;\n if (Object.hasOwn(map, next)) { flag(`'${next}' is already a projection target.`); return; }\n pending.splice(index, 1);\n commitMap({ ...map, [next]: row.source });\n });\n const sourceInput = pathSelect(row.source, sourceOptions, (next) => { row.source = next; render(); }, \"response path\");\n sourceInput.classList.add(\"wgd-map-source\");\n const remove = removeButton(() => { pending.splice(index, 1); render(); });\n container.append(h(\"div\", { class: \"wgd-rec-row wgd-rec-pending\" }, [targetInput, h(\"span\", { class: \"wgd-st-colon\" }, [\"\u2190\"]), sourceInput, remove]));\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"+ projection\"]);\n add.addEventListener(\"click\", () => { pending.push({ source: \"\" }); render(); });\n mismatch.hidden = problems.length === 0;\n mismatch.textContent = problems.length === 0 ? \"\" : `Type mismatch: ${problems.join(\"; \")}.`;\n container.append(h(\"div\", { class: \"wgd-row\" }, [add]), mismatch);\n }\n render();\n return container;\n }\n\n function render(): void {\n renderHead();\n renderInput();\n renderOutput();\n }\n render();\n return {\n element,\n setValue(binding) {\n current = binding === undefined ? undefined : clone(binding);\n render();\n }\n };\n}\n", "/**\n * Template editing: a structured node tree and a JSON source pane \u2014 two\n * projections of one canonical model (the draft's template). The JSON\n * pane is parse-gated (invalid JSON never reaches the store; last valid\n * wins); structural edits from either side may still fail\n * `validateTemplate`, which surfaces as diagnostics pinned to the node\n * path without ever losing the draft.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { collectActionRefs } from \"@widgentic/core\";\nimport {\n CURRENCY_DISPLAYS,\n DATE_TOKENS,\n FORMAT_DECIMALS_MAX,\n FORMAT_DECIMALS_MIN,\n FORMAT_TYPES,\n JOIN_DEFAULT_SEPARATOR,\n LIST_FORMAT_TYPES,\n JOIN_SEPARATOR_MAX,\n PLURAL_COUNT_PLACEHOLDER,\n TRUNCATE_DEFAULT_ELLIPSIS,\n TRUNCATE_ELLIPSIS_MAX,\n TRUNCATE_LENGTH_MAX,\n TRUNCATE_LENGTH_MIN,\n activeTransform,\n isCurrencyDisplay,\n isFormatType\n} from \"@widgentic/core\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { WidgetTemplate } from \"@widgentic/core\";\nimport type { ActionBinding, StoredAction } from \"@widgentic/core\";\nimport { createBindingEditor } from \"./action-editor.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { collectPaths, itemSchema, schemaAt, schemaType } from \"./schema-paths.js\";\nimport { effectiveDataSchema } from \"./validate.js\";\nimport { diagnosticLine, fitSelect, h, menuButton, select } from \"./dom.js\";\nimport { createRecordEditor } from \"./record-editor.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\n\ntype Path = (string | number)[];\n\n/** What a data path is being used for \u2014 decides which paths are offered. */\n/** `listBind`: a bind whose format reads a list, so array paths are offered too. */\ntype PathUse = \"bind\" | \"listBind\" | \"each\" | \"when\";\n\n/** The path use of a bind carrying `format`. */\nconst bindUse = (format: unknown): PathUse =>\n isPlainObject(format) && LIST_FORMAT_TYPES.some((type) => type === format.type) ? \"listBind\" : \"bind\";\n\n/** Paths worth offering for a given use. */\nfunction pathOptions(scope: unknown, use: PathUse): string[] {\n // An ARRAY scope offers only itself: nothing but an index resolves inside\n // it, and its item's properties belong to the each that walks it.\n if (schemaType(scope) === \"array\") return [\".\"];\n const entries: { path: string; schema: unknown }[] = [];\n collectPaths(scope, \"\", entries);\n const scalars = new Set([\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"null\",\n undefined\n ]);\n const filtered = entries.filter(({ schema }) => {\n const type = schemaType(schema);\n if (use === \"each\") return type === \"array\";\n if (use === \"bind\") return scalars.has(type);\n if (use === \"listBind\") return scalars.has(type) || type === \"array\";\n return true; // `when` tests truthiness of anything\n });\n const paths = filtered.map((entry) => entry.path);\n // \".\" is the scope itself \u2014 the item inside an each over scalars.\n if (use !== \"each\" && scalars.has(schemaType(scope))) paths.unshift(\".\");\n return paths;\n}\n\n/**\n * Schema in effect inside `each: <path>` \u2014 the item schema of the array\n * that path resolves to. `schemaAt` does the walking, so `each: \".\"` over\n * a root-array schema scopes to its item like any other each.\n */\nfunction itemScope(scope: unknown, eachPath: string): unknown {\n const target = schemaAt(scope, eachPath);\n return schemaType(target) === \"array\" ? itemSchema(target) : undefined;\n}\n\nconst REMOVE = Symbol(\"remove\");\n\nfunction pathString(path: Path): string {\n let out = \"\";\n for (const step of path) {\n const segment = typeof step === \"number\" ? `children.${step}` : step;\n out = out === \"\" ? segment : `${out}.${segment}`;\n }\n return out;\n}\n\n/** Immutable set/remove at a node path (numbers index `children`). */\nfunction setNode(node: unknown, path: Path, next: unknown): unknown {\n if (path.length === 0) return next === REMOVE ? undefined : next;\n const [step, ...rest] = path as [string | number, ...Path];\n if (typeof step === \"number\") {\n if (!isPlainObject(node) || !Array.isArray(node.children)) return node;\n const children = [...(node.children as unknown[])];\n if (rest.length === 0 && next === REMOVE) {\n children.splice(step, 1);\n } else {\n children[step] = setNode(children[step], rest, next);\n }\n return { ...node, children };\n }\n if (!isPlainObject(node)) return node;\n if (rest.length === 0 && next === REMOVE) {\n const { [step]: _removed, ...remaining } = node;\n return remaining;\n }\n return { ...node, [step]: setNode(node[step], rest, next) };\n}\n\nfunction swapChildren(root: unknown, parent: Path, a: number, b: number): unknown {\n const holder = parent.length === 0 ? root : getNode(root, parent);\n if (!isPlainObject(holder) || !Array.isArray(holder.children)) return root;\n const children = [...(holder.children as unknown[])];\n if (a < 0 || b < 0 || a >= children.length || b >= children.length) return root;\n const [x, y] = [children[a], children[b]];\n children[a] = y;\n children[b] = x;\n const swapped = { ...holder, children };\n return parent.length === 0 ? swapped : setNode(root, parent, swapped);\n}\n\nfunction getNode(node: unknown, path: Path): unknown {\n let current = node;\n for (const step of path) {\n if (!isPlainObject(current)) return undefined;\n current =\n typeof step === \"number\"\n ? Array.isArray(current.children)\n ? (current.children as unknown[])[step]\n : undefined\n : current[step];\n }\n return current;\n}\n\nconst NODE_PRESETS: Record<string, () => unknown> = {\n text: () => \"text\",\n bind: () => ({ bind: \".\" }),\n element: () => ({ tag: \"div\", children: [] }),\n each: () => ({ each: \".\", template: \"item\" }),\n when: () => ({ when: \".\", template: \"shown\" })\n};\n\n/** What element bindings can reach: shared actions, secrets, schemas. */\nexport interface TemplateActionContext {\n actions: StoredAction[];\n secretNames: string[];\n schemas: SchemaEntry[];\n}\n\nexport interface TemplatePanelOptions {\n actionContext?: TemplateActionContext;\n}\n\n/** A bound attribute value, narrowed once per attribute row (a type literal: comparable with the raw record). */\ntype AttrBind = {\n bind: string;\n prefix?: string;\n map?: Record<string, string>;\n default?: string;\n format?: Record<string, unknown>;\n};\n\nexport function mountTemplatePanel(\n store: DraftStore,\n refreshers: ((draft: WidgetDraft) => void)[],\n options: TemplatePanelOptions = {}\n): {\n element: HTMLElement;\n refresh(draft: WidgetDraft, diagnostics: DesignerDiagnostics): void;\n dispose(): void;\n} {\n const actionContext: TemplateActionContext = options.actionContext ?? { actions: [], secretNames: [], schemas: [] };\n // Shared refs the draft binds that no supplied action answers to.\n let unknownRefs = new Set<string>();\n const treeHost = h(\"div\", { class: \"wgd-tree\" });\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", {\n class: \"wgd-textarea wgd-template-json\",\n rows: \"14\",\n spellcheck: \"false\"\n });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n attachJsonHighlight(jsonArea);\n jsonWrap.hidden = true;\n\n const treeTab = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Tree\"]);\n const jsonTab = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"JSON\"]);\n treeTab.addEventListener(\"click\", () => {\n treeHost.hidden = false;\n jsonWrap.hidden = true;\n });\n jsonTab.addEventListener(\"click\", () => {\n treeHost.hidden = true;\n jsonWrap.hidden = false;\n });\n\n const templateDiag = diagnosticLine(undefined);\n const element = h(\"details\", { class: \"wgd-section\", open: \"\" }, [\n h(\"summary\", { class: \"wgd-section-title\" }, [\"Template\"]),\n h(\"div\", { class: \"wgd-section-body\" }, [\n h(\"div\", { class: \"wgd-row\" }, [treeTab, jsonTab]),\n templateDiag,\n treeHost,\n jsonWrap\n ])\n ]);\n\n function commit(next: unknown): void {\n store.update((draft) => ({ ...draft, template: next as WidgetTemplate }));\n }\n\n function commitAt(path: Path, next: unknown): void {\n commit(setNode(store.get().template, path, next));\n }\n\n // --- JSON pane: parse-gated projection --------------------------------\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n commit(parsed);\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid JSON (template keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n });\n\n // --- Tree editor -------------------------------------------------------\n function changeInput(\n value: string,\n onCommit: (value: string) => void,\n className = \"wgd-input wgd-node-value\"\n ): HTMLInputElement {\n const input = h(\"input\", { type: \"text\", class: className });\n input.value = value;\n input.addEventListener(\"change\", () => onCommit(input.value));\n return input;\n }\n\n /**\n * The compact format editor shared by text binds and attribute binds:\n * a type select revealing that type's fields. Switching type commits a\n * COMPLETE spec (a real currency code, a real pattern) so the draft is\n * never momentarily invalid \u2014 the same discipline the binding editor's\n * unnamed rows follow.\n */\n function formatEditor(\n spec: Record<string, unknown> | undefined,\n onCommit: (next: Record<string, unknown> | undefined) => void\n ): HTMLElement[] {\n const active = spec !== undefined && isFormatType(spec.type) ? spec : undefined;\n const typeSelect = select(\n [{ value: \"none\", label: \"raw\" }, ...FORMAT_TYPES.map((value) => ({ value }))],\n active === undefined ? \"none\" : (active.type as string),\n \"wgd-select wgd-format-type\",\n (next) => {\n // Switching type commits a COMPLETE spec, so the draft is never\n // momentarily invalid.\n if (next === \"number\") onCommit({ type: \"number\", decimals: 2 });\n else if (next === \"currency\") onCommit({ type: \"currency\", currency: \"USD\", decimals: 2 });\n else if (next === \"date\") onCommit({ type: \"date\", pattern: \"yyyy-MM-dd\" });\n else if (next === \"count\") onCommit({ type: \"count\" });\n else if (next === \"join\") onCommit({ type: \"join\", separator: JOIN_DEFAULT_SEPARATOR });\n else if (next === \"truncate\") onCommit({ type: \"truncate\", length: 80 });\n else if (next === \"pluralize\") {\n onCommit({\n type: \"pluralize\",\n forms: { one: `${PLURAL_COUNT_PLACEHOLDER} item`, other: `${PLURAL_COUNT_PLACEHOLDER} items` }\n });\n } else onCommit(undefined);\n },\n \"Present the bound value: a number, a currency amount or a date; a list's count or its items joined; text truncated; or a plural form\"\n );\n if (active === undefined) return [typeSelect];\n\n /** A text field of the spec: an empty input drops it, so the engine's default applies. */\n const specInput = (\n field: string,\n placeholder: string,\n title: string,\n className: string\n ): HTMLInputElement => {\n const current = active[field];\n const input = changeInput(\n typeof current === \"string\" || typeof current === \"number\" ? String(current) : \"\",\n (next) => {\n const { [field]: _gone, ...rest } = active;\n onCommit(next === \"\" ? rest : { ...rest, [field]: next });\n },\n `wgd-input ${className}`\n );\n input.placeholder = placeholder;\n input.title = title;\n return input;\n };\n\n if (active.type === \"count\") return [typeSelect];\n if (active.type === \"join\") {\n return [\n typeSelect,\n specInput(\"separator\", \"sep\", `Between items (at most ${JOIN_SEPARATOR_MAX} characters; default \"${JOIN_DEFAULT_SEPARATOR}\")`, \"wgd-format-separator\"),\n specInput(\"last\", \"last\", `Before the last item, e.g. \" and \" (at most ${JOIN_SEPARATOR_MAX} characters)`, \"wgd-format-last\"),\n specInput(\"field\", \"field\", \"Each item's field to join, e.g. name (leave empty for the items themselves)\", \"wgd-format-field\")\n ];\n }\n if (active.type === \"truncate\") {\n const length = changeInput(\n typeof active.length === \"number\" ? String(active.length) : \"\",\n (next) => {\n const parsed = Number(next);\n onCommit({ ...active, length: next !== \"\" && Number.isFinite(parsed) ? parsed : next });\n },\n \"wgd-input wgd-format-length\"\n );\n length.placeholder = \"len\";\n length.title = `Characters kept (${TRUNCATE_LENGTH_MIN}-${TRUNCATE_LENGTH_MAX})`;\n return [\n typeSelect,\n length,\n specInput(\"ellipsis\", TRUNCATE_DEFAULT_ELLIPSIS, `Appended when cut (at most ${TRUNCATE_ELLIPSIS_MAX} characters)`, \"wgd-format-ellipsis\")\n ];\n }\n if (active.type === \"pluralize\") {\n const forms = isPlainObject(active.forms) ? active.forms : {};\n // The row edits zero, one and other; any other category (few, many\n // for some locales) and the locale ride along untouched.\n const formInput = (category: \"zero\" | \"one\" | \"other\"): HTMLInputElement => {\n const current = forms[category];\n const input = changeInput(\n typeof current === \"string\" ? current : \"\",\n (next) => {\n const { [category]: _gone, ...rest } = forms;\n const nextForms = next === \"\" && category !== \"other\" ? rest : { ...rest, [category]: next };\n onCommit({ ...active, forms: nextForms });\n },\n `wgd-input wgd-format-form wgd-format-form-${category}`\n );\n input.placeholder = category;\n input.title = `The ${category} form; ${PLURAL_COUNT_PLACEHOLDER} becomes the number`;\n return input;\n };\n return [typeSelect, formInput(\"zero\"), formInput(\"one\"), formInput(\"other\")];\n }\n\n const decimalsInput = (): HTMLInputElement => {\n const input = changeInput(\n active.decimals === undefined ? \"\" : String(active.decimals),\n (next) => {\n const { decimals: _gone, ...rest } = active;\n const parsed = Number(next);\n onCommit(next === \"\" ? rest : { ...rest, decimals: Number.isFinite(parsed) ? parsed : next });\n },\n \"wgd-input wgd-format-decimals\"\n );\n input.placeholder = \"dec\";\n input.title = `Decimal places (${FORMAT_DECIMALS_MIN}-${FORMAT_DECIMALS_MAX})`;\n return input;\n };\n\n if (active.type === \"currency\") {\n const code = changeInput(\n typeof active.currency === \"string\" ? active.currency : \"\",\n (next) => onCommit({ ...active, currency: next.toUpperCase() }),\n \"wgd-input wgd-format-currency\"\n );\n code.placeholder = \"CUR\";\n code.title = \"ISO-4217 currency code, e.g. COP\";\n const display = select(\n CURRENCY_DISPLAYS.map((value) => ({ value })),\n isCurrencyDisplay(active.currencyDisplay) ? active.currencyDisplay : CURRENCY_DISPLAYS[0],\n \"wgd-select wgd-format-display\",\n (next) => onCommit({ ...active, currencyDisplay: next }),\n \"How the currency names itself\"\n );\n return [typeSelect, code, decimalsInput(), display];\n }\n if (active.type === \"number\") return [typeSelect, decimalsInput()];\n const pattern = changeInput(\n typeof active.pattern === \"string\" ? active.pattern : \"\",\n (next) => onCommit({ ...active, pattern: next }),\n \"wgd-input wgd-format-pattern\"\n );\n pattern.placeholder = \"pattern\";\n pattern.title = `Date pattern from ${DATE_TOKENS.join(\" \")} plus separators, e.g. dd-MM-yyyy HH:mm`;\n return [typeSelect, pattern];\n }\n\n\n /**\n * Collapse state, keyed by node path so it survives the full re-render\n * every draft edit triggers. Paths shift when siblings move or vanish \u2014\n * an accepted approximation, exactly like text-editor fold markers.\n */\n const collapsedPaths = new Set<string>();\n\n /**\n * One node = one header row: chevron, badge, the node's own value\n * control(s), then add/move/remove icons (revealed on hover). Sub-\n * structure (attrs, children, slots) nests below and folds away when\n * the node is collapsed; a muted summary keeps the hidden shape legible.\n */\n function nodeShell(\n /** Omitted for elements \u2014 their tag select already names the node. */\n badge: string | undefined,\n path: Path,\n inline: (Node | string)[],\n body: (Node | string)[],\n errorText: string | undefined,\n removable: boolean,\n moves?: { parent: Path; index: number; count: number },\n extras?: { icons?: (Node | string)[]; summary?: string }\n ): HTMLElement {\n const key = pathString(path);\n const collapsible = body.length > 0;\n const isCollapsed = collapsible && collapsedPaths.has(key);\n let chevron: HTMLElement;\n if (collapsible) {\n chevron = h(\n \"button\",\n {\n class: \"wgd-chevron\",\n type: \"button\",\n title: isCollapsed ? \"Expand\" : \"Collapse\"\n },\n [isCollapsed ? \"\u25B8\" : \"\u25BE\"]\n );\n chevron.addEventListener(\"click\", () => {\n if (isCollapsed) collapsedPaths.delete(key);\n else collapsedPaths.add(key);\n renderTree();\n });\n } else {\n // Every row reserves the chevron column so values align.\n chevron = h(\"span\", { class: \"wgd-chevron wgd-chevron-none\" });\n }\n const header: (Node | string)[] =\n badge === undefined\n ? [chevron, ...inline]\n : [chevron, h(\"span\", { class: \"wgd-node-badge\" }, [badge]), ...inline];\n if (isCollapsed && extras?.summary !== undefined) {\n header.push(h(\"span\", { class: \"wgd-node-summary\" }, [extras.summary]));\n }\n const icons: (Node | string)[] = [...(extras?.icons ?? [])];\n if (moves && moves.count > 1) {\n if (moves.index > 0) {\n const up = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Move up\" }, [\"\u2191\"]);\n up.addEventListener(\"click\", () =>\n commit(swapChildren(store.get().template, moves.parent, moves.index, moves.index - 1))\n );\n icons.push(up);\n }\n if (moves.index < moves.count - 1) {\n const down = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Move down\" }, [\"\u2193\"]);\n down.addEventListener(\"click\", () =>\n commit(swapChildren(store.get().template, moves.parent, moves.index, moves.index + 1))\n );\n icons.push(down);\n }\n }\n if (removable) {\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () =>\n path.length === 0 ? commit(\"\") : commitAt(path, REMOVE)\n );\n icons.push(remove);\n }\n if (icons.length > 0) {\n header.push(h(\"span\", { class: \"wgd-node-icons\" }, icons));\n }\n const children: (Node | string)[] = [h(\"div\", { class: \"wgd-node-row\" }, header)];\n // Diagnostics stay visible even on a collapsed node \u2014 folding must\n // never hide an error.\n if (errorText !== undefined) children.push(diagnosticLine(errorText));\n if (!isCollapsed) children.push(...body);\n return h(\"div\", { class: \"wgd-node\", \"data-path\": key }, children);\n }\n\n /** Tags the built-in styles and typical widget markup actually use. */\n const TAG_OPTIONS = [\n \"div\", \"span\", \"p\", \"section\", \"article\", \"header\", \"footer\",\n \"h1\", \"h2\", \"h3\", \"h4\", \"strong\", \"em\", \"small\", \"code\", \"pre\",\n \"ul\", \"ol\", \"li\", \"dl\", \"dt\", \"dd\",\n \"table\", \"thead\", \"tbody\", \"tr\", \"th\", \"td\",\n \"img\", \"a\", \"figure\", \"figcaption\", \"hr\", \"br\", \"label\"\n ];\n\n /**\n * Data-path control. With a schema in scope it is a select of the paths\n * that scope actually offers (plus the current value if it is off-schema,\n * and a custom escape); without one it stays a free-text input.\n */\n function pathControl(\n value: string,\n scope: unknown,\n use: PathUse,\n onCommit: (path: string) => void,\n className = \"wgd-input wgd-node-value\"\n ): HTMLElement {\n const options = isPlainObject(scope) ? pathOptions(scope, use) : [];\n if (options.length === 0) {\n return changeInput(value, onCommit, className);\n }\n const select = h(\"select\", { class: \"wgd-select wgd-path\" });\n const known = options.includes(value);\n for (const option of known ? options : [value, ...options]) {\n select.append(\n h(\"option\", { value: option }, [\n option === value && !known ? `${option} (off-schema)` : option\n ])\n );\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = value;\n fitSelect(select);\n const custom = changeInput(value, onCommit, className);\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(select.value);\n });\n // The wrap carries the row-shape marker (e.g. wgd-attr-value) so rows\n // read the same whether the value is a select or free text.\n const marker = className.includes(\"wgd-attr-value\") ? \" wgd-attr-value\" : \"\";\n return h(\"span\", { class: `wgd-pathwrap${marker}` }, [select, custom]);\n }\n\n /**\n * An `each` node's optional key: the item path that identifies a row, so\n * a reordered list patches by identity. Completions are the item scope's\n * bind paths; the empty choice (or an emptied input) removes the key.\n */\n function keyControl(\n value: string | undefined,\n scope: unknown,\n onCommit: (key: string | undefined) => void\n ): HTMLElement {\n const current = value ?? \"\";\n const commit = (next: string) => onCommit(next === \"\" ? undefined : next);\n const title = \"Optional item key (e.g. id): a reordered list keeps each item's state\";\n const options = isPlainObject(scope) ? pathOptions(scope, \"bind\") : [];\n if (options.length === 0) {\n const input = changeInput(current, commit, \"wgd-input wgd-each-key\");\n input.placeholder = \"key path\";\n input.title = title;\n return input;\n }\n const select = h(\"select\", { class: \"wgd-select wgd-each-key\", title });\n const known = current === \"\" || options.includes(current);\n select.append(h(\"option\", { value: \"\" }, [\"no key\"]));\n for (const option of known ? options : [current, ...options]) {\n select.append(\n h(\"option\", { value: option }, [option === current && !known ? `${option} (off-schema)` : option])\n );\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = current;\n fitSelect(select);\n const custom = changeInput(current, commit, \"wgd-input wgd-each-key\");\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n commit(select.value);\n });\n return h(\"span\", { class: \"wgd-pathwrap\" }, [select, custom]);\n }\n\n function tagControl(tag: string, onCommit: (tag: string) => void): HTMLElement {\n const select = h(\"select\", { class: \"wgd-select wgd-tag\" });\n const options = TAG_OPTIONS.includes(tag) ? TAG_OPTIONS : [tag, ...TAG_OPTIONS];\n for (const option of options) {\n select.append(h(\"option\", { value: option }, [option]));\n }\n select.append(h(\"option\", { value: \"__custom__\" }, [\"custom\u2026\"]));\n select.value = tag;\n fitSelect(select);\n const custom = changeInput(tag, onCommit, \"wgd-input wgd-tag-custom\");\n custom.hidden = true;\n select.addEventListener(\"change\", () => {\n if (select.value === \"__custom__\") {\n custom.hidden = false;\n custom.focus();\n return;\n }\n custom.hidden = true;\n onCommit(select.value);\n });\n return h(\"span\", { class: \"wgd-tagwrap\" }, [select, custom]);\n }\n\n function slotEditor(\n label: string,\n parentPath: Path,\n slot: \"template\" | \"empty\" | \"else\",\n node: unknown,\n required: boolean,\n errorPath: string | undefined,\n scope: unknown\n ): HTMLElement {\n const slotPath = [...parentPath, slot];\n if (node === undefined) {\n const menu = menuButton(\n `+ ${label}`,\n `Set '${label}' to a node`,\n Object.keys(NODE_PRESETS),\n (name) => {\n const preset = NODE_PRESETS[name];\n if (preset) commitAt(slotPath, preset());\n }\n );\n return required\n ? h(\"div\", { class: \"wgd-slot\" }, [\n diagnosticLine(`Missing required '${label}'.`),\n menu\n ])\n : h(\"div\", { class: \"wgd-slot wgd-slot-unset\" }, [menu]);\n }\n return h(\"div\", { class: \"wgd-slot\" }, [\n h(\"span\", { class: \"wgd-slot-label\" }, [label]),\n renderNode(node, slotPath, errorPath, !required, undefined, scope)\n ]);\n }\n\n function renderNode(\n node: unknown,\n path: Path,\n errorPath: string | undefined,\n removable = true,\n moves?: { parent: Path; index: number; count: number },\n scope?: unknown\n ): HTMLElement {\n const here = pathString(path);\n const errorHere =\n errorPath !== undefined &&\n (errorPath === here ||\n ((errorPath.startsWith(here === \"\" ? \"attrs.\" : `${here}.attrs.`) ||\n errorPath.startsWith(here === \"\" ? \"action\" : `${here}.action`)) &&\n isPlainObject(node) &&\n typeof node.tag === \"string\"))\n ? currentError\n : undefined;\n\n if (typeof node === \"string\") {\n return nodeShell(\n \"text\",\n path,\n [changeInput(node, (value) => commitAt(path, value))],\n [],\n errorHere,\n removable,\n moves\n );\n }\n if (!isPlainObject(node)) {\n return nodeShell(\n \"invalid\",\n path,\n [h(\"code\", undefined, [JSON.stringify(node)])],\n [],\n errorHere ?? \"Not a template node.\",\n removable,\n moves\n );\n }\n if (typeof node.bind === \"string\") {\n const bind = node.bind;\n // Markdown is a text-bind mode beside the transforms: on, it hides both.\n const markdown = node.markdown === true;\n const transform = markdown ? \"markdown\" : activeTransform(node);\n const bindFormat = isPlainObject(node.format) ? node.format : undefined;\n const bindMap = isPlainObject(node.map) ? (node.map as Record<string, string>) : undefined;\n // A text bind carries `map` (value \u2192 authored label) or `format`; the\n // other control hides while one is active, mirroring the validator.\n // `prefix` is attribute-only and is not offered here.\n const withBind = (extra: Record<string, unknown>): Record<string, unknown> => ({ bind, ...extra });\n const inline: (Node | string)[] = [\n pathControl(bind, scope, bindUse(bindFormat), (value) => commitAt(path, { ...node, bind: value }))\n ];\n if (transform === undefined || transform === \"format\") {\n inline.push(\n ...formatEditor(bindFormat, (next) => commitAt(path, next === undefined ? { bind } : withBind({ format: next })))\n );\n }\n if (markdown) {\n const off = h(\n \"button\",\n { class: \"wgd-md-toggle\", type: \"button\", \"aria-pressed\": \"true\", title: \"Rendered as Markdown \u2014 click for plain text\" },\n [\"markdown\"]\n );\n off.addEventListener(\"click\", () => commitAt(path, { bind }));\n inline.push(off);\n }\n const icons: (Node | string)[] = [];\n if (transform === undefined) {\n const addMarkdown = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Render the value as Markdown (paragraphs, lists, emphasis, code, links)\" },\n [\"md\"]\n );\n addMarkdown.addEventListener(\"click\", () => commitAt(path, withBind({ markdown: true })));\n icons.push(addMarkdown);\n const addMap = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Map values to authored labels (e.g. status \u2192 text)\" },\n [\"map\"]\n );\n addMap.addEventListener(\"click\", () => commitAt(path, withBind({ map: {} })));\n icons.push(addMap);\n }\n const body: (Node | string)[] = [];\n if (transform === \"map\") {\n const mapEditor = createRecordEditor(\n bindMap,\n { key: \"data value\", value: \"authored label\", add: \"+ mapping\" },\n (nextMap) => commitAt(path, nextMap === undefined ? { bind } : withBind({ map: nextMap, ...(typeof node.default === \"string\" ? { default: node.default } : {}) }))\n );\n const defaultInput = changeInput(\n typeof node.default === \"string\" ? node.default : \"\",\n (next) => commitAt(path, withBind({ map: bindMap ?? {}, ...(next === \"\" ? {} : { default: next }) })),\n \"wgd-input wgd-attr-map-default\"\n );\n defaultInput.placeholder = \"default (on miss)\";\n body.push(\n h(\"div\", { class: \"wgd-attr-map\" }, [\n mapEditor.element,\n h(\"div\", { class: \"wgd-rec-row\" }, [h(\"span\", { class: \"wgd-st-colon\" }, [\"\u21B3\"]), defaultInput])\n ])\n );\n }\n return nodeShell(\"bind\", path, inline, body, errorHere, removable, moves, icons.length > 0 ? { icons } : undefined);\n }\n if (typeof node.each === \"string\") {\n const each = node.each;\n const { each: _each, key: _key, ...rest } = node;\n return nodeShell(\n \"each\",\n path,\n [\n pathControl(each, scope, \"each\", (value) =>\n commitAt(path, { ...node, each: value })\n ),\n h(\"span\", { class: \"wgd-st-colon\" }, [\"key\"]),\n keyControl(typeof node.key === \"string\" ? node.key : undefined, itemScope(scope, each), (key) =>\n commitAt(path, { each, ...(key === undefined ? {} : { key }), ...rest })\n )\n ],\n [\n // Inside an each, the scope becomes the array's item schema.\n slotEditor(\n \"template\",\n path,\n \"template\",\n node.template,\n true,\n errorPath,\n itemScope(scope, node.each)\n ),\n slotEditor(\n \"empty\",\n path,\n \"empty\",\n node.empty,\n false,\n errorPath,\n scope\n )\n ],\n errorHere,\n removable,\n moves,\n { summary: node.empty !== undefined ? \"template \u00B7 empty\" : \"template\" }\n );\n }\n if (typeof node.when === \"string\") {\n return nodeShell(\n \"when\",\n path,\n [\n pathControl(node.when, scope, \"when\", (value) =>\n commitAt(path, { ...node, when: value })\n )\n ],\n [\n slotEditor(\"template\", path, \"template\", node.template, true, errorPath, scope),\n slotEditor(\"else\", path, \"else\", node.else, false, errorPath, scope)\n ],\n errorHere,\n removable,\n moves,\n { summary: node.else !== undefined ? \"template \u00B7 else\" : \"template\" }\n );\n }\n if (typeof node.tag === \"string\") {\n const attrs = isPlainObject(node.attrs) ? node.attrs : {};\n const binding = isPlainObject(node.action) ? (node.action as ActionBinding) : undefined;\n const attrRows = Object.entries(attrs).map(([name, value]) => {\n // The bind's transform fields, when present. Every write goes\n // through rebuild() so editing one field never drops the others.\n // `bound` is meaningful only while `isBind`; narrowed once here.\n const bound: AttrBind =\n isPlainObject(value) && typeof value.bind === \"string\" ? (value as AttrBind) : { bind: \"\" };\n const isBind = isPlainObject(value) && typeof value.bind === \"string\";\n const bindValue = isBind ? bound : undefined;\n const rebuild = (fields: {\n bind: string;\n prefix?: string | undefined;\n map?: Record<string, string> | undefined;\n default?: string | undefined;\n format?: Record<string, unknown> | undefined;\n }): Record<string, unknown> => {\n const out: Record<string, unknown> = { bind: fields.bind };\n // One transform per value, in the validator's own precedence.\n if (fields.map !== undefined) {\n out.map = fields.map;\n if (fields.default !== undefined && fields.default !== \"\") {\n out.default = fields.default;\n }\n } else if (fields.prefix !== undefined && fields.prefix !== \"\") {\n out.prefix = fields.prefix;\n } else if (fields.format !== undefined) {\n out.format = fields.format;\n }\n return out;\n };\n const setAttr = (nextValue: unknown): void => {\n commitAt(path, { ...node, attrs: { ...attrs, [name]: nextValue } });\n };\n const nameInput = changeInput(\n name,\n (nextName) => {\n const entries = Object.entries(attrs).map(([k, v]) =>\n k === name ? ([nextName, v] as const) : ([k, v] as const)\n );\n commitAt(path, { ...node, attrs: Object.fromEntries(entries) });\n },\n \"wgd-input wgd-attr-name\"\n );\n const mode = h(\"select\", { class: \"wgd-select wgd-attr-mode\" });\n mode.append(h(\"option\", { value: \"literal\" }, [\"literal\"]));\n mode.append(h(\"option\", { value: \"bind\" }, [\"bind\"]));\n mode.value = isBind ? \"bind\" : \"literal\";\n fitSelect(mode);\n // Literal: free text. Bind: the same path dropdown the bind/each/when nodes use.\n const literalInput = changeInput(String(isBind ? \"\" : value), (next) => setAttr(next), \"wgd-input wgd-attr-value\");\n const valueInput: HTMLElement = isBind\n ? pathControl(\n bound.bind,\n scope,\n bindUse(bound.format),\n (next) => setAttr(rebuild({ ...bound, bind: next })),\n \"wgd-input wgd-attr-value\"\n )\n : literalInput;\n mode.addEventListener(\"change\", () => {\n // Switching modes carries the current text across as a starting point.\n const current = isBind ? bound.bind : literalInput.value;\n setAttr(mode.value === \"bind\" ? { bind: current || \".\" } : current);\n });\n const removeAttr = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove attribute\" }, [\"\u2715\"]);\n removeAttr.addEventListener(\"click\", () => {\n const { [name]: _gone, ...rest } = attrs;\n commitAt(path, { ...node, attrs: rest });\n });\n\n const row: (Node | string)[] = [nameInput, mode, valueInput];\n const transform = bindValue === undefined ? undefined : activeTransform(bindValue);\n const attrFormat = isPlainObject(bindValue?.format) ? bindValue.format : undefined;\n // One transform per value, mirroring the validator: each editor shows\n // while nothing else is active (or it is the active one).\n const showFormat = isBind && (transform === undefined || transform === \"format\");\n const showPrefix = isBind && (transform === undefined || transform === \"prefix\");\n const showAddMap = isBind && transform === undefined;\n if (showFormat) {\n row.push(...formatEditor(attrFormat, (next) => setAttr(rebuild({ ...bound, format: next }))));\n }\n if (showPrefix) {\n const prefixInput = changeInput(\n bindValue?.prefix ?? \"\",\n (next) => setAttr(rebuild({ ...bound, prefix: next })),\n \"wgd-input wgd-attr-prefix\"\n );\n prefixInput.placeholder = \"prefix\";\n prefixInput.title = \"Literal prefix, e.g. mailto: \u2014 emitted only when the bound value is non-empty\";\n row.push(prefixInput);\n }\n if (showAddMap) {\n const addMap = h(\n \"button\",\n { class: \"wgd-icon\", type: \"button\", title: \"Map values to authored literals (e.g. status \u2192 class)\" },\n [\"map\"]\n );\n addMap.addEventListener(\"click\", () => setAttr(rebuild({ ...bound, map: {} })));\n row.push(h(\"span\", { class: \"wgd-node-icons\" }, [addMap, removeAttr]));\n } else {\n row.push(removeAttr);\n }\n\n const attrRow = h(\"div\", { class: \"wgd-attr-row\" }, row);\n const parts: (Node | string)[] = [attrRow];\n if (isBind && transform === \"map\") {\n // The map block: data value \u2192 authored literal rows, plus the\n // miss default. Emptying the record drops the transform.\n const mapEditor = createRecordEditor(\n bound.map,\n { key: \"data value\", value: \"authored literal\", add: \"+ mapping\" },\n (nextMap) => {\n setAttr(\n nextMap === undefined\n ? { bind: bound.bind }\n : rebuild({ ...bound, map: nextMap })\n );\n }\n );\n const defaultInput = changeInput(\n bound.default ?? \"\",\n (next) => setAttr(rebuild({ ...bound, default: next })),\n \"wgd-input wgd-attr-map-default\"\n );\n defaultInput.placeholder = \"default (on miss)\";\n parts.push(\n h(\"div\", { class: \"wgd-attr-map\" }, [\n mapEditor.element,\n h(\"div\", { class: \"wgd-rec-row\" }, [\n h(\"span\", { class: \"wgd-st-colon\" }, [\"\u21B3\"]),\n defaultInput\n ])\n ])\n );\n }\n return parts.length === 1\n ? attrRow\n : h(\"div\", { class: \"wgd-attr\" }, parts);\n });\n const childNodes = Array.isArray(node.children) ? (node.children as unknown[]) : [];\n // One add menu per element covers attributes and every child form \u2014\n // the tree carries no persistent per-form button rows.\n const addMenu = menuButton(\n \"+\",\n \"Add attribute or child node\",\n // Actions belong on activatable elements: buttons and links.\n [\n \"attribute\",\n ...(binding === undefined && (node.tag === \"button\" || node.tag === \"a\") ? [\"action\"] : []),\n ...Object.keys(NODE_PRESETS)\n ],\n (choice) => {\n collapsedPaths.delete(pathString(path)); // never add into a fold\n const preset = NODE_PRESETS[choice];\n if (choice === \"attribute\") {\n commitAt(path, { ...node, attrs: { ...attrs, \"\": \"\" } });\n } else if (choice === \"action\") {\n const first = actionContext.actions[0];\n commitAt(path, {\n ...node,\n action: first !== undefined ? { ref: first.name } : { definition: { kind: \"prompt\", text: [\"Tell me more\"] } }\n });\n } else if (preset) {\n commitAt([...path, childNodes.length], preset());\n }\n }\n );\n const body: (Node | string)[] = [];\n if (attrRows.length > 0) body.push(h(\"div\", { class: \"wgd-attrs\" }, attrRows));\n // Action binding: the element becomes activatable in Apps hosts. The\n // editor commits the whole binding; `undefined` drops the key.\n if (binding !== undefined) {\n const scopePaths = isPlainObject(scope) ? pathOptions(scope, \"when\") : [];\n const bindingEditor = createBindingEditor(\n binding,\n {\n ...actionContext,\n scopePaths,\n // The widget's effective data schema drives output-map targets.\n getDataSchema: () => effectiveDataSchema(store.get(), actionContext.schemas)\n },\n (next) => {\n if (next === undefined) {\n const { action: _gone, ...rest } = node;\n commitAt(path, rest);\n } else {\n commitAt(path, { ...node, action: next });\n }\n }\n );\n const actionParts: (Node | string)[] = [h(\"span\", { class: \"wgd-slot-label\" }, [\"action\"]), bindingEditor.element];\n // An unknown shared ref is flagged at the element carrying it.\n const ref = \"ref\" in binding && typeof binding.ref === \"string\" ? binding.ref : undefined;\n if (ref !== undefined && unknownRefs.has(ref)) {\n actionParts.push(diagnosticLine(`Unknown shared action '${ref}' \u2014 this element renders disabled.`));\n }\n body.push(h(\"div\", { class: \"wgd-attrs wgd-node-action\" }, actionParts));\n }\n if (childNodes.length > 0) {\n body.push(\n h(\n \"div\",\n { class: \"wgd-children\" },\n childNodes.map((child, index) =>\n renderNode(\n child,\n [...path, index],\n errorPath,\n true,\n { parent: path, index, count: childNodes.length },\n scope\n )\n )\n )\n );\n }\n const summaryParts: string[] = [];\n if (attrRows.length > 0) {\n summaryParts.push(`${attrRows.length} attr${attrRows.length === 1 ? \"\" : \"s\"}`);\n }\n if (binding !== undefined) summaryParts.push(\"action\");\n if (childNodes.length > 0) {\n summaryParts.push(\n `${childNodes.length} ${childNodes.length === 1 ? \"child\" : \"children\"}`\n );\n }\n return nodeShell(\n undefined, // the tag select is the node's label\n path,\n [tagControl(node.tag, (value) => commitAt(path, { ...node, tag: value }))],\n body,\n errorHere,\n removable,\n moves,\n { icons: [addMenu], summary: summaryParts.join(\" \u00B7 \") }\n );\n }\n return nodeShell(\n \"unknown\",\n path,\n [h(\"code\", undefined, [JSON.stringify(node)])],\n [],\n errorHere ?? \"Unknown template node form.\",\n removable,\n moves\n );\n }\n\n let currentError: string | undefined;\n let lastDraft: WidgetDraft | undefined;\n let lastErrorPath: string | undefined;\n\n /** Rebuild the tree from the last refresh inputs (collapse toggles). */\n function renderTree(): void {\n if (lastDraft === undefined) return;\n // Shared refs resolve like inline schemas \u2014 a ref-based widget gets the same path completions.\n treeHost.replaceChildren(\n renderNode(\n lastDraft.template,\n [],\n lastErrorPath,\n true,\n undefined,\n effectiveDataSchema(lastDraft, actionContext.schemas)\n )\n );\n }\n\n function refresh(draft: WidgetDraft, diagnostics: DesignerDiagnostics): void {\n currentError = diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}`\n : undefined;\n lastDraft = draft;\n lastErrorPath = diagnostics.template?.path;\n const known = new Set(actionContext.actions.map((action) => action.name));\n unknownRefs = new Set(collectActionRefs(draft.template, draft.load).filter((ref) => !known.has(ref)));\n const templateMessage = diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}` +\n (diagnostics.template.path !== undefined && diagnostics.template.path !== \"\"\n ? ` (at ${diagnostics.template.path})`\n : \"\")\n : diagnostics.actionRefs;\n templateDiag.hidden = templateMessage === undefined;\n templateDiag.textContent = templateMessage ?? \"\";\n if (!treeHost.hidden || treeHost.childNodes.length === 0) {\n renderTree();\n }\n if (document.activeElement !== jsonArea) {\n jsonArea.value = JSON.stringify(draft.template, null, 2);\n repaintHighlight(jsonArea);\n }\n }\n\n refreshers.push(() => undefined); // template refresh runs via refresh() below\n\n return { element, refresh, dispose: () => element.remove() };\n}\n", "/**\n * Preview controls in the widget designer: which of the host-supplied\n * named themes the DRAFT renders under \u2014 plus a read-only reference of\n * the effective tokens, so style authoring can reach for\n * `var(--wg-\u2026)` by sight instead of memory.\n *\n * Theme *authoring* lives in the standalone theme designer \u2014 this panel\n * only selects and displays. There is deliberately no preview-kind\n * selector: the widget designer previews the draft, and previewing\n * arbitrary kinds under a theme is the theme designer's job.\n */\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { TOKEN_SPECS } from \"@widgentic/core\";\nimport { diagnosticLine, h, section } from \"./dom.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\n\nexport function mountThemePanel(\n store: DraftStore,\n refreshers: ((draft: WidgetDraft) => void)[],\n themes: ThemeEntry[] = []\n): {\n element: HTMLElement;\n /** Show the theme validator's error \u2014 this panel owns the value. */\n setDiagnostic(message: string | undefined): void;\n dispose(): void;\n} {\n // Theme validation errors were computed and dropped before this: the\n // panel that owns the offending value showed nothing at all.\n const themeDiag = diagnosticLine(undefined);\n // Theme selector: \"none\" plus whatever the host supplied.\n const themeSelect = h(\"select\", {\n class: \"wgd-select wgd-theme-select\"\n });\n themeSelect.append(h(\"option\", { value: \"\" }, [\"(none \u2014 defaults)\"]));\n for (const entry of themes) {\n themeSelect.append(\n h(\"option\", { value: entry.name }, [entry.label ?? entry.name])\n );\n }\n // The selection is the person's: it names the draft's `previewTheme`\n // and only a pick here changes it \u2014 tokens a host or agent layers on\n // top never re-select by content.\n const showChoice = (draft: WidgetDraft) => {\n themeSelect.value = themes.some((entry) => entry.name === draft.previewTheme) ? draft.previewTheme ?? \"\" : \"\";\n };\n showChoice(store.get());\n themeSelect.addEventListener(\"change\", () => {\n const entry = themes.find((candidate) => candidate.name === themeSelect.value);\n store.update((draft) => {\n const { theme: _theme, themeStyles: _styles, previewTheme: _name, ...rest } = draft;\n if (entry === undefined) return rest;\n // A pick replaces any layered tokens. The entry's shared styles dress\n // the preview too, so its classes look in the draft as they will\n // under this theme.\n return {\n ...rest,\n theme: entry.tokens,\n previewTheme: entry.name,\n ...(entry.styles === undefined ? {} : { themeStyles: entry.styles })\n };\n });\n });\n\n // Token reference: the EFFECTIVE preview tokens \u2014 the selected entry\n // merged over the registry defaults \u2014 plus the entry's x-* customs.\n // Types come from TOKEN_SPECS metadata (color \u2192 swatch), never inferred.\n const tokenList = h(\"div\", { class: \"wgd-token-ref\" });\n\n function renderTokenReference(theme: Record<string, string> | undefined): void {\n tokenList.replaceChildren();\n for (const [name, spec] of Object.entries(TOKEN_SPECS)) {\n const value = theme?.[name] ?? spec.default;\n const row = h(\"div\", { class: \"wgd-token-ref-row\", title: spec.use }, [\n spec.type === \"color\"\n ? h(\"span\", {\n class: \"wgd-token-ref-swatch\",\n style: `background: ${value}`\n })\n : h(\"span\", { class: \"wgd-token-ref-swatch wgd-token-ref-noswatch\" }),\n h(\"code\", { class: \"wgd-token-ref-name\" }, [`--wg-${name}`]),\n h(\"span\", { class: \"wgd-token-ref-value\" }, [value])\n ]);\n tokenList.append(row);\n }\n for (const [name, value] of Object.entries(theme ?? {})) {\n if (!name.startsWith(\"x-\")) continue;\n const row = h(\"div\", { class: \"wgd-token-ref-row\", title: \"Custom variable\" }, [\n h(\"span\", { class: \"wgd-token-ref-swatch wgd-token-ref-noswatch\" }),\n h(\"code\", { class: \"wgd-token-ref-name\" }, [`--wg-${name}`]),\n h(\"span\", { class: \"wgd-token-ref-value\" }, [value])\n ]);\n tokenList.append(row);\n }\n }\n renderTokenReference(store.get().theme);\n\n refreshers.push((draft) => {\n showChoice(draft);\n renderTokenReference(draft.theme);\n });\n\n const rows: (Node | string)[] = [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Preview theme\"]),\n themeSelect\n ]),\n h(\"span\", { class: \"wgd-field-label\" }, [\n themes.length === 0\n ? \"No themes supplied by the host \u2014 design themes in the theme designer.\"\n : \"Themes come from the host; edit them in the theme designer.\"\n ]),\n themeDiag,\n h(\"details\", { class: \"wgd-token-ref-details\" }, [\n h(\"summary\", { class: \"wgd-field-label\" }, [\n \"Theme tokens (reference for styles)\"\n ]),\n tokenList\n ])\n ];\n\n const element = section(\"Preview\", rows);\n return {\n element,\n setDiagnostic(message) {\n themeDiag.hidden = message === undefined;\n themeDiag.textContent = message ?? \"\";\n },\n dispose: () => element.remove()\n };\n}\n", "/**\n * Editor panels: plain modules over the draft store. Refresh discipline:\n * every store change re-derives diagnostics and refreshes bound controls,\n * but never overwrites the control the user is typing in\n * (`document.activeElement` wins) \u2014 the store is the single model, the\n * DOM is a projection.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { diagnosticLine, h, section, tabs, textArea, textField, requireChild } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { mountIoPanel } from \"./io.js\";\nimport { createJsonTreeEditor } from \"./json-tree-editor.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\nimport { createRecordEditor } from \"./record-editor.js\";\nimport { createSchemaForm } from \"./schema-form.js\";\nimport { createStylesPanel } from \"./styles-panel.js\";\nimport type { DraftStore, WidgetDraft } from \"./store.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport { mountTemplatePanel } from \"./template-panel.js\";\nimport type { TemplateActionContext } from \"./template-panel.js\";\nimport { createBindingEditor } from \"./action-editor.js\";\nimport type { ActionBinding } from \"@widgentic/core\";\nimport { mountThemePanel } from \"./theme-panel.js\";\nimport { deriveDiagnostics, effectiveDataSchema } from \"./validate.js\";\n\n/** Column layout: definition (exported) on the left, presentation on the right. */\nexport interface PanelColumns {\n left: HTMLElement;\n right: HTMLElement;\n}\n\ntype Refresher = (draft: WidgetDraft) => void;\n\n/**\n * JSON-valued textarea with parse gating: invalid JSON never reaches the\n * store (last-valid-wins) \u2014 the parse error shows beside the field.\n */\nfunction jsonField(\n label: string,\n read: (draft: WidgetDraft) => unknown,\n write: (draft: WidgetDraft, value: unknown) => WidgetDraft,\n clear: ((draft: WidgetDraft) => WidgetDraft) | undefined,\n store: DraftStore,\n refreshers: Refresher[],\n rows = 6\n): HTMLElement {\n const parseError = diagnosticLine(undefined);\n const initial = read(store.get());\n const field = textArea(\n label,\n initial === undefined ? \"\" : JSON.stringify(initial, null, 2),\n (text) => {\n if (text.trim() === \"\") {\n parseError.hidden = true;\n if (clear) store.update((draft) => clear(draft));\n return;\n }\n try {\n const value: unknown = JSON.parse(text);\n parseError.hidden = true;\n parseError.textContent = \"\";\n store.update((draft) => write(draft, value));\n } catch (error) {\n parseError.hidden = false;\n parseError.textContent = `Invalid JSON (draft keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n },\n rows\n );\n const area = requireChild(field, \"textarea\");\n attachJsonHighlight(area);\n refreshers.push((draft) => {\n if (document.activeElement === area) return;\n const value = read(draft);\n area.value = value === undefined ? \"\" : JSON.stringify(value, null, 2);\n repaintHighlight(area); // programmatic writes fire no input event\n });\n return h(\"div\", undefined, [field, parseError]);\n}\n\nexport function mountPanels(\n store: DraftStore,\n columns: PanelColumns,\n themes: ThemeEntry[] = [],\n schemas: SchemaEntry[] = [],\n actionContext: TemplateActionContext = { actions: [], secretNames: [], schemas: [] }\n): { dispose(): void } {\n const refreshers: Refresher[] = [];\n const disposers: (() => void)[] = [];\n\n function bindText(\n label: string,\n read: (draft: WidgetDraft) => string,\n write: (draft: WidgetDraft, value: string) => WidgetDraft\n ): HTMLElement {\n const field = textField(label, read(store.get()), (value) =>\n store.update((draft) => write(draft, value))\n );\n const input = requireChild(field, \"input\");\n refreshers.push((draft) => {\n if (document.activeElement !== input) input.value = read(draft);\n });\n return field;\n }\n\n // --- General: kind + prose descriptor fields (left) -------------------\n const kindDiag = diagnosticLine(undefined);\n // Hints: name\u2192doc rows beside the parse-gated JSON pane \u2014 the same\n // Tree/JSON pair as styles, scaled down to a flat record.\n const hintsEditor = createRecordEditor(\n store.get().descriptor.hints,\n { key: \"hint name\", value: \"what the hint does\", add: \"+ hint\" },\n (hints) =>\n store.update((d) => {\n if (hints === undefined) {\n const { hints: _h, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, hints } };\n })\n );\n refreshers.push((draft) => hintsEditor.setValue(draft.descriptor.hints));\n const dataShapeDiag = diagnosticLine(undefined);\n const generalPanel = section(\"General\", [\n bindText(\"Kind (id)\", (d) => d.kind, (d, v) => ({ ...d, kind: v })),\n kindDiag,\n bindText(\n \"Description\",\n (d) => d.descriptor.description ?? \"\",\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, description: v } })\n ),\n bindText(\n \"Data shape (prose)\",\n (d) => d.descriptor.dataShape ?? \"\",\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataShape: v } })\n ),\n dataShapeDiag,\n h(\"div\", { class: \"wgd-field\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Hints\"]),\n tabs([\n { label: \"Tree\", element: hintsEditor.element },\n {\n label: \"JSON\",\n element: jsonField(\n \"\",\n (d) => d.descriptor.hints,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n const hints = Object.fromEntries(\n Object.entries(v).map(([k, doc]) => [k, String(doc)])\n ) as Record<string, string>;\n return { ...d, descriptor: { ...d.descriptor, hints } };\n },\n (d) => {\n const { hints: _hints, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers,\n 3\n )\n }\n ])\n ])\n ]);\n\n // --- Data schema (left, definition): inline editing OR a shared ref ----\n // Two modes, mirroring the store's contract: an inline dataSchema, or a\n // dataSchemaRef into the host-supplied shared schemas \u2014 never both.\n const schemaBuilder = createSchemaBuilder(store.get().descriptor.dataSchema, (schema) =>\n store.update((d) => {\n if (schema === undefined) {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, dataSchema: schema } };\n })\n );\n refreshers.push((draft) => schemaBuilder.setValue(draft.descriptor.dataSchema));\n const inlineEditors = tabs([\n { label: \"Builder\", element: schemaBuilder.element },\n {\n label: \"JSON\",\n element: jsonField(\n \"dataSchema (JSON-Schema subset: type/properties/required/items/enum/pattern)\",\n (d) => d.descriptor.dataSchema,\n (d, v) => {\n if (!isPlainObject(v)) return d;\n return { ...d, descriptor: { ...d.descriptor, dataSchema: v } };\n },\n (d) => {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]);\n\n const modeSelect = h(\"select\", { class: \"wgd-select wgd-schema-mode\" });\n modeSelect.append(h(\"option\", { value: \"inline\" }, [\"define inline\"]));\n const sharedOption = h(\"option\", { value: \"shared\" }, [\"use shared\"]);\n if (schemas.length === 0) sharedOption.disabled = true;\n modeSelect.append(sharedOption);\n\n const refSelect = h(\"select\", { class: \"wgd-select wgd-schema-ref\" });\n for (const entry of schemas) {\n refSelect.append(h(\"option\", { value: entry.name }, [entry.label ?? entry.name]));\n }\n refSelect.addEventListener(\"change\", () => {\n store.update((d) => ({\n ...d,\n descriptor: { ...d.descriptor, dataSchemaRef: refSelect.value }\n }));\n });\n\n // The shared schema shows read-only: editing it from inside a widget\n // draft would be edit-at-a-distance \u2014 that belongs to the schema section.\n const sharedView = h(\"textarea\", {\n class: \"wgd-textarea wgd-schema-shared\",\n rows: \"10\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const schemaRefDiag = diagnosticLine(undefined);\n const schemaAuditDiag = diagnosticLine(undefined);\n const sharedWrap = h(\"div\", undefined, [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Shared schema\"]),\n refSelect\n ]),\n sharedView,\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Read-only here \u2014 edit shared schemas in the Data schemas section.\"\n ])\n ]);\n\n modeSelect.addEventListener(\"change\", () => {\n if (modeSelect.value === \"shared\") {\n const name =\n store.get().descriptor.dataSchemaRef ?? schemas[0]?.name ?? \"\";\n store.update((d) => {\n const { dataSchema: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: { ...rest, dataSchemaRef: name } };\n });\n } else {\n // Back to inline: seed with the resolved shared schema (a copy), so\n // \"customize from here\" is one switch away.\n const resolved = effectiveDataSchema(store.get(), schemas);\n store.update((d) => {\n const { dataSchemaRef: _r, ...rest } = d.descriptor;\n return {\n ...d,\n descriptor: {\n ...rest,\n dataSchema: (resolved ?? { type: \"object\" }) as Record<string, unknown>\n }\n };\n });\n }\n });\n\n function refreshSchemaMode(draft: WidgetDraft): void {\n const ref = draft.descriptor.dataSchemaRef;\n const shared = typeof ref === \"string\";\n modeSelect.value = shared ? \"shared\" : \"inline\";\n inlineEditors.hidden = shared;\n sharedWrap.hidden = !shared;\n if (shared) {\n if (refSelect.value !== ref) refSelect.value = ref;\n const resolved = schemas.find((entry) => entry.name === ref)?.schema;\n sharedView.value =\n resolved === undefined ? \"\" : JSON.stringify(resolved, null, 2);\n repaintHighlight(sharedView); // programmatic writes fire no input event\n }\n }\n refreshers.push(refreshSchemaMode);\n refreshSchemaMode(store.get());\n\n const schemaPanel = section(\n \"Data schema\",\n [\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Source\"]),\n modeSelect\n ]),\n schemaRefDiag,\n inlineEditors,\n schemaAuditDiag,\n sharedWrap\n ],\n false\n );\n // The highlight layer wraps the textarea in place, so attach after the\n // section assembly gives it a parent.\n attachJsonHighlight(sharedView);\n\n /**\n * Adaptive data editor: schema-driven form when a dataSchema exists,\n * generic JSON tree otherwise \u2014 rebuilt when the schema changes; the raw\n * JSON textarea remains as a sibling tab either way.\n */\n function adaptiveDataEditor(\n read: (d: WidgetDraft) => unknown,\n write: (d: WidgetDraft, v: unknown) => WidgetDraft\n ): HTMLElement {\n const hostEl = h(\"div\");\n let schemaKey = \"\";\n let editor:\n | { element: HTMLElement; setValue(v: unknown): void }\n | undefined;\n\n function rebuild(draft: WidgetDraft): void {\n const schema = effectiveDataSchema(draft, schemas);\n const key = schema === undefined ? \"\" : JSON.stringify(schema);\n if (editor !== undefined && key === schemaKey) {\n editor.setValue(read(draft));\n return;\n }\n schemaKey = key;\n const onChange = (value: unknown): void =>\n store.update((d) => write(d, value));\n editor =\n schema !== undefined && isPlainObject(schema)\n ? createSchemaForm(schema as DataSchema, read(draft), onChange)\n : createJsonTreeEditor(read(draft), onChange);\n hostEl.replaceChildren(editor.element);\n }\n\n rebuild(store.get());\n refreshers.push(rebuild);\n return hostEl;\n }\n\n // --- Sample data = the descriptor's dataExample (left, exported) -------\n const exampleDiag = diagnosticLine(undefined);\n const samplePanel = section(\n \"Sample data\",\n [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"dataExample \u2014 ships with the widget as the example agents imitate\"\n ]),\n tabs([\n {\n label: \"Edit\",\n element: adaptiveDataEditor(\n (d) => d.descriptor.dataExample,\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataExample: v } })\n )\n },\n {\n label: \"JSON\",\n element: jsonField(\n \"dataExample (JSON)\",\n (d) => d.descriptor.dataExample,\n (d, v) => ({ ...d, descriptor: { ...d.descriptor, dataExample: v } }),\n (d) => {\n const { dataExample: _e, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n },\n store,\n refreshers\n )\n }\n ]),\n exampleDiag\n ],\n false\n );\n\n // --- Data for preview (right, session-only) ----------------------------\n const sampleDiag = diagnosticLine(undefined);\n const previewDataPanel = section(\n \"Data for preview\",\n [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Overrides dataExample in the preview only (not exported)\"\n ]),\n tabs([\n {\n label: \"Edit\",\n element: adaptiveDataEditor(\n (d) => d.sampleData,\n (d, v) => ({ ...d, sampleData: v })\n )\n },\n {\n label: \"JSON\",\n element: jsonField(\n \"Preview data (JSON)\",\n (d) => d.sampleData,\n (d, v) => ({ ...d, sampleData: v }),\n (d) => {\n const { sampleData: _s, ...rest } = d;\n return rest;\n },\n store,\n refreshers,\n 4\n )\n }\n ]),\n sampleDiag\n ],\n false\n );\n\n // --- Styles panel (right, presentation): the panel the theme designer\n // shares \u2014 Tree and JSON over the one draft value, plus the audit.\n const stylesPanel = createStylesPanel(store.get().descriptor.styles, (styles) =>\n store.update((d) => {\n if (styles === undefined) {\n const { styles: _s, ...rest } = d.descriptor;\n return { ...d, descriptor: rest };\n }\n return { ...d, descriptor: { ...d.descriptor, styles } };\n })\n );\n refreshers.push((draft) => stylesPanel.setValue(draft.descriptor.styles));\n\n const templatePanel = mountTemplatePanel(store, refreshers, { actionContext });\n const themePanel = mountThemePanel(store, refreshers, themes);\n\n // --- Load: the widget-level http GET action run once per instance -------\n const loadDiag = diagnosticLine(undefined);\n const loadEditor = createBindingEditor(\n store.get().load,\n {\n ...actionContext,\n loadOnly: true,\n getDataSchema: () => effectiveDataSchema(store.get(), schemas)\n },\n (binding: ActionBinding | undefined) =>\n store.update((d) => {\n if (binding === undefined) {\n const { load: _l, ...rest } = d;\n return rest;\n }\n return { ...d, load: binding };\n })\n );\n refreshers.push((draft) => {\n if (!loadEditor.element.contains(document.activeElement)) loadEditor.setValue(draft.load);\n });\n // Same compact chrome as an element's binding editor in the tree.\n const loadPanel = section(\n \"Load action (http GET, runs once when the widget first renders in an Apps host)\",\n [h(\"div\", { class: \"wgd-compact wgd-load\" }, [loadEditor.element]), loadDiag],\n false\n );\n const ioPanel = mountIoPanel(store);\n\n // Read-only marks the right column's EDITING sections; the theme panel\n // (preview selector + token reference) stays live in that mode.\n previewDataPanel.classList.add(\"wgd-edit-only\");\n stylesPanel.element.classList.add(\"wgd-edit-only\");\n\n // Left: the widget definition (what export produces). Right: presentation.\n columns.left.append(\n generalPanel,\n schemaPanel,\n samplePanel,\n templatePanel.element,\n loadPanel,\n ioPanel.element\n );\n columns.right.append(previewDataPanel, stylesPanel.element, themePanel.element);\n disposers.push(templatePanel.dispose, themePanel.dispose, ioPanel.dispose);\n\n // Diagnostics refresh: derive once per change here (cheap, pure) \u2014 and\n // once immediately, so the tree/JSON projections render before any edit.\n function applyDiagnostics(draft: WidgetDraft): void {\n const diagnostics = deriveDiagnostics(draft, { schemas, actions: actionContext.actions });\n kindDiag.hidden = diagnostics.kind === undefined;\n // Unknown refs are flagged in the template panel, at the element; the\n // Load section only ever speaks about the load binding.\n loadDiag.hidden = diagnostics.load === undefined;\n loadDiag.textContent = diagnostics.load ?? \"\";\n kindDiag.textContent = diagnostics.kind ?? \"\";\n exampleDiag.hidden = diagnostics.example === undefined;\n exampleDiag.textContent = diagnostics.example\n ? `dataExample vs dataSchema: ${diagnostics.example.code} at ${diagnostics.example.path} \u2014 ${diagnostics.example.message}`\n : \"\";\n sampleDiag.hidden = diagnostics.sample === undefined;\n sampleDiag.textContent = diagnostics.sample\n ? `sample vs dataSchema: ${diagnostics.sample.code} at ${diagnostics.sample.path} \u2014 ${diagnostics.sample.message}`\n : \"\";\n dataShapeDiag.hidden = diagnostics.dataShape === undefined;\n dataShapeDiag.textContent = diagnostics.dataShape ?? \"\";\n schemaRefDiag.hidden = diagnostics.schemaRef === undefined;\n schemaRefDiag.textContent = diagnostics.schemaRef ?? \"\";\n schemaAuditDiag.hidden = diagnostics.dataSchema === undefined;\n schemaAuditDiag.textContent = diagnostics.dataSchema?.join(\"\\n\") ?? \"\";\n themePanel.setDiagnostic(\n diagnostics.theme\n ? `${diagnostics.theme.code}: ${diagnostics.theme.message}`\n : undefined\n );\n stylesPanel.setIssues(diagnostics.styles);\n for (const refresh of refreshers) refresh(draft);\n templatePanel.refresh(draft, diagnostics);\n }\n\n const off = store.subscribe(applyDiagnostics);\n disposers.push(off);\n applyDiagnostics(store.get());\n\n return {\n dispose() {\n for (const dispose of disposers) dispose();\n columns.left.replaceChildren();\n columns.right.replaceChildren();\n }\n };\n}\n", "/**\n * Live preview through the real pipeline: the draft template compiles into\n * a delegating renderer registered ONCE under a stable internal kind, so a\n * single `mountWidget` handle survives every template revision and updates\n * patch the DOM in place (`reactive-rendering` dogfooded). Built-in kinds\n * share the same scratch catalog for theme-designer previews.\n *\n * Invalid drafts freeze the last good render behind an error banner \u2014\n * never a blank pane (the app-template error-state lesson).\n */\nimport { isPlainObject } from \"@widgentic/core\";\nimport { createCatalog } from \"@widgentic/core\";\nimport type { WidgetRenderer } from \"@widgentic/core\";\nimport type { WidgetPayload } from \"@widgentic/core\";\nimport { mountWidget } from \"@widgentic/core\";\nimport type { WidgetMount } from \"@widgentic/core\";\nimport { compileTemplate, validateTemplate } from \"@widgentic/core\";\nimport { applyTheme, injectBaseStyles, themeStylesToCss } from \"@widgentic/core\";\nimport { h } from \"./dom.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\nimport type { StoredAction } from \"@widgentic/core\";\n\n/** Internal kind the draft renders under (stable across recompiles). */\nexport const PREVIEW_KIND = \"designer-preview\";\n\n/**\n * A host-supplied definition the preview can render by kind. `descriptor`\n * stays `unknown` on purpose: hosts hand these straight off the wire, so\n * the preview narrows what it needs and ignores the rest.\n */\nexport interface PreviewWidget {\n kind: string;\n template: unknown;\n descriptor?: unknown;\n}\n\nexport interface PreviewOptions {\n /**\n * Custom widget definitions to make previewable by kind \u2014 a theme is\n * judged against the widgets it will actually dress, not only the\n * built-ins. Definitions that fail template validation are skipped.\n */\n widgets?: PreviewWidget[];\n /** Shared actions, so `{ ref }` bindings preview with their real kind. */\n actions?: StoredAction[];\n}\n\nexport interface PreviewController {\n readonly pane: HTMLElement;\n /** Selectable kinds: built-ins plus the registered customs. */\n readonly kinds: string[];\n /**\n * Re-render for a draft revision. The WIDGET designer always renders\n * the draft (no `previewKind`); the optional kind parameter exists for\n * the THEME designer, whose job is previewing catalog kinds under a\n * theme.\n */\n update(\n draft: WidgetDraft,\n diagnostics: DesignerDiagnostics,\n previewKind?: string\n ): void;\n dispose(): void;\n}\n\n/**\n * Distinguishes previews on one page, so a theme's styles stay in theirs.\n * The random part keeps two copies of this module (two bundles on one page)\n * from handing out the same id.\n */\nlet previewCount = 0;\nconst previewSalt = Math.random().toString(36).slice(2, 8);\n\nexport function createPreview(options: PreviewOptions = {}): PreviewController {\n injectBaseStyles(document);\n\n const banner = h(\"div\", { class: \"wgd-banner\" });\n banner.hidden = true;\n // Theme styles first: the previewed kind's own rule wins a tie, as it\n // does in a render.\n const themeStyles = h(\"style\");\n const kindStyles = h(\"style\");\n const scope = `wgd-preview-${previewSalt}-${++previewCount}`;\n const mountRoot = h(\"div\", { class: \"wgd-preview\", \"data-wgd-scope\": scope });\n // Every style the preview emits \u2014 the widget's and the theme's \u2014 is\n // scoped to this preview at no added weight: the preview shares the host\n // page's DOM, and a widget's `.wg-title` must not restyle the page.\n const scoped = (styles: Record<string, Record<string, string>>) =>\n themeStylesToCss(styles, `[data-wgd-scope=\"${scope}\"]`);\n const pane = h(\"div\", { class: \"wgd-preview-pane\" }, [banner, themeStyles, kindStyles, mountRoot]);\n\n const catalog = createCatalog();\n let renderer: WidgetRenderer = () => ({ tag: \"div\", children: [\"\u2026\"] });\n catalog.register(\n PREVIEW_KIND,\n (payload: WidgetPayload) => renderer(payload),\n {\n description: \"Designer preview delegate.\",\n dataShape: \"Defined by the draft being designed.\"\n }\n );\n\n // Host-supplied customs join the scratch catalog so the theme designer\n // can preview them. Each carries its own styles, emitted when selected.\n const customStyles = new Map<string, string>();\n for (const widget of options.widgets ?? []) {\n const validated = validateTemplate(widget.template);\n // Untrusted-ish input: a bad definition is skipped, never fatal.\n if (!validated.ok || typeof widget.kind !== \"string\" || widget.kind === \"\") continue;\n const compiled = compileTemplate(validated.template);\n const descriptor = isPlainObject(widget.descriptor) ? widget.descriptor : {};\n try {\n catalog.register(widget.kind, (payload: WidgetPayload) => compiled(payload), {\n description: `Custom widget '${widget.kind}' supplied for preview.`,\n dataShape: \"Defined by the supplied definition.\",\n ...(descriptor.dataExample !== undefined\n ? { dataExample: descriptor.dataExample }\n : {})\n });\n } catch {\n continue; // a reserved/duplicate kind never breaks the designer\n }\n if (isPlainObject(descriptor.styles)) {\n customStyles.set(\n widget.kind,\n scoped(descriptor.styles as Record<string, Record<string, string>>)\n );\n }\n }\n const kinds = catalog.kinds().filter((kind) => kind !== PREVIEW_KIND);\n\n let mount: WidgetMount | undefined;\n\n function update(\n draft: WidgetDraft,\n diagnostics: DesignerDiagnostics,\n previewKind?: string\n ): void {\n const renderingDraft = previewKind === undefined || previewKind === PREVIEW_KIND;\n if (renderingDraft && !diagnostics.previewable) {\n const issue =\n diagnostics.kind ??\n (diagnostics.template\n ? `${diagnostics.template.code}: ${diagnostics.template.message}` +\n (diagnostics.template.path ? ` (at ${diagnostics.template.path})` : \"\")\n : \"Draft is not previewable.\");\n banner.hidden = false;\n // Freezing needs something to freeze ON. On the first update there\n // is no mount yet \u2014 reachable whenever a host supplies an invalid\n // or reserved-kind `initialWidget` \u2014 and returning here left the\n // pane blank, the one state the contract forbids.\n if (mount === undefined) {\n banner.textContent = `Nothing to preview yet \u2014 ${issue}`;\n mountRoot.replaceChildren(\n h(\"div\", { class: \"wgd-preview-empty\" }, [\n \"No preview: the draft has never been valid.\"\n ])\n );\n return;\n }\n banner.textContent = `Preview frozen on the last valid draft \u2014 ${issue}`;\n return; // keep the last good render mounted\n }\n // A first valid render replaces the empty state.\n mountRoot.querySelector(\".wgd-preview-empty\")?.remove();\n banner.hidden = true;\n banner.textContent = \"\";\n\n if (renderingDraft) {\n const validated = validateTemplate(draft.template);\n if (!validated.ok) return; // defensive: previewable implies ok\n const shared = options.actions ?? [];\n renderer = compileTemplate(validated.template, {\n actions: (ref) => shared.find((action) => action.name === ref)?.definition\n });\n }\n // Styles follow whatever is on screen: the draft's own, or the\n // selected custom kind's (a built-in needs none).\n kindStyles.textContent = renderingDraft\n ? draft.descriptor.styles\n ? scoped(draft.descriptor.styles)\n : \"\"\n : customStyles.get(previewKind as string) ?? \"\";\n // Unsafe values are also skipped inside applyTheme (lenient layer).\n applyTheme(mountRoot, draft.theme ?? {});\n // The guards drop unsafe entries.\n themeStyles.textContent = draft.themeStyles ? scoped(draft.themeStyles) : \"\";\n\n const payload = {\n kind: renderingDraft ? PREVIEW_KIND : (previewKind as string),\n data: renderingDraft\n ? draft.sampleData ?? draft.descriptor.dataExample ?? null\n : sampleFor(previewKind as string)\n };\n if (mount === undefined) {\n // No onAction: the preview never executes anything; bound elements\n // only wear the inert badge below.\n mount = mountWidget(payload, mountRoot, { catalog });\n } else {\n mount.update(payload);\n }\n for (const bound of mountRoot.querySelectorAll(\"[data-wg-action]\")) {\n bound.classList.add(\"wg-designer-action\");\n }\n }\n\n /** Built-in preview data for the THEME designer's kind previews. */\n function sampleFor(kind: string): unknown {\n return catalog.describe(kind)?.dataExample ?? { value: \"preview\" };\n }\n\n return {\n pane,\n kinds,\n update,\n dispose() {\n mount?.dispose();\n mount = undefined;\n pane.replaceChildren();\n }\n };\n}\n", "/**\n * Designer draft store: one micro-store per designer instance \u2014 get,\n * immutable update, subscribe, and a bounded undo stack. Deliberately\n * framework-free (the \"Arrow JS direction\": fine-grained subscriptions,\n * no VDOM) so the designer stays a zero-dependency embeddable.\n */\nimport type { WidgetDescriptorInput } from \"@widgentic/core\";\nimport type { WidgetTemplate } from \"@widgentic/core\";\nimport type { WidgetStyles, WidgetTheme } from \"@widgentic/core\";\nimport type { ActionBinding } from \"@widgentic/core\";\n\n/** The draft being designed \u2014 the server's `CustomWidget` shape plus session extras. */\nexport interface WidgetDraft {\n kind: string;\n template: WidgetTemplate;\n /**\n * Mirrors the store's shape: `dataSchemaRef` names a shared schema in\n * place of an inline `dataSchema` (never both). Export carries the ref\n * as authored \u2014 resolution belongs to the server's composition.\n */\n descriptor: WidgetDescriptorInput & { dataSchemaRef?: string };\n /** Optional http GET action run once when the widget first renders. */\n load?: ActionBinding;\n /** Optional preview data overriding `descriptor.dataExample`. */\n sampleData?: unknown;\n /** Preview theme (also the theme-designer working copy). */\n theme?: WidgetTheme;\n /** The preview theme's shared styles; preview-only, never exported. */\n themeStyles?: WidgetStyles;\n /**\n * The supplied theme the person chose for the preview, by name; `theme`\n * is its tokens with any programmatic tokens layered over them.\n * Preview-only, never exported.\n */\n previewTheme?: string;\n}\n\nexport type DraftListener = (draft: WidgetDraft) => void;\n\nconst UNDO_LIMIT = 50;\n\nexport interface DraftStore {\n get(): WidgetDraft;\n /** Replace the draft via an updater; records undo history. */\n update(updater: (draft: WidgetDraft) => WidgetDraft): void;\n /** Replace wholesale (imports/loads); clears history. */\n replace(draft: WidgetDraft): void;\n undo(): boolean;\n subscribe(listener: DraftListener): () => void;\n}\n\n/** Structured-clone with JSON semantics \u2014 drafts are serializable by contract. */\nexport function cloneDraft(draft: WidgetDraft): WidgetDraft {\n return JSON.parse(JSON.stringify(draft)) as WidgetDraft;\n}\n\nexport function starterDraft(): WidgetDraft {\n // Everything the starter binds is DECLARED in its dataSchema \u2014 the\n // preferred pattern: schema-declared properties validate, `$meta.*`\n // paths do not, so new drafts start on the validated side.\n return {\n kind: \"my-widget\",\n template: {\n tag: \"div\",\n attrs: { class: \"wg-template\" },\n children: [{ tag: \"h2\", children: [{ bind: \"title\" }] }, { bind: \"message\" }]\n },\n descriptor: {\n description: \"Describe what this widget is for.\",\n dataShape: \"{ title?, message }\",\n dataExample: {\n title: \"My widget\",\n message: \"Hello from the widgentic designer\"\n },\n dataSchema: {\n type: \"object\",\n required: [\"message\"],\n properties: {\n title: { type: \"string\" },\n message: { type: \"string\" }\n }\n }\n }\n };\n}\n\nexport function createDraftStore(initial?: WidgetDraft): DraftStore {\n let current = cloneDraft(initial ?? starterDraft());\n const history: WidgetDraft[] = [];\n const listeners = new Set<DraftListener>();\n\n function notify(): void {\n for (const listener of [...listeners]) listener(current);\n }\n\n return {\n get: () => current,\n update(updater) {\n history.push(current);\n if (history.length > UNDO_LIMIT) history.shift();\n current = cloneDraft(updater(cloneDraft(current)));\n notify();\n },\n replace(draft) {\n history.length = 0;\n current = cloneDraft(draft);\n notify();\n },\n undo() {\n const previous = history.pop();\n if (previous === undefined) return false;\n current = previous;\n notify();\n return true;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n };\n}\n", "/**\n * The designer shell: layout, store wiring, and the embedding handle.\n * Panels and the preview are plain modules receiving the store \u2014 every\n * designer instance is fully closure-scoped so multiple instances coexist\n * in one document.\n */\nimport { validateTheme } from \"@widgentic/core\";\nimport type { ThemeEntry, WidgetTheme } from \"@widgentic/core\";\nimport { applyChrome, h, injectDesignerStyles } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { applyDefinition, checkDefinition } from \"./io.js\";\nimport type { WidgetDefinition } from \"./io.js\";\nimport { mountPanels } from \"./panels.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\nimport type { StoredAction } from \"@widgentic/core\";\nimport { createPreview } from \"./preview.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport { cloneDraft, createDraftStore, starterDraft } from \"./store.js\";\nimport { deriveDiagnostics } from \"./validate.js\";\nimport type { DesignerDiagnostics } from \"./validate.js\";\n\nexport type { WidgetDefinition } from \"./io.js\";\n\nexport interface DesignerOptions {\n initialWidget?: WidgetDefinition;\n initialTheme?: WidgetTheme;\n /**\n * Named themes offered as preview options. Theme authoring belongs to\n * the standalone theme designer; the widget designer only selects.\n */\n themes?: ThemeEntry[];\n /**\n * The name of one of `themes` to open with as the preview theme \u2014 its\n * tokens and styles applied \u2014 e.g. the person's light default. A name\n * that matches no supplied entry is ignored. Wins over `initialTheme`.\n */\n previewTheme?: string;\n /**\n * Shared data schemas the draft may reference by name (the Data schema\n * section's \"use shared\" mode). Schema authoring belongs to the\n * standalone schema designer; the widget designer only selects.\n */\n schemas?: SchemaEntry[];\n /**\n * Shared actions the draft may bind by name (element `action` bindings\n * and the widget-level `load`). Action authoring belongs to the\n * standalone action designer; the widget designer only binds.\n */\n actions?: StoredAction[];\n /** Secret names offered when an inline http action needs a header or query secret. */\n secretNames?: string[];\n /**\n * Designer chrome appearance. \"auto\" (default) follows the host's\n * `prefers-color-scheme`; the explicit values pin it. This is the\n * designer's own UI \u2014 the widget preview uses the draft's theme.\n */\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Mount with editing disabled: panels stay visible but inert, only the\n * preview and its theme selector operate. Toggle later via\n * `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type LoadResult = { ok: true } | { ok: false; errors: string[] };\nexport type WidgetCheckResult = { ok: true; diagnostics: DesignerDiagnostics } | { ok: false; errors: string[] };\n\nexport interface DesignerHandle {\n getDraft(): WidgetDraft;\n /**\n * The current draft's diagnostics, resolved against the shared schemas and\n * actions the host supplied \u2014 what subscribers receive on every change.\n */\n getDiagnostics(): DesignerDiagnostics;\n loadWidget(definition: unknown): LoadResult;\n /**\n * Check a definition exactly as `loadWidget` would \u2014 the same refusals \u2014\n * and return its diagnostics against the host's shared entries, without\n * touching the draft.\n */\n checkWidget(definition: unknown): WidgetCheckResult;\n loadTheme(theme: unknown): LoadResult;\n /** Disable/enable editing; the preview and theme selector stay live. */\n setReadOnly(readOnly: boolean): void;\n subscribe(\n listener: (draft: WidgetDraft, diagnostics: DesignerDiagnostics) => void\n ): () => void;\n dispose(): void;\n}\n\nexport function createDesigner(\n container: Element,\n options: DesignerOptions = {}\n): DesignerHandle {\n injectDesignerStyles(document);\n\n const base: WidgetDraft = options.initialWidget\n ? cloneDraft({ ...options.initialWidget })\n : starterDraft();\n const preselected = options.themes?.find((entry) => entry.name === options.previewTheme);\n const initial: WidgetDraft =\n preselected !== undefined\n ? {\n ...base,\n theme: preselected.tokens,\n previewTheme: preselected.name,\n ...(preselected.styles === undefined ? {} : { themeStyles: preselected.styles })\n }\n : options.initialTheme !== undefined\n ? { ...base, theme: options.initialTheme }\n : base;\n const store = createDraftStore(initial);\n\n const listeners = new Set<\n (draft: WidgetDraft, diagnostics: DesignerDiagnostics) => void\n >();\n\n const preview = createPreview({ actions: options.actions ?? [] });\n const leftColumn = h(\"div\", { class: \"wgd-panels\" });\n const rightSections = h(\"div\", { class: \"wgd-preview-pane\" });\n const rightColumn = h(\"div\", { class: \"wgd-side\" }, [preview.pane, rightSections]);\n const root = h(\"div\", { class: \"wgd-root\" }, [leftColumn, rightColumn]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n const actionContext = {\n actions: options.actions ?? [],\n secretNames: options.secretNames ?? [],\n schemas: options.schemas ?? []\n };\n const panels = mountPanels(\n store,\n { left: leftColumn, right: rightSections },\n options.themes ?? [],\n options.schemas ?? [],\n actionContext\n );\n\n // Every diagnostic resolves against the shared entries the host supplied;\n // with no schemas supplied a reference is unverifiable, never \"unknown\".\n const diagnose = (draft: WidgetDraft): DesignerDiagnostics =>\n deriveDiagnostics(draft, {\n ...(options.schemas === undefined ? {} : { schemas: options.schemas }),\n actions: options.actions ?? []\n });\n\n function refresh(draft: WidgetDraft): void {\n const diagnostics = diagnose(draft);\n preview.update(draft, diagnostics);\n for (const listener of [...listeners]) listener(draft, diagnostics);\n }\n\n const unsubscribe = store.subscribe(refresh);\n refresh(store.get());\n\n /**\n * Read-only: every editing surface goes inert (visible, inoperable \u2014\n * section summaries stay clickable so content can still be inspected),\n * while the preview and the theme panel's selector keep working. inert\n * is applied to section BODIES, which are stable elements: panel\n * re-renders replace children inside them, never the bodies themselves.\n */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n // Complex selectors inside :not() are not universally supported, so\n // the view-only exclusion is filtered here rather than in the query.\n const bodies = [\n ...root.querySelectorAll(\n \".wgd-panels .wgd-section-body, .wgd-edit-only > .wgd-section-body\"\n )\n ].filter((body) => !body.parentElement?.classList.contains(\"wgd-view-only\"));\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getDraft: () => cloneDraft(store.get()),\n getDiagnostics: () => diagnose(store.get()),\n setReadOnly,\n loadWidget(definition) {\n const errors = checkDefinition(definition, store.get().kind);\n if (errors.length > 0) return { ok: false, errors };\n applyDefinition(store, definition as unknown as WidgetDefinition);\n return { ok: true };\n },\n checkWidget(definition) {\n const errors = checkDefinition(definition, store.get().kind);\n if (errors.length > 0) return { ok: false, errors };\n const { kind, template, descriptor, load } = definition as unknown as WidgetDefinition;\n return { ok: true, diagnostics: diagnose({ kind, template, descriptor, ...(load === undefined ? {} : { load }) }) };\n },\n loadTheme(theme) {\n const validated = validateTheme(theme);\n if (!validated.ok) {\n return { ok: false, errors: [validated.error.message] };\n }\n // Tokens layer over the person's chosen preview theme, which stays\n // chosen with its shared styles, so `{}` returns to it exactly. With\n // nothing chosen they are the whole preview theme.\n store.update((draft) => {\n const { themeStyles: _previous, ...rest } = draft;\n const chosen = options.themes?.find((entry) => entry.name === draft.previewTheme);\n return {\n ...rest,\n theme: { ...(chosen?.tokens ?? {}), ...validated.theme },\n ...(chosen?.styles === undefined ? {} : { themeStyles: chosen.styles })\n };\n });\n return { ok: true };\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n unsubscribe();\n panels.dispose();\n preview.dispose();\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone schema designer: edits a stored-schema entry\n * (`{ name, label?, description?, schema }` \u2014 the widget-store's shape)\n * so one definition (`person`) can serve many widgets. Split out like the\n * theme designer: an app routes to \"design a schema\" as its own\n * destination, and a host embedding one designer should not ship the\n * others. Shares the chrome, the schema builder, and the parse-gated\n * JSON discipline.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { auditDataSchema, isPlainObject, SAFE_IDENTIFIER } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { createSchemaBuilder } from \"./schema-builder.js\";\n\nexport interface SchemaEntry {\n name: string;\n label?: string;\n description?: string;\n schema: Record<string, unknown>;\n}\n\nexport interface SchemaDesignerOptions {\n initialSchema?: SchemaEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Mount with editing disabled: panels stay visible but inert. Toggle\n * later via `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type SchemaLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface SchemaDesignerHandle {\n getSchema(): SchemaEntry;\n loadSchema(entry: unknown): SchemaLoadResult;\n /** Disable/enable editing. */\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: SchemaEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): SchemaEntry {\n return {\n name: \"my-schema\",\n label: \"My schema\",\n schema: { type: \"object\", properties: {} }\n };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkSchemaEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(entry)) return [\"Schema entry must be an object.\"];\n if (typeof entry.name !== \"string\" || entry.name.trim() === \"\") {\n errors.push(\"'name' must be a non-empty string.\");\n } else if (!SAFE_IDENTIFIER.test(entry.name)) {\n errors.push(\n `'${entry.name}' is not a valid schema name \u2014 use letters, digits, '.', '_' or '-'.`\n );\n }\n if (!isPlainObject(entry.schema)) {\n errors.push(\"'schema' must be a plain object.\");\n }\n return errors;\n}\n\nexport function createSchemaDesigner(\n container: Element,\n options: SchemaDesignerOptions = {}\n): SchemaDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: SchemaEntry = options.initialSchema\n ? (JSON.parse(JSON.stringify(options.initialSchema)) as SchemaEntry)\n : starterEntry();\n const listeners = new Set<(entry: SchemaEntry) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-schema-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n function getEntry(): SchemaEntry {\n return JSON.parse(JSON.stringify(entry)) as SchemaEntry;\n }\n\n // What the validator would ignore in the schema: a warning the person\n // sees while editing, never a refusal (the store accepts it).\n const schemaDiag = diagnosticLine(undefined);\n function showSchemaWarnings(): void {\n const warnings = isPlainObject(entry.schema) ? auditDataSchema(entry.schema) : [];\n schemaDiag.hidden = warnings.length === 0;\n schemaDiag.textContent = warnings.join(\"\\n\");\n }\n\n function notify(): void {\n showSchemaWarnings();\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n // --- Identity panel ----------------------------------------------------\n const identityRefreshers: (() => void)[] = [];\n const nameDiag = diagnosticLine(undefined);\n\n function identityField(\n label: string,\n read: () => string,\n write: (value: string) => void\n ): HTMLElement {\n const field = textField(label, read(), write);\n const input = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== input) input.value = read();\n });\n return field;\n }\n\n const identity = section(\"Schema\", [\n identityField(\n \"Name (id)\",\n () => entry.name,\n (value) => {\n entry = { ...entry, name: value };\n const bad = value.trim() === \"\" || !SAFE_IDENTIFIER.test(value);\n nameDiag.hidden = !bad;\n nameDiag.textContent = bad\n ? \"Name must be non-empty using letters, digits, '.', '_' or '-'.\"\n : \"\";\n notify();\n }\n ),\n nameDiag,\n identityField(\n \"Label\",\n () => entry.label ?? \"\",\n (value) => {\n entry = { ...entry, label: value };\n notify();\n }\n ),\n identityField(\n \"Description\",\n () => entry.description ?? \"\",\n (value) => {\n entry = { ...entry, description: value };\n notify();\n }\n )\n ]);\n\n // --- Definition panel: builder + parse-gated JSON, one view at a time --\n const builder = createSchemaBuilder(entry.schema as DataSchema, (schema) => {\n entry = { ...entry, schema: (schema ?? {}) as Record<string, unknown> };\n syncJson();\n notify();\n });\n\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"12\",\n spellcheck: \"false\"\n });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n jsonArea.value = JSON.stringify(entry.schema, null, 2);\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n if (!isPlainObject(parsed)) throw new Error(\"schema must be an object\");\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n entry = { ...entry, schema: parsed };\n builder.setValue(parsed as DataSchema);\n notify();\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid JSON (schema keeps the last valid value): ${String(\n errorMessage(error)\n )}`;\n }\n });\n\n function syncJson(): void {\n if (document.activeElement === jsonArea) return;\n jsonArea.value = JSON.stringify(entry.schema, null, 2);\n repaintHighlight(jsonArea);\n }\n\n const builderTab = h(\n \"button\",\n { class: \"wgd-button wgd-tab wgd-tab-active\", type: \"button\" },\n [\"Builder\"]\n );\n const jsonTab = h(\"button\", { class: \"wgd-button wgd-tab\", type: \"button\" }, [\n \"JSON\"\n ]);\n jsonWrap.hidden = true;\n builderTab.addEventListener(\"click\", () => {\n builder.element.hidden = false;\n jsonWrap.hidden = true;\n builderTab.classList.add(\"wgd-tab-active\");\n jsonTab.classList.remove(\"wgd-tab-active\");\n });\n jsonTab.addEventListener(\"click\", () => {\n builder.element.hidden = true;\n jsonWrap.hidden = false;\n jsonTab.classList.add(\"wgd-tab-active\");\n builderTab.classList.remove(\"wgd-tab-active\");\n syncJson();\n });\n\n const definition = section(\"Definition\", [\n h(\"div\", { class: \"wgd-row\" }, [builderTab, jsonTab]),\n builder.element,\n jsonWrap,\n schemaDiag\n ]);\n\n // --- Import / Export: the agent hand-off -------------------------------\n // Live testing surfaced this within a day of list_schemas shipping: an\n // agent drafts the complete entry JSON from the guide, and Import is\n // where the user pastes it. Same two-section shape as the siblings.\n const importError = diagnosticLine(undefined);\n const importArea = h(\"textarea\", {\n class: \"wgd-textarea wgd-schema-import\",\n rows: \"6\",\n spellcheck: \"false\"\n });\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\n \"Import\"\n ]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadSchema(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n const importSection = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Import schema entry JSON ({ name, label?, description?, schema })\"\n ]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"Export schema entry\"\n ]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n repaintHighlight(output);\n });\n const exportSection = section(\"Export\", [\n h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]),\n output\n ]);\n // Export copies out what is on screen \u2014 read-only leaves it operable.\n exportSection.classList.add(\"wgd-view-only\");\n\n panels.append(identity, definition, importSection, exportSection);\n showSchemaWarnings();\n // The JSON layer wraps the textareas in place, so attach after assembly.\n attachJsonHighlight(jsonArea);\n attachJsonHighlight(importArea);\n attachJsonHighlight(output);\n\n function loadSchema(input: unknown): SchemaLoadResult {\n const errors = checkSchemaEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = JSON.parse(JSON.stringify(input)) as SchemaEntry;\n for (const refresh of identityRefreshers) refresh();\n nameDiag.hidden = true;\n builder.setValue(entry.schema as DataSchema);\n syncJson();\n notify();\n return { ok: true };\n }\n\n /** Same mechanism as the other designers: inert the section bodies \u2014\n * except the view-only Export, which restricts nothing. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getSchema: getEntry,\n loadSchema,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone theme designer: edits a NAMED theme entry\n * (`{ name, label?, description?, tokens, styles? }` \u2014 the theme\n * registry's shape, which is also what a host persists) with live preview\n * against any catalog kind. Its styles are edited with the widget\n * designer's own styles panel: one shape, one rule set, one editor.\n *\n * Split from the widget designer on purpose: an app routes to \"design a\n * theme\" and \"design a widget\" as separate destinations, and a host\n * embedding one should not ship the other. Both share the preview\n * controller, chrome, and store discipline.\n */\nimport { errorMessage } from \"./internal.js\";\nimport { createCatalog, createThemeRegistry, SAFE_IDENTIFIER } from \"@widgentic/core\";\nimport {\n THEME_TOKENS,\n TOKEN_DEFAULTS,\n TOKEN_SPECS,\n isSafeTokenValue,\n TOKEN_VALUE_RULE,\n isStyleMap,\n validateTheme\n} from \"@widgentic/core\";\nimport type { ThemeEntry, WidgetStyles, WidgetThemeInput } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { createPreview } from \"./preview.js\";\nimport type { PreviewWidget } from \"./preview.js\";\nimport { starterDraft } from \"./store.js\";\nimport type { WidgetDraft } from \"./store.js\";\nimport { createStylesPanel } from \"./styles-panel.js\";\nimport { auditStyles } from \"./validate.js\";\n\nconst BASE_KINDS = createCatalog().kinds();\n\n/** Hex form the native color input accepts. */\nconst HEX = /^#[0-9a-f]{3}([0-9a-f]{3})?$/i;\nconst CUSTOM_NAME = /^x-[a-z0-9][a-z0-9-]*$/;\n\nfunction toHexInput(value: string): string | undefined {\n if (!HEX.test(value)) return undefined;\n if (value.length === 7) return value.toLowerCase();\n const [, r, g, b] = value.toLowerCase();\n return `#${r}${r}${g}${g}${b}${b}`;\n}\n\nexport interface ThemeDesignerOptions {\n initialTheme?: ThemeEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n /**\n * Custom widget definitions to offer in the preview-kind selector\n * beside the built-ins \u2014 a theme is judged against the widgets it will\n * actually dress. Invalid definitions are skipped.\n */\n widgets?: PreviewWidget[];\n /**\n * Mount with editing disabled: panels stay visible but inert, only the\n * preview and its kind selector operate. Toggle later via `setReadOnly`.\n */\n readOnly?: boolean;\n}\n\nexport type ThemeLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface ThemeDesignerHandle {\n getTheme(): ThemeEntry;\n loadTheme(entry: unknown): ThemeLoadResult;\n /** Disable/enable editing; the preview and kind selector stay live. */\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: ThemeEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): ThemeEntry {\n return { name: \"my-theme\", label: \"My theme\", tokens: {} };\n}\n\n/** Theme names a stored theme may never take, read from the registry. */\nconst BUILT_IN_THEMES: ReadonlySet<string> = new Set(createThemeRegistry().names());\n\n/** What saving would refuse about a name, in the store's terms. */\nfunction nameProblem(name: string): string | undefined {\n if (!SAFE_IDENTIFIER.test(name)) {\n return `INVALID_IDENTIFIER \u2014 '${name}' may use letters, digits, '.', '_' or '-' only.`;\n }\n if (BUILT_IN_THEMES.has(name)) {\n return `RESERVED_THEME \u2014 '${name}' is a built-in theme; give yours its own name.`;\n }\n return undefined;\n}\n\n/**\n * A copy of an entry for the designer to hold. A retired `extends` is left\n * behind: the registry ignores it, and a field the designer handed back\n * (to `getTheme`, Export, Save or an agent) would look meaningful.\n */\nfunction takeEntry(input: unknown): ThemeEntry {\n const { extends: _retired, ...entry } = JSON.parse(JSON.stringify(input)) as ThemeEntry & { extends?: unknown };\n return entry;\n}\n\n/**\n * Validate an untrusted entry; errors instead of throwing. The name is held\n * to what saving accepts only when it differs from `currentName`: a name the\n * entry already has is the person's to fix (the Name field flags it), and\n * reloading the same entry with new tokens must not fail on it.\n */\nexport function checkThemeEntry(entry: unknown, currentName?: string): string[] {\n const errors: string[] = [];\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n return [\"Theme entry must be an object.\"];\n }\n const candidate = entry as Record<string, unknown>;\n if (typeof candidate.name !== \"string\" || candidate.name.trim() === \"\") {\n errors.push(\"'name' must be a non-empty string.\");\n } else if (candidate.name !== currentName) {\n const problem = nameProblem(candidate.name);\n if (problem !== undefined) errors.push(`name: ${problem}`);\n }\n const validated = validateTheme(candidate.tokens ?? {});\n if (!validated.ok) {\n errors.push(`tokens: ${validated.error.code} \u2014 ${validated.error.message}`);\n }\n if (candidate.styles !== undefined && !isStyleMap(candidate.styles)) {\n errors.push(\"styles: must map selectors to objects of property/value strings.\");\n }\n return errors;\n}\n\nexport function createThemeDesigner(\n container: Element,\n options: ThemeDesignerOptions = {}\n): ThemeDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: ThemeEntry = options.initialTheme ? takeEntry(options.initialTheme) : starterEntry();\n const listeners = new Set<(entry: ThemeEntry) => void>();\n\n const preview = createPreview(\n options.widgets ? { widgets: options.widgets } : {}\n );\n // Built-ins plus whatever custom definitions the host supplied.\n const previewKinds = preview.kinds.length > 0 ? preview.kinds : BASE_KINDS;\n let previewKind = previewKinds[0] ?? \"card\";\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const side = h(\"div\", { class: \"wgd-side\" }, [preview.pane]);\n const root = h(\"div\", { class: \"wgd-root wgd-theme-designer\" }, [panels, side]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n /** A draft carrying only what the preview needs: kind + this theme. */\n function previewDraft(): WidgetDraft {\n const draft: WidgetDraft = { ...starterDraft(), theme: entry.tokens };\n return entry.styles === undefined ? draft : { ...draft, themeStyles: entry.styles };\n }\n\n function refresh(): void {\n preview.update(previewDraft(), { styles: [], previewable: true }, previewKind);\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n function getEntry(): ThemeEntry {\n return JSON.parse(JSON.stringify(entry)) as ThemeEntry;\n }\n\n function setToken(key: string, value: string): void {\n const tokens = { ...entry.tokens } as Record<string, string>;\n if (value === \"\") delete tokens[key];\n else tokens[key] = value;\n entry = { ...entry, tokens: tokens as WidgetThemeInput };\n refresh();\n }\n\n // --- Identity panel ----------------------------------------------------\n /** Bind a text field and register its refresher (import must update it). */\n const identityRefreshers: (() => void)[] = [];\n function identityField(\n label: string,\n read: () => string,\n write: (value: string) => void\n ): HTMLElement {\n const field = textField(label, read(), write);\n const input = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== input) input.value = read();\n });\n return field;\n }\n\n // A name saving would refuse is flagged as it is typed, in the store's terms.\n const nameDiag = diagnosticLine(undefined);\n function showNameProblem(): void {\n const problem = entry.name.trim() === \"\" ? \"'name' must be a non-empty string.\" : nameProblem(entry.name);\n nameDiag.hidden = problem === undefined;\n nameDiag.textContent = problem ?? \"\";\n }\n identityRefreshers.push(showNameProblem);\n const identity = section(\"Theme\", [\n identityField(\n \"Name (id)\",\n () => entry.name,\n (value) => {\n entry = { ...entry, name: value };\n showNameProblem();\n refresh();\n }\n ),\n nameDiag,\n identityField(\n \"Label\",\n () => entry.label ?? \"\",\n (value) => {\n entry = { ...entry, label: value };\n refresh();\n }\n ),\n identityField(\n \"Description\",\n () => entry.description ?? \"\",\n (value) => {\n entry = { ...entry, description: value };\n refresh();\n }\n )\n ]);\n\n showNameProblem();\n\n // The kind selector is a PREVIEW control, so it lives beside the\n // preview, outside the editing panels \u2014 read-only mode keeps it live.\n const kindSelect = h(\"select\", {\n class: \"wgd-select wgd-preview-kind\"\n });\n for (const kind of previewKinds) {\n kindSelect.append(h(\"option\", { value: kind }, [kind]));\n }\n kindSelect.value = previewKind;\n kindSelect.addEventListener(\"change\", () => {\n previewKind = kindSelect.value;\n refresh();\n });\n side.prepend(\n h(\"div\", { class: \"wgd-row\" }, [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Preview kind\"]),\n kindSelect\n ])\n );\n\n // --- Token panel -------------------------------------------------------\n const tokenRefreshers: (() => void)[] = [];\n const tokenRows: (Node | string)[] = [];\n for (const token of THEME_TOKENS) {\n const input = h(\"input\", {\n type: \"text\",\n class: \"wgd-input\",\n placeholder: TOKEN_DEFAULTS[token]\n });\n input.value = entry.tokens[token] ?? \"\";\n const issue = diagnosticLine(undefined);\n // Control choice comes from the token's declared type \u2014 no guessing.\n const swatch = TOKEN_SPECS[token].type === \"color\"\n ? (h(\"input\", {\n type: \"color\",\n class: \"wgd-swatch\",\n title: `Pick --wg-${token}`\n }))\n : undefined;\n\n const paint = (value: string): void => {\n const effective = value === \"\" ? TOKEN_DEFAULTS[token] : value;\n if (swatch !== undefined) {\n const hex = toHexInput(effective);\n if (hex !== undefined) swatch.value = hex;\n swatch.style.background = isSafeTokenValue(effective) ? effective : \"transparent\";\n }\n };\n paint(input.value);\n swatch?.addEventListener(\"input\", () => {\n input.value = swatch.value;\n input.dispatchEvent(new Event(\"input\", { bubbles: true }));\n });\n input.addEventListener(\"input\", () => {\n const unsafe = input.value !== \"\" && !isSafeTokenValue(input.value);\n issue.hidden = !unsafe;\n issue.textContent = unsafe\n ? `INVALID_TOKEN_VALUE: unsafe value withheld from the preview. ${TOKEN_VALUE_RULE}`\n : \"\";\n paint(input.value);\n setToken(token, input.value);\n });\n tokenRefreshers.push(() => {\n if (document.activeElement !== input) {\n input.value = entry.tokens[token] ?? \"\";\n paint(input.value);\n }\n });\n tokenRows.push(\n h(\"div\", undefined, [\n h(\"label\", { class: \"wgd-field\", title: TOKEN_SPECS[token].use }, [\n h(\"span\", { class: \"wgd-field-label\" }, [`--wg-${token}`]),\n h(\n \"div\",\n { class: \"wgd-token-row\" },\n swatch === undefined ? [input] : [input, swatch]\n )\n ]),\n issue\n ])\n );\n }\n const tokenPanel = section(\"Tokens\", tokenRows);\n\n // --- Custom variables --------------------------------------------------\n const customHost = h(\"div\", { class: \"wgd-jt-children\" });\n const customError = diagnosticLine(undefined);\n\n function customEntries(): [string, string][] {\n return Object.entries(entry.tokens).filter(([key]) =>\n CUSTOM_NAME.test(key)\n ) as [string, string][];\n }\n\n function renderCustom(): void {\n const rows = customEntries().map(([key, value]) => {\n const nameInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-jt-keyinput\"\n });\n nameInput.value = key;\n nameInput.addEventListener(\"change\", () => {\n const next = nameInput.value;\n if (!CUSTOM_NAME.test(next)) {\n customError.hidden = false;\n customError.textContent = `'${next}' is not a valid custom name \u2014 use x-<lowercase-kebab>.`;\n nameInput.value = key;\n return;\n }\n customError.hidden = true;\n const tokens = { ...entry.tokens } as Record<string, string>;\n delete tokens[key];\n tokens[next] = value;\n entry = { ...entry, tokens: tokens as WidgetThemeInput };\n renderCustom();\n refresh();\n });\n const valueInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input\"\n });\n valueInput.value = value;\n valueInput.addEventListener(\"input\", () => setToken(key, valueInput.value));\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => {\n setToken(key, \"\");\n renderCustom();\n });\n return h(\"div\", { class: \"wgd-attr-row\" }, [nameInput, valueInput, remove]);\n });\n const add = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"+ variable\"\n ]);\n add.addEventListener(\"click\", () => {\n let name = \"x-custom\";\n for (let i = 1; name in entry.tokens; i++) name = `x-custom${i}`;\n setToken(name, \"0\");\n renderCustom();\n });\n customHost.replaceChildren(...rows, h(\"div\", { class: \"wgd-toolbar\" }, [add]));\n }\n renderCustom();\n const customPanel = section(\"Custom variables (--wg-x-*)\", [\n customHost,\n customError\n ]);\n\n // --- Import / export ---------------------------------------------------\n const output = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"8\",\n readonly: \"\",\n spellcheck: \"false\"\n });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\n \"Export theme entry\"\n ]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n });\n const importArea = h(\"textarea\", {\n class: \"wgd-textarea\",\n rows: \"5\",\n spellcheck: \"false\"\n });\n const importError = diagnosticLine(undefined);\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Import\"]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadTheme(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n // Two independent sections, import first \u2014 the same shape the widget\n // designer uses, so both designers read alike.\n const importPanel = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Import theme entry JSON\"]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n const exportPanel = section(\"Export\", [\n h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]),\n output\n ]);\n exportPanel.classList.add(\"wgd-view-only\");\n\n // Shared classes for every widget the theme dresses \u2014 the widget\n // designer's own panel, so the shape, guards and audit are identical.\n const stylesPanel = createStylesPanel(entry.styles, (styles: WidgetStyles | undefined) => {\n const { styles: _previous, ...rest } = entry;\n entry = styles === undefined ? rest : { ...rest, styles };\n stylesPanel.setIssues(auditStyles(entry.styles));\n refresh();\n });\n stylesPanel.setIssues(auditStyles(entry.styles));\n\n panels.append(identity, tokenPanel, customPanel, importPanel, exportPanel);\n // Under the preview, where the widget designer keeps its Styles panel:\n // styles are judged against what they dress.\n stylesPanel.element.classList.add(\"wgd-edit-only\");\n side.append(stylesPanel.element);\n\n function loadTheme(input: unknown): ThemeLoadResult {\n const errors = checkThemeEntry(input, entry.name);\n if (errors.length > 0) return { ok: false, errors };\n entry = takeEntry(input);\n for (const refreshIdentity of identityRefreshers) refreshIdentity();\n for (const refreshToken of tokenRefreshers) refreshToken();\n renderCustom();\n stylesPanel.setValue(entry.styles);\n stylesPanel.setIssues(auditStyles(entry.styles));\n refresh();\n return { ok: true };\n }\n\n refresh();\n\n /** Same mechanism as the widget designer: inert the section bodies. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [\n ...root.querySelectorAll(\".wgd-panels .wgd-section-body, .wgd-edit-only > .wgd-section-body\")\n ].filter((body) => !body.parentElement?.classList.contains(\"wgd-view-only\"));\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getTheme: getEntry,\n loadTheme,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n preview.dispose();\n root.remove();\n }\n };\n}\n", "/**\n * Standalone action designer: edits a stored-action entry\n * (`{ name, label?, description?, definition }` \u2014 the widget-store's\n * shape). Split out like the theme and schema designers. The Test control\n * appears only when the host supplies `options.testCall`: the library\n * performs no network I/O, and a test call must run through the host's\n * production execution path (secrets, SSRF guard, redaction).\n */\nimport { errorMessage } from \"./internal.js\";\nimport { isPlainObject } from \"@widgentic/core\";\nimport type { ActionDefinition, HttpActionDefinition, StoredAction } from \"@widgentic/core\";\nimport { ACTION_NAME, validateActionDefinition } from \"@widgentic/core\";\nimport type { DataSchema } from \"@widgentic/core\";\nimport { clone } from \"./internal.js\";\nimport { createDefinitionEditor } from \"./action-editor.js\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section, textField, requireChild } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { attachJsonHighlight, repaintHighlight } from \"./highlight.js\";\nimport { createSchemaForm } from \"./schema-form.js\";\nimport type { SchemaEntry } from \"./schema-designer.js\";\n\nexport type ActionEntry = StoredAction;\n\nexport interface ActionDesignerOptions {\n initialAction?: ActionEntry;\n appearance?: \"auto\" | \"light\" | \"dark\";\n /**\n * Host chrome: a partial map over `CHROME_TOKENS` applied inline on the\n * root, winning over the built-in light/dark defaults. Values may be\n * `var()` references to the host's own properties; CSS-wide keywords are\n * ignored (pass `var(--host-font, system-ui, sans-serif)`, not `inherit`).\n */\n chrome?: ChromeOptions;\n readOnly?: boolean;\n /** Shared schemas offered as \"copy from\" sources for input/output. */\n schemas?: SchemaEntry[];\n /** Secret names offered for header/query values. */\n secretNames?: string[];\n /**\n * Host-supplied test call (the production execute path). Without it no\n * Test control renders. Resolves to whatever the host wants shown \u2014\n * typically the redacted response or a structured error.\n */\n testCall?: (definition: HttpActionDefinition, args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport type ActionLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface ActionDesignerHandle {\n getAction(): ActionEntry;\n loadAction(entry: unknown): ActionLoadResult;\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (entry: ActionEntry) => void): () => void;\n dispose(): void;\n}\n\nfunction starterEntry(): ActionEntry {\n return {\n name: \"my-action\",\n label: \"My action\",\n definition: { kind: \"prompt\", text: [\"Tell me more about \", { bind: \"title\" }] }\n };\n}\n\n/** Validate an untrusted entry; errors instead of throwing. */\nexport function checkActionEntry(entry: unknown): string[] {\n const errors: string[] = [];\n if (!isPlainObject(entry)) return [\"Action entry must be an object.\"];\n if (typeof entry.name !== \"string\" || !ACTION_NAME.test(entry.name)) {\n errors.push(\"'name' must be lowercase letters, digits and dashes, starting with a letter (max 64).\");\n }\n for (const field of [\"label\", \"description\"] as const) {\n if (entry[field] !== undefined && typeof entry[field] !== \"string\") {\n errors.push(`'${field}' must be a string when present.`);\n }\n }\n const problem = validateActionDefinition(entry.definition, \"definition\");\n if (problem) errors.push(`${problem.message} (at ${problem.path})`);\n return errors;\n}\n\n/** A checked entry with only the fields the shape declares; empty texts are dropped. */\nfunction normalizeEntry(input: Record<string, unknown>): ActionEntry {\n const entry: ActionEntry = { name: input.name as string, definition: clone(input.definition as ActionDefinition) };\n if (typeof input.label === \"string\" && input.label !== \"\") entry.label = input.label;\n if (typeof input.description === \"string\" && input.description !== \"\") entry.description = input.description;\n return entry;\n}\n\n/** Set or drop an optional text field: an emptied field leaves the entry. */\nfunction withText(current: ActionEntry, field: \"label\" | \"description\", value: string): ActionEntry {\n const { [field]: _gone, ...rest } = current;\n return value === \"\" ? rest : { ...rest, [field]: value };\n}\n\nexport function createActionDesigner(\n container: Element,\n options: ActionDesignerOptions = {}\n): ActionDesignerHandle {\n injectDesignerStyles(document);\n\n let entry: ActionEntry = options.initialAction ? clone(options.initialAction) : starterEntry();\n const testCall = options.testCall;\n const listeners = new Set<(entry: ActionEntry) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-action-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n const getEntry = (): ActionEntry => clone(entry);\n function notify(): void {\n for (const listener of [...listeners]) listener(getEntry());\n }\n\n // --- Identity --------------------------------------------------------\n const identityRefreshers: (() => void)[] = [];\n const nameDiag = diagnosticLine(undefined);\n function identityField(label: string, read: () => string, write: (value: string) => void): HTMLElement {\n const field = textField(label, read(), write);\n const inputEl = requireChild(field, \"input\");\n identityRefreshers.push(() => {\n if (document.activeElement !== inputEl) inputEl.value = read();\n });\n return field;\n }\n const identity = section(\"Action\", [\n identityField(\"Name (id)\", () => entry.name, (value) => {\n entry = { ...entry, name: value };\n const bad = !ACTION_NAME.test(value);\n nameDiag.hidden = !bad;\n nameDiag.textContent = bad ? \"Name must be lowercase letters, digits and dashes, starting with a letter.\" : \"\";\n notify();\n }),\n nameDiag,\n identityField(\"Label\", () => entry.label ?? \"\", (value) => {\n entry = withText(entry, \"label\", value);\n notify();\n }),\n identityField(\"Description\", () => entry.description ?? \"\", (value) => {\n entry = withText(entry, \"description\", value);\n notify();\n })\n ]);\n\n // --- Definition: editor + parse-gated JSON -----------------------------\n const definitionDiag = diagnosticLine(undefined);\n const editor = createDefinitionEditor(\n entry.definition,\n { ...(options.schemas ? { schemas: options.schemas } : {}), ...(options.secretNames ? { secretNames: options.secretNames } : {}) },\n (definition) => {\n entry = { ...entry, definition };\n syncJson();\n refreshDefinitionDiag();\n refreshTest();\n notify();\n }\n );\n const jsonError = diagnosticLine(undefined);\n const jsonArea = h(\"textarea\", { class: \"wgd-textarea\", rows: \"12\", spellcheck: \"false\" });\n const jsonWrap = h(\"div\", undefined, [jsonArea, jsonError]);\n jsonArea.value = JSON.stringify(entry.definition, null, 2);\n jsonArea.addEventListener(\"input\", () => {\n try {\n const parsed: unknown = JSON.parse(jsonArea.value);\n const problem = validateActionDefinition(parsed, \"definition\");\n if (problem) throw new Error(`${problem.message} (at ${problem.path})`);\n jsonError.hidden = true;\n jsonError.textContent = \"\";\n entry = { ...entry, definition: parsed as ActionDefinition };\n editor.setValue(entry.definition);\n refreshDefinitionDiag();\n refreshTest();\n notify();\n } catch (error) {\n jsonError.hidden = false;\n jsonError.textContent = `Invalid (definition keeps the last valid value): ${errorMessage(error)}`;\n }\n });\n function syncJson(): void {\n if (document.activeElement === jsonArea) return;\n jsonArea.value = JSON.stringify(entry.definition, null, 2);\n repaintHighlight(jsonArea);\n }\n function refreshDefinitionDiag(): void {\n const problem = validateActionDefinition(entry.definition, \"definition\");\n definitionDiag.hidden = problem === undefined;\n definitionDiag.textContent = problem ? `${problem.message} (at ${problem.path})` : \"\";\n }\n refreshDefinitionDiag();\n\n const builderTab = h(\"button\", { class: \"wgd-button wgd-tab wgd-tab-active\", type: \"button\" }, [\"Editor\"]);\n const jsonTab = h(\"button\", { class: \"wgd-button wgd-tab\", type: \"button\" }, [\"JSON\"]);\n jsonWrap.hidden = true;\n builderTab.addEventListener(\"click\", () => {\n editor.element.hidden = false;\n jsonWrap.hidden = true;\n builderTab.classList.add(\"wgd-tab-active\");\n jsonTab.classList.remove(\"wgd-tab-active\");\n });\n jsonTab.addEventListener(\"click\", () => {\n editor.element.hidden = true;\n jsonWrap.hidden = false;\n jsonTab.classList.add(\"wgd-tab-active\");\n builderTab.classList.remove(\"wgd-tab-active\");\n syncJson();\n });\n const definition = section(\"Definition\", [\n h(\"div\", { class: \"wgd-row\" }, [builderTab, jsonTab]),\n definitionDiag,\n editor.element,\n jsonWrap\n ]);\n\n // --- Test (host-supplied) ------------------------------------------------\n const testHost = h(\"div\", { class: \"wgd-action-test\" });\n const testSection = section(\"Test\", [testHost]);\n let testArgs: Record<string, unknown> = {};\n // Arguments belong to one input schema: a different schema starts them over.\n let testInputJson: string | undefined;\n function refreshTest(): void {\n if (testCall === undefined) return;\n testHost.replaceChildren();\n if (entry.definition.kind !== \"http\") {\n testInputJson = undefined;\n testArgs = {};\n testHost.append(h(\"p\", { class: \"wgd-diagnostic\" }, [\"Prompt actions run in the host's composer; nothing to test.\"]));\n return;\n }\n const definitionNow = entry.definition;\n const inputJson = JSON.stringify(definitionNow.input);\n if (inputJson !== testInputJson) testArgs = {};\n testInputJson = inputJson;\n const form = createSchemaForm(definitionNow.input as DataSchema, testArgs, (value) => {\n testArgs = isPlainObject(value) ? value : {};\n });\n testArgs = isPlainObject(form.getValue()) ? (form.getValue() as Record<string, unknown>) : {};\n const output = h(\"pre\", { class: \"wgd-test-output\" });\n const run = h(\"button\", { class: \"wgd-button wgd-add wgd-test-run\", type: \"button\" }, [\"Test call\"]);\n run.addEventListener(\"click\", () => {\n run.disabled = true;\n run.classList.add(\"wgd-busy\");\n run.setAttribute(\"aria-busy\", \"true\");\n output.textContent = \"\u2026\";\n void testCall(definitionNow, testArgs)\n .then((result) => {\n output.textContent = typeof result === \"string\" ? result : JSON.stringify(result, null, 2);\n })\n .catch((error: Error) => {\n output.textContent = `Test failed: ${error.message}`;\n })\n .finally(() => {\n run.disabled = false;\n run.classList.remove(\"wgd-busy\");\n run.removeAttribute(\"aria-busy\");\n });\n });\n testHost.append(h(\"span\", { class: \"wgd-field-label\" }, [\"Arguments\"]), form.element, h(\"div\", { class: \"wgd-row\" }, [run]), output);\n }\n refreshTest();\n\n // --- Import / Export ------------------------------------------------------\n const importError = diagnosticLine(undefined);\n const importArea = h(\"textarea\", { class: \"wgd-textarea wgd-action-import\", rows: \"6\", spellcheck: \"false\" });\n const importButton = h(\"button\", { class: \"wgd-button\", type: \"button\" }, [\"Import\"]);\n importButton.addEventListener(\"click\", () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(importArea.value);\n } catch (error) {\n importError.hidden = false;\n importError.textContent = `Invalid JSON: ${errorMessage(error)}`;\n return;\n }\n const result = loadAction(parsed);\n importError.hidden = result.ok;\n importError.textContent = result.ok ? \"\" : result.errors.join(\"\\n\");\n });\n const importSection = section(\"Import\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\"Import action entry JSON ({ name, label?, description?, definition })\"]),\n importArea,\n importError,\n h(\"div\", { class: \"wgd-row\" }, [importButton])\n ]);\n const output = h(\"textarea\", { class: \"wgd-textarea\", rows: \"8\", readonly: \"\", spellcheck: \"false\" });\n const exportButton = h(\"button\", { class: \"wgd-button wgd-add\", type: \"button\" }, [\"Export action entry\"]);\n exportButton.addEventListener(\"click\", () => {\n output.value = JSON.stringify(getEntry(), null, 2);\n repaintHighlight(output);\n });\n const exportSection = section(\"Export\", [h(\"div\", { class: \"wgd-toolbar\" }, [exportButton]), output]);\n exportSection.classList.add(\"wgd-view-only\");\n\n panels.append(identity, definition, ...(testCall === undefined ? [] : [testSection]), importSection, exportSection);\n attachJsonHighlight(jsonArea);\n attachJsonHighlight(importArea);\n attachJsonHighlight(output);\n\n function loadAction(input: unknown): ActionLoadResult {\n const errors = checkActionEntry(input);\n if (errors.length > 0) return { ok: false, errors };\n entry = normalizeEntry(input as Record<string, unknown>);\n testArgs = {};\n for (const refresh of identityRefreshers) refresh();\n nameDiag.hidden = true;\n editor.setValue(entry.definition);\n syncJson();\n refreshDefinitionDiag();\n refreshTest();\n notify();\n return { ok: true };\n }\n\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n const bodies = [...panels.querySelectorAll(\".wgd-section-body\")].filter(\n (body) => !body.parentElement?.classList.contains(\"wgd-view-only\")\n );\n for (const body of bodies) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n return {\n getAction: getEntry,\n loadAction,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Settings designer: edits a principal's settings record \u2014 account-wide\n * preferences, one titled subsection per section. This version edits\n * `defaultThemes` (the theme light hosts and dark hosts get when a render\n * names none; one choice per mode, so choosing a theme replaces the mode's\n * previous one) and `resourceDomains` (the domains MCP Apps frames may load\n * images from directly), each entry checked live by the core rule the store\n * applies: a valid one is recorded canonical, an invalid one as typed, so\n * the save's refusal names what the person sees. Sections it does not edit\n * pass through untouched, and the host saves (the designer writes nothing).\n */\nimport { RESOURCE_DOMAIN_LIMIT, isPlainObject, parseResourceDomain } from \"@widgentic/core\";\nimport type { ThemeEntry, ThemeMode } from \"@widgentic/core\";\nimport { applyChrome, diagnosticLine, h, injectDesignerStyles, section } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\nimport { clone } from \"./internal.js\";\n\n/** The settings record as the designer sees it: known sections plus any it passes through. */\nexport interface SettingsRecord {\n defaultThemes?: Partial<Record<ThemeMode, string>>;\n /** Canonical origins, plus any entry the person typed that the rule refuses. */\n resourceDomains?: string[];\n [section: string]: unknown;\n}\n\nexport interface SettingsDesignerOptions {\n initialSettings?: SettingsRecord;\n /** The person's themes, offered as choices beside the built-ins. */\n themes?: Pick<ThemeEntry, \"name\" | \"label\">[];\n appearance?: \"auto\" | \"light\" | \"dark\";\n /** Host chrome, as for the other designers. */\n chrome?: ChromeOptions;\n /** Mount with the choices visible but inert. Toggle later via `setReadOnly`. */\n readOnly?: boolean;\n}\n\nexport type SettingsLoadResult = { ok: true } | { ok: false; errors: string[] };\n\nexport interface SettingsDesignerHandle {\n /** The record, built-in choices omitted; unedited sections as supplied. */\n getSettings(): SettingsRecord;\n loadSettings(settings: unknown): SettingsLoadResult;\n /** Replace the themes offered as choices; the record is kept as it is. */\n setThemes(themes: Pick<ThemeEntry, \"name\" | \"label\">[]): void;\n setReadOnly(readOnly: boolean): void;\n subscribe(listener: (settings: SettingsRecord) => void): () => void;\n dispose(): void;\n}\n\nconst MODES: readonly { mode: ThemeMode; label: string; builtIn: string }[] = [\n { mode: \"light\", label: \"Light hosts\", builtIn: \"Built-in light\" },\n { mode: \"dark\", label: \"Dark hosts\", builtIn: \"Built-in dark\" }\n];\n\n/** Shape check for an untrusted record; errors instead of throwing. */\nfunction checkSettings(settings: unknown): string[] {\n if (!isPlainObject(settings)) return [\"Settings must be an object of named sections.\"];\n const errors: string[] = [];\n const domains = settings.resourceDomains;\n if (domains !== undefined && (!Array.isArray(domains) || !domains.every((entry) => typeof entry === \"string\"))) {\n errors.push(\"resourceDomains: must be a list of domain strings.\");\n }\n const themes = settings.defaultThemes;\n if (themes === undefined) return errors;\n if (!isPlainObject(themes)) return [...errors, \"defaultThemes: must be an object of { light?, dark? }.\"];\n for (const [mode, name] of Object.entries(themes)) {\n if (!MODES.some((known) => known.mode === mode)) errors.push(`defaultThemes: '${mode}' is not a theme mode.`);\n else if (typeof name !== \"string\") errors.push(`defaultThemes: the ${mode} default must be a theme name.`);\n }\n return errors;\n}\n\nexport function createSettingsDesigner(\n container: Element,\n options: SettingsDesignerOptions = {}\n): SettingsDesignerHandle {\n injectDesignerStyles(document);\n\n let themes = options.themes ?? [];\n let record: SettingsRecord = options.initialSettings ? clone(options.initialSettings) : {};\n const listeners = new Set<(settings: SettingsRecord) => void>();\n\n const panels = h(\"div\", { class: \"wgd-panels\" });\n const root = h(\"div\", { class: \"wgd-root wgd-settings-designer\" }, [panels]);\n if (options.appearance === \"light\" || options.appearance === \"dark\") {\n root.setAttribute(\"data-wgd-theme\", options.appearance);\n }\n applyChrome(root, options.chrome);\n container.appendChild(root);\n\n function getSettings(): SettingsRecord {\n // The edited section is always present (possibly empty), so a host\n // saving it clears a mode the person set back to the built-in.\n return { ...clone(record), defaultThemes: clone(record.defaultThemes ?? {}) };\n }\n\n function notify(): void {\n for (const listener of [...listeners]) listener(getSettings());\n }\n\n // --- Default themes ----------------------------------------------------\n const selects = new Map<ThemeMode, HTMLSelectElement>();\n\n function fillSelect(select: HTMLSelectElement, mode: ThemeMode, builtIn: string): void {\n const current = record.defaultThemes?.[mode];\n select.replaceChildren(h(\"option\", { value: \"\" }, [builtIn]));\n for (const theme of themes) {\n select.append(h(\"option\", { value: theme.name }, [theme.label ?? theme.name]));\n }\n // A default whose theme the host did not supply stays visible and\n // selected until the person picks another \u2014 never dropped silently.\n if (current !== undefined && !themes.some((theme) => theme.name === current)) {\n select.append(h(\"option\", { value: current, class: \"wgd-unavailable\" }, [`${current} (unavailable)`]));\n }\n select.value = current ?? \"\";\n }\n\n const rows = MODES.map(({ mode, label, builtIn }) => {\n const select = h(\"select\", { class: \"wgd-select wgd-default-theme\", \"data-mode\": mode });\n fillSelect(select, mode, builtIn);\n select.addEventListener(\"change\", () => {\n const next = { ...(record.defaultThemes ?? {}) };\n if (select.value === \"\") delete next[mode];\n else next[mode] = select.value;\n record = { ...record, defaultThemes: next };\n notify();\n });\n selects.set(mode, select);\n return h(\"label\", { class: \"wgd-row\" }, [h(\"span\", { class: \"wgd-field-label\" }, [label]), select]);\n });\n\n const defaultsPanel = section(\"Default themes\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"The theme a render uses when it names none: light hosts get the light default, dark hosts the dark one.\"\n ]),\n ...rows\n ]);\n panels.append(defaultsPanel);\n\n // --- Resource domains --------------------------------------------------\n // The section is in the record once supplied or edited (possibly empty),\n // so a save clears a list the person emptied and never adds one unasked.\n const domainRows = h(\"div\", { class: \"wgd-domains\" });\n const addInput = h(\"input\", {\n type: \"text\",\n class: \"wgd-input wgd-domain-add\",\n placeholder: \"cdn.example.com\",\n spellcheck: \"false\",\n \"aria-label\": \"Add a resource domain\"\n });\n const addButton = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Add domain\" }, [\"+\"]);\n\n /** A typed entry as the record keeps it: canonical when the rule accepts it, else as typed. */\n function recorded(typed: string): { value: string; mark: string; error: boolean } {\n const parsed = parseResourceDomain(typed);\n return \"error\" in parsed\n ? { value: typed.trim(), mark: `Not a resource domain: ${parsed.error}.`, error: true }\n : { value: parsed.origin, mark: parsed.origin, error: false };\n }\n\n function setDomains(next: string[]): void {\n record = { ...record, resourceDomains: next };\n renderDomains();\n notify();\n }\n\n function renderDomains(): void {\n const domains = record.resourceDomains ?? [];\n domainRows.replaceChildren(\n ...domains.map((entry, index) => {\n const input = h(\"input\", { type: \"text\", class: \"wgd-input wgd-domain\", spellcheck: \"false\", \"aria-label\": `Resource domain ${index + 1}` });\n input.value = entry;\n input.addEventListener(\"change\", () => {\n const next = [...domains];\n next[index] = recorded(input.value).value;\n setDomains(next);\n });\n const remove = h(\"button\", { class: \"wgd-icon\", type: \"button\", title: \"Remove domain\" }, [\"\u2715\"]);\n remove.addEventListener(\"click\", () => setDomains(domains.filter((_entry, at) => at !== index)));\n const { mark, error } = recorded(entry);\n return h(\"div\", { class: \"wgd-domain-entry\" }, [\n h(\"div\", { class: \"wgd-row\" }, [input, remove]),\n error ? diagnosticLine(mark) : h(\"span\", { class: \"wgd-field-label wgd-domain-origin\" }, [mark])\n ]);\n })\n );\n const full = domains.length >= RESOURCE_DOMAIN_LIMIT;\n addInput.disabled = full;\n addButton.disabled = full;\n }\n\n function addDomain(): void {\n if (addInput.value.trim() === \"\" || (record.resourceDomains ?? []).length >= RESOURCE_DOMAIN_LIMIT) return;\n const entry = recorded(addInput.value).value;\n addInput.value = \"\";\n setDomains([...(record.resourceDomains ?? []), entry]);\n }\n addButton.addEventListener(\"click\", addDomain);\n addInput.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Enter\") {\n event.preventDefault();\n addDomain();\n }\n });\n\n const domainsPanel = section(\"Resource domains\", [\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Domains your widgets' images may load from directly in chat hosts that honor them, \" +\n \"when the server does not copy an image inline. Enter cdn.example.com or *.example.com, \" +\n `optionally with https:// (no ports, paths or IP addresses), at most ${RESOURCE_DOMAIN_LIMIT}.`\n ]),\n h(\"span\", { class: \"wgd-field-label\" }, [\n \"Any render, including image addresses an agent supplies, may load from these domains in the \" +\n \"viewer's browser, so list only domains you control. A domain that redirects needs its target \" +\n \"listed too, and a chat client keeps the list it read until it reloads.\"\n ]),\n domainRows,\n h(\"div\", { class: \"wgd-row\" }, [addInput, addButton])\n ]);\n panels.append(domainsPanel);\n renderDomains();\n\n function loadSettings(settings: unknown): SettingsLoadResult {\n const errors = checkSettings(settings);\n if (errors.length > 0) return { ok: false, errors };\n record = clone(settings as SettingsRecord);\n for (const { mode, builtIn } of MODES) {\n const select = selects.get(mode);\n if (select !== undefined) fillSelect(select, mode, builtIn);\n }\n renderDomains();\n notify();\n return { ok: true };\n }\n\n /** Same mechanism as the other designers: inert the section bodies. */\n function setReadOnly(readOnly: boolean): void {\n root.classList.toggle(\"wgd-readonly\", readOnly);\n for (const body of panels.querySelectorAll(\".wgd-section-body\")) {\n if (readOnly) body.setAttribute(\"inert\", \"\");\n else body.removeAttribute(\"inert\");\n }\n }\n if (options.readOnly === true) setReadOnly(true);\n\n function setThemes(next: Pick<ThemeEntry, \"name\" | \"label\">[]): void {\n themes = [...next];\n for (const { mode, builtIn } of MODES) {\n const select = selects.get(mode);\n if (select !== undefined) fillSelect(select, mode, builtIn);\n }\n }\n\n return {\n getSettings,\n loadSettings,\n setThemes,\n setReadOnly,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n listeners.clear();\n root.remove();\n }\n };\n}\n", "/**\n * Opt-in custom element wrapping the factory. Registration only ever\n * happens through the explicit call \u2014 importing this module has no\n * custom-element registry side effects, so hosts stay in control.\n */\nimport { createDesigner } from \"./shell.js\";\nimport type { DesignerHandle } from \"./shell.js\";\nimport { createSchemaDesigner } from \"./schema-designer.js\";\nimport type { SchemaDesignerHandle } from \"./schema-designer.js\";\nimport { createThemeDesigner } from \"./theme-designer.js\";\nimport type { ThemeDesignerHandle } from \"./theme-designer.js\";\nimport { createActionDesigner } from \"./action-designer.js\";\nimport type { ActionDesignerHandle } from \"./action-designer.js\";\nimport { createSettingsDesigner } from \"./settings-designer.js\";\nimport type { SettingsDesignerHandle } from \"./settings-designer.js\";\nimport type { ThemeEntry } from \"@widgentic/core\";\nimport { parseChromeAttribute } from \"./dom.js\";\nimport type { ChromeOptions } from \"./dom.js\";\n\n/**\n * The attributes every designer element shares, read once at connect:\n * `appearance` pins the chrome scheme, `chrome` (JSON) hands over the\n * host's chrome tokens. Anything invalid is ignored, never thrown.\n */\nfunction elementOptions(\n element: Element\n): { appearance?: \"light\" | \"dark\"; chrome?: ChromeOptions } {\n const appearance = element.getAttribute(\"appearance\");\n const chrome = parseChromeAttribute(element.getAttribute(\"chrome\"));\n return {\n ...(appearance === \"light\" || appearance === \"dark\" ? { appearance } : {}),\n ...(chrome === undefined ? {} : { chrome })\n };\n}\n\nexport const DEFAULT_TAG = \"widgentic-designer\";\nexport const DEFAULT_THEME_TAG = \"widgentic-theme-designer\";\nexport const DEFAULT_SCHEMA_TAG = \"widgentic-schema-designer\";\nexport const DEFAULT_ACTION_TAG = \"widgentic-action-designer\";\nexport const DEFAULT_SETTINGS_TAG = \"widgentic-settings-designer\";\n\nexport function defineDesignerElement(tagName: string = DEFAULT_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticDesignerElement extends HTMLElement {\n #handle: DesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((draft, diagnostics) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", {\n detail: { draft, diagnostics },\n bubbles: true\n })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n /** The embedding host's programmatic access to the wrapped handle. */\n get designer(): DesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticDesignerElement);\n}\n\n/** Sibling registrar for the standalone theme designer. */\nexport function defineThemeDesignerElement(tagName: string = DEFAULT_THEME_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticThemeDesignerElement extends HTMLElement {\n #handle: ThemeDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createThemeDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { theme: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): ThemeDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticThemeDesignerElement);\n}\n\n/** Sibling registrar for the standalone schema designer. */\nexport function defineSchemaDesignerElement(tagName: string = DEFAULT_SCHEMA_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticSchemaDesignerElement extends HTMLElement {\n #handle: SchemaDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createSchemaDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { schema: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): SchemaDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticSchemaDesignerElement);\n}\n\n/** Sibling registrar for the standalone action designer. */\nexport function defineActionDesignerElement(tagName: string = DEFAULT_ACTION_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticActionDesignerElement extends HTMLElement {\n #handle: ActionDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createActionDesigner(this, elementOptions(this));\n this.#unsubscribe = this.#handle.subscribe((entry) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { action: entry }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): ActionDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticActionDesignerElement);\n}\n\n/**\n * A property set on an element before its class was defined is an own\n * property shadowing the class accessor; at upgrade, move it onto the\n * accessor so the value is not lost.\n */\nexport function upgradeProperty(element: HTMLElement, name: string): void {\n if (!Object.prototype.hasOwnProperty.call(element, name)) return;\n const own = element as unknown as Record<string, unknown>;\n const value = own[name];\n delete own[name];\n own[name] = value;\n}\n\n/** Sibling registrar for the settings designer. */\nexport function defineSettingsDesignerElement(tagName: string = DEFAULT_SETTINGS_TAG): void {\n if (customElements.get(tagName) !== undefined) return;\n\n class WidgenticSettingsDesignerElement extends HTMLElement {\n #handle: SettingsDesignerHandle | undefined;\n #unsubscribe: (() => void) | undefined;\n #themes: Pick<ThemeEntry, \"name\" | \"label\">[] = [];\n\n constructor() {\n super();\n upgradeProperty(this, \"themes\");\n }\n\n /** The themes offered as choices; settable before or after connecting, or before the element is defined. */\n get themes(): Pick<ThemeEntry, \"name\" | \"label\">[] {\n return [...this.#themes];\n }\n\n set themes(themes: Pick<ThemeEntry, \"name\" | \"label\">[]) {\n this.#themes = Array.isArray(themes) ? [...themes] : [];\n this.#handle?.setThemes(this.#themes);\n }\n\n connectedCallback(): void {\n if (this.#handle !== undefined) return;\n this.#handle = createSettingsDesigner(this, { ...elementOptions(this), themes: this.#themes });\n this.#unsubscribe = this.#handle.subscribe((settings) => {\n this.dispatchEvent(\n new CustomEvent(\"widgentic-change\", { detail: { settings }, bubbles: true })\n );\n });\n }\n\n disconnectedCallback(): void {\n this.#unsubscribe?.();\n this.#handle?.dispose();\n this.#handle = undefined;\n this.#unsubscribe = undefined;\n }\n\n get designer(): SettingsDesignerHandle | undefined {\n return this.#handle;\n }\n }\n\n customElements.define(tagName, WidgenticSettingsDesignerElement);\n}\n", "/**\n * Browser bundle entry (`@widgentic/designer/browser`): loading this module\n * from a <script type=\"module\"> registers the designer custom elements, so a\n * page without a bundler can host the designers. Bundler users import the\n * package root instead.\n */\nimport {\n defineActionDesignerElement,\n defineDesignerElement,\n defineSchemaDesignerElement,\n defineSettingsDesignerElement,\n defineThemeDesignerElement\n} from \"./index.js\";\n\ndefineActionDesignerElement();\ndefineDesignerElement();\ndefineSchemaDesignerElement();\ndefineThemeDesignerElement();\ndefineSettingsDesignerElement();\n\nexport {};\n"],
5
+ "mappings": "AAgBA,SAASA,GAAcC,EAAkD,CACvE,OAAO,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,CAC5E,CASO,SAASC,GACdC,EACAC,EAA2B,CAAC,EACZ,CAChB,GAAI,CAACJ,GAAcG,CAAK,EACtB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,GACN,QAAS,iCACX,CACF,EAGF,GAAI,EAAE,SAAUA,GACd,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,gBACN,KAAM,OACN,QAAS,2CACX,CACF,EAGF,IAAME,EAAOF,EAAM,KACnB,GAAI,OAAOE,GAAS,SAClB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,OACN,QAAS,gCACX,CACF,EAEF,GAAIA,EAAK,SAAW,EAClB,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,gBACN,KAAM,OACN,QAAS,0CACX,CACF,EAGF,GAAI,EAAE,SAAUF,GACd,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,gBACN,KAAM,OACN,QAAS,2CACX,CACF,EAGF,GAAI,UAAWA,GAASA,EAAM,QAAU,QAAa,CAACH,GAAcG,EAAM,KAAK,EAC7E,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,QACN,QAAS,+CACX,CACF,EAGF,GAAI,SAAUA,GAASA,EAAM,OAAS,QAAa,CAACH,GAAcG,EAAM,IAAI,EAC1E,MAAO,CACL,GAAI,GACJ,MAAO,CACL,KAAM,eACN,KAAM,OACN,QAAS,8CACX,CACF,EAGF,GAAM,CAAE,WAAAG,CAA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,KAAKA,GAAU,OACf,KAAKC,GAAe,MACtB,CAEA,IAAI,UAA+C,CACjD,OAAO,KAAKD,EACd,CACF,CAEA,eAAe,OAAOF,EAASsB,CAAgC,CACjE,CC9NAK,GAA4B,EAC5BC,GAAsB,EACtBC,GAA4B,EAC5BC,GAA2B,EAC3BC,GAA8B",
6
+ "names": ["isPlainObject", "value", "validateWidgetPayload", "input", "options", "kind", "knownKinds", "ALLOWED_SCHEMES", "cleanUrl", "value", "isSafeUrl", "match", "scheme", "isLinkableUrl", "DATA_IMAGE", "HTTP_URL", "isSafeImageSrc", "cleaned", "IMAGE_EXTENSION", "looksLikeImageUrl", "LABEL", "hostProblem", "host", "wildcard", "labels", "label", "bad", "parseResourceDomain", "input", "trimmed", "lower", "rest", "problem", "el", "tag", "attrs", "children", "key", "node", "LABEL_STYLE_RULE", "BUILTIN_DESCRIPTORS", "NESTED_QUANTIFIER", "compileSafePattern", "pattern", "isPlainObject", "value", "DATA_SCHEMA_TYPES", "matchesSingleType", "type", "data", "matchesType", "candidate", "enumMatches", "allowed", "formatType", "validateDataAgainstSchema", "schema", "path", "regex", "key", "subschema", "error", "i", "auditDataSchema", "warnings", "names", "name", "isPlainObject", "value", "formatValue", "labelFor", "key", "hints", "label", "applyPattern", "pattern", "linkOrText", "raw", "display", "hint", "href", "isLinkableUrl", "el", "HINTABLE_SHAPES", "SHAPES", "resolveImage", "key", "value", "hints", "defaultShape", "hint", "isPlainObject", "isSafeImageSrc", "looksLikeImageUrl", "imageNode", "alt", "src", "shape", "el", "renderCard", "payload", "data", "meta", "fieldFormat", "isPlainObject", "title", "subtitle", "fieldEntries", "value", "key", "formatValue", "children", "el", "fieldValue", "label", "labelFor", "image", "resolveImage", "display", "imageNode", "raw", "pattern", "text", "applyPattern", "linkOrText", "keysFromIds", "items", "keys", "seen", "item", "isPlainObject", "id", "key", "renderTable", "payload", "rows", "fieldFormat", "isPlainObject", "records", "row", "hintColumns", "columns", "column", "seen", "record", "key", "rowKeys", "keysFromIds", "chrome", "title", "subtitle", "parts", "el", "formatValue", "labelFor", "index", "value", "image", "resolveImage", "display", "imageNode", "raw", "pattern", "text", "applyPattern", "linkOrText", "renderTree", "payload", "depthHint", "expandDepth", "roots", "list", "el", "renderList", "title", "formatValue", "nodeLabel", "node", "isPlainObject", "_children", "_icon", "rest", "iconNode", "icon", "image", "resolveImage", "imageNode", "labelChildren", "label", "MAX_TREE_DEPTH", "childrenOf", "nodes", "depth", "keys", "keysFromIds", "index", "renderNode", "key", "childNodes", "isOpen", "GROUP_MAX_ITEMS", "GROUP_LAYOUTS", "GROUP_GAPS", "GROUP_MAX_COLUMNS", "checkGroupEnvelope", "data", "isPlainObject", "items", "checked", "i", "item", "entry", "renderGroupContainer", "hints", "children", "h", "layout", "known", "gap", "classes", "raw", "columns", "el", "stampActionLocation", "node", "location", "raw", "attrs", "descriptor", "children", "child", "DuplicateKindError", "kind", "createCatalog", "renderers", "descriptors", "catalog", "renderer", "payload", "options", "validated", "validateWidgetPayload", "schema", "schemaError", "validateDataAgainstSchema", "envelope", "checkGroupEnvelope", "i", "item", "sub", "subPath", "renderGroupContainer", "thrown", "renderCard", "BUILTIN_DESCRIPTORS", "renderTable", "renderTree", "result", "isPlainObject", "value", "isNewline", "char", "scan", "text", "out", "depth", "quote", "isBracket", "isBalanced", "open", "i", "splitTopLevel", "separator", "pieces", "current", "quoted", "piece", "topLevelText", "indexOfTopLevel", "test", "pseudoArguments", "names", "chars", "args", "entry", "before", "name", "end", "closer", "UNSAFE", "PROPERTY_NAME", "isStyleMap", "value", "isPlainObject", "declarations", "v", "UNSAFE_FUNCTIONS", "COMMENT", "callsUnsafeFunction", "text", "call", "FORWARDING_PSEUDOS", "COMBINATOR", "char", "isConstrainedList", "selector", "depth", "parts", "splitTopLevel", "part", "isConstrainedPart", "MAX_FORWARDING_DEPTH", "compound", "topLevelText", "pseudoArguments", "argument", "isSafeSelector", "isBalanced", "isSafeValue", "scopePart", "scope", "found", "indexOfTopLevel", "end", "widgetStylesToCss", "styles", "guardedStylesToCss", "rules", "lines", "property", "scoped", "SAFE_IDENTIFIER", "STYLE_RULES", "UNSAFE", "UNSAFE_FUNCTIONS", "PROPERTY_NAME", "FORMAT_TYPES", "LIST_FORMAT_TYPES", "isFormatType", "value", "type", "FORMAT_DECIMALS_MIN", "FORMAT_DECIMALS_MAX", "CURRENCY_DISPLAYS", "isCurrencyDisplay", "display", "CURRENCY_CODE", "DATE_TOKENS", "DATE_PATTERN_SEPARATORS", "DATE_PATTERN_MAX", "DATE_PATTERN_ALLOWED", "EPOCH_SECONDS_BELOW", "LOCALE_TAG", "DEFAULT_FORMAT_LOCALE", "JOIN_SEPARATOR_MAX", "JOIN_DEFAULT_SEPARATOR", "TRUNCATE_LENGTH_MIN", "TRUNCATE_LENGTH_MAX", "TRUNCATE_ELLIPSIS_MAX", "TRUNCATE_DEFAULT_ELLIPSIS", "PLURAL_CATEGORIES", "isPluralCategory", "category", "PLURAL_FORM_MAX", "PLURAL_COUNT_PLACEHOLDER", "isPlainDottedPath", "segment", "tokenizeDatePattern", "pattern", "parts", "literal", "tokens", "outer", "token", "char", "isKnownLocale", "tag", "toFiniteNumber", "trimmed", "parsed", "toEpochMillis", "iso", "date", "time", "fraction", "zone", "millis", "clock", "pad", "width", "formatDate", "at", "field", "part", "UNICODE_SPACES", "plain", "formatValue", "parseFormatSpec", "spec", "isPlainObject", "locale", "withLocale", "bounded", "ellipsis", "forms", "form", "other", "decimals", "common", "buildFormatter", "joinFormatter", "truncateFormatter", "grouped", "groupedNumber", "pluralizeFormatter", "digits", "intl", "numeric", "itemText", "item", "segments", "current", "index", "separator", "texts", "text", "points", "rules", "count", "compiled", "compileFormat", "cached", "formatter", "formatBoundValue", "TOKEN_SPECS", "TOKEN_DEFAULTS", "name", "spec", "THEME_TOKENS", "TOKEN_VALUE_UNSAFE", "isSafeTokenValue", "value", "isBalanced", "UNSAFE_FUNCTIONS", "call", "TOKEN_VALUE_RULE", "v", "token", "TOKEN_DEFAULTS", "tokenDefaultsBlock", "THEME_TOKENS", "ICON_BOX", "baseStylesheet", "STYLE_MARKER", "injectBaseStyles", "doc", "style", "isPlainObject", "value", "KNOWN_TOKENS", "THEME_TOKENS", "CUSTOM_VARIABLE", "customKeys", "theme", "key", "propertyName", "validateTheme", "input", "token", "isSafeTokenValue", "withFallbacks", "source", "filled", "fallback", "TOKEN_SPECS", "inherited", "applyTheme", "container", "style", "i", "property", "keys", "darkTheme", "DuplicateThemeError", "name", "InvalidThemeEntryError", "code", "message", "copyStyles", "styles", "copy", "selector", "declarations", "createThemeRegistry", "entries", "defaultNames", "registry", "entry", "validated", "validateTheme", "isStyleMap", "stored", "mode", "darkTheme", "themeStylesToCss", "styles", "scope", "guardedStylesToCss", "FORBIDDEN_ATTR", "FORBIDDEN_TAGS", "RESERVED_ATTR", "URL_ATTRS", "MAX_TEMPLATE_DEPTH", "RESERVED", "parsePath", "value", "tokens", "i", "base", "up", "rest", "segment", "SECRET_NAME", "ACTION_NAME", "OUTPUT_MODES", "HTTP_METHODS", "join", "path", "segment", "fail", "message", "HEADER_TOKEN", "RESERVED_HEADERS", "FORBIDDEN_SEGMENTS", "isDataPath", "value", "checkHeaderValue", "isPlainObject", "SECRET_NAME", "containsSecretRef", "checkUrl", "url", "parsed", "validateActionDefinition", "input", "options", "literal", "HTTP_METHODS", "m", "urlError", "field", "map", "name", "namePath", "error", "definitionOf", "binding", "validateActionBinding", "definitionError", "definition", "declared", "fieldPath", "outPath", "mode", "target", "OUTPUT_MODES", "entries", "key", "entryPath", "validateLoadBinding", "join", "path", "segment", "nodeError", "message", "checkFormat", "spec", "label", "bad", "isPlainObject", "isFormatType", "FORMAT_TYPES", "DATE_PATTERN_MAX", "DATE_PATTERN_ALLOWED", "tokenizeDatePattern", "DATE_TOKENS", "field", "value", "JOIN_SEPARATOR_MAX", "isPlainDottedPath", "TRUNCATE_LENGTH_MIN", "TRUNCATE_LENGTH_MAX", "TRUNCATE_ELLIPSIS_MAX", "category", "form", "isPluralCategory", "PLURAL_CATEGORIES", "PLURAL_FORM_MAX", "FORMAT_DECIMALS_MIN", "FORMAT_DECIMALS_MAX", "LOCALE_TAG", "isKnownLocale", "CURRENCY_CODE", "isCurrencyDisplay", "CURRENCY_DISPLAYS", "parseFormatSpec", "TRANSFORM_KEYS", "activeTransform", "present", "key", "checkPathSyntax", "parsePath", "check", "node", "depth", "MAX_TEMPLATE_DEPTH", "pathError", "entry", "keyError", "templateError", "FORBIDDEN_TAGS", "name", "attrPath", "FORBIDDEN_ATTR", "RESERVED_ATTR", "transform", "hasMap", "hasPrefix", "hasFormat", "formatError", "actionError", "validateActionBinding", "i", "childError", "validateTemplate", "input", "error", "eachBinding", "template", "load", "onBinding", "visit", "node", "isPlainObject", "key", "child", "collectActionRefs", "refs", "binding", "MARKDOWN_SOURCE_MAX", "BULLET", "ORDERED", "FENCE", "blocksOf", "text", "blocks", "current", "lines", "index", "line", "fence", "closing", "literal", "bullet", "ordered", "kind", "content", "ESCAPABLE", "isWhitespace", "char", "isPunctuation", "nodesOf", "entries", "out", "entry", "piece", "last", "tickRuns", "runs", "i", "end", "list", "cursors", "length", "from", "cursor", "LINK_LABEL_MAX", "LINK_URL_MAX", "linkAt", "start", "depth", "labelEnd", "urlEnd", "close", "parens", "url", "inline", "links", "stack", "openers", "pushText", "value", "pushNode", "node", "closingTicks", "code", "image", "link", "label", "href", "isSafeUrl", "anchor", "delim", "before", "after", "left", "right", "canOpen", "canClose", "remaining", "mine", "opener", "use", "inner", "theirs", "children", "element", "spend", "budget", "child", "kept", "copy", "tag", "attrs", "parseMarkdown", "source", "MARKDOWN_SOURCE_MAX", "block", "items", "root", "join", "path", "segment", "resolvePath", "frames", "meta", "parsed", "parsePath", "current", "depth", "frame", "index", "isPlainObject", "keyOf", "value", "DEFAULT_MAX_NODES", "buildDescriptor", "binding", "id", "ctx", "definition", "unresolved", "text", "segments", "formatValue", "prompt", "args", "field", "resolved", "descriptor", "interpretNode", "node", "budget", "tpath", "parseMarkdown", "key", "hit", "formatBoundValue", "items", "out", "itemPath", "keyPath", "i", "rendered", "only", "truthy", "branch", "FORBIDDEN_TAGS", "attrs", "name", "raw", "FORBIDDEN_ATTR", "RESERVED_ATTR", "lower", "URL_ATTRS", "imageContext", "isSafeUrl", "isSafeImageSrc", "children", "child", "element", "compileTemplate", "template", "options", "maxNodes", "DEFAULT_MAX_NODES", "ctx", "payload", "budget", "frames", "nodes", "interpretNode", "only", "attrs", "buildDom", "node", "doc", "element", "name", "value", "child", "patchNode", "prev", "next", "dom", "patchElement", "doc", "replacement", "buildDom", "element", "prevAttrs", "nextAttrs", "name", "value", "patchChildren", "keyIndex", "list", "index", "i", "node", "patchKeyed", "prevIndex", "domChildren", "kept", "placed", "child", "prevChild", "at", "elements", "shared", "nextChild", "childDom", "extra", "surplus", "mountWidget", "payload", "container", "options", "catalog", "createCatalog", "current", "root", "disposed", "mountedPayload", "onAction", "parseDescriptor", "el", "parsed", "activation", "event", "key", "descriptor", "update", "nextPayload", "rendered", "built", "buildDom", "patchNode", "dispose", "CHROME_TOKENS", "TYPOGRAPHY", "CHROME_DEFAULTS", "declarations", "scheme", "prefix", "indent", "token", "chromeCss", "palette", "options", "selector", "darkMediaSelector", "blocks", "requireChild", "parent", "selector", "found", "h", "tag", "attrs", "children", "element", "name", "value", "child", "textField", "label", "onInput", "input", "textArea", "rows", "area", "section", "title", "open", "select", "options", "className", "onChange", "el", "option", "fitSelect", "fit", "menuButton", "onPick", "wrap", "toggle", "menu", "close", "onOutside", "onKey", "event", "item", "diagnosticLine", "text", "CHROME_TOKEN_SET", "CHROME_TOKENS", "CSS_WIDE_KEYWORD", "applyChrome", "root", "chrome", "token", "parseChromeAttribute", "parsed", "STYLE_MARKER", "injectDesignerStyles", "doc", "style", "chromeCss", "CHROME_DEFAULTS", "tabs", "entries", "buttons", "entry", "index", "button", "other", "i", "clone", "value", "errorMessage", "error", "effectiveDataSchema", "draft", "schemas", "ref", "entry", "inline", "isPlainObject", "BASE_KINDS", "createCatalog", "kindProblem", "kind", "SAFE_IDENTIFIER", "auditStyles", "styles", "issues", "selector", "declarations", "widgetStylesToCss", "STYLE_RULES", "property", "value", "PROPERTY_NAME", "deriveDiagnostics", "options", "diagnostics", "problem", "dataShape", "inlineSchema", "warnings", "auditDataSchema", "template", "validateTemplate", "issue", "path", "schema", "error", "validateDataAgainstSchema", "validateLoadBinding", "parsePath", "known", "action", "unknown", "collectActionRefs", "theme", "validateTheme", "JSON_TOKENS", "tokenizeJson", "text", "out", "last", "match", "paint", "layer", "nodes", "token", "span", "attachJsonHighlight", "textarea", "parent", "wrap", "sync", "syncScroll", "onTab", "event", "selectionStart", "selectionEnd", "value", "repaintHighlight", "checkDefinition", "definition", "currentKind", "errors", "isPlainObject", "problem", "kindProblem", "template", "validateTemplate", "dataSchema", "dataSchemaRef", "SAFE_IDENTIFIER", "validateLoadBinding", "value", "parsePath", "exportWidgetJson", "draft", "importWidgetJson", "text", "currentKind", "parsed", "error", "errorMessage", "errors", "checkDefinition", "applyDefinition", "store", "definition", "theme", "themeStyles", "previewTheme", "camelCase", "kind", "part", "i", "toTypeScriptModule", "draft", "mountIoPanel", "output", "h", "button", "label", "produce", "el", "repaintHighlight", "importError", "diagnosticLine", "importField", "textArea", "importArea", "requireChild", "attachJsonHighlight", "importButton", "result", "importSection", "section", "exportSection", "exportWidgetJson", "element", "TYPE_OPTIONS", "typeOf", "value", "defaultFor", "type", "previous", "parsed", "setAt", "root", "path", "remove", "step", "rest", "copy", "renameKey", "from", "to", "holder", "node", "entries", "k", "v", "createJsonTreeEditor", "initial", "onChange", "current", "element", "h", "commit", "next", "render", "commitText", "text", "typeSelect", "select", "option", "valueControl", "box", "input", "entryRow", "keyLabel", "removable", "row", "wrap", "renderContainer", "body", "item", "index", "add", "key", "keyInput", "name", "i", "TYPES", "ENUM_TYPES", "createSchemaBuilder", "initial", "onChange", "current", "element", "h", "commit", "next", "rerender", "render", "withKey", "node", "key", "value", "copy", "renderNode", "apply", "depth", "lead", "trail", "rows", "typeSelect", "t", "rawType", "typeList", "nullable", "currentType", "type", "fitSelect", "nullBox", "typeValue", "selected", "allowNull", "constraints", "pattern", "enumError", "diagnosticLine", "enumInput", "parsed", "error", "errorMessage", "properties", "isPlainObject", "required", "k", "cards", "name", "sub", "nameInput", "entries", "v", "nextRequired", "requiredBox", "removeProp", "_gone", "rest", "nextSub", "addProp", "i", "nextItems", "start", "clear", "schema", "createRecordEditor", "initial", "placeholders", "onChange", "current", "element", "h", "commit", "next", "render", "changeInput", "value", "placeholder", "className", "onCommit", "input", "record", "rows", "key", "keyInput", "entries", "k", "v", "valueInput", "remove", "_gone", "rest", "add", "i", "firstType", "schema", "type", "primary", "t", "seedFor", "seed", "isPlainObject", "key", "createSchemaForm", "initial", "onChange", "current", "element", "h", "setAt", "root", "path", "value", "remove", "step", "rest", "copy", "holder", "commit", "rerender", "render", "control", "node", "label", "select", "option", "field", "box", "input", "parsed", "body", "properties", "required", "name", "sub", "isRequired", "itemsSchema", "items", "item", "index", "row", "add", "controlEl", "createStylesEditor", "initial", "onChange", "current", "element", "h", "commit", "next", "render", "changeInput", "value", "placeholder", "className", "onCommit", "input", "renderSelector", "selector", "declarations", "styles", "rename", "entries", "k", "v", "addDecl", "removeSelector", "_gone", "rest", "declRows", "property", "propInput", "valueInput", "removeDecl", "addSelector", "name", "i", "isPlainObject", "createStylesPanel", "initial", "onChange", "tree", "createStylesEditor", "styles", "showJson", "parseError", "diagnosticLine", "field", "textArea", "text", "value", "isStyleMap", "next", "error", "errorMessage", "area", "requireChild", "attachJsonHighlight", "repaintHighlight", "issues", "h", "section", "tabs", "list", "issue", "MAX_SCHEMA_DEPTH", "schemaType", "schema", "isPlainObject", "type", "primary", "t", "collectPaths", "prefix", "out", "depth", "name", "sub", "path", "itemSchema", "schemaAt", "current", "segment", "typesConflict", "a", "b", "norm", "schemaMismatch", "source", "target", "sourceType", "targetType", "allPaths", "entries", "entry", "CUSTOM_PATH", "starterPromptDefinition", "starterHttpDefinition", "isRefBinding", "binding", "textInput", "value", "className", "onCommit", "placeholder", "el", "h", "label", "text", "removeButton", "onClick", "button", "pathSelect", "options", "sel", "known", "listed", "option", "fitSelect", "custom", "headerMapEditor", "initial", "secretNames", "labels", "onChange", "current", "clone", "pending", "element", "duplicate", "diagnosticLine", "commit", "next", "render", "flagDuplicate", "name", "valueControl", "onValue", "isSecret", "isPlainObject", "mode", "select", "names", "picker", "n", "nameInput", "entries", "k", "v", "controls", "remove", "_gone", "rest", "row", "index", "add", "segmentsEditor", "segment", "isBind", "copy", "_", "i", "addText", "addBind", "createDefinitionEditor", "ctx", "headEl", "schemasEl", "mapsEl", "http", "rerender", "renderSchemas", "schemaSection", "title", "which", "builder", "createSchemaBuilder", "schema", "parts", "shared", "copyFrom", "s", "entry", "renderHead", "kind", "method", "HTTP_METHODS", "m", "url", "renderMaps", "headers", "_h", "query", "_q", "definition", "createBindingEditor", "inputEl", "outputEl", "definitionOf", "a", "inputOf", "outputOf", "renderInput", "renderOutput", "withMapping", "input", "output", "helperPaths", "allPaths", "p", "modeSelect", "ref", "refSelect", "editor", "properties", "scopePaths", "pathOptions", "mapping", "rows", "field", "isConst", "kindSelect", "nextMapping", "literal", "valueInput", "modeSel", "OUTPUT_MODES", "nextOutput", "outputRow", "outputMapEditor", "map", "onMap", "container", "widgetSchema", "base", "targetSide", "schemaAt", "targetRoot", "itemSchema", "targetOptions", "selectedSchema", "perItemResponse", "schemaType", "sourceRoot", "selectOptions", "mismatch", "commitMap", "flag", "targetControl", "target", "onTarget", "control", "problems", "mapped", "key", "sourceOptions", "source", "conflict", "schemaMismatch", "targetInput", "sourceInput", "bindUse", "format", "isPlainObject", "LIST_FORMAT_TYPES", "type", "pathOptions", "scope", "use", "schemaType", "entries", "collectPaths", "scalars", "paths", "schema", "entry", "itemScope", "eachPath", "target", "schemaAt", "itemSchema", "REMOVE", "pathString", "path", "out", "step", "segment", "setNode", "node", "next", "rest", "children", "_removed", "remaining", "swapChildren", "root", "parent", "a", "b", "holder", "getNode", "x", "y", "swapped", "current", "NODE_PRESETS", "mountTemplatePanel", "store", "refreshers", "options", "actionContext", "unknownRefs", "treeHost", "h", "jsonError", "diagnosticLine", "jsonArea", "jsonWrap", "attachJsonHighlight", "treeTab", "jsonTab", "templateDiag", "element", "commit", "draft", "commitAt", "parsed", "error", "errorMessage", "changeInput", "value", "onCommit", "className", "input", "formatEditor", "spec", "active", "isFormatType", "typeSelect", "select", "FORMAT_TYPES", "JOIN_DEFAULT_SEPARATOR", "PLURAL_COUNT_PLACEHOLDER", "specInput", "field", "placeholder", "title", "_gone", "JOIN_SEPARATOR_MAX", "length", "TRUNCATE_LENGTH_MIN", "TRUNCATE_LENGTH_MAX", "TRUNCATE_DEFAULT_ELLIPSIS", "TRUNCATE_ELLIPSIS_MAX", "forms", "formInput", "category", "nextForms", "decimalsInput", "FORMAT_DECIMALS_MIN", "FORMAT_DECIMALS_MAX", "code", "display", "CURRENCY_DISPLAYS", "isCurrencyDisplay", "pattern", "DATE_TOKENS", "collapsedPaths", "nodeShell", "badge", "inline", "body", "errorText", "removable", "moves", "extras", "key", "collapsible", "isCollapsed", "chevron", "renderTree", "header", "icons", "up", "down", "remove", "TAG_OPTIONS", "pathControl", "known", "option", "fitSelect", "custom", "marker", "keyControl", "tagControl", "tag", "slotEditor", "label", "parentPath", "slot", "required", "errorPath", "slotPath", "menu", "menuButton", "name", "preset", "renderNode", "here", "errorHere", "currentError", "bind", "markdown", "transform", "activeTransform", "bindFormat", "bindMap", "withBind", "extra", "off", "addMarkdown", "addMap", "mapEditor", "createRecordEditor", "nextMap", "defaultInput", "each", "_each", "_key", "attrs", "binding", "attrRows", "bound", "isBind", "bindValue", "rebuild", "fields", "setAttr", "nextValue", "nameInput", "nextName", "k", "v", "mode", "literalInput", "valueInput", "removeAttr", "row", "attrFormat", "showFormat", "showPrefix", "showAddMap", "prefixInput", "attrRow", "parts", "childNodes", "addMenu", "choice", "first", "scopePaths", "bindingEditor", "createBindingEditor", "effectiveDataSchema", "actionParts", "ref", "child", "index", "summaryParts", "lastDraft", "lastErrorPath", "refresh", "diagnostics", "action", "collectActionRefs", "templateMessage", "repaintHighlight", "mountThemePanel", "store", "refreshers", "themes", "themeDiag", "diagnosticLine", "themeSelect", "h", "entry", "showChoice", "draft", "candidate", "_theme", "_styles", "_name", "rest", "tokenList", "renderTokenReference", "theme", "name", "spec", "TOKEN_SPECS", "value", "row", "rows", "element", "section", "message", "jsonField", "label", "read", "write", "clear", "store", "refreshers", "rows", "parseError", "diagnosticLine", "initial", "field", "textArea", "text", "draft", "value", "error", "errorMessage", "area", "requireChild", "attachJsonHighlight", "repaintHighlight", "h", "mountPanels", "columns", "themes", "schemas", "actionContext", "disposers", "bindText", "textField", "input", "kindDiag", "hintsEditor", "createRecordEditor", "hints", "d", "_h", "rest", "dataShapeDiag", "generalPanel", "section", "v", "tabs", "isPlainObject", "k", "doc", "_hints", "schemaBuilder", "createSchemaBuilder", "schema", "_s", "inlineEditors", "modeSelect", "sharedOption", "refSelect", "entry", "sharedView", "schemaRefDiag", "schemaAuditDiag", "sharedWrap", "name", "resolved", "effectiveDataSchema", "_r", "refreshSchemaMode", "ref", "shared", "schemaPanel", "adaptiveDataEditor", "hostEl", "schemaKey", "editor", "rebuild", "key", "onChange", "createSchemaForm", "createJsonTreeEditor", "exampleDiag", "samplePanel", "_e", "sampleDiag", "previewDataPanel", "stylesPanel", "createStylesPanel", "styles", "templatePanel", "mountTemplatePanel", "themePanel", "mountThemePanel", "loadDiag", "loadEditor", "createBindingEditor", "binding", "_l", "loadPanel", "ioPanel", "mountIoPanel", "applyDiagnostics", "diagnostics", "deriveDiagnostics", "refresh", "off", "dispose", "PREVIEW_KIND", "previewCount", "previewSalt", "createPreview", "options", "injectBaseStyles", "banner", "h", "themeStyles", "kindStyles", "scope", "mountRoot", "scoped", "styles", "themeStylesToCss", "pane", "catalog", "createCatalog", "renderer", "payload", "customStyles", "widget", "validated", "validateTemplate", "compiled", "compileTemplate", "descriptor", "isPlainObject", "kinds", "kind", "mount", "update", "draft", "diagnostics", "previewKind", "renderingDraft", "issue", "shared", "ref", "action", "applyTheme", "sampleFor", "mountWidget", "bound", "cloneDraft", "draft", "starterDraft", "createDraftStore", "initial", "current", "history", "listeners", "notify", "listener", "updater", "previous", "createDesigner", "container", "options", "injectDesignerStyles", "base", "cloneDraft", "starterDraft", "preselected", "entry", "initial", "store", "createDraftStore", "listeners", "preview", "createPreview", "leftColumn", "h", "rightSections", "rightColumn", "root", "applyChrome", "actionContext", "panels", "mountPanels", "diagnose", "draft", "deriveDiagnostics", "refresh", "diagnostics", "listener", "unsubscribe", "setReadOnly", "readOnly", "bodies", "body", "definition", "errors", "checkDefinition", "applyDefinition", "kind", "template", "descriptor", "load", "theme", "validated", "validateTheme", "_previous", "rest", "chosen", "starterEntry", "checkSchemaEntry", "entry", "errors", "isPlainObject", "SAFE_IDENTIFIER", "createSchemaDesigner", "container", "options", "injectDesignerStyles", "listeners", "panels", "h", "root", "applyChrome", "getEntry", "schemaDiag", "diagnosticLine", "showSchemaWarnings", "warnings", "auditDataSchema", "notify", "listener", "identityRefreshers", "nameDiag", "identityField", "label", "read", "write", "field", "textField", "input", "requireChild", "identity", "section", "value", "bad", "builder", "createSchemaBuilder", "schema", "syncJson", "jsonError", "jsonArea", "jsonWrap", "parsed", "error", "errorMessage", "repaintHighlight", "builderTab", "jsonTab", "definition", "importError", "importArea", "importButton", "result", "loadSchema", "importSection", "output", "exportButton", "exportSection", "attachJsonHighlight", "refresh", "setReadOnly", "readOnly", "bodies", "body", "BASE_KINDS", "createCatalog", "HEX", "CUSTOM_NAME", "toHexInput", "value", "r", "g", "b", "starterEntry", "BUILT_IN_THEMES", "createThemeRegistry", "nameProblem", "name", "SAFE_IDENTIFIER", "takeEntry", "input", "_retired", "entry", "checkThemeEntry", "currentName", "errors", "candidate", "problem", "validated", "validateTheme", "isStyleMap", "createThemeDesigner", "container", "options", "injectDesignerStyles", "listeners", "preview", "createPreview", "previewKinds", "previewKind", "panels", "h", "side", "root", "applyChrome", "previewDraft", "draft", "starterDraft", "refresh", "listener", "getEntry", "setToken", "key", "tokens", "identityRefreshers", "identityField", "label", "read", "write", "field", "textField", "requireChild", "nameDiag", "diagnosticLine", "showNameProblem", "identity", "section", "kindSelect", "kind", "tokenRefreshers", "tokenRows", "token", "THEME_TOKENS", "TOKEN_DEFAULTS", "issue", "swatch", "TOKEN_SPECS", "paint", "effective", "hex", "isSafeTokenValue", "unsafe", "TOKEN_VALUE_RULE", "tokenPanel", "customHost", "customError", "customEntries", "renderCustom", "rows", "nameInput", "next", "valueInput", "remove", "add", "i", "customPanel", "output", "exportButton", "importArea", "importError", "importButton", "parsed", "error", "errorMessage", "result", "loadTheme", "importPanel", "exportPanel", "stylesPanel", "createStylesPanel", "styles", "_previous", "rest", "auditStyles", "refreshIdentity", "refreshToken", "setReadOnly", "readOnly", "bodies", "body", "starterEntry", "checkActionEntry", "entry", "errors", "isPlainObject", "ACTION_NAME", "field", "problem", "validateActionDefinition", "normalizeEntry", "input", "clone", "withText", "current", "value", "_gone", "rest", "createActionDesigner", "container", "options", "injectDesignerStyles", "testCall", "listeners", "panels", "h", "root", "applyChrome", "getEntry", "notify", "listener", "identityRefreshers", "nameDiag", "diagnosticLine", "identityField", "label", "read", "write", "textField", "inputEl", "requireChild", "identity", "section", "bad", "definitionDiag", "editor", "createDefinitionEditor", "definition", "syncJson", "refreshDefinitionDiag", "refreshTest", "jsonError", "jsonArea", "jsonWrap", "parsed", "error", "errorMessage", "repaintHighlight", "builderTab", "jsonTab", "testHost", "testSection", "testArgs", "testInputJson", "definitionNow", "inputJson", "form", "createSchemaForm", "output", "run", "result", "importError", "importArea", "importButton", "loadAction", "importSection", "exportButton", "exportSection", "attachJsonHighlight", "refresh", "setReadOnly", "readOnly", "bodies", "body", "MODES", "checkSettings", "settings", "isPlainObject", "errors", "domains", "entry", "themes", "mode", "name", "known", "createSettingsDesigner", "container", "options", "injectDesignerStyles", "record", "clone", "listeners", "panels", "h", "root", "applyChrome", "getSettings", "notify", "listener", "selects", "fillSelect", "select", "builtIn", "current", "theme", "rows", "label", "next", "defaultsPanel", "section", "domainRows", "addInput", "addButton", "recorded", "typed", "parsed", "parseResourceDomain", "setDomains", "renderDomains", "index", "input", "remove", "_entry", "at", "mark", "error", "diagnosticLine", "full", "addDomain", "event", "domainsPanel", "loadSettings", "setReadOnly", "readOnly", "body", "setThemes", "elementOptions", "element", "appearance", "chrome", "parseChromeAttribute", "DEFAULT_TAG", "DEFAULT_THEME_TAG", "DEFAULT_SCHEMA_TAG", "DEFAULT_ACTION_TAG", "DEFAULT_SETTINGS_TAG", "defineDesignerElement", "tagName", "WidgenticDesignerElement", "#handle", "#unsubscribe", "createDesigner", "draft", "diagnostics", "defineThemeDesignerElement", "WidgenticThemeDesignerElement", "createThemeDesigner", "entry", "defineSchemaDesignerElement", "WidgenticSchemaDesignerElement", "createSchemaDesigner", "defineActionDesignerElement", "WidgenticActionDesignerElement", "createActionDesigner", "upgradeProperty", "name", "own", "value", "defineSettingsDesignerElement", "WidgenticSettingsDesignerElement", "#themes", "themes", "createSettingsDesigner", "settings", "defineActionDesignerElement", "defineDesignerElement", "defineSchemaDesignerElement", "defineThemeDesignerElement", "defineSettingsDesignerElement"]
7
7
  }