@matterfact/embed 0.2.2 → 0.3.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.
Files changed (40) hide show
  1. package/README.md +28 -0
  2. package/dist/{chunk-6VW4CCNF.js → chunk-33LPVL2R.js} +2 -2
  3. package/dist/{chunk-VMYCQB4O.js → chunk-CHPADW72.js} +45 -10
  4. package/dist/chunk-CHPADW72.js.map +1 -0
  5. package/dist/chunk-F7DLOR7F.js +2 -0
  6. package/dist/chunk-F7DLOR7F.js.map +7 -0
  7. package/dist/chunk-FBIJZJGL.js +2 -0
  8. package/dist/{chunk-6N5OYQLF.js → chunk-SQJX27LT.js} +45 -8
  9. package/dist/chunk-SQJX27LT.js.map +1 -0
  10. package/dist/context-BFNFFHC2.js +3 -0
  11. package/dist/{context-23EUTK33.js.map → context-BFNFFHC2.js.map} +1 -1
  12. package/dist/{context-CWMQYYFI.js → context-MORDASRH.js} +6 -2
  13. package/dist/embed.js +1 -1
  14. package/dist/embed.js.map +2 -2
  15. package/dist/index.cjs +41 -4
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +11 -1
  18. package/dist/index.d.ts +11 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/react.cjs +68 -6
  22. package/dist/react.cjs.map +1 -1
  23. package/dist/react.d.cts +20 -1
  24. package/dist/react.d.ts +20 -1
  25. package/dist/react.js +26 -2
  26. package/dist/react.js.map +1 -1
  27. package/dist/{snapshot-Z7YUSB27.js → snapshot-IWVXLE4G.js} +2 -2
  28. package/dist/{snapshot-KN2KJ2PM.js → snapshot-QBV7DTJP.js} +3 -3
  29. package/dist/{snapshot-KN2KJ2PM.js.map → snapshot-QBV7DTJP.js.map} +1 -1
  30. package/package.json +2 -2
  31. package/dist/chunk-6N5OYQLF.js.map +0 -1
  32. package/dist/chunk-MWRVWYWX.js +0 -2
  33. package/dist/chunk-MWRVWYWX.js.map +0 -7
  34. package/dist/chunk-U4IRZU6E.js +0 -2
  35. package/dist/chunk-VMYCQB4O.js.map +0 -1
  36. package/dist/context-23EUTK33.js +0 -3
  37. /package/dist/{chunk-6VW4CCNF.js.map → chunk-33LPVL2R.js.map} +0 -0
  38. /package/dist/{chunk-U4IRZU6E.js.map → chunk-FBIJZJGL.js.map} +0 -0
  39. /package/dist/{context-CWMQYYFI.js.map → context-MORDASRH.js.map} +0 -0
  40. /package/dist/{snapshot-Z7YUSB27.js.map → snapshot-IWVXLE4G.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dom/a11y.ts","../src/dom/refs.ts","../src/dom/snapshot.ts","../src/context.ts","../src/protocol.ts","../src/loader.ts"],"names":["isDisabled","getRole","computeAccessibleName","isInaccessible","snapshot","snapshotRegion","resolveRef"],"mappings":";;;;;;;;;;;;;AAkCO,SAAS,gBAAA,GAA4B;AAC1C,EAAA,MAAM,KAAA,uBAAY,OAAA,EAAsC;AACxD,EAAA,QAAQ,CAAC,IAAa,MAAA,KAAgD;AAEpE,IAAA,IAAI,MAAA,EAAQ,OAAO,MAAA,CAAO,gBAAA,CAAiB,IAAI,MAAM,CAAA;AACrD,IAAA,IAAI,KAAA,GAAQ,KAAA,CAAM,GAAA,CAAI,EAAE,CAAA;AACxB,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,KAAA,GAAQ,MAAA,CAAO,iBAAiB,EAAE,CAAA;AAClC,MAAA,KAAA,CAAM,GAAA,CAAI,IAAI,KAAK,CAAA;AAAA,IACrB;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AACF;AAYO,SAAS,SAAA,GAAqB;AACnC,EAAA,OAAO,QAAA,CAAS,eAAA,CAAgB,cAAA,EAAe,CAAE,MAAA,GAAS,CAAA;AAC5D;AAWO,SAAS,SAAA,CACd,EAAA,EACA,KAAA,EACA,MAAA,EACS;AACT,EAAA,MAAM,UAAU,KAAA,CAAM,OAAA;AACtB,EAAA,IAAI,OAAA,KAAY,QA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,EAAc,MAAM,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA;AAAA,MAC3D;AACA,MAAA,OAAO,CAAA;AAAA,IACT,CAAC,CAAA,CAAA;AACD,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA,EAYQ,KAAA,GAAQ;AACd,IAAA,MAAM,UAAU,IAAA,CAAK,KAAA;AACrB,IAAA,IAAA,CAAK,QAAQ,EAAC;AACd,IAAA,KAAA,MAAW,CAAA,IAAK,OAAA,EAAS,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA,EAKA,OAAA,GAAU;AACR,IAAA,MAAA,CAAO,mBAAA,CAAoB,SAAA,EAAW,IAAA,CAAK,SAAS,CAAA;AACpD,IAAA,IAAA,CAAK,QAAQ,MAAA,EAAO;AACpB,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AACF;AAOO,SAAS,MAAM,MAAA,EAAiC;AACrD,EAAA,MAAM,IAAA,GAAO,IAAI,SAAA,CAAU,MAAM,CAAA;AACjC,EAAA,IAAA,CAAK,KAAA,EAAM;AACX,EAAA,OAAO,IAAA;AACT","file":"index.cjs","sourcesContent":["import {\n computeAccessibleName,\n getRole,\n isDisabled,\n} from 'dom-accessibility-api';\n\n/**\n * Role, name, visibility, interactability, state.\n *\n * WHAT WE ADOPTED: role and accessible name come from `dom-accessibility-api`\n * (MIT, zero deps) — the engine behind testing-library's `getByRole`. Accessible\n * name is a genuinely hard spec (accname walks aria-labelledby graphs, ::before\n * content, <label> associations, alt/title fallbacks, and recursive\n * name-from-content) and a hand-rolled version is wrong in ways you only discover\n * on a customer's page.\n *\n * WHAT WE BUILT: everything below that. Visibility and pointer-events are ~20 lines\n * from first principles (see `isVisible`/`receivesPointerEvents`) and the state\n * reads are direct DOM/ARIA reads, so we vendored nothing and took on no\n * Apache-2.0 attribution obligation.\n */\n\n/** A memoised `getComputedStyle`, shaped to be passed straight to accname. */\nexport type StyleOf = typeof window.getComputedStyle;\n\n/**\n * One computed style per element per snapshot.\n *\n * Not a micro-optimisation: `computeAccessibleName` calls back into\n * getComputedStyle for every descendant it walks while building a name from\n * content, so on a page of nested divs the uncached cost is quadratic-ish. The\n * cache is per-snapshot (a fresh WeakMap each walk), so it can never go stale\n * across snapshots.\n */\nexport function createStyleCache(): StyleOf {\n const cache = new WeakMap<Element, CSSStyleDeclaration>();\n return ((el: Element, pseudo?: string | null): CSSStyleDeclaration => {\n // Pseudo-element lookups are rare and must not poison the element cache.\n if (pseudo) return window.getComputedStyle(el, pseudo);\n let style = cache.get(el);\n if (!style) {\n style = window.getComputedStyle(el);\n cache.set(el, style);\n }\n return style;\n }) as StyleOf;\n}\n\n/**\n * Does this environment do layout at all?\n *\n * In a browser the root element always has a box. In jsdom — which has no layout\n * engine — *everything* reports zero client rects, so a box-based visibility check\n * would hide the entire page and our tests would assert on an empty snapshot. So we\n * feature-detect layout once per walk and fall back to style-only visibility when\n * there is none. This is a test-environment concession, stated out loud rather than\n * hidden behind a mock.\n */\nexport function hasLayout(): boolean {\n return document.documentElement.getClientRects().length > 0;\n}\n\n/**\n * Visible enough to be worth telling the agent about.\n *\n * `display` and `visibility` are read from the computed style, which already\n * accounts for inheritance — and because the walk is top-down and prunes whole\n * subtrees, we never pay for an ancestor walk. `display: contents` is the one\n * subtlety: such an element generates no box of its own but its children do, so it\n * must not be treated as invisible or we would drop a real subtree.\n */\nexport function isVisible(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n const display = style.display;\n if (display === 'none') return false;\n\n const visibility = style.visibility;\n if (visibility === 'hidden' || visibility === 'collapse') return false;\n\n // `opacity: 0` is a standard \"hide from sight, keep for a11y\" technique. It still\n // reports a box, so the area check below misses it. We treat fully-transparent as\n // hidden; a partially-transparent element is genuinely on screen.\n if (Number(style.opacity) === 0) return false;\n\n // A `display: contents` element generates no box of its own but its children do,\n // so it must not be judged by its own (nonexistent) geometry — we let it through\n // and test each child on its own merits.\n if (layout && display !== 'contents') {\n // Area, not merely \"has a box\": `width:0;height:0;overflow:hidden` is one of the\n // commonest ways to hide a thing, and such an element still reports a client\n // rect. This is the check Playwright's own isVisible() makes.\n const box = el.getBoundingClientRect();\n if (box.width <= 0 || box.height <= 0) return false;\n\n // The sr-only / visually-hidden family: `clip: rect(0 0 0 0)` and its modern\n // `clip-path: inset(50%)` shrink the element to nothing while keeping a 1px box,\n // and `position:absolute; left:-9999px` parks it far off any real page. All three\n // are \"screen-reader only\" idioms — present for a11y, not for sight — so an agent\n // reading the page should skip them too. (getClientRects().length === 0 catches\n // the clipped ones; the far-offscreen check catches the parked ones.)\n if (el.getClientRects().length === 0) return false;\n if (box.right < -2000 || box.bottom < -2000) return false;\n }\n\n return true;\n}\n\n/**\n * Can a pointer actually reach it?\n *\n * `pointer-events` is an INHERITED property, so the computed value on the element\n * already encodes every ancestor's `pointer-events: none` — and correctly honours a\n * descendant that opts back in with `pointer-events: auto`. That is the whole check:\n * no ancestor walk, no hit-test. We deliberately do NOT test for occlusion (is\n * something painted on top of it) the way Playwright's actionability check does —\n * we are describing the page, not clicking it, and an element under a sticky header\n * is still worth telling the agent about.\n */\nexport function receivesPointerEvents(style: CSSStyleDeclaration): boolean {\n return style.pointerEvents !== 'none';\n}\n\n/** Roles that are inherently operable. */\nconst INTERACTIVE_ROLES = new Set([\n 'button',\n 'checkbox',\n 'combobox',\n 'link',\n 'listbox',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'searchbox',\n 'slider',\n 'spinbutton',\n 'switch',\n 'tab',\n 'textbox',\n 'treeitem',\n]);\n\n/** Tags that are operable regardless of what role they compute to. */\nconst INTERACTIVE_TAGS = new Set([\n 'BUTTON',\n 'INPUT',\n 'SELECT',\n 'TEXTAREA',\n 'SUMMARY',\n]);\n\n/** `contenteditable` — present and not explicitly \"false\" (covers \"\", \"true\", \"plaintext-only\"). */\nexport function isEditable(el: Element): boolean {\n const v = el.getAttribute('contenteditable');\n return v !== null && v !== 'false';\n}\n\n/**\n * Is this element something the user can operate?\n *\n * THIS IS THE INTERESTING FUNCTION, so here is the reasoning in full.\n *\n * The obvious way to answer it — ask the DOM what event listeners are attached —\n * IS NOT AVAILABLE. `getEventListeners()` exists only inside DevTools (and via CDP).\n * We are ordinary page JS on a customer's website, so every `addEventListener` a\n * React, Vue or Svelte app ever registered is, to us, completely invisible. This is\n * precisely where the browser-use style of in-page DOM extraction degrades on real\n * apps: it cannot see a single handler, so it either misses the app's controls or\n * guesses wildly. We therefore never ask \"does it have a handler\"; we ask \"does it\n * PRESENT ITSELF as operable\", in four descending tiers of confidence:\n *\n * 1. TAG SEMANTICS (certain). button, input, select, textarea, summary, a[href].\n * 2. COMPUTED ROLE (certain). role=button|link|checkbox|… whether implicit or\n * author-supplied. A div with role=\"button\" is a\n * button as far as the platform, a screen reader,\n * and the user are concerned.\n * 3. FOCUSABILITY (strong). tabindex >= 0, or contenteditable. An app that\n * made a div keyboard-reachable did so on purpose.\n * 4. `cursor: pointer` (WEAK). Last resort, and the reason for the guard below.\n *\n * Tier 4 needs care, because `cursor` is INHERITED: a card with `cursor: pointer`\n * makes every span, every icon and every text node inside it report `pointer` too,\n * and a naive check would mint a ref for each of them and drown the snapshot. So we\n * only count the element that *introduced* the pointer cursor — the one whose parent\n * did not already have it. That is almost exactly the clickable card itself.\n */\nexport function isInteractive(\n el: Element,\n role: string | null,\n style: CSSStyleDeclaration,\n parentStyle: CSSStyleDeclaration | null,\n): boolean {\n const tag = el.tagName;\n\n // 1. tag semantics\n // An <a href> is interactive, but a hrefless <a> is NOT a dead end — it may be a\n // JS-nav link, an <a role=\"button\">, or a Bootstrap `.btn` anchor. So href is a\n // positive signal, not a gate: fall through to the role/tabindex/cursor tiers\n // rather than returning false and dropping every SPA link.\n if (tag === 'A' && el.hasAttribute('href')) return true;\n if (INTERACTIVE_TAGS.has(tag)) return true;\n\n // 2. computed role\n if (role !== null && INTERACTIVE_ROLES.has(role)) return true;\n\n // 3. focusability\n const tabindex = el.getAttribute('tabindex');\n if (tabindex !== null && Number(tabindex) >= 0) return true;\n if (isEditable(el)) return true;\n\n // 4. cursor: pointer, but only where it originates (see above)\n if (style.cursor === 'pointer' && parentStyle?.cursor !== 'pointer')\n return true;\n\n return false;\n}\n\n/**\n * Roles whose accessible name IS their text content (ARIA \"Name From: contents\").\n *\n * This is the exact list from the ARIA spec, and it earns its place: it is what tells\n * the walk that the \"Export CSV\" inside `<button>Export CSV</button>` has ALREADY been\n * emitted, as the button's name, and must not be repeated as a child text node.\n *\n * The tempting shortcut — \"skip any text that appears inside the parent's name\" — is\n * wrong, and wrong in a way that silently deletes content: a card labelled\n * `aria-label=\"Acme Corp order\"` containing the text \"Acme Corp\" would lose it,\n * because one is a substring of the other by coincidence. Ask the role, not the string.\n */\nexport const NAME_FROM_CONTENT = new Set([\n 'button',\n 'cell',\n 'checkbox',\n 'columnheader',\n 'gridcell',\n 'heading',\n 'link',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'row',\n 'rowheader',\n 'switch',\n 'tab',\n 'tooltip',\n 'treeitem',\n]);\n\n/* ─────────────────────────────── state ────────────────────────────────── */\n\n/** Roles whose content IS the user's data. We report that a value exists, never what it is. */\nconst VALUE_ROLES = new Set(['textbox', 'searchbox', 'spinbutton']);\n\n/**\n * Roles we refuse to descend into, because their children/content ARE the value.\n *\n * A `<textarea>`'s child text node is literally what the user typed; a\n * contenteditable's subtree is the document they are writing. Refusing to walk in is\n * how \"never emit a value\" is enforced STRUCTURALLY, rather than by remembering to\n * filter at every emit site.\n *\n * `<select>` is deliberately NOT here. Its options are a bounded, author-defined\n * enumeration — the affordance the agent most needs (\"what can I set this to\"), not\n * the free-text user data the opaque rule exists to contain. The snapshot emits them\n * directly instead (capped, selected one marked): see emitSelectOptions in\n * snapshot.ts.\n */\nconst OPAQUE_TAGS = new Set(['INPUT', 'TEXTAREA']);\n\nexport function isOpaque(el: Element): boolean {\n return OPAQUE_TAGS.has(el.tagName) || isEditable(el);\n}\n\n/**\n * Has the user put something in this field?\n *\n * `.value` is read and immediately thrown away — only its LENGTH escapes. This is\n * the single most useful bit about a form (\"is the email box already filled in?\")\n * and the single most dangerous string on the page, so it is reduced to one bit at\n * the point of reading and never travels.\n */\nfunction isFilled(el: Element, role: string): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA') {\n if (!VALUE_ROLES.has(role)) return false; // checkbox.value is \"on\" — meaningless\n return ((el as HTMLInputElement).value ?? '').length > 0;\n }\n if (isEditable(el)) return (el.textContent ?? '').trim().length > 0;\n return false;\n}\n\nfunction ariaFlag(el: Element, attr: string): 'true' | 'mixed' | null {\n const v = el.getAttribute(attr);\n if (v === 'true') return 'true';\n if (v === 'mixed') return 'mixed';\n return null;\n}\n\n/**\n * The bracketed attributes, in Playwright's order:\n * [checked] [disabled] [expanded] [level=N] [pressed] [selected]\n * plus our one addition, [filled] — see isFilled. `[ref=eN]` is appended by the\n * caller and always comes last.\n */\nexport function states(el: Element, role: string): string {\n const out: string[] = [];\n const tag = el.tagName;\n\n // checked\n if (tag === 'INPUT' && (role === 'checkbox' || role === 'radio')) {\n if ((el as HTMLInputElement).checked) out.push('[checked]');\n } else {\n const checked = ariaFlag(el, 'aria-checked');\n if (checked === 'mixed') out.push('[checked=mixed]');\n else if (checked === 'true') out.push('[checked]');\n }\n\n // disabled — dom-accessibility-api handles fieldset/optgroup inheritance and aria-disabled\n if (isDisabled(el)) out.push('[disabled]');\n\n // expanded — <summary> reflects its parent <details>, which has no ARIA attribute\n const expanded = el.getAttribute('aria-expanded');\n if (expanded === 'true' || expanded === 'false') {\n if (expanded === 'true') out.push('[expanded]');\n } else if (tag === 'SUMMARY') {\n const details = el.parentElement;\n if (\n details?.tagName === 'DETAILS' &&\n (details as HTMLDetailsElement).open\n ) {\n out.push('[expanded]');\n }\n }\n\n // level\n if (role === 'heading') {\n const aria = el.getAttribute('aria-level');\n const level = aria ? Number(aria) : Number(tag[1]);\n if (Number.isFinite(level) && level > 0) out.push(`[level=${level}]`);\n }\n\n // pressed\n const pressed = ariaFlag(el, 'aria-pressed');\n if (pressed === 'mixed') out.push('[pressed=mixed]');\n else if (pressed === 'true') out.push('[pressed]');\n\n // selected\n if (el.getAttribute('aria-selected') === 'true') out.push('[selected]');\n\n // filled (ours — a boolean, never the value)\n if (isFilled(el, role)) out.push('[filled]');\n\n return out.join(' ');\n}\n\n/* ─────────────────────────── role & name ──────────────────────────────── */\n\n/**\n * The computed role, with one correction.\n *\n * `getRole` follows HTML-AAM and returns null for a contenteditable div — but every\n * real browser exposes it to assistive tech as a textbox, and that is what it is to\n * the user and to the agent. We say textbox.\n */\nexport function roleOf(el: Element): string | null {\n if (isEditable(el)) return 'textbox';\n return getRole(el);\n}\n\n/**\n * Selector for anything whose CONTENT is the user's data — a form control, a\n * contenteditable, a valued widget, or a host-marked private region.\n */\nconst UNTRUSTED_CONTENT =\n 'input,textarea,select,[contenteditable=\"\"],[contenteditable=\"true\"],[aria-valuetext],[data-mf-private]';\n\n/**\n * Would computing this element's ACCESSIBLE NAME read the user's data?\n *\n * This is the leak the structural `isOpaque` walk cannot see. `computeAccessibleName`\n * runs its OWN descendant walk, inside dom-accessibility-api, that knows nothing about\n * our opaque set or `data-mf-private` — it will happily read `input.value`,\n * `aria-valuetext`, a contenteditable's text, or a private subtree, and fold it into\n * the name of a name-from-content ANCESTOR or any `aria-labelledby` referrer. So a\n * value our walk refuses to enter re-enters through the parent's name.\n *\n * Two vectors, both handled:\n * - name-from-content: the name is built from descendant text. If any descendant is\n * untrusted, the name is tainted.\n * - aria-labelledby: the name is pulled from a referenced element. If any referent\n * is (or contains) untrusted content, the name is tainted.\n *\n * `aria-label` and `title` are author-written static strings; a site that copies its\n * own secret into one is exposing it deliberately and we cannot defend that. The\n * automatic-computation vectors are the ones we must close.\n */\nfunction nameIsUntrusted(el: Element): boolean {\n const labelledby = el.getAttribute('aria-labelledby');\n if (labelledby) {\n for (const id of labelledby.split(/\\s+/)) {\n if (!id) continue;\n const ref = el.ownerDocument.getElementById(id);\n if (!ref) continue;\n if (\n ref.matches(UNTRUSTED_CONTENT) ||\n ref.querySelector(UNTRUSTED_CONTENT)\n ) {\n return true;\n }\n }\n return false;\n }\n // No explicit label attributes → the name, if any, is name-from-content.\n if (el.hasAttribute('aria-label')) return false;\n return el.querySelector(UNTRUSTED_CONTENT) !== null;\n}\n\nexport function nameOf(el: Element, styleOf: StyleOf): string {\n const name = computeAccessibleName(el, {\n getComputedStyle: styleOf,\n // jsdom logs a console error if you claim pseudo-element support it doesn't have.\n computedStyleSupportsPseudoElements: false,\n });\n if (!name) return '';\n\n // A tainted name would leak a value or a private string. Drop it entirely and let\n // the element stand on its role + ref. Losing a name costs the agent a little\n // context; keeping a leaked one is a breach. The trade is not close.\n if (nameIsUntrusted(el)) {\n // Preserve an explicit author label if one exists and is not itself the taint —\n // aria-labelledby taints were already caught above, so any aria-label here is safe.\n return el.getAttribute('aria-label') || '';\n }\n return name;\n}\n","import type { ElementRef } from '../protocol';\n\n/**\n * Element handles.\n *\n * The mechanism is Playwright's, deliberately (see protocol.ts): the agent never\n * learns a selector, it learns `e12`, and `e12` is turned back into an element\n * HERE, in the page, by us.\n *\n * Three properties matter and all are load-bearing:\n *\n * 1. THE MAP IS A WeakMap, NOT AN EXPANDO ON THE ELEMENT. An earlier version\n * stamped `el._mfRef`. Non-enumerable, so invisible to `Object.keys`/spreads/\n * `JSON.stringify` — but STILL reachable via `Object.getOwnPropertyNames` and\n * `Reflect.ownKeys`, and, worse, it parked the element's accessible name on the\n * customer's live DOM node indefinitely. A `WeakMap<Element, RefEntry>` mutates\n * nothing on their objects, is invisible to every enumeration and serialization\n * API without exception, cannot collide with a property the host already has,\n * and still gives us node-identity survival across GC for free.\n *\n * 2. A REF IS REGENERATED WHEN ROLE OR NAME CHANGES. Frameworks recycle DOM nodes:\n * a virtualised list scrolls, and the <button> that said \"Approve\" is the very\n * same node that now says \"Delete\". Keying the ref on (role, name) means that\n * node gets a NEW id and the old id resolves to nothing.\n *\n * 3. A REF IS SCOPED TO ONE SNAPSHOT GENERATION. (2) is necessary but not\n * sufficient: two icon-only \"Delete\" buttons in a virtualised table have the\n * SAME (role, name), so a recycled node whose role+name are unchanged would keep\n * its ref and silently retarget a different logical row. So a ref also carries\n * the generation it was minted in, and resolveRef refuses a ref from an older\n * generation — the agent must re-snapshot to get a fresh, valid handle. Loud\n * staleness beats silent retargeting.\n */\n\ninterface RefEntry {\n id: ElementRef;\n /** role + name at mint time. Changes here invalidate the ref. */\n key: string;\n /** The snapshot generation this ref belongs to. */\n gen: number;\n}\n\n/**\n * Monotonic across snapshots, never reused — like Playwright's. An id is only ever\n * handed out once in a page's lifetime, so a stale ref can never be *silently*\n * correct by colliding with a newer element; it just resolves to null.\n */\nlet counter = 0;\n\n/** Bumped once per full snapshot. A ref is only valid within its own generation. */\nlet generation = 0;\n\n/**\n * Element identity, off the host's objects entirely. Keyed by element so a recycled\n * node is recognised across snapshots; the entry carries the (role,name) key and the\n * generation for the two staleness checks above.\n */\nconst entries = new WeakMap<Element, RefEntry>();\n\n/** id -> element, for resolution. Rebuilt each generation from exactly what was emitted. */\nconst registry = new Map<ElementRef, Element>();\n\n/** Called once per FULL snapshot, before the walk. A region read does NOT call this. */\nexport function beginSnapshot(): void {\n generation++;\n registry.clear();\n}\n\n/**\n * Mint (or reuse) the ref for an element and register it for resolution.\n * Only ever called for elements that are visible AND receive pointer events.\n */\nexport function refFor(el: Element, role: string, name: string): ElementRef {\n const key = `${role} ${name}`;\n\n let entry = entries.get(el);\n if (!entry || entry.key !== key) {\n entry = { id: `e${++counter}`, key, gen: generation };\n entries.set(el, entry);\n } else {\n // Same node, same identity — carry it into the current generation so a fresh\n // snapshot re-validates a still-present element rather than orphaning it.\n entry.gen = generation;\n }\n\n registry.set(entry.id, el);\n return entry.id;\n}\n\n/**\n * Turn a ref back into an element.\n *\n * Three ways this returns null, each deliberate:\n * - unknown id (never minted, or from a cleared generation) → not in the registry;\n * - the element left the page → `isConnected` is false. A detached node still\n * answers every question (role, name, a zero box), so without this an action\n * would silently no-op against a ghost;\n * - the ref is from an OLDER generation → its entry.gen has been superseded. This is\n * what stops a recycled-node retarget: the agent is told the handle is stale and\n * must re-snapshot, rather than acting on the wrong row.\n */\nexport function resolveRef(ref: ElementRef): Element | null {\n const el = registry.get(ref);\n if (!el) return null;\n if (!el.isConnected) {\n registry.delete(ref);\n return null;\n }\n const entry = entries.get(el);\n if (!entry || entry.id !== ref || entry.gen !== generation) return null;\n return el;\n}\n\n/** Test-only: reset counters so refs are deterministic per test. */\nexport function __resetRefs(): void {\n counter = 0;\n generation = 0;\n registry.clear();\n}\n","import { isDisabled, isInaccessible } from 'dom-accessibility-api';\n\nimport { isPrivate, redact } from '../context';\nimport {\n createStyleCache,\n hasLayout,\n isInteractive,\n NAME_FROM_CONTENT,\n isOpaque,\n isVisible,\n nameOf,\n receivesPointerEvents,\n roleOf,\n states,\n type StyleOf,\n} from './a11y';\nimport { beginSnapshot, refFor } from './refs';\n\nexport { resolveRef } from './refs';\n\n/**\n * The page, as the agent sees it.\n *\n * We emit Playwright's ARIA-snapshot YAML, and that choice is the point of this\n * file. It is not our format: it is the one the frontier models have seen most, via\n * playwright-mcp, so a model already knows how to read it and already knows that\n * `[ref=e12]` is the thing you hand back to act. Inventing our own dialect here\n * would cost us capability for nothing.\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - list:\n * - listitem:\n * - link \"Order #1043\" [ref=e8]\n * - text: \"Unpaid\"\n * - button \"Export CSV\" [ref=e12]\n *\n * Not raw HTML: a real page is tens of thousands of tokens of div soup, gives the\n * model nothing to act with, and is a prompt-injection firehose.\n */\n\n/* ─────────────────────────────── budgets ──────────────────────────────── */\n\n/**\n * These exist because the failure they prevent is not \"the snapshot is big\", it is\n * \"the agent confidently tells the user about a button that does not exist\". A model\n * given a silently-cut-off page has no way to know it was cut off, so it fills the\n * gap. Hence: hard caps, and `truncated: true` travels with the payload so the agent\n * can be TOLD it is not seeing everything.\n *\n * The two caps do different jobs, and conflating them is how you get a bad snapshot:\n *\n * MAX_LINES bounds the MODEL'S CONTEXT. 800 lines of ARIA YAML is ~12 KB, a few\n * thousand tokens — a dense dashboard, and about as much page as is useful to\n * reason over at once.\n *\n * MAX_NODES bounds the MAIN THREAD. It counts elements *visited*, most of which are\n * the wrapper divs of a modern app and emit nothing at all. Measured in Chrome on a\n * deeply-nested 52k-element table, visiting 4000 nodes costs ~25ms of walk. Set it\n * to 1500 (a tempting round number) and a div-soup page truncates at ~460 lines —\n * we would stop while HALF the line budget was still unspent, and tell the agent it\n * could not see a page we had simply given up on early.\n */\nconst MAX_NODES = 4000;\nconst MAX_LINES = 800;\nconst MAX_NAME = 120;\nconst MAX_TEXT = 120;\n/**\n * Max `<option>`s emitted per `<select>` before the rest is summarised. A country or\n * timezone picker runs to hundreds; the option list is an affordance to show, not a\n * reason to spend the line budget. The selected option is always in the first slice\n * in practice, but if a huge list has its selection past the cap the \"+N more\"\n * marker tells the agent it isn't seeing every choice.\n */\nconst MAX_OPTIONS = 25;\n\n/* ─────────────────────────────── model ────────────────────────────────── */\n\ninterface AriaNode {\n role: string;\n /** Raw accessible name. Redacted and truncated at render time, not here. */\n name: string;\n /** Pre-rendered bracket attributes, `[checked] [ref=e5]`. */\n props: string;\n children: (AriaNode | string)[];\n}\n\ninterface Walk {\n styleOf: StyleOf;\n layout: boolean;\n nodes: number;\n lines: number;\n truncated: boolean;\n /** Called for every element that gets a ref, so a caller can note which are on screen. */\n onRef?: (ref: string, el: Element) => void;\n}\n\n/** Elements that carry no meaning of their own: their children stand in for them. */\nconst TRANSPARENT = new Set(['generic', 'presentation', 'none']);\n\n/**\n * Never walked. `<script>`/`<style>`/`<noscript>` are the obvious ones; `<svg>` is\n * here because its innards are hundreds of `<path>` nodes of pure noise — any title\n * it carries is already folded into its parent's accessible name by accname.\n */\nconst SKIP_TAGS = new Set([\n 'SCRIPT',\n 'STYLE',\n 'NOSCRIPT',\n 'TEMPLATE',\n 'SVG',\n 'HEAD',\n 'LINK',\n 'META',\n 'BASE',\n]);\n\n/* ─────────────────────────────── walking ──────────────────────────────── */\n\n/** False once any budget is spent — the caller stops and we mark the snapshot truncated. */\nfunction withinBudget(w: Walk): boolean {\n if (w.nodes >= MAX_NODES || w.lines >= MAX_LINES) {\n w.truncated = true;\n return false;\n }\n return true;\n}\n\n/**\n * Is this element ours?\n *\n * The widget must never appear in its own snapshot: the agent describing its own\n * chat window back to itself is both useless and a lovely little feedback loop.\n */\nfunction isOurs(el: Element): boolean {\n return el.id === 'matterfact-embed' || el.hasAttribute('data-mf-embed');\n}\n\n/**\n * Hidden from assistive tech — and therefore from us.\n *\n * This is `isInaccessible()`'s rule set applied ONE NODE AT A TIME, top-down.\n * `isInaccessible()` itself walks every ancestor on every call, which over a whole\n * tree is the O(n·depth) blow-up the budget forbids; because we descend from the\n * root and prune the entire subtree the moment a node is hidden, the composition of\n * these local checks is exactly equivalent and costs O(1) per node. (We still call\n * the real thing once, on the root, as a backstop.)\n */\nfunction isHidden(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n if (el.getAttribute('aria-hidden') === 'true') return true;\n if (el.hasAttribute('hidden') || el.hasAttribute('inert')) return true;\n return !isVisible(el, style, layout);\n}\n\n/**\n * The nodes a parent should walk.\n *\n * An open shadow root REPLACES its host's light children — those only reach the\n * screen by being slotted, and we pick them up when we hit the `<slot>` that pulls\n * them in. Walking both would emit every web component's contents twice. A closed\n * shadow root is opaque to us by design, exactly as it is to the rest of the page.\n */\nfunction childrenOf(el: Element): ArrayLike<Node> {\n if (el.shadowRoot) return el.shadowRoot.childNodes;\n if (el.tagName === 'SLOT') {\n const assigned = (el as HTMLSlotElement).assignedNodes({ flatten: true });\n // An unfilled slot renders its own fallback content.\n if (assigned.length) return assigned;\n }\n return el.childNodes;\n}\n\n/** ArrayLike + index loop, not for-of: a NodeList needs `DOM.Iterable`, and copying one to iterate it allocates an array per element for nothing. */\nfunction visitChildren(\n el: Element,\n parent: AriaNode,\n style: CSSStyleDeclaration,\n w: Walk,\n): void {\n const children = childrenOf(el);\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (child) visitNode(child, parent, style, w);\n }\n}\n\nfunction visitText(node: Text, parent: AriaNode, w: Walk): void {\n const text = (node.nodeValue ?? '').replace(/\\s+/g, ' ').trim();\n if (!text) return;\n\n // The text of a button, a link or a heading IS its accessible name — we already\n // emitted it on the parent's line, and repeating it as a child would double the\n // tokens and imply a second, separate thing on the page. Decided by ROLE, never by\n // string-matching against the name (see NAME_FROM_CONTENT).\n if (NAME_FROM_CONTENT.has(parent.role)) return;\n\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(text);\n}\n\n/**\n * A native `<select>`, expanded into its options.\n *\n * The generic walk can't do this: a closed select's `<option>`s have no layout box,\n * so isVisible would prune them. Yet the options are exactly the affordance the agent\n * needs — \"what can I set this to\" — and, unlike an `<input>` value, they are a\n * bounded, author-defined set rather than free text the user typed. So we emit them,\n * and mark the selected one: it names one of the choices we are ALREADY showing, so\n * it reveals nothing a human looking at the control wouldn't see. Labels are redacted\n * at render time like every other name; the list is capped; a select the host deems\n * sensitive is hidden the usual way (`data-mf-private`) and never reaches here.\n *\n * `.options` is the flat HTMLOptionsCollection, so `<optgroup>` nesting is already\n * flattened for us; `<select multiple>` (role listbox) works through the same path.\n */\n/** One option, in Playwright's shape: `- option \"label\" [disabled] [selected]`. The\n * name is trimmed so a whitespace-only option renders `- option` (no \"\"). Disabled is\n * `:disabled` (which catches an <optgroup disabled> that isDisabled/opt.disabled miss)\n * OR isDisabled (which adds aria-disabled). Bracket order matches states(): [disabled]\n * before [selected]. */\nfunction optionNode(opt: HTMLOptionElement): AriaNode {\n const disabled = opt.matches(':disabled') || isDisabled(opt);\n return {\n role: 'option',\n name: (opt.label || opt.textContent || '').trim(),\n props:\n (disabled ? ' [disabled]' : '') + (opt.selected ? ' [selected]' : ''),\n children: [],\n };\n}\n\nfunction emitSelectOptions(\n select: HTMLSelectElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const options = select.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n // The selected option IS the field's current value — the one option the agent most\n // needs. In a long list (country, timezone) the selection can sit past the cap, so\n // the front slice above would show none marked [selected]. Surface any selected\n // option that fell outside the cap regardless, and don't double-count it as hidden.\n let extraSelected = 0;\n const selected = select.selectedOptions;\n for (let i = 0; i < selected.length; i++) {\n const opt = selected[i];\n if (opt && opt.index >= shown && !isPrivate(opt)) {\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(optionNode(opt));\n extraSelected++;\n }\n }\n const remaining = options.length - shown - extraSelected;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\n/**\n * An `<input list=\"…\">`'s datalist suggestions.\n *\n * Same affordance as a `<select>`'s options — a bounded, author-defined set the user\n * can pick — but surfaced under the (still value-opaque) input, because the\n * `<datalist>` element is display:none, so the generic walk never reaches it. The\n * input's own value stays hidden; only the suggestion labels are emitted (redacted at\n * render like every name, and capped). No [selected] — a datalist has no current\n * choice, only completions.\n */\nfunction emitDatalistOptions(\n input: HTMLInputElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const list = input.list as HTMLDataListElement | null;\n if (!list) return;\n const options = list.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n const remaining = options.length - shown;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\nfunction visitElement(\n el: Element,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (!withinBudget(w)) return;\n if (SKIP_TAGS.has(el.tagName) || isOurs(el)) return;\n\n // Privacy first, before we so much as compute a style: `data-mf-private` and\n // password/hidden inputs take their whole subtree with them.\n if (isPrivate(el)) return;\n\n w.nodes++;\n\n const style = w.styleOf(el);\n if (isHidden(el, style, w.layout)) return;\n\n const role = roleOf(el);\n const transparent = role === null || TRANSPARENT.has(role);\n const interactive = isInteractive(el, role, style, parentStyle);\n\n // A div with a click handler is invisible to us (no getEventListeners), but a div\n // that is FOCUSABLE, or that flips the cursor to a pointer, is announcing itself.\n // Playwright emits those as `- generic [ref=eN]` and so do we: without this, every\n // custom card, chip and icon-button on a modern app would be unreachable.\n if (transparent && !interactive) {\n visitChildren(el, parent, style, w);\n return;\n }\n\n const emittedRole = role === null || TRANSPARENT.has(role) ? 'generic' : role;\n const name = nameOf(el, w.styleOf);\n\n // Refs are for things you can act on. Static text does not get one — it would be a\n // handle the agent can only ever misuse, and it doubles the size of the snapshot.\n let ref = '';\n if (interactive && receivesPointerEvents(style)) {\n const r = refFor(el, emittedRole, name);\n ref = ` [ref=${r}]`;\n w.onRef?.(r, el);\n }\n\n const state = states(el, emittedRole);\n const node: AriaNode = {\n role: emittedRole,\n name,\n props: (state ? ` ${state}` : '') + ref,\n children: [],\n };\n\n w.lines++;\n parent.children.push(node);\n\n // A native <select>: emit its options — the affordance the opaque rule used to\n // hide — instead of walking its (layout-less, hence prune-able) children.\n if (el.tagName === 'SELECT') {\n emitSelectOptions(el as HTMLSelectElement, node, w);\n return;\n }\n\n // An <input list=\"…\">: surface its datalist suggestions (the affordance) under the\n // input, then fall through to the opaque return — the value itself is never emitted.\n if (el.tagName === 'INPUT' && (el as HTMLInputElement).list) {\n emitDatalistOptions(el as HTMLInputElement, node, w);\n }\n\n // isOpaque: an <input>, <textarea> or contenteditable. Its content IS the user's\n // data, so we do not walk into it — the value cannot leak because we never go and\n // look at it. See a11y.ts.\n if (isOpaque(el)) return;\n\n visitChildren(el, node, style, w);\n}\n\nfunction visitNode(\n node: Node,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (node.nodeType === 3 /* TEXT_NODE */) {\n visitText(node as Text, parent, w);\n } else if (node.nodeType === 1 /* ELEMENT_NODE */) {\n visitElement(node as Element, parent, parentStyle, w);\n }\n // Comments, CDATA, processing instructions: nothing to say.\n}\n\n/* ────────────────────────────── rendering ─────────────────────────────── */\n\n/**\n * Redact, then truncate — in that order, and the order is the point.\n *\n * Truncate first and a 130-character line containing an email address gets cut\n * through the middle of it, the regex no longer matches, and you have shipped\n * `jane.doe@acmecorp` to the model. Redaction runs on the whole string, every time,\n * before anything is thrown away.\n */\nfunction sanitize(text: string, max: number): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n const clean = redact(collapsed);\n return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;\n}\n\nfunction quote(text: string): string {\n return `\"${text.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\nfunction render(\n children: (AriaNode | string)[],\n depth: number,\n out: string[],\n): void {\n const pad = ' '.repeat(depth);\n for (const child of children) {\n if (typeof child === 'string') {\n out.push(`${pad}- text: ${quote(sanitize(child, MAX_TEXT))}`);\n continue;\n }\n const name = child.name ? ` ${quote(sanitize(child.name, MAX_NAME))}` : '';\n const head = `${pad}- ${child.role}${name}${child.props}`;\n if (child.children.length) {\n out.push(`${head}:`);\n render(child.children, depth + 1, out);\n } else {\n out.push(head);\n }\n }\n}\n\n/* ─────────────────────────────── entry ────────────────────────────────── */\n\n/**\n * Walk the page and render it. Called by context.ts, which redacts the result a\n * second time on the way out — the belt to this file's braces.\n */\nfunction walk(\n root: Element,\n onRef?: (ref: string, el: Element) => void,\n): { yaml: string; truncated: boolean } {\n const styleOf = createStyleCache();\n const w: Walk = {\n styleOf,\n layout: hasLayout(),\n nodes: 0,\n lines: 0,\n truncated: false,\n onRef,\n };\n\n // The one call to the real isInaccessible(): a cheap backstop on the root, where\n // the ancestor walk costs nothing.\n if (isInaccessible(root, { getComputedStyle: styleOf })) {\n return { yaml: '', truncated: false };\n }\n\n const tree: AriaNode = { role: '', name: '', props: '', children: [] };\n visitChildren(root, tree, styleOf(root), w);\n\n const lines: string[] = [];\n render(tree.children, 0, lines);\n\n // An in-band marker, not just the out-of-band `truncated` flag. The YAML is what\n // lands in the prompt; a backend template that injects the tree but forgets to\n // surface the flag would hand the model a page that simply stops, and the model\n // fills the gap. This line is inside the payload, so it cannot be dropped on the\n // way to the prompt. (Depth-first, so what is missing is the BOTTOM of the page.)\n //\n // It REPLACES the last emitted line rather than appending — the marker is part of\n // the line budget, not an exemption from it. The final line was a truncated node\n // anyway (see MAX_LINES), so nothing meaningful is lost.\n if (w.truncated && lines.length) {\n lines[lines.length - 1] =\n '- text: \"… (snapshot truncated — more of the page is below)\"';\n }\n\n return { yaml: lines.join('\\n'), truncated: w.truncated };\n}\n\n/**\n * The full page. Mints a fresh generation of refs (beginSnapshot), so any ref the\n * agent held from a previous snapshot is now stale and resolves to null — which is\n * correct: the page may have changed under it.\n *\n * `visibleRefs` is the viewport slice — the refs whose element is actually on screen.\n * That is the \"where is your attention\" signal, and it lets the focus context name\n * the handful of things in view out of the whole tree.\n */\nexport function snapshot(): {\n yaml: string;\n truncated: boolean;\n visibleRefs: string[];\n} {\n const root = document.body;\n if (!root) return { yaml: '', truncated: false, visibleRefs: [] };\n\n beginSnapshot();\n\n const visibleRefs: string[] = [];\n const vh = window.innerHeight || 0;\n const vw = window.innerWidth || 0;\n const result = walk(root, (ref, el) => {\n const r = el.getBoundingClientRect();\n // On screen = its box intersects the viewport. Cheap; the walk already forced\n // layout, so getBoundingClientRect here is reading a warm value.\n if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) {\n visibleRefs.push(ref);\n }\n });\n\n return { ...result, visibleRefs };\n}\n\n/**\n * Zoom in on one ref — the a11y sub-tree under it.\n *\n * This is the pull half: the agent has the focus context and a shallow page, and when\n * it wants the detail of a specific table or form it asks for that region rather than\n * us re-sending the whole page. It does NOT call beginSnapshot — that would clear the\n * ref map and invalidate the very ref being asked about — so the refs it mints join\n * the current generation.\n */\nexport function snapshotRegion(root: Element): {\n yaml: string;\n truncated: boolean;\n} {\n if (!root.isConnected) return { yaml: '', truncated: false };\n return walk(root);\n}\n","import type {\n ActivityEvent,\n FocusContext,\n HostToWidget,\n PageContext,\n PageEntity,\n ToolCall,\n} from './protocol';\n\n/** The origin serving our chat — how we tell OUR embedded content from the host's own\n * iframes. Set by start(); empty until then, which just means we spot nothing. */\nlet widgetOrigin = '';\n\n/**\n * The eye.\n *\n * Everything in this module can see the customer's page. It is a SEPARATE CHUNK,\n * loaded only when someone actually opens the chat — so a page whose visitors never\n * click the widget pays nothing for any of it, and a security reviewer can read\n * exactly one file to know what we look at.\n *\n * The rules, which are not negotiable:\n *\n * NEVER captured — no config enables it: the value of any <input>, <textarea> or\n * contenteditable; anything inside a password field; cookies; localStorage;\n * sessionStorage; the raw DOM; screenshots; network traffic; anything inside an\n * element marked `data-mf-private`.\n *\n * The agent never gets a selector and never touches the DOM. It gets refs. A ref\n * is resolved to an element HERE, in the page, by us.\n */\n\ntype Send = (msg: HostToWidget) => void;\n\nconst MAX_ACTIVITY = 40;\n\nlet send: Send | null = null;\nlet activitySeq = 0;\nconst activity: ActivityEvent[] = [];\nlet lastUrl = '';\n\n/* ─────────────────────────── redaction ────────────────────────────────── */\n\nconst PII = [\n /\\b[\\w.+-]+@[\\w-]+\\.[\\w.]{2,}\\b/g, // email\n /\\b(?:\\d[ -]?){13,19}\\b/g, // card-ish\n /\\b\\d{3}[- ]?\\d{2}[- ]?\\d{4}\\b/g, // ssn — dashed, spaced, OR bare 9 digits\n /\\b\\d{9,}\\b/g, // long bare digit runs: account / MRN / routing numbers\n /(?:\\+?\\d{1,2}[\\s.-]?)?\\(?\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}\\b/g, // us phone\n /\\b(?:sk|pk|rk|ak)_(?:live|test)_[A-Za-z0-9]{8,}\\b/g, // stripe-style api keys\n /\\beyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+\\b/g, // jwt\n];\n\n/**\n * Scrub before anything leaves the page — not after it arrives.\n *\n * A compromised widget, or a bug in ours, must not be able to retroactively obtain\n * a customer's users' email addresses. The only way to guarantee that is to never\n * put them on the wire.\n */\nexport function redact(text: string): string {\n let out = text;\n for (const re of PII) out = out.replace(re, '[redacted]');\n return out;\n}\n\n/** Anything the host has marked private, or that is inherently sensitive, is out. */\nexport function isPrivate(el: Element): boolean {\n if (el.closest('[data-mf-private]')) return true;\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const t = (el as HTMLInputElement).type;\n if (t === 'password' || t === 'hidden') return true;\n }\n return false;\n}\n\n/* ───────────────────────── page context ───────────────────────────────── */\n\n/**\n * What the page says about itself.\n *\n * A host that declares nothing still gets URL + title, which is what every other\n * embeddable assistant on the market offers in total. The interesting fields\n * (`route`, `description`, `entities`) are host-declared, because only the host\n * knows that `/o/8813` is \"the Acme Corp order, 3 items, unpaid\".\n *\n * Declared via a global the host sets before we load:\n * window.matterfact = { context: { route: '/orders/:id', description: '...', entities: [...] } }\n */\n/**\n * matterfact content embedded IN the host page — today, artifact iframes.\n *\n * A cross-origin iframe is opaque: `contentDocument` throws, so the DOM snapshot walks\n * straight past an embedded artifact and the agent is blind to the very thing the page\n * is built around. It reads the page as empty and asks which URL you mean.\n *\n * We don't need to see inside, and shouldn't want to. The artifact's ID is right there\n * in the src, and the agent can already resolve `artifacts/<id>/` in its session — the\n * same path an `@`-mention uses. So we report the ID and let the backend fetch the real\n * thing, which beats scraping a rendering of it: it gets the data, not the picture.\n *\n * Matched by ORIGIN, not by path shape: a customer is perfectly entitled to their own\n * /artifacts/ route, and it isn't ours.\n */\nfunction embeddedMatterfactEntities(): PageEntity[] {\n if (!widgetOrigin) return [];\n const out: PageEntity[] = [];\n for (const frame of Array.from(document.querySelectorAll('iframe'))) {\n let u: URL;\n try {\n u = new URL(frame.getAttribute('src') || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== widgetOrigin) continue;\n const m = u.pathname.match(/^\\/artifacts\\/(.+?)\\/?$/);\n if (!m) continue;\n const id = decodeURIComponent(m[1]);\n if (!id || out.some((e) => e.id === id)) continue; // same artifact twice = once\n // No url field: the agent reaches an artifact by ID (`artifacts/<id>/`), never by\n // fetching the page, and an artifact URL can carry a share token we've no business\n // forwarding. The id is the whole useful payload.\n out.push({\n kind: 'artifact',\n id,\n label: redact(frame.getAttribute('title') || '') || id,\n });\n }\n return out;\n}\n\n/**\n * Frames we can see the existence of but nothing inside — someone else's cross-origin\n * embed. Worth one line: \"there is a thing here I cannot read\" is a true and useful\n * statement, and much better than the agent confidently describing a page while missing\n * the widget the user is actually asking about.\n */\nfunction opaqueFrameCount(): number {\n return Array.from(document.querySelectorAll('iframe')).filter((f) => {\n try {\n const u = new URL(f.getAttribute('src') || '', location.href);\n return u.origin !== location.origin && u.origin !== widgetOrigin;\n } catch {\n return false;\n }\n }).length;\n}\n\nexport function readPageContext(): PageContext {\n const declared =\n (window as { matterfact?: { context?: PageContext } }).matterfact\n ?.context ?? {};\n\n const found = embeddedMatterfactEntities();\n const opaque = opaqueFrameCount();\n\n return {\n // Path only. A query string is where session ids, tokens and email addresses\n // live; it is not ours to take.\n url: location.origin + location.pathname,\n path: location.pathname,\n title: redact(document.title),\n locale: document.documentElement.lang || undefined,\n ...declared,\n // After the spread: what we FOUND is additive to what the host DECLARED, never a\n // replacement. A host that declares its own entities still gets the artifacts we\n // spotted, and vice versa.\n entities: [...(declared.entities ?? []), ...found],\n data: {\n ...(declared.data ?? {}),\n ...(opaque ? { opaque_frames: opaque } : {}),\n },\n };\n}\n\nfunction publishContext() {\n send?.({ type: 'host.context', context: readPageContext() });\n}\n\n/* ────────────────────────── activity ──────────────────────────────────── */\n\nfunction pushActivity(e: Omit<ActivityEvent, 'seq' | 'ts'>) {\n activity.push({ ...e, seq: ++activitySeq, ts: Date.now() });\n if (activity.length > MAX_ACTIVITY) activity.shift();\n send?.({ type: 'host.activity', events: [activity[activity.length - 1]] });\n}\n\n/**\n * A short, human-readable label for what got clicked.\n *\n * Shaped after PostHog's autocapture, not after a session-replay frame: rrweb would\n * give us `{source:2, type:2, id:417, x:210, y:88}` — no text, no role, no href,\n * meaningless to a model without the full DOM snapshot it deltas against. One line\n * of \"clicked button 'Export CSV'\" is worth more and costs less.\n */\n/**\n * The accessible NAME of a form control — never its value.\n *\n * A control has no `innerText`, so the generic path below misses it. We look where a\n * control's name actually lives: `aria-label`, then a `<label for>` or a wrapping\n * `<label>`, then `placeholder`. `placeholder` is a LABEL, not a value — it is the\n * hint shown when the field is empty (\"Order number or customer\"), so it is safe.\n */\nfunction controlLabel(el: Element): string {\n const aria = el.getAttribute('aria-label');\n if (aria) return aria;\n\n const id = el.id;\n if (id) {\n const forLabel = document.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n const t = forLabel?.textContent?.trim();\n if (t) return t;\n }\n const wrapping = el.closest('label')?.textContent?.trim();\n if (wrapping) return wrapping;\n\n const placeholder = el.getAttribute('placeholder');\n if (placeholder) return placeholder;\n\n return '';\n}\n\nconst FORM_CONTROLS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);\n\nfunction describe(el: Element): string {\n const role = el.getAttribute('role') || el.tagName.toLowerCase();\n const label =\n el.getAttribute('aria-label') ||\n (FORM_CONTROLS.has(el.tagName)\n ? controlLabel(el)\n : (el as HTMLElement).innerText?.trim().slice(0, 60)) ||\n el.getAttribute('title') ||\n '';\n return label ? `${role} \"${redact(label)}\"` : role;\n}\n\n/**\n * Elements a click is worth recording. Deliberately tight: the point of the activity\n * stream is INTENT (\"the user chose to export\"), and a click on a heading, a label,\n * a card gutter, or blank page is not intent, it is noise. We only log a click that\n * lands on something actionable.\n */\nconst ACTIONABLE =\n 'a[href],button,input,select,textarea,summary,' +\n '[role=\"button\"],[role=\"link\"],[role=\"menuitem\"],[role=\"tab\"],[role=\"option\"],' +\n '[role=\"checkbox\"],[role=\"switch\"],[role=\"radio\"],[onclick],[tabindex]';\n\nfunction onClick(ev: Event) {\n const target = ev.target as Element | null;\n if (!target || !(target instanceof Element)) return;\n\n // Clicking a <label> operates the control it labels — record THAT, not \"clicked\n // label\", so the event reads as the user's actual intent.\n const label = target.closest('label');\n const labelled = label\n ? (label.getAttribute('for') &&\n document.getElementById(label.getAttribute('for')!)) ||\n label.querySelector('input,select,textarea')\n : null;\n\n const actionable = labelled ?? target.closest(ACTIONABLE);\n // No actionable target — a click on text, a gutter, or blank space. That is not an\n // action; dropping it is the whole fix for the click-log noise.\n if (!actionable || isPrivate(actionable)) return;\n\n pushActivity({ type: 'click', summary: `clicked ${describe(actionable)}` });\n}\n\nfunction onSubmit(ev: Event) {\n const el = ev.target as Element | null;\n if (!el || isPrivate(el)) return;\n // The FORM was submitted — never its values.\n pushActivity({ type: 'submit', summary: `submitted ${describe(el)}` });\n}\n\n/**\n * A form field changed.\n *\n * The rule is the same as everywhere else and the temptation here is sharpest:\n * record THAT a field changed and WHICH field (its label), never WHAT it was\n * changed to. `change` fires on exactly the elements whose values are off-limits.\n *\n * One safe exception: a <select>, a checkbox, or a radio chose from a fixed, visible\n * set of options the agent can already see in the snapshot — \"Unpaid\", \"Shipped\".\n * That is a user *choice*, not typed data, so the chosen option's LABEL is fair to\n * include and is the useful part (\"filtered status to Shipped\"). Free-text and\n * numeric inputs get their label only.\n */\nfunction onChange(ev: Event) {\n const el = ev.target as (HTMLElement & { type?: string }) | null;\n if (!el || !(el instanceof Element) || isPrivate(el)) return;\n\n const tag = el.tagName;\n const type = (el as HTMLInputElement).type;\n\n // Never a password/hidden field, and isPrivate already covered data-mf-private.\n if (tag === 'INPUT' && (type === 'password' || type === 'hidden')) return;\n\n let summary = `changed ${describe(el)}`;\n\n if (tag === 'SELECT') {\n const opt = (el as HTMLSelectElement).selectedOptions[0]?.text;\n if (opt) summary = `${describe(el)} → \"${redact(opt)}\"`;\n } else if (type === 'checkbox' || type === 'radio') {\n summary = `${(el as HTMLInputElement).checked ? 'checked' : 'unchecked'} ${describe(el)}`;\n }\n\n pushActivity({ type: 'input', summary });\n}\n\n/**\n * SPA navigation. There is no event for `pushState`, so we wrap it — a 20-line job\n * that no library does better.\n */\nfunction watchNavigation() {\n const fire = () => {\n const url = location.pathname;\n if (url === lastUrl) return;\n lastUrl = url;\n pushActivity({ type: 'nav', summary: `navigated to ${url}` });\n publishContext();\n };\n\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = history[name];\n history[name] = function (\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const r = orig.apply(this, args);\n fire();\n return r;\n } as History[typeof name];\n }\n window.addEventListener('popstate', fire);\n}\n\n/* ─────────────────────────── focal context ────────────────────────────── */\n\n/**\n * Where the user's attention is, right now.\n *\n * This is the \"knows what you're doing\" layer, and it is deliberately small so it can\n * ride on every turn — where the full snapshot cannot. It is also the most sensitive:\n * `selection` is whatever the user highlighted, which could be their own email, so it\n * is redacted and respects data-mf-private like everything else. Focus and the\n * viewport are labels and refs — never a value.\n *\n * Held so the last-known focus can travel with a turn even between the (throttled)\n * push updates.\n */\nlet lastFocus: FocusContext = {};\n\nasync function readFocus(): Promise<FocusContext> {\n const focus: FocusContext = {};\n\n // Selection — the single strongest \"this is what I'm asking about\" signal.\n const sel = window.getSelection?.();\n if (sel && !sel.isCollapsed) {\n const anchor = sel.anchorNode?.parentElement ?? null;\n // Don't lift a selection out of a private region, and cap it — a user can select\n // the whole page.\n if (!anchor || !anchor.closest('[data-mf-private]')) {\n const text = sel.toString().trim().slice(0, 500);\n if (text) focus.selection = redact(text);\n }\n }\n\n // The control they're working in — its label, never its contents.\n const active = document.activeElement;\n if (\n active &&\n active !== document.body &&\n !isPrivate(active) &&\n !active.closest('[data-mf-private]')\n ) {\n const { snapshot } = await import('./dom/snapshot');\n void snapshot; // ensure the chunk that owns refFor is loaded before we describe\n focus.focused = {\n label: redact(describeControl(active)),\n role: active.getAttribute('role') || active.tagName.toLowerCase(),\n };\n }\n\n const doc = document.documentElement;\n const scrollable = doc.scrollHeight - doc.clientHeight;\n focus.scroll =\n scrollable > 0 ? Math.round((doc.scrollTop / scrollable) * 100) / 100 : 0;\n\n return focus;\n}\n\n/** A label for whatever is focused, reusing the same value-blind rules as activity. */\nfunction describeControl(el: Element): string {\n return describe(el);\n}\n\nlet focusTimer: ReturnType<typeof setTimeout> | null = null;\n\n/** Coalesce a burst of selection/focus/scroll events into one push. */\nfunction scheduleFocus() {\n if (focusTimer) return;\n focusTimer = setTimeout(async () => {\n focusTimer = null;\n lastFocus = await readFocus();\n send?.({ type: 'host.focus', focus: lastFocus });\n }, 250);\n}\n\n/* ───────────────────────────── snapshot ───────────────────────────────── */\n\nlet snapshotSeq = 0;\n\nexport async function sendSnapshot(emit: Send) {\n // The a11y walk is itself lazily imported: a host that only ever declares\n // PageContext and never lets the agent look at the page never downloads it.\n const { snapshot } = await import('./dom/snapshot');\n const { yaml, truncated, visibleRefs } = snapshot();\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // The viewport slice rides with the focus context so the agent can tell the few\n // things on screen from the whole tree it just received.\n lastFocus = { ...lastFocus, visibleRefs };\n emit({ type: 'host.focus', focus: lastFocus });\n}\n\n/**\n * Zoom in on one ref — the pull half of the model. The agent asks; we resolve the ref\n * to a live element and return just its sub-tree.\n */\nexport async function sendRegion(ref: string, emit: Send) {\n const { snapshotRegion, resolveRef } = await import('./dom/snapshot');\n const el = resolveRef(ref);\n if (!el) {\n emit({\n type: 'host.region',\n ref,\n yaml: '(this element is no longer on the page)',\n });\n return;\n }\n const { yaml } = snapshotRegion(el);\n emit({ type: 'host.region', ref, yaml: redact(yaml) });\n}\n\n/* ───────────────────────────── tools ──────────────────────────────────── */\n\n/**\n * v1 IS READ-ONLY.\n *\n * The page's content is untrusted — text on it can try to instruct the agent — and\n * the moment the agent can act, a bad answer becomes a bad ACTION. So no tool here\n * mutates the page yet. The call path exists, and the enforcement point is HERE (in\n * the page, where we control what actually happens) rather than in the widget, which\n * can be lied to.\n *\n * When write tools land: anything not `readOnly` gets a user confirmation, on every\n * call. Not \"unless the host opts out\" — every call, because the trigger may have\n * been written by the page.\n */\nexport async function callTool(call: ToolCall, emit: Send) {\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: false,\n error: 'Host tools are read-only in this version; no action was taken.',\n });\n}\n\n/* ───────────────────────────── auth ───────────────────────────────────── */\n\n/**\n * Hosted login, in a POPUP — and the popup is not a UX preference.\n *\n * Our iframe on acme.com gets a PARTITIONED cookie jar: it cannot see the user's\n * existing matterfact session, no matter that it is served from our own origin.\n * A popup, however, is a TOP-LEVEL window on app.matterfact.com — first-party, real\n * cookies, silent SSO if they are already signed in. It hands the token back by\n * postMessage and we forward it into the iframe.\n */\nexport function beginAuth(\n config: { origin: string; publishableKey: string },\n emit: Send,\n) {\n const w = window.open(\n `${config.origin}/embed/authorize?k=${encodeURIComponent(\n config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}`,\n 'mf_auth',\n 'width=460,height=640',\n );\n if (!w) return; // popup blocked; the widget shows its own \"sign in\" affordance\n\n const onMsg = (event: MessageEvent) => {\n if (event.origin !== config.origin) return;\n const d = event.data;\n if (d?.type !== 'mf:embed:auth') return;\n window.removeEventListener('message', onMsg);\n emit({ type: 'host.auth', token: d.token, expiresAt: d.expiresAt });\n };\n window.addEventListener('message', onMsg);\n}\n\n/* ───────────────────────────── start ──────────────────────────────────── */\n\nexport function start(emit: Send, origin?: string) {\n send = emit;\n widgetOrigin = origin || '';\n lastUrl = location.pathname;\n\n publishContext();\n watchNavigation();\n\n // Passive + capture: we observe, we never interfere with the host's own handling.\n document.addEventListener('click', onClick, { capture: true, passive: true });\n document.addEventListener('submit', onSubmit, {\n capture: true,\n passive: true,\n });\n // `change` fires on blur/commit for text inputs and immediately for select/\n // checkbox/radio — not on every keystroke, which is what we want: a settled\n // choice, not a stream of partial values.\n document.addEventListener('change', onChange, {\n capture: true,\n passive: true,\n });\n\n // Focal context: what the user is attending to. Coalesced (scheduleFocus), because\n // selectionchange and scroll fire in torrents.\n document.addEventListener('selectionchange', scheduleFocus, {\n passive: true,\n });\n document.addEventListener('focusin', scheduleFocus, {\n capture: true,\n passive: true,\n });\n window.addEventListener('scroll', scheduleFocus, {\n capture: true,\n passive: true,\n });\n\n const theme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light';\n emit({ type: 'host.theme', mode: theme });\n}\n","/**\n * The matterfact embed bridge protocol.\n *\n * This is the contract between the HOST PAGE (a customer's site, running our\n * loader) and the WIDGET (our chat, running in a cross-origin iframe on\n * app.matterfact.com).\n *\n * Two things to understand before changing anything here:\n *\n * 1. THE IFRAME CANNOT SEE THE PAGE. It is cross-origin — that is the entire\n * point of it. So every fact about the host page (its URL, its DOM, what the\n * user just did) reaches the agent only because the LOADER, which runs as\n * ordinary page JS and *can* see it, chose to send it. The loader is the eye;\n * the widget is the mouth.\n *\n * 2. THIS CONTRACT OUTLIVES THE IFRAME. The next tier is an in-page React SDK\n * with no iframe at all — and it will speak exactly this. If the message\n * shapes are right, \"deeper integration\" is a transport swap (postMessage ->\n * direct call), not a rewrite. So model the DOMAIN here, not the plumbing.\n */\n\nexport const PROTOCOL_VERSION = 1;\n\n/** Every message is namespaced so we never collide with the host page's own postMessage traffic. */\nexport const CHANNEL = 'mf-embed';\n\n/* ────────────────────────────── refs ──────────────────────────────────── */\n\n/**\n * A handle on a real element in the host page.\n *\n * Format and semantics are lifted from Playwright's ARIA snapshot (`ref=e12`),\n * for a specific reason: it is the element-handle syntax the frontier models have\n * seen most, via playwright-mcp. We are not being original here on purpose.\n *\n * The ref is an in-page expando plus a snapshot-scoped Map — never an attribute,\n * so it is invisible to the host page's CSS, its serialization, and its own\n * mutation observers. It is resolved back to an element by the LOADER; the agent\n * never touches the DOM, and never learns a selector.\n */\nexport type ElementRef = string; // 'e12'\n\n/* ──────────────────────────── host → widget ───────────────────────────── */\n\n/** Ambient facts about the page. Cheap, sent on every navigation. */\nexport interface PageContext {\n url?: string;\n /** A route PATTERN ('/orders/:id') beats a raw path — it tells the agent what KIND of page this is. */\n route?: string;\n path?: string;\n title?: string;\n locale?: string;\n /** 1–2 sentences, written the way you'd brief a colleague. The highest-value field by far. */\n description?: string;\n /** Things the page is about. These also become @-mentionable in the composer, for free. */\n entities?: PageEntity[];\n /** Allowlisted only. Never a dump of app state. */\n data?: Record<string, unknown>;\n}\n\nexport interface PageEntity {\n /** Host kinds are namespaced (`x:ticker`) so they can never collide with matterfact's own. */\n kind: string;\n id: string;\n label: string;\n /** Pre-rendered, agent-readable. Keep it short. */\n text?: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * A snapshot of the page as the agent sees it.\n *\n * `yaml` is Playwright's ARIA-snapshot rendering — role, accessible name, state,\n * and a ref on anything interactable:\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - button \"Export CSV\" [ref=e9]\n *\n * NOT raw HTML. A real page is tens of thousands of tokens of div soup, it gives\n * the model no handle to act with, and it is a prompt-injection firehose. The\n * a11y tree is a tenth the size and is the only signal that survives in-page —\n * `getEventListeners()` is DevTools-only, so listener-sniffing (the browser-use\n * approach) cannot see a single React handler on a real customer's app.\n */\nexport interface DomSnapshot {\n yaml: string;\n /** Monotonic. A ref is only valid within the snapshot that minted it. */\n seq: number;\n /** True when the walk hit its node budget and stopped. The agent must be told it is not seeing everything. */\n truncated: boolean;\n}\n\n/**\n * Where the user's attention is RIGHT NOW.\n *\n * This is the difference between an assistant that can read your page and one that\n * knows what you're doing. A full DOM snapshot answers \"what is on this screen\"; this\n * answers \"what are you looking at and working in\" — which is what a colleague\n * leaning over reads first. It is small, so it rides on every turn, where the full\n * snapshot does not.\n *\n * Every field here is a LABEL or a REF, never a value. `selection` is the sharpest\n * intent signal there is (\"this is the thing I'm asking about\"), and for exactly that\n * reason it is also where a user might have highlighted their own email — so it is\n * redacted and honours data-mf-private like everything else.\n */\nexport interface FocusContext {\n /** Text the user has selected. The single strongest \"I'm asking about this\" signal. Redacted. */\n selection?: string;\n /** The control the user is working IN — by label and ref, never its contents. */\n focused?: { ref?: ElementRef; label: string; role: string };\n /** The refs currently in the viewport: the handful of things actually on screen, out of the whole tree. */\n visibleRefs?: ElementRef[];\n /** How far down the page they are, 0–1. A cheap proxy for \"which part am I reading\". */\n scroll?: number;\n}\n\n/** Something the user did. Shaped after PostHog's autocapture — one readable line, not a replay frame. */\nexport interface ActivityEvent {\n seq: number;\n ts: number;\n type: 'nav' | 'click' | 'input' | 'submit' | 'selection' | 'custom';\n /** Human-readable: 'clicked button \"Export CSV\"'. Semantic, not coordinates. */\n summary: string;\n ref?: ElementRef;\n data?: Record<string, unknown>;\n}\n\n/**\n * A tool the HOST page exposes to the agent.\n *\n * Deliberately shaped as a superset of WebMCP (`navigator.modelContext`, W3C\n * WebML CG draft / Chrome origin trial). A customer who adopts WebMCP should be\n * able to hand us their existing tool declarations unchanged.\n */\nexport interface HostTool {\n name: string;\n description: string;\n /** JSON Schema. */\n inputSchema: Record<string, unknown>;\n /**\n * A read-only tool may run without asking. Anything that MUTATES the page\n * requires the user to confirm, every time — see the note on ToolCall.\n */\n readOnly?: boolean;\n}\n\nexport type HostToWidget =\n | { type: 'host.ready'; protocol: number; origin: string }\n | { type: 'host.context'; context: PageContext }\n | { type: 'host.focus'; focus: FocusContext }\n | { type: 'host.snapshot'; snapshot: DomSnapshot }\n | { type: 'host.region'; ref: ElementRef; yaml: string }\n | { type: 'host.activity'; events: ActivityEvent[] }\n | { type: 'host.tools'; tools: HostTool[] }\n | {\n type: 'host.toolResult';\n callId: string;\n ok: boolean;\n result?: unknown;\n error?: string;\n }\n | { type: 'host.auth'; token: string; expiresAt: number }\n | { type: 'host.theme'; mode: 'light' | 'dark' };\n\n/* ──────────────────────────── widget → host ───────────────────────────── */\n\n/**\n * The agent asking the host to do something.\n *\n * THE SECURITY MODEL, stated once: the page's content is UNTRUSTED. Text on the\n * page can try to instruct the agent, and the moment the agent can act, that stops\n * being a bad answer and becomes a bad ACTION. So:\n *\n * - v1 is READ-ONLY. `snapshot` and `activity` flow; no tool mutates the page.\n * - A tool that is not `readOnly` must be confirmed by the USER, every call. Not\n * \"unless the host opts out\" — every call. The trigger may have been written by\n * the page.\n * - The host is the enforcement point, not the widget. The widget can be lied to;\n * the loader runs in the page and decides what actually happens.\n */\nexport interface ToolCall {\n callId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\nexport type WidgetToHost =\n | { type: 'widget.ready'; protocol: number }\n /**\n * Ask for the FULL page snapshot. This is the agent PULLING detail, not us pushing\n * it: the focus context rides on every turn, but the whole tree is fetched only\n * when the agent decides it needs to look — cheaper, and it reads what's relevant\n * to the question instead of drowning in the footer nav every turn.\n */\n | { type: 'widget.requestSnapshot' }\n /** Zoom in: the a11y sub-tree under one ref (a table, a form, a card the agent cares about). */\n | { type: 'widget.readRegion'; ref: ElementRef }\n | { type: 'widget.callTool'; call: ToolCall }\n /** Chat opened/closed — the loader resizes the iframe and starts/stops observing. */\n | { type: 'widget.setOpen'; open: boolean }\n | { type: 'widget.resize'; height: number }\n /**\n * Maximize / restore. Expanded makes the iframe fill the viewport (with a small\n * margin) so the composer's `/` picker, mention previews, and the transcript have\n * room the corner popup can't give them. The loader owns the iframe size, so only\n * it can do this — `widget.resize` (height-only) can't widen the popup.\n */\n | { type: 'widget.setExpanded'; expanded: boolean }\n /**\n * Launcher drag. The widget tracks the gesture; the host only moves the element.\n *\n * It has to be this way round, and the reason is easy to get wrong: a press that starts\n * inside an iframe is implicitly captured by that iframe, so every pointermove and the\n * pointerup belong to the widget's document until the button comes up. The host cannot\n * see them at all — not even through an overlay of its own, because capture beats hit\n * testing. So the host cannot take over a drag mid-gesture; it can only be told.\n *\n * `dx`/`dy` are deltas in SCREEN coordinates, which is the other half of the trick:\n * client coordinates are measured against the iframe's own viewport, and the iframe is\n * being moved under the cursor as the drag proceeds — so the pointer would appear to\n * stop moving and the launcher would stall after one step. Screen coordinates are\n * absolute and immune to that feedback loop.\n */\n | { type: 'widget.dragStart' }\n | { type: 'widget.dragMove'; dx: number; dy: number }\n | { type: 'widget.dragEnd' }\n /**\n * Grow/shrink the iframe to fit the launcher's context menu. The collapsed launcher is\n * only ~64px tall, so a menu rendered inside it would be clipped by the iframe's own\n * bounds — the host has to make room before it can be seen. `widget.resize` can't do\n * this: it's height-only AND ignored while closed.\n */\n | { type: 'widget.setMenu'; open: boolean; height: number }\n /** Put the launcher back in the default corner and forget the dragged position. */\n | { type: 'widget.resetPos' }\n /** Get out of the way until the page reloads (a menu action, not a setting). */\n | { type: 'widget.hide' }\n /** The widget has no session; the host must run the hosted-login popup. */\n | { type: 'widget.needsAuth' };\n\n/* ───────────────────────────── envelope ───────────────────────────────── */\n\n/**\n * Everything on the wire is wrapped.\n *\n * `channel` keeps us out of the host page's own postMessage traffic (and out of\n * every other widget's). The receiver ALSO checks `event.origin` against an\n * allowlist and `event.source` against the expected window, on every single\n * message — a namespace is not a security boundary, it is a politeness.\n */\nexport interface Envelope<T> {\n channel: typeof CHANNEL;\n protocol: number;\n /** Correlates a response to its request; absent for notifications. */\n id?: string;\n payload: T;\n}\n\nexport function envelope<T>(payload: T, id?: string): Envelope<T> {\n return {\n channel: CHANNEL,\n protocol: PROTOCOL_VERSION,\n ...(id ? { id } : {}),\n payload,\n };\n}\n\nexport function isEnvelope(data: unknown): data is Envelope<unknown> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { channel?: unknown }).channel === CHANNEL\n );\n}\n","import {\n CHANNEL,\n PROTOCOL_VERSION,\n envelope,\n isEnvelope,\n type HostToWidget,\n type WidgetToHost,\n} from './protocol';\n\n/**\n * The matterfact embed loader.\n *\n * <script src=\"https://cdn.matterfact.com/embed.js\"\n * data-key=\"pk_live_acme_...\"\n * defer></script>\n *\n * This file runs on EVERY page load of a customer's site, so it is deliberately\n * tiny and deliberately dumb:\n *\n * - zero dependencies\n * - it does NOT read the DOM. The snapshot/activity code is a separate chunk,\n * fetched only when the user actually opens the chat. A customer should pay\n * nothing for a widget nobody clicked.\n * - it does NOT bundle React, or a CSS framework, or an RPC library.\n *\n * `iframe-resizer` is the thing you will be tempted to reach for here. It is\n * GPL-3.0 and cannot ship in this file. The ResizeObserver bridge below is the\n * fifteen lines it would have cost you anyway.\n */\n\n/** Returns a token this matterfact deployment's auth provider trusts (Firebase idToken,\n * Entra token, …). May be async; return null when there's no signed-in user. */\nexport type AuthTokenProvider = () => string | null | Promise<string | null>;\n\nexport interface LoaderConfig {\n publishableKey: string;\n /** Origin of the widget. Overridable for dev/self-hosted; defaults to production. */\n origin: string;\n theme: 'light' | 'dark' | 'auto';\n /** Optional label identifying THIS embedding, when one app embeds the agent in more\n * than one place (e.g. \"orders\" vs \"support\"). Stamped on runs/threads so usage and\n * history can be told apart per surface. Free-form; the app_id (from the session)\n * is the trusted half. */\n surface: string;\n /**\n * OPTIONAL host-auth passthrough, for TRUSTED first-party embeds (the admin portal,\n * EMC). When set, the host page already holds a token this deployment's auth provider\n * trusts (its Firebase idToken, an Entra token, …); the loader hands it to the widget\n * on `widget.needsAuth` instead of opening a sign-in popup. The backend still verifies\n * the token, so identity can't be forged — this only skips a redundant second sign-in.\n * Called on demand (so tokens can refresh). Absent ⇒ the popup/inline sign-in flow.\n * The `<script>` loader has no config here; it reads window.matterfact.getEmbedAuthToken\n * instead (see provideAuth).\n */\n authTokenProvider?: AuthTokenProvider;\n /**\n * Render INTO this element instead of floating in the corner — for a host that has its\n * own side panel, tool drawer or tab and wants the agent to live there.\n *\n * This inverts who owns the chrome. In corner mode the widget owns everything: it draws\n * its own launcher and it tells us how big to be (setOpen/setExpanded/resize). Inside\n * someone else's panel, both are theirs — a widget that resized its host's drawer, or\n * drew a second floating bubble inside it, is just broken. So here we fill the\n * container, ignore the size messages, and the widget skips the launcher and renders\n * the chat directly.\n *\n * The host also owns visibility: showing and hiding their own panel IS the open/close\n * control, so there is nothing for us to add.\n */\n container?: HTMLElement | null;\n}\n\nconst DEFAULT_ORIGIN = 'https://app.matterfact.com';\n\n/**\n * Has someone asked to see what the widget is doing? `?mfdev=1` on the HOST page.\n *\n * Driven by the host's own URL rather than a `data-` attribute on purpose: an engineer\n * debugging a page they didn't write can add a query param, but they cannot redeploy the\n * customer's site to change a script tag. It's also ephemeral — it lasts exactly as long\n * as that URL, so nobody can leave it on by accident.\n *\n * This only surfaces what the widget already collects FROM THE PAGE IT'S ON, to the\n * person whose page it is. It grants no access: the session, the origin allowlist and\n * the route scope are all enforced server-side and none of them consult this.\n */\nfunction devRequested(): boolean {\n try {\n return new URLSearchParams(location.search).get('mfdev') === '1';\n } catch {\n return false;\n }\n}\n\nfunction readConfig(): LoaderConfig | null {\n // `document.currentScript` is null inside a module or after async execution, so\n // fall back to finding our own tag by src.\n const el =\n (document.currentScript as HTMLScriptElement | null) ??\n document.querySelector<HTMLScriptElement>('script[data-key][src*=\"embed\"]');\n\n const publishableKey = el?.dataset.key;\n if (!publishableKey) {\n console.error('[matterfact] missing data-key on the embed script tag');\n return null;\n }\n // `data-container=\"#panel\"` renders into the host's own element instead of the\n // corner. A selector rather than an element, because a script tag can't hand us a\n // reference — and if it doesn't resolve we fall back to the corner rather than\n // vanish: a widget nobody can find looks identical to a broken install.\n const sel = el?.dataset.container;\n const container = sel ? document.querySelector<HTMLElement>(sel) : null;\n if (sel && !container) {\n console.error(\n `[matterfact] data-container=\"${sel}\" matched nothing; falling back to the corner`,\n );\n }\n\n return {\n publishableKey,\n origin: el?.dataset.origin || DEFAULT_ORIGIN,\n theme: (el?.dataset.theme as LoaderConfig['theme']) || 'auto',\n surface: el?.dataset.surface || '',\n container,\n };\n}\n\n/** Where the user dragged the launcher, in px from the viewport's bottom-right. */\ninterface DragPos {\n right: number;\n bottom: number;\n}\n\nconst POS_KEY = 'mf.embed.pos';\n\nclass EmbedHost {\n private iframe: HTMLIFrameElement | null = null;\n private shadow: ShadowRoot | null = null;\n /** Buffered until the widget says it's listening — postMessage before load is dropped silently. */\n private queue: HostToWidget[] = [];\n private ready = false;\n private open = false;\n private expanded = false;\n /** Null until the user drags; then it pins the corner offset and survives reloads. */\n private pos: DragPos | null = null;\n /** Where the launcher sat when the current drag began; deltas are applied to this. */\n private dragBase: DragPos | null = null;\n /** Loaded on first open. Holds everything that touches the customer's DOM. */\n private context: Promise<typeof import('./context')> | null = null;\n /** The host element; kept so `destroy()` can remove it (React lifecycle). */\n private hostEl: HTMLDivElement | null = null;\n /** Rendering into the host's own element: they own the box, the chrome and visibility. */\n private readonly inline: boolean;\n\n constructor(private config: LoaderConfig) {\n this.inline = !!config.container;\n }\n\n mount() {\n // A CLOSED shadow root, on a container that resets every inherited property.\n //\n // We are a guest on someone else's page. Their CSS must not reach into us, our\n // CSS must not leak out, and their JS should not be able to walk into our tree\n // by accident (closed mode: `host.shadowRoot` is null). `contain` stops our\n // layout/paint from invalidating theirs.\n const host = document.createElement('div');\n this.hostEl = host;\n host.id = 'matterfact-embed';\n\n if (this.inline) {\n // The container's box IS the widget's box. No fixed positioning, no z-index\n // scramble, no drag: where this sits is the host's layout problem, which is the\n // entire point of asking for it.\n host.style.cssText = [\n 'all: initial',\n 'position: relative',\n 'display: block',\n 'width: 100%',\n 'height: 100%',\n 'contain: layout style',\n ].join(';');\n this.config.container!.appendChild(host);\n } else {\n this.pos = this.readPos();\n host.style.cssText = [\n 'all: initial',\n 'position: fixed',\n `right: ${this.pos ? this.pos.right : 20}px`,\n `bottom: ${this.pos ? this.pos.bottom : 20}px`,\n // Below the max so a host that genuinely needs to cover us (a modal, a cookie\n // banner they are legally obliged to show) still can.\n 'z-index: 2147483000',\n 'contain: layout style',\n ].join(';');\n document.body.appendChild(host);\n }\n\n this.shadow = host.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n // Shared prefix, then only what differs. This ships on every page load and the stub\n // has ~no headroom, so the two modes must not each carry a whole stylesheet.\n //\n // Inline fills the host's box and adds nothing: no radius, no shadow. Their panel\n // already has whatever chrome they chose; ours would sit inside it looking like a\n // mistake.\n style.textContent =\n ':host{all:initial}iframe{border:0;display:block;color-scheme:light dark;}' +\n (this.inline\n ? 'iframe{width:100%;height:100%}'\n : // Hairline ring + soft ambient: the widget must read as a crisp card on\n // ANY host background, including pure white where a shadow alone bleeds.\n 'iframe{border-radius:12px;box-shadow:0 0 0 1px #00000014,0 8px 40px #00000029;width:400px;' +\n 'height:64px;transition:height .18s ease,width .18s ease}' +\n 'iframe[data-open=\"true\"]{width:420px;height:640px}' +\n // Expanded: a full-height SIDE PANEL docked to the host's right edge, not a\n // viewport-covering overlay — room for the composer's slash-picker and mention\n // previews, capped to the viewport on narrow screens.\n 'iframe[data-open=\"true\"][data-expanded=\"true\"]{width:min(600px,calc(100vw - 40px));' +\n 'height:calc(100vh - 40px)}');\n this.shadow.appendChild(style);\n\n const iframe = document.createElement('iframe');\n iframe.title = 'matterfact assistant';\n //\n // `allow-same-origin` is REQUIRED, and leaving it out is the trap.\n //\n // Without it the framed document gets an OPAQUE origin: its postMessage arrives\n // as `event.origin === \"null\"`, so our own origin check rejects the handshake and\n // the bridge silently never connects. It also denies the widget any storage at\n // all — no session, no auth, ever.\n //\n // The familiar warning — \"allow-scripts + allow-same-origin lets the frame escape\n // its sandbox\" — is about a frame that is SAME-ORIGIN WITH THE FRAMER, which can\n // then reach up and delete its own sandbox attribute. Ours is cross-origin to the\n // host by construction (that is the entire security model), so it cannot touch\n // this element. What the sandbox still buys us is real: no top-level navigation,\n // no downloads, no pointer lock.\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox',\n );\n // Dictation needs an explicit permissions-policy grant: without `allow`,\n // getUserMedia inside the frame is hard-blocked no matter what the user\n // approves. The bare token scopes the grant to the iframe's own origin\n // (the app), not the host page. A host page can still deny the feature\n // via its own Permissions-Policy response header — outside our control.\n iframe.setAttribute('allow', 'microphone');\n iframe.src =\n `${this.config.origin}/embed/chat?k=${encodeURIComponent(\n this.config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}` +\n (this.config.surface\n ? `&s=${encodeURIComponent(this.config.surface)}`\n : '') +\n (devRequested() ? '&dev=1' : '') +\n (this.inline ? '&inline=1' : '');\n this.iframe = iframe;\n this.shadow.appendChild(iframe);\n\n window.addEventListener('message', this.onMessage);\n }\n\n /**\n * Every message is checked twice, on every single message — not once at setup.\n *\n * `channel` is a namespace, not a boundary. The origin and source checks are the\n * boundary: any frame on the page can postMessage us, and a page with an ad iframe\n * on it has plenty of frames.\n */\n private onMessage = (event: MessageEvent) => {\n if (event.origin !== this.config.origin) return;\n if (event.source !== this.iframe?.contentWindow) return;\n if (!isEnvelope(event.data)) return;\n\n const msg = event.data.payload as WidgetToHost;\n\n switch (msg.type) {\n case 'widget.ready':\n this.ready = true;\n this.send({\n type: 'host.ready',\n protocol: PROTOCOL_VERSION,\n origin: location.origin,\n });\n this.flush();\n // Inline has no \"open\" event to hang this off — the chat is visible the moment\n // the host renders their panel, so the eye has to load now or the agent is\n // blind to the page for the whole session. The corner keeps its lazy load: a\n // page whose visitors never click still pays nothing.\n if (this.inline) void this.loadContext();\n break;\n\n case 'widget.setOpen':\n // Inline: the host's panel IS the open/close control. There's no popup to size.\n if (this.inline) break;\n this.open = msg.open;\n this.iframe?.setAttribute('data-open', String(msg.open));\n // Closing the popup always restores it — a widget that reopens should start\n // at the corner size, not wherever it was maximized to last time.\n if (!msg.open) {\n this.expanded = false;\n this.iframe?.setAttribute('data-expanded', 'false');\n }\n // The DOM code is fetched HERE — the first time someone actually opens the\n // chat — and never on a page where they don't.\n if (msg.open) void this.loadContext();\n break;\n\n case 'widget.setExpanded':\n // Inline: \"maximize\" would mean resizing someone else's panel from inside it.\n if (this.inline) break;\n this.expanded = msg.expanded;\n this.iframe?.setAttribute('data-expanded', String(msg.expanded));\n // A prior widget.resize set an inline height; clear it so the maximized CSS\n // (and, on restore, the popup CSS) wins.\n if (this.iframe) this.iframe.style.height = '';\n break;\n\n case 'widget.resize':\n // Inline: the container's height is the host's business, and an auto-grow here\n // would fight their layout every time the transcript got longer.\n if (this.inline) break;\n // Height auto-grow is for the corner popup only; when maximized the CSS owns\n // the size, so don't let a resize shrink it back.\n if (this.iframe && this.open && !this.expanded) {\n this.iframe.style.height = `${Math.min(msg.height, window.innerHeight - 40)}px`;\n }\n break;\n\n case 'widget.requestSnapshot':\n void this.loadContext().then((m) => m.sendSnapshot(this.send));\n break;\n\n case 'widget.readRegion':\n void this.loadContext().then((m) => m.sendRegion(msg.ref, this.send));\n break;\n\n case 'widget.callTool':\n void this.loadContext().then((m) => m.callTool(msg.call, this.send));\n break;\n\n // Everything below is LAUNCHER chrome: there is no launcher inline (the widget\n // doesn't draw one), and moving or hiding the host's own panel from inside it\n // would be us redecorating their app. An older cached loader could still be told\n // any of these by a newer widget, so they're guarded rather than assumed absent.\n case 'widget.dragStart':\n if (this.inline) break;\n this.dragBase = this.cornerOffset();\n break;\n\n case 'widget.dragMove':\n if (this.inline) break;\n this.dragTo(msg.dx, msg.dy);\n break;\n\n case 'widget.dragEnd':\n if (this.inline) break;\n this.dragBase = null;\n this.writePos(this.pos);\n break;\n\n case 'widget.setMenu':\n if (this.inline) break;\n // Make room for the launcher's menu. Only meaningful while collapsed — open,\n // the popup is already taller than any menu.\n if (this.iframe && !this.open) {\n this.iframe.style.height = msg.open ? `${64 + msg.height}px` : '';\n }\n break;\n\n case 'widget.resetPos':\n if (this.inline) break;\n this.resetPos();\n break;\n\n case 'widget.hide':\n // Inline: hiding is the host's panel to hide. Blanking their drawer from in\n // here would leave them with an empty box and no way to get it back.\n if (this.inline) break;\n if (this.hostEl) this.hostEl.style.display = 'none';\n break;\n\n case 'widget.needsAuth':\n void this.provideAuth();\n break;\n }\n };\n\n /**\n * Own a drag for its lifetime.\n *\n * The widget reports the press and then goes quiet: a cross-origin iframe only gets\n * pointer events while the pointer is over it, and a drag leaves that box immediately.\n * So we lay a transparent layer over the whole viewport and track the gesture in the\n * host document, where it can't be lost. The layer also stops the pointer landing on\n * the customer's own UI mid-drag (text selection, hover states, stray clicks).\n *\n * We are the dumb half on purpose — see `widget.dragMove` in the protocol for why the\n * widget has to own the gesture. All we do is take a delta and place the element.\n */\n private cornerOffset(): DragPos {\n const rect = this.hostEl!.getBoundingClientRect();\n return {\n right: window.innerWidth - rect.right,\n bottom: window.innerHeight - rect.bottom,\n };\n }\n\n private dragTo(dx: number, dy: number) {\n if (!this.dragBase || !this.hostEl) return;\n const rect = this.hostEl.getBoundingClientRect();\n // Clamp to the viewport: the position persists, so letting someone drop the launcher\n // off-screen would strand it there across reloads with no way back to it.\n const maxRight = Math.max(0, window.innerWidth - rect.width);\n const maxBottom = Math.max(0, window.innerHeight - rect.height);\n const right = Math.min(Math.max(0, this.dragBase.right - dx), maxRight);\n const bottom = Math.min(Math.max(0, this.dragBase.bottom - dy), maxBottom);\n this.pos = { right, bottom };\n this.hostEl.style.right = `${right}px`;\n this.hostEl.style.bottom = `${bottom}px`;\n }\n\n /** Reset to the default corner (a menu action — the drag is otherwise sticky). */\n private resetPos() {\n this.pos = null;\n this.writePos(null);\n if (this.hostEl) {\n this.hostEl.style.right = '20px';\n this.hostEl.style.bottom = '20px';\n }\n }\n\n private readPos(): DragPos | null {\n // First-party storage on the CUSTOMER's origin, so each site remembers its own spot.\n // Never throws: storage is unavailable in some embedding contexts, and a widget that\n // can't remember where it was put is fine — one that fails to mount is not.\n try {\n const raw = localStorage.getItem(POS_KEY);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<DragPos>;\n return typeof p?.right === 'number' && typeof p?.bottom === 'number'\n ? { right: p.right, bottom: p.bottom }\n : null;\n } catch {\n return null;\n }\n }\n\n private writePos(pos: DragPos | null) {\n try {\n if (pos) localStorage.setItem(POS_KEY, JSON.stringify(pos));\n else localStorage.removeItem(POS_KEY);\n } catch {\n /* storage denied — the position just won't survive the reload */\n }\n }\n\n /**\n * Answer `widget.needsAuth`. If a trusted first-party host has an auth-token provider,\n * call it and hand the token straight to the widget via `host.auth` — no popup. The\n * provider comes from EITHER the programmatic config (the React `<MatterfactAgent\n * getAuthToken>` prop) OR a global the host page sets for the `<script>` loader:\n *\n * window.matterfact = { getEmbedAuthToken: () => getIdToken(user) };\n *\n * Read fresh at call time (not at readConfig), so a global set after the loader booted\n * — e.g. once the host's auth is ready — is still picked up. Otherwise fall back to the\n * hosted-login popup. `expiresAt: 0`: the widget doesn't cache it, it exchanges the\n * token for a rotating embed session anyway.\n */\n private async provideAuth() {\n const provider =\n this.config.authTokenProvider ??\n (globalThis as { matterfact?: { getEmbedAuthToken?: AuthTokenProvider } })\n .matterfact?.getEmbedAuthToken;\n if (provider) {\n try {\n const token = await provider();\n if (token) {\n this.send({ type: 'host.auth', token, expiresAt: 0 });\n return;\n }\n } catch {\n /* fall through to the popup */\n }\n }\n void this.loadContext().then((m) => m.beginAuth(this.config, this.send));\n }\n\n private loadContext() {\n // One chunk, one fetch, cached. Everything that can see the customer's page\n // lives behind this boundary.\n this.context ??= import('./context').then((m) => {\n m.start(this.send, this.config.origin);\n // start() emits the OS-preference theme. An explicit data-theme on the\n // script tag is the host's choice — resend it so it wins over auto-detect\n // (a light-branded site must be able to force a light widget on a dark-OS\n // visitor, and vice versa).\n if (this.config.theme !== 'auto') {\n this.send({ type: 'host.theme', mode: this.config.theme });\n }\n return m;\n });\n return this.context;\n }\n\n private send = (msg: HostToWidget) => {\n if (!this.ready) {\n this.queue.push(msg);\n return;\n }\n // targetOrigin is the widget's exact origin — never '*'. A '*' here would\n // broadcast the customer's page content to whatever happens to be listening.\n this.iframe?.contentWindow?.postMessage(envelope(msg), this.config.origin);\n };\n\n private flush() {\n const pending = this.queue;\n this.queue = [];\n for (const m of pending) this.send(m);\n }\n\n /** Tear down: stop listening and remove the host element. For the React wrapper's\n * unmount — the vanilla `<script>` loader lives for the page's lifetime and never\n * calls this. */\n destroy() {\n window.removeEventListener('message', this.onMessage);\n this.hostEl?.remove();\n this.hostEl = null;\n this.iframe = null;\n this.shadow = null;\n this.ready = false;\n }\n}\n\n/**\n * Programmatic entry — mount the widget from a config object instead of the DOM\n * `<script data-*>`. This is what the React wrapper (`@matterfact/embed/react`) drives;\n * the vanilla loader below reads the script tag and calls this same class.\n */\nexport function mount(config: LoaderConfig): EmbedHost {\n const host = new EmbedHost(config);\n host.mount();\n return host;\n}\n\nexport { EmbedHost, CHANNEL, readConfig };\n"]}
1
+ {"version":3,"sources":["../src/dom/a11y.ts","../src/dom/refs.ts","../src/dom/snapshot.ts","../src/context.ts","../src/protocol.ts","../src/loader.ts"],"names":["isDisabled","getRole","computeAccessibleName","isInaccessible","snapshot","snapshotRegion","resolveRef"],"mappings":";;;;;;;;;;;;;AAkCO,SAAS,gBAAA,GAA4B;AAC1C,EAAA,MAAM,KAAA,uBAAY,OAAA,EAAsC;AACxD,EAAA,QAAQ,CAAC,IAAa,MAAA,KAAgD;AAEpE,IAAA,IAAI,MAAA,EAAQ,OAAO,MAAA,CAAO,gBAAA,CAAiB,IAAI,MAAM,CAAA;AACrD,IAAA,IAAI,KAAA,GAAQ,KAAA,CAAM,GAAA,CAAI,EAAE,CAAA;AACxB,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,KAAA,GAAQ,MAAA,CAAO,iBAAiB,EAAE,CAAA;AAClC,MAAA,KAAA,CAAM,GAAA,CAAI,IAAI,KAAK,CAAA;AAAA,IACrB;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AACF;AAYO,SAAS,SAAA,GAAqB;AACnC,EAAA,OAAO,QAAA,CAAS,eAAA,CAAgB,cAAA,EAAe,CAAE,MAAA,GAAS,CAAA;AAC5D;AAWO,SAAS,SAAA,CACd,EAAA,EACA,KAAA,EACA,MAAA,EACS;AACT,E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;AACT","file":"index.cjs","sourcesContent":["import {\n computeAccessibleName,\n getRole,\n isDisabled,\n} from 'dom-accessibility-api';\n\n/**\n * Role, name, visibility, interactability, state.\n *\n * WHAT WE ADOPTED: role and accessible name come from `dom-accessibility-api`\n * (MIT, zero deps) — the engine behind testing-library's `getByRole`. Accessible\n * name is a genuinely hard spec (accname walks aria-labelledby graphs, ::before\n * content, <label> associations, alt/title fallbacks, and recursive\n * name-from-content) and a hand-rolled version is wrong in ways you only discover\n * on a customer's page.\n *\n * WHAT WE BUILT: everything below that. Visibility and pointer-events are ~20 lines\n * from first principles (see `isVisible`/`receivesPointerEvents`) and the state\n * reads are direct DOM/ARIA reads, so we vendored nothing and took on no\n * Apache-2.0 attribution obligation.\n */\n\n/** A memoised `getComputedStyle`, shaped to be passed straight to accname. */\nexport type StyleOf = typeof window.getComputedStyle;\n\n/**\n * One computed style per element per snapshot.\n *\n * Not a micro-optimisation: `computeAccessibleName` calls back into\n * getComputedStyle for every descendant it walks while building a name from\n * content, so on a page of nested divs the uncached cost is quadratic-ish. The\n * cache is per-snapshot (a fresh WeakMap each walk), so it can never go stale\n * across snapshots.\n */\nexport function createStyleCache(): StyleOf {\n const cache = new WeakMap<Element, CSSStyleDeclaration>();\n return ((el: Element, pseudo?: string | null): CSSStyleDeclaration => {\n // Pseudo-element lookups are rare and must not poison the element cache.\n if (pseudo) return window.getComputedStyle(el, pseudo);\n let style = cache.get(el);\n if (!style) {\n style = window.getComputedStyle(el);\n cache.set(el, style);\n }\n return style;\n }) as StyleOf;\n}\n\n/**\n * Does this environment do layout at all?\n *\n * In a browser the root element always has a box. In jsdom — which has no layout\n * engine — *everything* reports zero client rects, so a box-based visibility check\n * would hide the entire page and our tests would assert on an empty snapshot. So we\n * feature-detect layout once per walk and fall back to style-only visibility when\n * there is none. This is a test-environment concession, stated out loud rather than\n * hidden behind a mock.\n */\nexport function hasLayout(): boolean {\n return document.documentElement.getClientRects().length > 0;\n}\n\n/**\n * Visible enough to be worth telling the agent about.\n *\n * `display` and `visibility` are read from the computed style, which already\n * accounts for inheritance — and because the walk is top-down and prunes whole\n * subtrees, we never pay for an ancestor walk. `display: contents` is the one\n * subtlety: such an element generates no box of its own but its children do, so it\n * must not be treated as invisible or we would drop a real subtree.\n */\nexport function isVisible(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n const display = style.display;\n if (display === 'none') return false;\n\n const visibility = style.visibility;\n if (visibility === 'hidden' || visibility === 'collapse') return false;\n\n // `opacity: 0` is a standard \"hide from sight, keep for a11y\" technique. It still\n // reports a box, so the area check below misses it. We treat fully-transparent as\n // hidden; a partially-transparent element is genuinely on screen.\n if (Number(style.opacity) === 0) return false;\n\n // A `display: contents` element generates no box of its own but its children do,\n // so it must not be judged by its own (nonexistent) geometry — we let it through\n // and test each child on its own merits.\n if (layout && display !== 'contents') {\n // Area, not merely \"has a box\": `width:0;height:0;overflow:hidden` is one of the\n // commonest ways to hide a thing, and such an element still reports a client\n // rect. This is the check Playwright's own isVisible() makes.\n const box = el.getBoundingClientRect();\n if (box.width <= 0 || box.height <= 0) return false;\n\n // The sr-only / visually-hidden family: `clip: rect(0 0 0 0)` and its modern\n // `clip-path: inset(50%)` shrink the element to nothing while keeping a 1px box,\n // and `position:absolute; left:-9999px` parks it far off any real page. All three\n // are \"screen-reader only\" idioms — present for a11y, not for sight — so an agent\n // reading the page should skip them too. (getClientRects().length === 0 catches\n // the clipped ones; the far-offscreen check catches the parked ones.)\n if (el.getClientRects().length === 0) return false;\n if (box.right < -2000 || box.bottom < -2000) return false;\n }\n\n return true;\n}\n\n/**\n * Can a pointer actually reach it?\n *\n * `pointer-events` is an INHERITED property, so the computed value on the element\n * already encodes every ancestor's `pointer-events: none` — and correctly honours a\n * descendant that opts back in with `pointer-events: auto`. That is the whole check:\n * no ancestor walk, no hit-test. We deliberately do NOT test for occlusion (is\n * something painted on top of it) the way Playwright's actionability check does —\n * we are describing the page, not clicking it, and an element under a sticky header\n * is still worth telling the agent about.\n */\nexport function receivesPointerEvents(style: CSSStyleDeclaration): boolean {\n return style.pointerEvents !== 'none';\n}\n\n/** Roles that are inherently operable. */\nconst INTERACTIVE_ROLES = new Set([\n 'button',\n 'checkbox',\n 'combobox',\n 'link',\n 'listbox',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'searchbox',\n 'slider',\n 'spinbutton',\n 'switch',\n 'tab',\n 'textbox',\n 'treeitem',\n]);\n\n/** Tags that are operable regardless of what role they compute to. */\nconst INTERACTIVE_TAGS = new Set([\n 'BUTTON',\n 'INPUT',\n 'SELECT',\n 'TEXTAREA',\n 'SUMMARY',\n]);\n\n/** `contenteditable` — present and not explicitly \"false\" (covers \"\", \"true\", \"plaintext-only\"). */\nexport function isEditable(el: Element): boolean {\n const v = el.getAttribute('contenteditable');\n return v !== null && v !== 'false';\n}\n\n/**\n * Is this element something the user can operate?\n *\n * THIS IS THE INTERESTING FUNCTION, so here is the reasoning in full.\n *\n * The obvious way to answer it — ask the DOM what event listeners are attached —\n * IS NOT AVAILABLE. `getEventListeners()` exists only inside DevTools (and via CDP).\n * We are ordinary page JS on a customer's website, so every `addEventListener` a\n * React, Vue or Svelte app ever registered is, to us, completely invisible. This is\n * precisely where the browser-use style of in-page DOM extraction degrades on real\n * apps: it cannot see a single handler, so it either misses the app's controls or\n * guesses wildly. We therefore never ask \"does it have a handler\"; we ask \"does it\n * PRESENT ITSELF as operable\", in four descending tiers of confidence:\n *\n * 1. TAG SEMANTICS (certain). button, input, select, textarea, summary, a[href].\n * 2. COMPUTED ROLE (certain). role=button|link|checkbox|… whether implicit or\n * author-supplied. A div with role=\"button\" is a\n * button as far as the platform, a screen reader,\n * and the user are concerned.\n * 3. FOCUSABILITY (strong). tabindex >= 0, or contenteditable. An app that\n * made a div keyboard-reachable did so on purpose.\n * 4. `cursor: pointer` (WEAK). Last resort, and the reason for the guard below.\n *\n * Tier 4 needs care, because `cursor` is INHERITED: a card with `cursor: pointer`\n * makes every span, every icon and every text node inside it report `pointer` too,\n * and a naive check would mint a ref for each of them and drown the snapshot. So we\n * only count the element that *introduced* the pointer cursor — the one whose parent\n * did not already have it. That is almost exactly the clickable card itself.\n */\nexport function isInteractive(\n el: Element,\n role: string | null,\n style: CSSStyleDeclaration,\n parentStyle: CSSStyleDeclaration | null,\n): boolean {\n const tag = el.tagName;\n\n // 1. tag semantics\n // An <a href> is interactive, but a hrefless <a> is NOT a dead end — it may be a\n // JS-nav link, an <a role=\"button\">, or a Bootstrap `.btn` anchor. So href is a\n // positive signal, not a gate: fall through to the role/tabindex/cursor tiers\n // rather than returning false and dropping every SPA link.\n if (tag === 'A' && el.hasAttribute('href')) return true;\n if (INTERACTIVE_TAGS.has(tag)) return true;\n\n // 2. computed role\n if (role !== null && INTERACTIVE_ROLES.has(role)) return true;\n\n // 3. focusability\n const tabindex = el.getAttribute('tabindex');\n if (tabindex !== null && Number(tabindex) >= 0) return true;\n if (isEditable(el)) return true;\n\n // 4. cursor: pointer, but only where it originates (see above)\n if (style.cursor === 'pointer' && parentStyle?.cursor !== 'pointer')\n return true;\n\n return false;\n}\n\n/**\n * Roles whose accessible name IS their text content (ARIA \"Name From: contents\").\n *\n * This is the exact list from the ARIA spec, and it earns its place: it is what tells\n * the walk that the \"Export CSV\" inside `<button>Export CSV</button>` has ALREADY been\n * emitted, as the button's name, and must not be repeated as a child text node.\n *\n * The tempting shortcut — \"skip any text that appears inside the parent's name\" — is\n * wrong, and wrong in a way that silently deletes content: a card labelled\n * `aria-label=\"Acme Corp order\"` containing the text \"Acme Corp\" would lose it,\n * because one is a substring of the other by coincidence. Ask the role, not the string.\n */\nexport const NAME_FROM_CONTENT = new Set([\n 'button',\n 'cell',\n 'checkbox',\n 'columnheader',\n 'gridcell',\n 'heading',\n 'link',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'row',\n 'rowheader',\n 'switch',\n 'tab',\n 'tooltip',\n 'treeitem',\n]);\n\n/* ─────────────────────────────── state ────────────────────────────────── */\n\n/** Roles whose content IS the user's data. We report that a value exists, never what it is. */\nconst VALUE_ROLES = new Set(['textbox', 'searchbox', 'spinbutton']);\n\n/**\n * Roles we refuse to descend into, because their children/content ARE the value.\n *\n * A `<textarea>`'s child text node is literally what the user typed; a\n * contenteditable's subtree is the document they are writing. Refusing to walk in is\n * how \"never emit a value\" is enforced STRUCTURALLY, rather than by remembering to\n * filter at every emit site.\n *\n * `<select>` is deliberately NOT here. Its options are a bounded, author-defined\n * enumeration — the affordance the agent most needs (\"what can I set this to\"), not\n * the free-text user data the opaque rule exists to contain. The snapshot emits them\n * directly instead (capped, selected one marked): see emitSelectOptions in\n * snapshot.ts.\n */\nconst OPAQUE_TAGS = new Set(['INPUT', 'TEXTAREA']);\n\nexport function isOpaque(el: Element): boolean {\n return OPAQUE_TAGS.has(el.tagName) || isEditable(el);\n}\n\n/**\n * Has the user put something in this field?\n *\n * `.value` is read and immediately thrown away — only its LENGTH escapes. This is\n * the single most useful bit about a form (\"is the email box already filled in?\")\n * and the single most dangerous string on the page, so it is reduced to one bit at\n * the point of reading and never travels.\n */\nfunction isFilled(el: Element, role: string): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA') {\n if (!VALUE_ROLES.has(role)) return false; // checkbox.value is \"on\" — meaningless\n return ((el as HTMLInputElement).value ?? '').length > 0;\n }\n if (isEditable(el)) return (el.textContent ?? '').trim().length > 0;\n return false;\n}\n\nfunction ariaFlag(el: Element, attr: string): 'true' | 'mixed' | null {\n const v = el.getAttribute(attr);\n if (v === 'true') return 'true';\n if (v === 'mixed') return 'mixed';\n return null;\n}\n\n/**\n * The bracketed attributes, in Playwright's order:\n * [checked] [disabled] [expanded] [level=N] [pressed] [selected]\n * plus our one addition, [filled] — see isFilled. `[ref=eN]` is appended by the\n * caller and always comes last.\n */\nexport function states(el: Element, role: string): string {\n const out: string[] = [];\n const tag = el.tagName;\n\n // checked\n if (tag === 'INPUT' && (role === 'checkbox' || role === 'radio')) {\n if ((el as HTMLInputElement).checked) out.push('[checked]');\n } else {\n const checked = ariaFlag(el, 'aria-checked');\n if (checked === 'mixed') out.push('[checked=mixed]');\n else if (checked === 'true') out.push('[checked]');\n }\n\n // disabled — dom-accessibility-api handles fieldset/optgroup inheritance and aria-disabled\n if (isDisabled(el)) out.push('[disabled]');\n\n // expanded — <summary> reflects its parent <details>, which has no ARIA attribute\n const expanded = el.getAttribute('aria-expanded');\n if (expanded === 'true' || expanded === 'false') {\n if (expanded === 'true') out.push('[expanded]');\n } else if (tag === 'SUMMARY') {\n const details = el.parentElement;\n if (\n details?.tagName === 'DETAILS' &&\n (details as HTMLDetailsElement).open\n ) {\n out.push('[expanded]');\n }\n }\n\n // level\n if (role === 'heading') {\n const aria = el.getAttribute('aria-level');\n const level = aria ? Number(aria) : Number(tag[1]);\n if (Number.isFinite(level) && level > 0) out.push(`[level=${level}]`);\n }\n\n // pressed\n const pressed = ariaFlag(el, 'aria-pressed');\n if (pressed === 'mixed') out.push('[pressed=mixed]');\n else if (pressed === 'true') out.push('[pressed]');\n\n // selected\n if (el.getAttribute('aria-selected') === 'true') out.push('[selected]');\n\n // filled (ours — a boolean, never the value)\n if (isFilled(el, role)) out.push('[filled]');\n\n return out.join(' ');\n}\n\n/* ─────────────────────────── role & name ──────────────────────────────── */\n\n/**\n * The computed role, with one correction.\n *\n * `getRole` follows HTML-AAM and returns null for a contenteditable div — but every\n * real browser exposes it to assistive tech as a textbox, and that is what it is to\n * the user and to the agent. We say textbox.\n */\nexport function roleOf(el: Element): string | null {\n if (isEditable(el)) return 'textbox';\n return getRole(el);\n}\n\n/**\n * Selector for anything whose CONTENT is the user's data — a form control, a\n * contenteditable, a valued widget, or a host-marked private region.\n */\nconst UNTRUSTED_CONTENT =\n 'input,textarea,select,[contenteditable=\"\"],[contenteditable=\"true\"],[aria-valuetext],[data-mf-private]';\n\n/**\n * Would computing this element's ACCESSIBLE NAME read the user's data?\n *\n * This is the leak the structural `isOpaque` walk cannot see. `computeAccessibleName`\n * runs its OWN descendant walk, inside dom-accessibility-api, that knows nothing about\n * our opaque set or `data-mf-private` — it will happily read `input.value`,\n * `aria-valuetext`, a contenteditable's text, or a private subtree, and fold it into\n * the name of a name-from-content ANCESTOR or any `aria-labelledby` referrer. So a\n * value our walk refuses to enter re-enters through the parent's name.\n *\n * Two vectors, both handled:\n * - name-from-content: the name is built from descendant text. If any descendant is\n * untrusted, the name is tainted.\n * - aria-labelledby: the name is pulled from a referenced element. If any referent\n * is (or contains) untrusted content, the name is tainted.\n *\n * `aria-label` and `title` are author-written static strings; a site that copies its\n * own secret into one is exposing it deliberately and we cannot defend that. The\n * automatic-computation vectors are the ones we must close.\n */\nfunction nameIsUntrusted(el: Element): boolean {\n const labelledby = el.getAttribute('aria-labelledby');\n if (labelledby) {\n for (const id of labelledby.split(/\\s+/)) {\n if (!id) continue;\n const ref = el.ownerDocument.getElementById(id);\n if (!ref) continue;\n if (\n ref.matches(UNTRUSTED_CONTENT) ||\n ref.querySelector(UNTRUSTED_CONTENT)\n ) {\n return true;\n }\n }\n return false;\n }\n // No explicit label attributes → the name, if any, is name-from-content.\n if (el.hasAttribute('aria-label')) return false;\n return el.querySelector(UNTRUSTED_CONTENT) !== null;\n}\n\nexport function nameOf(el: Element, styleOf: StyleOf): string {\n const name = computeAccessibleName(el, {\n getComputedStyle: styleOf,\n // jsdom logs a console error if you claim pseudo-element support it doesn't have.\n computedStyleSupportsPseudoElements: false,\n });\n if (!name) return '';\n\n // A tainted name would leak a value or a private string. Drop it entirely and let\n // the element stand on its role + ref. Losing a name costs the agent a little\n // context; keeping a leaked one is a breach. The trade is not close.\n if (nameIsUntrusted(el)) {\n // Preserve an explicit author label if one exists and is not itself the taint —\n // aria-labelledby taints were already caught above, so any aria-label here is safe.\n return el.getAttribute('aria-label') || '';\n }\n return name;\n}\n","import type { ElementRef } from '../protocol';\n\n/**\n * Element handles.\n *\n * The mechanism is Playwright's, deliberately (see protocol.ts): the agent never\n * learns a selector, it learns `e12`, and `e12` is turned back into an element\n * HERE, in the page, by us.\n *\n * Three properties matter and all are load-bearing:\n *\n * 1. THE MAP IS A WeakMap, NOT AN EXPANDO ON THE ELEMENT. An earlier version\n * stamped `el._mfRef`. Non-enumerable, so invisible to `Object.keys`/spreads/\n * `JSON.stringify` — but STILL reachable via `Object.getOwnPropertyNames` and\n * `Reflect.ownKeys`, and, worse, it parked the element's accessible name on the\n * customer's live DOM node indefinitely. A `WeakMap<Element, RefEntry>` mutates\n * nothing on their objects, is invisible to every enumeration and serialization\n * API without exception, cannot collide with a property the host already has,\n * and still gives us node-identity survival across GC for free.\n *\n * 2. A REF IS REGENERATED WHEN ROLE OR NAME CHANGES. Frameworks recycle DOM nodes:\n * a virtualised list scrolls, and the <button> that said \"Approve\" is the very\n * same node that now says \"Delete\". Keying the ref on (role, name) means that\n * node gets a NEW id and the old id resolves to nothing.\n *\n * 3. A REF IS SCOPED TO ONE SNAPSHOT GENERATION. (2) is necessary but not\n * sufficient: two icon-only \"Delete\" buttons in a virtualised table have the\n * SAME (role, name), so a recycled node whose role+name are unchanged would keep\n * its ref and silently retarget a different logical row. So a ref also carries\n * the generation it was minted in, and resolveRef refuses a ref from an older\n * generation — the agent must re-snapshot to get a fresh, valid handle. Loud\n * staleness beats silent retargeting.\n */\n\ninterface RefEntry {\n id: ElementRef;\n /** role + name at mint time. Changes here invalidate the ref. */\n key: string;\n /** The snapshot generation this ref belongs to. */\n gen: number;\n}\n\n/**\n * Monotonic across snapshots, never reused — like Playwright's. An id is only ever\n * handed out once in a page's lifetime, so a stale ref can never be *silently*\n * correct by colliding with a newer element; it just resolves to null.\n */\nlet counter = 0;\n\n/** Bumped once per full snapshot. A ref is only valid within its own generation. */\nlet generation = 0;\n\n/**\n * Element identity, off the host's objects entirely. Keyed by element so a recycled\n * node is recognised across snapshots; the entry carries the (role,name) key and the\n * generation for the two staleness checks above.\n */\nconst entries = new WeakMap<Element, RefEntry>();\n\n/** id -> element, for resolution. Rebuilt each generation from exactly what was emitted. */\nconst registry = new Map<ElementRef, Element>();\n\n/** Called once per FULL snapshot, before the walk. A region read does NOT call this. */\nexport function beginSnapshot(): void {\n generation++;\n registry.clear();\n}\n\n/**\n * Mint (or reuse) the ref for an element and register it for resolution.\n * Only ever called for elements that are visible AND receive pointer events.\n */\nexport function refFor(el: Element, role: string, name: string): ElementRef {\n const key = `${role} ${name}`;\n\n let entry = entries.get(el);\n if (!entry || entry.key !== key) {\n entry = { id: `e${++counter}`, key, gen: generation };\n entries.set(el, entry);\n } else {\n // Same node, same identity — carry it into the current generation so a fresh\n // snapshot re-validates a still-present element rather than orphaning it.\n entry.gen = generation;\n }\n\n registry.set(entry.id, el);\n return entry.id;\n}\n\n/**\n * Turn a ref back into an element.\n *\n * Three ways this returns null, each deliberate:\n * - unknown id (never minted, or from a cleared generation) → not in the registry;\n * - the element left the page → `isConnected` is false. A detached node still\n * answers every question (role, name, a zero box), so without this an action\n * would silently no-op against a ghost;\n * - the ref is from an OLDER generation → its entry.gen has been superseded. This is\n * what stops a recycled-node retarget: the agent is told the handle is stale and\n * must re-snapshot, rather than acting on the wrong row.\n */\nexport function resolveRef(ref: ElementRef): Element | null {\n const el = registry.get(ref);\n if (!el) return null;\n if (!el.isConnected) {\n registry.delete(ref);\n return null;\n }\n const entry = entries.get(el);\n if (!entry || entry.id !== ref || entry.gen !== generation) return null;\n return el;\n}\n\n/** Test-only: reset counters so refs are deterministic per test. */\nexport function __resetRefs(): void {\n counter = 0;\n generation = 0;\n registry.clear();\n}\n","import { isDisabled, isInaccessible } from 'dom-accessibility-api';\n\nimport { isPrivate, redact } from '../context';\nimport {\n createStyleCache,\n hasLayout,\n isInteractive,\n NAME_FROM_CONTENT,\n isOpaque,\n isVisible,\n nameOf,\n receivesPointerEvents,\n roleOf,\n states,\n type StyleOf,\n} from './a11y';\nimport { beginSnapshot, refFor } from './refs';\n\nexport { resolveRef } from './refs';\n\n/**\n * The page, as the agent sees it.\n *\n * We emit Playwright's ARIA-snapshot YAML, and that choice is the point of this\n * file. It is not our format: it is the one the frontier models have seen most, via\n * playwright-mcp, so a model already knows how to read it and already knows that\n * `[ref=e12]` is the thing you hand back to act. Inventing our own dialect here\n * would cost us capability for nothing.\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - list:\n * - listitem:\n * - link \"Order #1043\" [ref=e8]\n * - text: \"Unpaid\"\n * - button \"Export CSV\" [ref=e12]\n *\n * Not raw HTML: a real page is tens of thousands of tokens of div soup, gives the\n * model nothing to act with, and is a prompt-injection firehose.\n */\n\n/* ─────────────────────────────── budgets ──────────────────────────────── */\n\n/**\n * These exist because the failure they prevent is not \"the snapshot is big\", it is\n * \"the agent confidently tells the user about a button that does not exist\". A model\n * given a silently-cut-off page has no way to know it was cut off, so it fills the\n * gap. Hence: hard caps, and `truncated: true` travels with the payload so the agent\n * can be TOLD it is not seeing everything.\n *\n * The two caps do different jobs, and conflating them is how you get a bad snapshot:\n *\n * MAX_LINES bounds the MODEL'S CONTEXT. 800 lines of ARIA YAML is ~12 KB, a few\n * thousand tokens — a dense dashboard, and about as much page as is useful to\n * reason over at once.\n *\n * MAX_NODES bounds the MAIN THREAD. It counts elements *visited*, most of which are\n * the wrapper divs of a modern app and emit nothing at all. Measured in Chrome on a\n * deeply-nested 52k-element table, visiting 4000 nodes costs ~25ms of walk. Set it\n * to 1500 (a tempting round number) and a div-soup page truncates at ~460 lines —\n * we would stop while HALF the line budget was still unspent, and tell the agent it\n * could not see a page we had simply given up on early.\n */\nconst MAX_NODES = 4000;\nconst MAX_LINES = 800;\nconst MAX_NAME = 120;\nconst MAX_TEXT = 120;\n/**\n * Max `<option>`s emitted per `<select>` before the rest is summarised. A country or\n * timezone picker runs to hundreds; the option list is an affordance to show, not a\n * reason to spend the line budget. The selected option is always in the first slice\n * in practice, but if a huge list has its selection past the cap the \"+N more\"\n * marker tells the agent it isn't seeing every choice.\n */\nconst MAX_OPTIONS = 25;\n\n/* ─────────────────────────────── model ────────────────────────────────── */\n\ninterface AriaNode {\n role: string;\n /** Raw accessible name. Redacted and truncated at render time, not here. */\n name: string;\n /** Pre-rendered bracket attributes, `[checked] [ref=e5]`. */\n props: string;\n children: (AriaNode | string)[];\n}\n\ninterface Walk {\n styleOf: StyleOf;\n layout: boolean;\n nodes: number;\n lines: number;\n truncated: boolean;\n /** Called for every element that gets a ref, so a caller can note which are on screen. */\n onRef?: (ref: string, el: Element) => void;\n}\n\n/** Elements that carry no meaning of their own: their children stand in for them. */\nconst TRANSPARENT = new Set(['generic', 'presentation', 'none']);\n\n/**\n * Never walked. `<script>`/`<style>`/`<noscript>` are the obvious ones; `<svg>` is\n * here because its innards are hundreds of `<path>` nodes of pure noise — any title\n * it carries is already folded into its parent's accessible name by accname.\n */\nconst SKIP_TAGS = new Set([\n 'SCRIPT',\n 'STYLE',\n 'NOSCRIPT',\n 'TEMPLATE',\n 'SVG',\n 'HEAD',\n 'LINK',\n 'META',\n 'BASE',\n]);\n\n/* ─────────────────────────────── walking ──────────────────────────────── */\n\n/** False once any budget is spent — the caller stops and we mark the snapshot truncated. */\nfunction withinBudget(w: Walk): boolean {\n if (w.nodes >= MAX_NODES || w.lines >= MAX_LINES) {\n w.truncated = true;\n return false;\n }\n return true;\n}\n\n/**\n * Is this element ours?\n *\n * The widget must never appear in its own snapshot: the agent describing its own\n * chat window back to itself is both useless and a lovely little feedback loop.\n */\nfunction isOurs(el: Element): boolean {\n return el.id === 'matterfact-embed' || el.hasAttribute('data-mf-embed');\n}\n\n/**\n * Hidden from assistive tech — and therefore from us.\n *\n * This is `isInaccessible()`'s rule set applied ONE NODE AT A TIME, top-down.\n * `isInaccessible()` itself walks every ancestor on every call, which over a whole\n * tree is the O(n·depth) blow-up the budget forbids; because we descend from the\n * root and prune the entire subtree the moment a node is hidden, the composition of\n * these local checks is exactly equivalent and costs O(1) per node. (We still call\n * the real thing once, on the root, as a backstop.)\n */\nfunction isHidden(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n if (el.getAttribute('aria-hidden') === 'true') return true;\n if (el.hasAttribute('hidden') || el.hasAttribute('inert')) return true;\n return !isVisible(el, style, layout);\n}\n\n/**\n * The nodes a parent should walk.\n *\n * An open shadow root REPLACES its host's light children — those only reach the\n * screen by being slotted, and we pick them up when we hit the `<slot>` that pulls\n * them in. Walking both would emit every web component's contents twice. A closed\n * shadow root is opaque to us by design, exactly as it is to the rest of the page.\n */\nfunction childrenOf(el: Element): ArrayLike<Node> {\n if (el.shadowRoot) return el.shadowRoot.childNodes;\n if (el.tagName === 'SLOT') {\n const assigned = (el as HTMLSlotElement).assignedNodes({ flatten: true });\n // An unfilled slot renders its own fallback content.\n if (assigned.length) return assigned;\n }\n return el.childNodes;\n}\n\n/** ArrayLike + index loop, not for-of: a NodeList needs `DOM.Iterable`, and copying one to iterate it allocates an array per element for nothing. */\nfunction visitChildren(\n el: Element,\n parent: AriaNode,\n style: CSSStyleDeclaration,\n w: Walk,\n): void {\n const children = childrenOf(el);\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (child) visitNode(child, parent, style, w);\n }\n}\n\nfunction visitText(node: Text, parent: AriaNode, w: Walk): void {\n const text = (node.nodeValue ?? '').replace(/\\s+/g, ' ').trim();\n if (!text) return;\n\n // The text of a button, a link or a heading IS its accessible name — we already\n // emitted it on the parent's line, and repeating it as a child would double the\n // tokens and imply a second, separate thing on the page. Decided by ROLE, never by\n // string-matching against the name (see NAME_FROM_CONTENT).\n if (NAME_FROM_CONTENT.has(parent.role)) return;\n\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(text);\n}\n\n/**\n * A native `<select>`, expanded into its options.\n *\n * The generic walk can't do this: a closed select's `<option>`s have no layout box,\n * so isVisible would prune them. Yet the options are exactly the affordance the agent\n * needs — \"what can I set this to\" — and, unlike an `<input>` value, they are a\n * bounded, author-defined set rather than free text the user typed. So we emit them,\n * and mark the selected one: it names one of the choices we are ALREADY showing, so\n * it reveals nothing a human looking at the control wouldn't see. Labels are redacted\n * at render time like every other name; the list is capped; a select the host deems\n * sensitive is hidden the usual way (`data-mf-private`) and never reaches here.\n *\n * `.options` is the flat HTMLOptionsCollection, so `<optgroup>` nesting is already\n * flattened for us; `<select multiple>` (role listbox) works through the same path.\n */\n/** One option, in Playwright's shape: `- option \"label\" [disabled] [selected]`. The\n * name is trimmed so a whitespace-only option renders `- option` (no \"\"). Disabled is\n * `:disabled` (which catches an <optgroup disabled> that isDisabled/opt.disabled miss)\n * OR isDisabled (which adds aria-disabled). Bracket order matches states(): [disabled]\n * before [selected]. */\nfunction optionNode(opt: HTMLOptionElement): AriaNode {\n const disabled = opt.matches(':disabled') || isDisabled(opt);\n return {\n role: 'option',\n name: (opt.label || opt.textContent || '').trim(),\n props:\n (disabled ? ' [disabled]' : '') + (opt.selected ? ' [selected]' : ''),\n children: [],\n };\n}\n\nfunction emitSelectOptions(\n select: HTMLSelectElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const options = select.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n // The selected option IS the field's current value — the one option the agent most\n // needs. In a long list (country, timezone) the selection can sit past the cap, so\n // the front slice above would show none marked [selected]. Surface any selected\n // option that fell outside the cap regardless, and don't double-count it as hidden.\n let extraSelected = 0;\n const selected = select.selectedOptions;\n for (let i = 0; i < selected.length; i++) {\n const opt = selected[i];\n if (opt && opt.index >= shown && !isPrivate(opt)) {\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(optionNode(opt));\n extraSelected++;\n }\n }\n const remaining = options.length - shown - extraSelected;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\n/**\n * An `<input list=\"…\">`'s datalist suggestions.\n *\n * Same affordance as a `<select>`'s options — a bounded, author-defined set the user\n * can pick — but surfaced under the (still value-opaque) input, because the\n * `<datalist>` element is display:none, so the generic walk never reaches it. The\n * input's own value stays hidden; only the suggestion labels are emitted (redacted at\n * render like every name, and capped). No [selected] — a datalist has no current\n * choice, only completions.\n */\nfunction emitDatalistOptions(\n input: HTMLInputElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const list = input.list as HTMLDataListElement | null;\n if (!list) return;\n const options = list.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n const remaining = options.length - shown;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\nfunction visitElement(\n el: Element,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (!withinBudget(w)) return;\n if (SKIP_TAGS.has(el.tagName) || isOurs(el)) return;\n\n // Privacy first, before we so much as compute a style: `data-mf-private` and\n // password/hidden inputs take their whole subtree with them.\n if (isPrivate(el)) return;\n\n w.nodes++;\n\n const style = w.styleOf(el);\n if (isHidden(el, style, w.layout)) return;\n\n const role = roleOf(el);\n const transparent = role === null || TRANSPARENT.has(role);\n const interactive = isInteractive(el, role, style, parentStyle);\n\n // A div with a click handler is invisible to us (no getEventListeners), but a div\n // that is FOCUSABLE, or that flips the cursor to a pointer, is announcing itself.\n // Playwright emits those as `- generic [ref=eN]` and so do we: without this, every\n // custom card, chip and icon-button on a modern app would be unreachable.\n if (transparent && !interactive) {\n visitChildren(el, parent, style, w);\n return;\n }\n\n const emittedRole = role === null || TRANSPARENT.has(role) ? 'generic' : role;\n const name = nameOf(el, w.styleOf);\n\n // Refs are for things you can act on. Static text does not get one — it would be a\n // handle the agent can only ever misuse, and it doubles the size of the snapshot.\n let ref = '';\n if (interactive && receivesPointerEvents(style)) {\n const r = refFor(el, emittedRole, name);\n ref = ` [ref=${r}]`;\n w.onRef?.(r, el);\n }\n\n const state = states(el, emittedRole);\n const node: AriaNode = {\n role: emittedRole,\n name,\n props: (state ? ` ${state}` : '') + ref,\n children: [],\n };\n\n w.lines++;\n parent.children.push(node);\n\n // A native <select>: emit its options — the affordance the opaque rule used to\n // hide — instead of walking its (layout-less, hence prune-able) children.\n if (el.tagName === 'SELECT') {\n emitSelectOptions(el as HTMLSelectElement, node, w);\n return;\n }\n\n // An <input list=\"…\">: surface its datalist suggestions (the affordance) under the\n // input, then fall through to the opaque return — the value itself is never emitted.\n if (el.tagName === 'INPUT' && (el as HTMLInputElement).list) {\n emitDatalistOptions(el as HTMLInputElement, node, w);\n }\n\n // isOpaque: an <input>, <textarea> or contenteditable. Its content IS the user's\n // data, so we do not walk into it — the value cannot leak because we never go and\n // look at it. See a11y.ts.\n if (isOpaque(el)) return;\n\n visitChildren(el, node, style, w);\n}\n\nfunction visitNode(\n node: Node,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (node.nodeType === 3 /* TEXT_NODE */) {\n visitText(node as Text, parent, w);\n } else if (node.nodeType === 1 /* ELEMENT_NODE */) {\n visitElement(node as Element, parent, parentStyle, w);\n }\n // Comments, CDATA, processing instructions: nothing to say.\n}\n\n/* ────────────────────────────── rendering ─────────────────────────────── */\n\n/**\n * Redact, then truncate — in that order, and the order is the point.\n *\n * Truncate first and a 130-character line containing an email address gets cut\n * through the middle of it, the regex no longer matches, and you have shipped\n * `jane.doe@acmecorp` to the model. Redaction runs on the whole string, every time,\n * before anything is thrown away.\n */\nfunction sanitize(text: string, max: number): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n const clean = redact(collapsed);\n return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;\n}\n\nfunction quote(text: string): string {\n return `\"${text.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\nfunction render(\n children: (AriaNode | string)[],\n depth: number,\n out: string[],\n): void {\n const pad = ' '.repeat(depth);\n for (const child of children) {\n if (typeof child === 'string') {\n out.push(`${pad}- text: ${quote(sanitize(child, MAX_TEXT))}`);\n continue;\n }\n const name = child.name ? ` ${quote(sanitize(child.name, MAX_NAME))}` : '';\n const head = `${pad}- ${child.role}${name}${child.props}`;\n if (child.children.length) {\n out.push(`${head}:`);\n render(child.children, depth + 1, out);\n } else {\n out.push(head);\n }\n }\n}\n\n/* ─────────────────────────────── entry ────────────────────────────────── */\n\n/**\n * Walk the page and render it. Called by context.ts, which redacts the result a\n * second time on the way out — the belt to this file's braces.\n */\nfunction walk(\n root: Element,\n onRef?: (ref: string, el: Element) => void,\n): { yaml: string; truncated: boolean } {\n const styleOf = createStyleCache();\n const w: Walk = {\n styleOf,\n layout: hasLayout(),\n nodes: 0,\n lines: 0,\n truncated: false,\n onRef,\n };\n\n // The one call to the real isInaccessible(): a cheap backstop on the root, where\n // the ancestor walk costs nothing.\n if (isInaccessible(root, { getComputedStyle: styleOf })) {\n return { yaml: '', truncated: false };\n }\n\n const tree: AriaNode = { role: '', name: '', props: '', children: [] };\n visitChildren(root, tree, styleOf(root), w);\n\n const lines: string[] = [];\n render(tree.children, 0, lines);\n\n // An in-band marker, not just the out-of-band `truncated` flag. The YAML is what\n // lands in the prompt; a backend template that injects the tree but forgets to\n // surface the flag would hand the model a page that simply stops, and the model\n // fills the gap. This line is inside the payload, so it cannot be dropped on the\n // way to the prompt. (Depth-first, so what is missing is the BOTTOM of the page.)\n //\n // It REPLACES the last emitted line rather than appending — the marker is part of\n // the line budget, not an exemption from it. The final line was a truncated node\n // anyway (see MAX_LINES), so nothing meaningful is lost.\n if (w.truncated && lines.length) {\n lines[lines.length - 1] =\n '- text: \"… (snapshot truncated — more of the page is below)\"';\n }\n\n return { yaml: lines.join('\\n'), truncated: w.truncated };\n}\n\n/**\n * The full page. Mints a fresh generation of refs (beginSnapshot), so any ref the\n * agent held from a previous snapshot is now stale and resolves to null — which is\n * correct: the page may have changed under it.\n *\n * `visibleRefs` is the viewport slice — the refs whose element is actually on screen.\n * That is the \"where is your attention\" signal, and it lets the focus context name\n * the handful of things in view out of the whole tree.\n */\nexport function snapshot(): {\n yaml: string;\n truncated: boolean;\n visibleRefs: string[];\n} {\n const root = document.body;\n if (!root) return { yaml: '', truncated: false, visibleRefs: [] };\n\n beginSnapshot();\n\n const visibleRefs: string[] = [];\n const vh = window.innerHeight || 0;\n const vw = window.innerWidth || 0;\n const result = walk(root, (ref, el) => {\n const r = el.getBoundingClientRect();\n // On screen = its box intersects the viewport. Cheap; the walk already forced\n // layout, so getBoundingClientRect here is reading a warm value.\n if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) {\n visibleRefs.push(ref);\n }\n });\n\n return { ...result, visibleRefs };\n}\n\n/**\n * Zoom in on one ref — the a11y sub-tree under it.\n *\n * This is the pull half: the agent has the focus context and a shallow page, and when\n * it wants the detail of a specific table or form it asks for that region rather than\n * us re-sending the whole page. It does NOT call beginSnapshot — that would clear the\n * ref map and invalidate the very ref being asked about — so the refs it mints join\n * the current generation.\n */\nexport function snapshotRegion(root: Element): {\n yaml: string;\n truncated: boolean;\n} {\n if (!root.isConnected) return { yaml: '', truncated: false };\n return walk(root);\n}\n","import type {\n ActivityEvent,\n FocusContext,\n HostToWidget,\n PageContext,\n PageEntity,\n ToolCall,\n} from './protocol';\n\n/** The origin serving our chat — how we tell OUR embedded content from the host's own\n * iframes. Set by start(); empty until then, which just means we spot nothing. */\nlet widgetOrigin = '';\n\n/**\n * The eye.\n *\n * Everything in this module can see the customer's page. It is a SEPARATE CHUNK,\n * loaded only when someone actually opens the chat — so a page whose visitors never\n * click the widget pays nothing for any of it, and a security reviewer can read\n * exactly one file to know what we look at.\n *\n * The rules, which are not negotiable:\n *\n * NEVER captured — no config enables it: the value of any <input>, <textarea> or\n * contenteditable; anything inside a password field; cookies; localStorage;\n * sessionStorage; the raw DOM; screenshots; network traffic; anything inside an\n * element marked `data-mf-private`.\n *\n * The agent never gets a selector and never touches the DOM. It gets refs. A ref\n * is resolved to an element HERE, in the page, by us.\n */\n\ntype Send = (msg: HostToWidget) => void;\n\nconst MAX_ACTIVITY = 40;\n\nlet send: Send | null = null;\nlet activitySeq = 0;\nconst activity: ActivityEvent[] = [];\nlet lastUrl = '';\n\n/* ─────────────────────────── redaction ────────────────────────────────── */\n\nconst PII = [\n /\\b[\\w.+-]+@[\\w-]+\\.[\\w.]{2,}\\b/g, // email\n /\\b(?:\\d[ -]?){13,19}\\b/g, // card-ish\n /\\b\\d{3}[- ]?\\d{2}[- ]?\\d{4}\\b/g, // ssn — dashed, spaced, OR bare 9 digits\n /\\b\\d{9,}\\b/g, // long bare digit runs: account / MRN / routing numbers\n /(?:\\+?\\d{1,2}[\\s.-]?)?\\(?\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}\\b/g, // us phone\n /\\b(?:sk|pk|rk|ak)_(?:live|test)_[A-Za-z0-9]{8,}\\b/g, // stripe-style api keys\n /\\beyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+\\b/g, // jwt\n];\n\n/**\n * Scrub before anything leaves the page — not after it arrives.\n *\n * A compromised widget, or a bug in ours, must not be able to retroactively obtain\n * a customer's users' email addresses. The only way to guarantee that is to never\n * put them on the wire.\n */\nexport function redact(text: string): string {\n let out = text;\n for (const re of PII) out = out.replace(re, '[redacted]');\n return out;\n}\n\n/** Anything the host has marked private, or that is inherently sensitive, is out. */\nexport function isPrivate(el: Element): boolean {\n if (el.closest('[data-mf-private]')) return true;\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const t = (el as HTMLInputElement).type;\n if (t === 'password' || t === 'hidden') return true;\n }\n return false;\n}\n\n/* ───────────────────────── page context ───────────────────────────────── */\n\n/**\n * What the page says about itself.\n *\n * A host that declares nothing still gets URL + title, which is what every other\n * embeddable assistant on the market offers in total. The interesting fields\n * (`route`, `description`, `entities`) are host-declared, because only the host\n * knows that `/o/8813` is \"the Acme Corp order, 3 items, unpaid\".\n *\n * Declared via a global the host sets before we load:\n * window.matterfact = { context: { route: '/orders/:id', description: '...', entities: [...] } }\n */\n/**\n * matterfact content embedded IN the host page — today, artifact iframes.\n *\n * A cross-origin iframe is opaque: `contentDocument` throws, so the DOM snapshot walks\n * straight past an embedded artifact and the agent is blind to the very thing the page\n * is built around. It reads the page as empty and asks which URL you mean.\n *\n * We don't need to see inside, and shouldn't want to. The artifact's ID is right there\n * in the src, and the agent can already resolve `artifacts/<id>/` in its session — the\n * same path an `@`-mention uses. So we report the ID and let the backend fetch the real\n * thing, which beats scraping a rendering of it: it gets the data, not the picture.\n *\n * Matched by ORIGIN, not by path shape: a customer is perfectly entitled to their own\n * /artifacts/ route, and it isn't ours.\n */\n/** The artifact slug from a matterfact artifact path, or null. Matches both the\n * chrome-free embed route (/embed/artifacts/<slug>) and the bare /artifacts/<slug>. */\nexport function artifactIdFromPath(pathname: string): string | null {\n const m = pathname.match(/^\\/(?:embed\\/)?artifacts\\/(.+?)\\/?$/);\n return m ? decodeURIComponent(m[1]) : null;\n}\n\nfunction embeddedMatterfactEntities(): PageEntity[] {\n if (!widgetOrigin) return [];\n const out: PageEntity[] = [];\n for (const frame of Array.from(document.querySelectorAll('iframe'))) {\n let u: URL;\n try {\n u = new URL(frame.getAttribute('src') || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== widgetOrigin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n if (out.some((e) => e.id === id)) continue; // same artifact twice = once\n // No url field: the agent reaches an artifact by ID (`artifacts/<id>/`), never by\n // fetching the page, and an artifact URL can carry a share token we've no business\n // forwarding. The id is the whole useful payload.\n out.push({\n kind: 'artifact',\n id,\n label: redact(frame.getAttribute('title') || '') || id,\n });\n }\n return out;\n}\n\n/**\n * Frames we can see the existence of but nothing inside — someone else's cross-origin\n * embed. Worth one line: \"there is a thing here I cannot read\" is a true and useful\n * statement, and much better than the agent confidently describing a page while missing\n * the widget the user is actually asking about.\n */\nfunction opaqueFrameCount(): number {\n return Array.from(document.querySelectorAll('iframe')).filter((f) => {\n try {\n const u = new URL(f.getAttribute('src') || '', location.href);\n return u.origin !== location.origin && u.origin !== widgetOrigin;\n } catch {\n return false;\n }\n }).length;\n}\n\nexport function readPageContext(): PageContext {\n const declared =\n (window as { matterfact?: { context?: PageContext } }).matterfact\n ?.context ?? {};\n\n const found = embeddedMatterfactEntities();\n const opaque = opaqueFrameCount();\n\n return {\n // Path only. A query string is where session ids, tokens and email addresses\n // live; it is not ours to take.\n url: location.origin + location.pathname,\n path: location.pathname,\n title: redact(document.title),\n locale: document.documentElement.lang || undefined,\n ...declared,\n // After the spread: what we FOUND is additive to what the host DECLARED, never a\n // replacement. A host that declares its own entities still gets the artifacts we\n // spotted, and vice versa.\n entities: [...(declared.entities ?? []), ...found],\n data: {\n ...(declared.data ?? {}),\n ...(opaque ? { opaque_frames: opaque } : {}),\n },\n };\n}\n\nfunction publishContext() {\n send?.({ type: 'host.context', context: readPageContext() });\n}\n\n/* ─────────────────────── artifact grants (backend-only) ────────────────── */\n\nexport interface ArtifactGrantSrc {\n id: string;\n owner: string;\n token: string;\n}\n\n/** Read-only capability grants from co-embedded artifact iframes, for the backend to\n * materialize their data. Separate from entities on purpose: the token must never ride\n * ambient (rendered) context, only this backend-only channel. */\nexport function grantsFromIframeSrcs(\n srcs: string[],\n origin: string,\n): ArtifactGrantSrc[] {\n const out: ArtifactGrantSrc[] = [];\n for (const raw of srcs) {\n let u: URL;\n try {\n u = new URL(raw || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== origin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n const owner = u.searchParams.get('owner') || '';\n const token = u.searchParams.get('t') || '';\n if (!owner || !token) continue;\n if (out.some((g) => g.id === id)) continue;\n out.push({ id, owner, token });\n }\n return out;\n}\n\nfunction readArtifactGrants(): ArtifactGrantSrc[] {\n if (!widgetOrigin) return [];\n const srcs = Array.from(document.querySelectorAll('iframe')).map(\n (f) => f.getAttribute('src') || '',\n );\n return grantsFromIframeSrcs(srcs, widgetOrigin);\n}\n\nfunction publishArtifactGrants() {\n send?.({ type: 'host.artifactGrants', grants: readArtifactGrants() });\n}\n\n/* ────────────────────────── activity ──────────────────────────────────── */\n\nfunction pushActivity(e: Omit<ActivityEvent, 'seq' | 'ts'>) {\n activity.push({ ...e, seq: ++activitySeq, ts: Date.now() });\n if (activity.length > MAX_ACTIVITY) activity.shift();\n send?.({ type: 'host.activity', events: [activity[activity.length - 1]] });\n}\n\n/**\n * A short, human-readable label for what got clicked.\n *\n * Shaped after PostHog's autocapture, not after a session-replay frame: rrweb would\n * give us `{source:2, type:2, id:417, x:210, y:88}` — no text, no role, no href,\n * meaningless to a model without the full DOM snapshot it deltas against. One line\n * of \"clicked button 'Export CSV'\" is worth more and costs less.\n */\n/**\n * The accessible NAME of a form control — never its value.\n *\n * A control has no `innerText`, so the generic path below misses it. We look where a\n * control's name actually lives: `aria-label`, then a `<label for>` or a wrapping\n * `<label>`, then `placeholder`. `placeholder` is a LABEL, not a value — it is the\n * hint shown when the field is empty (\"Order number or customer\"), so it is safe.\n */\nfunction controlLabel(el: Element): string {\n const aria = el.getAttribute('aria-label');\n if (aria) return aria;\n\n const id = el.id;\n if (id) {\n const forLabel = document.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n const t = forLabel?.textContent?.trim();\n if (t) return t;\n }\n const wrapping = el.closest('label')?.textContent?.trim();\n if (wrapping) return wrapping;\n\n const placeholder = el.getAttribute('placeholder');\n if (placeholder) return placeholder;\n\n return '';\n}\n\nconst FORM_CONTROLS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);\n\nfunction describe(el: Element): string {\n const role = el.getAttribute('role') || el.tagName.toLowerCase();\n const label =\n el.getAttribute('aria-label') ||\n (FORM_CONTROLS.has(el.tagName)\n ? controlLabel(el)\n : (el as HTMLElement).innerText?.trim().slice(0, 60)) ||\n el.getAttribute('title') ||\n '';\n return label ? `${role} \"${redact(label)}\"` : role;\n}\n\n/**\n * Elements a click is worth recording. Deliberately tight: the point of the activity\n * stream is INTENT (\"the user chose to export\"), and a click on a heading, a label,\n * a card gutter, or blank page is not intent, it is noise. We only log a click that\n * lands on something actionable.\n */\nconst ACTIONABLE =\n 'a[href],button,input,select,textarea,summary,' +\n '[role=\"button\"],[role=\"link\"],[role=\"menuitem\"],[role=\"tab\"],[role=\"option\"],' +\n '[role=\"checkbox\"],[role=\"switch\"],[role=\"radio\"],[onclick],[tabindex]';\n\nfunction onClick(ev: Event) {\n const target = ev.target as Element | null;\n if (!target || !(target instanceof Element)) return;\n\n // Clicking a <label> operates the control it labels — record THAT, not \"clicked\n // label\", so the event reads as the user's actual intent.\n const label = target.closest('label');\n const labelled = label\n ? (label.getAttribute('for') &&\n document.getElementById(label.getAttribute('for')!)) ||\n label.querySelector('input,select,textarea')\n : null;\n\n const actionable = labelled ?? target.closest(ACTIONABLE);\n // No actionable target — a click on text, a gutter, or blank space. That is not an\n // action; dropping it is the whole fix for the click-log noise.\n if (!actionable || isPrivate(actionable)) return;\n\n pushActivity({ type: 'click', summary: `clicked ${describe(actionable)}` });\n}\n\nfunction onSubmit(ev: Event) {\n const el = ev.target as Element | null;\n if (!el || isPrivate(el)) return;\n // The FORM was submitted — never its values.\n pushActivity({ type: 'submit', summary: `submitted ${describe(el)}` });\n}\n\n/**\n * A form field changed.\n *\n * The rule is the same as everywhere else and the temptation here is sharpest:\n * record THAT a field changed and WHICH field (its label), never WHAT it was\n * changed to. `change` fires on exactly the elements whose values are off-limits.\n *\n * One safe exception: a <select>, a checkbox, or a radio chose from a fixed, visible\n * set of options the agent can already see in the snapshot — \"Unpaid\", \"Shipped\".\n * That is a user *choice*, not typed data, so the chosen option's LABEL is fair to\n * include and is the useful part (\"filtered status to Shipped\"). Free-text and\n * numeric inputs get their label only.\n */\nfunction onChange(ev: Event) {\n const el = ev.target as (HTMLElement & { type?: string }) | null;\n if (!el || !(el instanceof Element) || isPrivate(el)) return;\n\n const tag = el.tagName;\n const type = (el as HTMLInputElement).type;\n\n // Never a password/hidden field, and isPrivate already covered data-mf-private.\n if (tag === 'INPUT' && (type === 'password' || type === 'hidden')) return;\n\n let summary = `changed ${describe(el)}`;\n\n if (tag === 'SELECT') {\n const opt = (el as HTMLSelectElement).selectedOptions[0]?.text;\n if (opt) summary = `${describe(el)} → \"${redact(opt)}\"`;\n } else if (type === 'checkbox' || type === 'radio') {\n summary = `${(el as HTMLInputElement).checked ? 'checked' : 'unchecked'} ${describe(el)}`;\n }\n\n pushActivity({ type: 'input', summary });\n}\n\n/**\n * SPA navigation. There is no event for `pushState`, so we wrap it — a 20-line job\n * that no library does better.\n */\nfunction watchNavigation() {\n const fire = () => {\n const url = location.pathname;\n if (url === lastUrl) return;\n lastUrl = url;\n pushActivity({ type: 'nav', summary: `navigated to ${url}` });\n publishContext();\n publishArtifactGrants();\n };\n\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = history[name];\n history[name] = function (\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const r = orig.apply(this, args);\n fire();\n return r;\n } as History[typeof name];\n }\n window.addEventListener('popstate', fire);\n}\n\n/* ─────────────────────────── focal context ────────────────────────────── */\n\n/**\n * Where the user's attention is, right now.\n *\n * This is the \"knows what you're doing\" layer, and it is deliberately small so it can\n * ride on every turn — where the full snapshot cannot. It is also the most sensitive:\n * `selection` is whatever the user highlighted, which could be their own email, so it\n * is redacted and respects data-mf-private like everything else. Focus and the\n * viewport are labels and refs — never a value.\n *\n * Held so the last-known focus can travel with a turn even between the (throttled)\n * push updates.\n */\nlet lastFocus: FocusContext = {};\n\nasync function readFocus(): Promise<FocusContext> {\n const focus: FocusContext = {};\n\n // Selection — the single strongest \"this is what I'm asking about\" signal.\n const sel = window.getSelection?.();\n if (sel && !sel.isCollapsed) {\n const anchor = sel.anchorNode?.parentElement ?? null;\n // Don't lift a selection out of a private region, and cap it — a user can select\n // the whole page.\n if (!anchor || !anchor.closest('[data-mf-private]')) {\n const text = sel.toString().trim().slice(0, 500);\n if (text) focus.selection = redact(text);\n }\n }\n\n // The control they're working in — its label, never its contents.\n const active = document.activeElement;\n if (\n active &&\n active !== document.body &&\n !isPrivate(active) &&\n !active.closest('[data-mf-private]')\n ) {\n const { snapshot } = await import('./dom/snapshot');\n void snapshot; // ensure the chunk that owns refFor is loaded before we describe\n focus.focused = {\n label: redact(describeControl(active)),\n role: active.getAttribute('role') || active.tagName.toLowerCase(),\n };\n }\n\n const doc = document.documentElement;\n const scrollable = doc.scrollHeight - doc.clientHeight;\n focus.scroll =\n scrollable > 0 ? Math.round((doc.scrollTop / scrollable) * 100) / 100 : 0;\n\n return focus;\n}\n\n/** A label for whatever is focused, reusing the same value-blind rules as activity. */\nfunction describeControl(el: Element): string {\n return describe(el);\n}\n\nlet focusTimer: ReturnType<typeof setTimeout> | null = null;\n\n/** Coalesce a burst of selection/focus/scroll events into one push. */\nfunction scheduleFocus() {\n if (focusTimer) return;\n focusTimer = setTimeout(async () => {\n focusTimer = null;\n lastFocus = await readFocus();\n send?.({ type: 'host.focus', focus: lastFocus });\n }, 250);\n}\n\n/* ───────────────────────────── snapshot ───────────────────────────────── */\n\nlet snapshotSeq = 0;\n\nexport async function sendSnapshot(emit: Send) {\n // The a11y walk is itself lazily imported: a host that only ever declares\n // PageContext and never lets the agent look at the page never downloads it.\n const { snapshot } = await import('./dom/snapshot');\n const { yaml, truncated, visibleRefs } = snapshot();\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // The viewport slice rides with the focus context so the agent can tell the few\n // things on screen from the whole tree it just received.\n lastFocus = { ...lastFocus, visibleRefs };\n emit({ type: 'host.focus', focus: lastFocus });\n}\n\n/**\n * Zoom in on one ref — the pull half of the model. The agent asks; we resolve the ref\n * to a live element and return just its sub-tree.\n */\nexport async function sendRegion(ref: string, emit: Send) {\n const { snapshotRegion, resolveRef } = await import('./dom/snapshot');\n const el = resolveRef(ref);\n if (!el) {\n emit({\n type: 'host.region',\n ref,\n yaml: '(this element is no longer on the page)',\n });\n return;\n }\n const { yaml } = snapshotRegion(el);\n emit({ type: 'host.region', ref, yaml: redact(yaml) });\n}\n\n/* ───────────────────────────── tools ──────────────────────────────────── */\n\n/**\n * v1 IS READ-ONLY.\n *\n * The page's content is untrusted — text on it can try to instruct the agent — and\n * the moment the agent can act, a bad answer becomes a bad ACTION. So no tool here\n * mutates the page yet. The call path exists, and the enforcement point is HERE (in\n * the page, where we control what actually happens) rather than in the widget, which\n * can be lied to.\n *\n * When write tools land: anything not `readOnly` gets a user confirmation, on every\n * call. Not \"unless the host opts out\" — every call, because the trigger may have\n * been written by the page.\n */\nexport async function callTool(call: ToolCall, emit: Send) {\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: false,\n error: 'Host tools are read-only in this version; no action was taken.',\n });\n}\n\n/* ───────────────────────────── auth ───────────────────────────────────── */\n\n/**\n * Hosted login, in a POPUP — and the popup is not a UX preference.\n *\n * Our iframe on acme.com gets a PARTITIONED cookie jar: it cannot see the user's\n * existing matterfact session, no matter that it is served from our own origin.\n * A popup, however, is a TOP-LEVEL window on app.matterfact.com — first-party, real\n * cookies, silent SSO if they are already signed in. It hands the token back by\n * postMessage and we forward it into the iframe.\n */\nexport function beginAuth(\n config: { origin: string; publishableKey: string },\n emit: Send,\n) {\n const w = window.open(\n `${config.origin}/embed/authorize?k=${encodeURIComponent(\n config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}`,\n 'mf_auth',\n 'width=460,height=640',\n );\n if (!w) return; // popup blocked; the widget shows its own \"sign in\" affordance\n\n const onMsg = (event: MessageEvent) => {\n if (event.origin !== config.origin) return;\n const d = event.data;\n if (d?.type !== 'mf:embed:auth') return;\n window.removeEventListener('message', onMsg);\n emit({ type: 'host.auth', token: d.token, expiresAt: d.expiresAt });\n };\n window.addEventListener('message', onMsg);\n}\n\n/* ───────────────────────────── start ──────────────────────────────────── */\n\nexport function start(emit: Send, origin?: string) {\n send = emit;\n widgetOrigin = origin || '';\n lastUrl = location.pathname;\n\n publishContext();\n publishArtifactGrants();\n watchNavigation();\n\n // Passive + capture: we observe, we never interfere with the host's own handling.\n document.addEventListener('click', onClick, { capture: true, passive: true });\n document.addEventListener('submit', onSubmit, {\n capture: true,\n passive: true,\n });\n // `change` fires on blur/commit for text inputs and immediately for select/\n // checkbox/radio — not on every keystroke, which is what we want: a settled\n // choice, not a stream of partial values.\n document.addEventListener('change', onChange, {\n capture: true,\n passive: true,\n });\n\n // Focal context: what the user is attending to. Coalesced (scheduleFocus), because\n // selectionchange and scroll fire in torrents.\n document.addEventListener('selectionchange', scheduleFocus, {\n passive: true,\n });\n document.addEventListener('focusin', scheduleFocus, {\n capture: true,\n passive: true,\n });\n window.addEventListener('scroll', scheduleFocus, {\n capture: true,\n passive: true,\n });\n\n const theme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light';\n emit({ type: 'host.theme', mode: theme });\n}\n","/**\n * The matterfact embed bridge protocol.\n *\n * This is the contract between the HOST PAGE (a customer's site, running our\n * loader) and the WIDGET (our chat, running in a cross-origin iframe on\n * app.matterfact.com).\n *\n * Two things to understand before changing anything here:\n *\n * 1. THE IFRAME CANNOT SEE THE PAGE. It is cross-origin — that is the entire\n * point of it. So every fact about the host page (its URL, its DOM, what the\n * user just did) reaches the agent only because the LOADER, which runs as\n * ordinary page JS and *can* see it, chose to send it. The loader is the eye;\n * the widget is the mouth.\n *\n * 2. THIS CONTRACT OUTLIVES THE IFRAME. The next tier is an in-page React SDK\n * with no iframe at all — and it will speak exactly this. If the message\n * shapes are right, \"deeper integration\" is a transport swap (postMessage ->\n * direct call), not a rewrite. So model the DOMAIN here, not the plumbing.\n */\n\nexport const PROTOCOL_VERSION = 1;\n\n/** Every message is namespaced so we never collide with the host page's own postMessage traffic. */\nexport const CHANNEL = 'mf-embed';\n\n/* ────────────────────────────── refs ──────────────────────────────────── */\n\n/**\n * A handle on a real element in the host page.\n *\n * Format and semantics are lifted from Playwright's ARIA snapshot (`ref=e12`),\n * for a specific reason: it is the element-handle syntax the frontier models have\n * seen most, via playwright-mcp. We are not being original here on purpose.\n *\n * The ref is an in-page expando plus a snapshot-scoped Map — never an attribute,\n * so it is invisible to the host page's CSS, its serialization, and its own\n * mutation observers. It is resolved back to an element by the LOADER; the agent\n * never touches the DOM, and never learns a selector.\n */\nexport type ElementRef = string; // 'e12'\n\n/* ──────────────────────────── host → widget ───────────────────────────── */\n\n/** Ambient facts about the page. Cheap, sent on every navigation. */\nexport interface PageContext {\n url?: string;\n /** A route PATTERN ('/orders/:id') beats a raw path — it tells the agent what KIND of page this is. */\n route?: string;\n path?: string;\n title?: string;\n locale?: string;\n /** 1–2 sentences, written the way you'd brief a colleague. The highest-value field by far. */\n description?: string;\n /** Things the page is about. These also become @-mentionable in the composer, for free. */\n entities?: PageEntity[];\n /** Allowlisted only. Never a dump of app state. */\n data?: Record<string, unknown>;\n}\n\nexport interface PageEntity {\n /** Host kinds are namespaced (`x:ticker`) so they can never collide with matterfact's own. */\n kind: string;\n id: string;\n label: string;\n /** Pre-rendered, agent-readable. Keep it short. */\n text?: string;\n data?: Record<string, unknown>;\n}\n\n/** A co-embedded artifact's read-only capability, for the backend to materialize its\n * data. Backend-only — never rendered. `token` is the artifact's own embed token. */\nexport interface ArtifactGrant {\n id: string;\n owner: string;\n token: string;\n}\n\n/**\n * A snapshot of the page as the agent sees it.\n *\n * `yaml` is Playwright's ARIA-snapshot rendering — role, accessible name, state,\n * and a ref on anything interactable:\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - button \"Export CSV\" [ref=e9]\n *\n * NOT raw HTML. A real page is tens of thousands of tokens of div soup, it gives\n * the model no handle to act with, and it is a prompt-injection firehose. The\n * a11y tree is a tenth the size and is the only signal that survives in-page —\n * `getEventListeners()` is DevTools-only, so listener-sniffing (the browser-use\n * approach) cannot see a single React handler on a real customer's app.\n */\nexport interface DomSnapshot {\n yaml: string;\n /** Monotonic. A ref is only valid within the snapshot that minted it. */\n seq: number;\n /** True when the walk hit its node budget and stopped. The agent must be told it is not seeing everything. */\n truncated: boolean;\n}\n\n/**\n * Where the user's attention is RIGHT NOW.\n *\n * This is the difference between an assistant that can read your page and one that\n * knows what you're doing. A full DOM snapshot answers \"what is on this screen\"; this\n * answers \"what are you looking at and working in\" — which is what a colleague\n * leaning over reads first. It is small, so it rides on every turn, where the full\n * snapshot does not.\n *\n * Every field here is a LABEL or a REF, never a value. `selection` is the sharpest\n * intent signal there is (\"this is the thing I'm asking about\"), and for exactly that\n * reason it is also where a user might have highlighted their own email — so it is\n * redacted and honours data-mf-private like everything else.\n */\nexport interface FocusContext {\n /** Text the user has selected. The single strongest \"I'm asking about this\" signal. Redacted. */\n selection?: string;\n /** The control the user is working IN — by label and ref, never its contents. */\n focused?: { ref?: ElementRef; label: string; role: string };\n /** The refs currently in the viewport: the handful of things actually on screen, out of the whole tree. */\n visibleRefs?: ElementRef[];\n /** How far down the page they are, 0–1. A cheap proxy for \"which part am I reading\". */\n scroll?: number;\n}\n\n/** Something the user did. Shaped after PostHog's autocapture — one readable line, not a replay frame. */\nexport interface ActivityEvent {\n seq: number;\n ts: number;\n type: 'nav' | 'click' | 'input' | 'submit' | 'selection' | 'custom';\n /** Human-readable: 'clicked button \"Export CSV\"'. Semantic, not coordinates. */\n summary: string;\n ref?: ElementRef;\n data?: Record<string, unknown>;\n}\n\n/**\n * A tool the HOST page exposes to the agent.\n *\n * Deliberately shaped as a superset of WebMCP (`navigator.modelContext`, W3C\n * WebML CG draft / Chrome origin trial). A customer who adopts WebMCP should be\n * able to hand us their existing tool declarations unchanged.\n */\nexport interface HostTool {\n name: string;\n description: string;\n /** JSON Schema. */\n inputSchema: Record<string, unknown>;\n /**\n * A read-only tool may run without asking. Anything that MUTATES the page\n * requires the user to confirm, every time — see the note on ToolCall.\n */\n readOnly?: boolean;\n}\n\nexport type HostToWidget =\n | { type: 'host.ready'; protocol: number; origin: string }\n | { type: 'host.context'; context: PageContext }\n | { type: 'host.focus'; focus: FocusContext }\n | { type: 'host.snapshot'; snapshot: DomSnapshot }\n | { type: 'host.region'; ref: ElementRef; yaml: string }\n | { type: 'host.activity'; events: ActivityEvent[] }\n | { type: 'host.artifactGrants'; grants: ArtifactGrant[] }\n | { type: 'host.tools'; tools: HostTool[] }\n | {\n type: 'host.toolResult';\n callId: string;\n ok: boolean;\n result?: unknown;\n error?: string;\n }\n | { type: 'host.auth'; token: string; expiresAt: number }\n | { type: 'host.theme'; mode: 'light' | 'dark' };\n\n/* ──────────────────────────── widget → host ───────────────────────────── */\n\n/**\n * The agent asking the host to do something.\n *\n * THE SECURITY MODEL, stated once: the page's content is UNTRUSTED. Text on the\n * page can try to instruct the agent, and the moment the agent can act, that stops\n * being a bad answer and becomes a bad ACTION. So:\n *\n * - v1 is READ-ONLY. `snapshot` and `activity` flow; no tool mutates the page.\n * - A tool that is not `readOnly` must be confirmed by the USER, every call. Not\n * \"unless the host opts out\" — every call. The trigger may have been written by\n * the page.\n * - The host is the enforcement point, not the widget. The widget can be lied to;\n * the loader runs in the page and decides what actually happens.\n */\nexport interface ToolCall {\n callId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\nexport type WidgetToHost =\n | { type: 'widget.ready'; protocol: number }\n /**\n * Ask for the FULL page snapshot. This is the agent PULLING detail, not us pushing\n * it: the focus context rides on every turn, but the whole tree is fetched only\n * when the agent decides it needs to look — cheaper, and it reads what's relevant\n * to the question instead of drowning in the footer nav every turn.\n */\n | { type: 'widget.requestSnapshot' }\n /** Zoom in: the a11y sub-tree under one ref (a table, a form, a card the agent cares about). */\n | { type: 'widget.readRegion'; ref: ElementRef }\n | { type: 'widget.callTool'; call: ToolCall }\n /** Chat opened/closed — the loader resizes the iframe and starts/stops observing. */\n | { type: 'widget.setOpen'; open: boolean }\n | { type: 'widget.resize'; height: number }\n /**\n * Maximize / restore. Expanded makes the iframe fill the viewport (with a small\n * margin) so the composer's `/` picker, mention previews, and the transcript have\n * room the corner popup can't give them. The loader owns the iframe size, so only\n * it can do this — `widget.resize` (height-only) can't widen the popup.\n */\n | { type: 'widget.setExpanded'; expanded: boolean }\n /**\n * Launcher drag. The widget tracks the gesture; the host only moves the element.\n *\n * It has to be this way round, and the reason is easy to get wrong: a press that starts\n * inside an iframe is implicitly captured by that iframe, so every pointermove and the\n * pointerup belong to the widget's document until the button comes up. The host cannot\n * see them at all — not even through an overlay of its own, because capture beats hit\n * testing. So the host cannot take over a drag mid-gesture; it can only be told.\n *\n * `dx`/`dy` are deltas in SCREEN coordinates, which is the other half of the trick:\n * client coordinates are measured against the iframe's own viewport, and the iframe is\n * being moved under the cursor as the drag proceeds — so the pointer would appear to\n * stop moving and the launcher would stall after one step. Screen coordinates are\n * absolute and immune to that feedback loop.\n */\n | { type: 'widget.dragStart' }\n | { type: 'widget.dragMove'; dx: number; dy: number }\n | { type: 'widget.dragEnd' }\n /**\n * Grow/shrink the iframe to fit the launcher's context menu. The collapsed launcher is\n * only ~64px tall, so a menu rendered inside it would be clipped by the iframe's own\n * bounds — the host has to make room before it can be seen. `widget.resize` can't do\n * this: it's height-only AND ignored while closed.\n */\n | { type: 'widget.setMenu'; open: boolean; height: number }\n /** Put the launcher back in the default corner and forget the dragged position. */\n | { type: 'widget.resetPos' }\n /** Get out of the way until the page reloads (a menu action, not a setting). */\n | { type: 'widget.hide' }\n /** The widget has no session; the host must run the hosted-login popup. */\n | { type: 'widget.needsAuth' };\n\n/* ───────────────────────────── envelope ───────────────────────────────── */\n\n/**\n * Everything on the wire is wrapped.\n *\n * `channel` keeps us out of the host page's own postMessage traffic (and out of\n * every other widget's). The receiver ALSO checks `event.origin` against an\n * allowlist and `event.source` against the expected window, on every single\n * message — a namespace is not a security boundary, it is a politeness.\n */\nexport interface Envelope<T> {\n channel: typeof CHANNEL;\n protocol: number;\n /** Correlates a response to its request; absent for notifications. */\n id?: string;\n payload: T;\n}\n\nexport function envelope<T>(payload: T, id?: string): Envelope<T> {\n return {\n channel: CHANNEL,\n protocol: PROTOCOL_VERSION,\n ...(id ? { id } : {}),\n payload,\n };\n}\n\nexport function isEnvelope(data: unknown): data is Envelope<unknown> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { channel?: unknown }).channel === CHANNEL\n );\n}\n","import {\n CHANNEL,\n PROTOCOL_VERSION,\n envelope,\n isEnvelope,\n type HostToWidget,\n type WidgetToHost,\n} from './protocol';\n\n/**\n * The matterfact embed loader.\n *\n * <script src=\"https://cdn.matterfact.com/embed.js\"\n * data-key=\"pk_live_acme_...\"\n * defer></script>\n *\n * This file runs on EVERY page load of a customer's site, so it is deliberately\n * tiny and deliberately dumb:\n *\n * - zero dependencies\n * - it does NOT read the DOM. The snapshot/activity code is a separate chunk,\n * fetched only when the user actually opens the chat. A customer should pay\n * nothing for a widget nobody clicked.\n * - it does NOT bundle React, or a CSS framework, or an RPC library.\n *\n * `iframe-resizer` is the thing you will be tempted to reach for here. It is\n * GPL-3.0 and cannot ship in this file. The ResizeObserver bridge below is the\n * fifteen lines it would have cost you anyway.\n */\n\n/** Returns a token this matterfact deployment's auth provider trusts (Firebase idToken,\n * Entra token, …). May be async; return null when there's no signed-in user. */\nexport type AuthTokenProvider = () => string | null | Promise<string | null>;\n\nexport interface LoaderConfig {\n publishableKey: string;\n /** Origin of the widget. Overridable for dev/self-hosted; defaults to production. */\n origin: string;\n theme: 'light' | 'dark' | 'auto';\n /** Optional label identifying THIS embedding, when one app embeds the agent in more\n * than one place (e.g. \"orders\" vs \"support\"). Stamped on runs/threads so usage and\n * history can be told apart per surface. Free-form; the app_id (from the session)\n * is the trusted half. */\n surface: string;\n /**\n * OPTIONAL host-auth passthrough, for TRUSTED first-party embeds (the admin portal,\n * EMC). When set, the host page already holds a token this deployment's auth provider\n * trusts (its Firebase idToken, an Entra token, …); the loader hands it to the widget\n * on `widget.needsAuth` instead of opening a sign-in popup. The backend still verifies\n * the token, so identity can't be forged — this only skips a redundant second sign-in.\n * Called on demand (so tokens can refresh). Absent ⇒ the popup/inline sign-in flow.\n * The `<script>` loader has no config here; it reads window.matterfact.getEmbedAuthToken\n * instead (see provideAuth).\n */\n authTokenProvider?: AuthTokenProvider;\n /**\n * Render INTO this element instead of floating in the corner — for a host that has its\n * own side panel, tool drawer or tab and wants the agent to live there.\n *\n * This inverts who owns the chrome. In corner mode the widget owns everything: it draws\n * its own launcher and it tells us how big to be (setOpen/setExpanded/resize). Inside\n * someone else's panel, both are theirs — a widget that resized its host's drawer, or\n * drew a second floating bubble inside it, is just broken. So here we fill the\n * container, ignore the size messages, and the widget skips the launcher and renders\n * the chat directly.\n *\n * The host also owns visibility: showing and hiding their own panel IS the open/close\n * control, so there is nothing for us to add.\n */\n container?: HTMLElement | null;\n}\n\nconst DEFAULT_ORIGIN = 'https://app.matterfact.com';\n\n/**\n * Has someone asked to see what the widget is doing? `?mfdev=1` on the HOST page.\n *\n * Driven by the host's own URL rather than a `data-` attribute on purpose: an engineer\n * debugging a page they didn't write can add a query param, but they cannot redeploy the\n * customer's site to change a script tag. It's also ephemeral — it lasts exactly as long\n * as that URL, so nobody can leave it on by accident.\n *\n * This only surfaces what the widget already collects FROM THE PAGE IT'S ON, to the\n * person whose page it is. It grants no access: the session, the origin allowlist and\n * the route scope are all enforced server-side and none of them consult this.\n */\nfunction devRequested(): boolean {\n try {\n return new URLSearchParams(location.search).get('mfdev') === '1';\n } catch {\n return false;\n }\n}\n\nfunction readConfig(): LoaderConfig | null {\n // `document.currentScript` is null inside a module or after async execution, so\n // fall back to finding our own tag by src.\n const el =\n (document.currentScript as HTMLScriptElement | null) ??\n document.querySelector<HTMLScriptElement>('script[data-key][src*=\"embed\"]');\n\n const publishableKey = el?.dataset.key;\n if (!publishableKey) {\n console.error('[matterfact] missing data-key on the embed script tag');\n return null;\n }\n // `data-container=\"#panel\"` renders into the host's own element instead of the\n // corner. A selector rather than an element, because a script tag can't hand us a\n // reference — and if it doesn't resolve we fall back to the corner rather than\n // vanish: a widget nobody can find looks identical to a broken install.\n const sel = el?.dataset.container;\n const container = sel ? document.querySelector<HTMLElement>(sel) : null;\n if (sel && !container) {\n console.error(\n `[matterfact] data-container=\"${sel}\" matched nothing; falling back to the corner`,\n );\n }\n\n return {\n publishableKey,\n origin: el?.dataset.origin || DEFAULT_ORIGIN,\n theme: (el?.dataset.theme as LoaderConfig['theme']) || 'auto',\n surface: el?.dataset.surface || '',\n container,\n };\n}\n\n/** Where the user dragged the launcher, in px from the viewport's bottom-right. */\ninterface DragPos {\n right: number;\n bottom: number;\n}\n\nconst POS_KEY = 'mf.embed.pos';\n\nclass EmbedHost {\n private iframe: HTMLIFrameElement | null = null;\n private shadow: ShadowRoot | null = null;\n /** Buffered until the widget says it's listening — postMessage before load is dropped silently. */\n private queue: HostToWidget[] = [];\n private ready = false;\n private open = false;\n private expanded = false;\n /** Null until the user drags; then it pins the corner offset and survives reloads. */\n private pos: DragPos | null = null;\n /** Where the launcher sat when the current drag began; deltas are applied to this. */\n private dragBase: DragPos | null = null;\n /** Loaded on first open. Holds everything that touches the customer's DOM. */\n private context: Promise<typeof import('./context')> | null = null;\n /** The host element; kept so `destroy()` can remove it (React lifecycle). */\n private hostEl: HTMLDivElement | null = null;\n /** Rendering into the host's own element: they own the box, the chrome and visibility. */\n private readonly inline: boolean;\n\n constructor(private config: LoaderConfig) {\n this.inline = !!config.container;\n }\n\n mount() {\n // A CLOSED shadow root, on a container that resets every inherited property.\n //\n // We are a guest on someone else's page. Their CSS must not reach into us, our\n // CSS must not leak out, and their JS should not be able to walk into our tree\n // by accident (closed mode: `host.shadowRoot` is null). `contain` stops our\n // layout/paint from invalidating theirs.\n const host = document.createElement('div');\n this.hostEl = host;\n host.id = 'matterfact-embed';\n\n if (this.inline) {\n // The container's box IS the widget's box. No fixed positioning, no z-index\n // scramble, no drag: where this sits is the host's layout problem, which is the\n // entire point of asking for it.\n host.style.cssText = [\n 'all: initial',\n 'position: relative',\n 'display: block',\n 'width: 100%',\n 'height: 100%',\n 'contain: layout style',\n ].join(';');\n this.config.container!.appendChild(host);\n } else {\n this.pos = this.readPos();\n host.style.cssText = [\n 'all: initial',\n 'position: fixed',\n `right: ${this.pos ? this.pos.right : 20}px`,\n `bottom: ${this.pos ? this.pos.bottom : 20}px`,\n // Below the max so a host that genuinely needs to cover us (a modal, a cookie\n // banner they are legally obliged to show) still can.\n 'z-index: 2147483000',\n 'contain: layout style',\n ].join(';');\n document.body.appendChild(host);\n }\n\n this.shadow = host.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n // Shared prefix, then only what differs. This ships on every page load and the stub\n // has ~no headroom, so the two modes must not each carry a whole stylesheet.\n //\n // Inline fills the host's box and adds nothing: no radius, no shadow. Their panel\n // already has whatever chrome they chose; ours would sit inside it looking like a\n // mistake.\n style.textContent =\n ':host{all:initial}iframe{border:0;display:block;color-scheme:light dark;}' +\n (this.inline\n ? 'iframe{width:100%;height:100%}'\n : // Hairline ring + soft ambient: the widget must read as a crisp card on\n // ANY host background, including pure white where a shadow alone bleeds.\n 'iframe{border-radius:12px;box-shadow:0 0 0 1px #00000014,0 8px 40px #00000029;width:400px;' +\n 'height:64px;transition:height .18s ease,width .18s ease}' +\n 'iframe[data-open=\"true\"]{width:420px;height:640px}' +\n // Expanded: a full-height SIDE PANEL docked to the host's right edge, not a\n // viewport-covering overlay — room for the composer's slash-picker and mention\n // previews, capped to the viewport on narrow screens.\n 'iframe[data-open=\"true\"][data-expanded=\"true\"]{width:min(600px,calc(100vw - 40px));' +\n 'height:calc(100vh - 40px)}');\n this.shadow.appendChild(style);\n\n const iframe = document.createElement('iframe');\n iframe.title = 'matterfact assistant';\n //\n // `allow-same-origin` is REQUIRED, and leaving it out is the trap.\n //\n // Without it the framed document gets an OPAQUE origin: its postMessage arrives\n // as `event.origin === \"null\"`, so our own origin check rejects the handshake and\n // the bridge silently never connects. It also denies the widget any storage at\n // all — no session, no auth, ever.\n //\n // The familiar warning — \"allow-scripts + allow-same-origin lets the frame escape\n // its sandbox\" — is about a frame that is SAME-ORIGIN WITH THE FRAMER, which can\n // then reach up and delete its own sandbox attribute. Ours is cross-origin to the\n // host by construction (that is the entire security model), so it cannot touch\n // this element. What the sandbox still buys us is real: no top-level navigation,\n // no downloads, no pointer lock.\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox',\n );\n // Dictation needs an explicit permissions-policy grant: without `allow`,\n // getUserMedia inside the frame is hard-blocked no matter what the user\n // approves. The bare token scopes the grant to the iframe's own origin\n // (the app), not the host page. A host page can still deny the feature\n // via its own Permissions-Policy response header — outside our control.\n iframe.setAttribute('allow', 'microphone');\n iframe.src =\n `${this.config.origin}/embed/chat?k=${encodeURIComponent(\n this.config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}` +\n (this.config.surface\n ? `&s=${encodeURIComponent(this.config.surface)}`\n : '') +\n (devRequested() ? '&dev=1' : '') +\n (this.inline ? '&inline=1' : '');\n this.iframe = iframe;\n this.shadow.appendChild(iframe);\n\n window.addEventListener('message', this.onMessage);\n }\n\n /**\n * Every message is checked twice, on every single message — not once at setup.\n *\n * `channel` is a namespace, not a boundary. The origin and source checks are the\n * boundary: any frame on the page can postMessage us, and a page with an ad iframe\n * on it has plenty of frames.\n */\n private onMessage = (event: MessageEvent) => {\n if (event.origin !== this.config.origin) return;\n if (event.source !== this.iframe?.contentWindow) return;\n if (!isEnvelope(event.data)) return;\n\n const msg = event.data.payload as WidgetToHost;\n\n switch (msg.type) {\n case 'widget.ready':\n this.ready = true;\n this.send({\n type: 'host.ready',\n protocol: PROTOCOL_VERSION,\n origin: location.origin,\n });\n this.flush();\n // Inline has no \"open\" event to hang this off — the chat is visible the moment\n // the host renders their panel, so the eye has to load now or the agent is\n // blind to the page for the whole session. The corner keeps its lazy load: a\n // page whose visitors never click still pays nothing.\n if (this.inline) void this.loadContext();\n break;\n\n case 'widget.setOpen':\n // Inline: the host's panel IS the open/close control. There's no popup to size.\n if (this.inline) break;\n this.open = msg.open;\n this.iframe?.setAttribute('data-open', String(msg.open));\n // Closing the popup always restores it — a widget that reopens should start\n // at the corner size, not wherever it was maximized to last time.\n if (!msg.open) {\n this.expanded = false;\n this.iframe?.setAttribute('data-expanded', 'false');\n }\n // The DOM code is fetched HERE — the first time someone actually opens the\n // chat — and never on a page where they don't.\n if (msg.open) void this.loadContext();\n break;\n\n case 'widget.setExpanded':\n // Inline: \"maximize\" would mean resizing someone else's panel from inside it.\n if (this.inline) break;\n this.expanded = msg.expanded;\n this.iframe?.setAttribute('data-expanded', String(msg.expanded));\n // A prior widget.resize set an inline height; clear it so the maximized CSS\n // (and, on restore, the popup CSS) wins.\n if (this.iframe) this.iframe.style.height = '';\n break;\n\n case 'widget.resize':\n // Inline: the container's height is the host's business, and an auto-grow here\n // would fight their layout every time the transcript got longer.\n if (this.inline) break;\n // Height auto-grow is for the corner popup only; when maximized the CSS owns\n // the size, so don't let a resize shrink it back.\n if (this.iframe && this.open && !this.expanded) {\n this.iframe.style.height = `${Math.min(msg.height, window.innerHeight - 40)}px`;\n }\n break;\n\n case 'widget.requestSnapshot':\n void this.loadContext().then((m) => m.sendSnapshot(this.send));\n break;\n\n case 'widget.readRegion':\n void this.loadContext().then((m) => m.sendRegion(msg.ref, this.send));\n break;\n\n case 'widget.callTool':\n void this.loadContext().then((m) => m.callTool(msg.call, this.send));\n break;\n\n // Everything below is LAUNCHER chrome: there is no launcher inline (the widget\n // doesn't draw one), and moving or hiding the host's own panel from inside it\n // would be us redecorating their app. An older cached loader could still be told\n // any of these by a newer widget, so they're guarded rather than assumed absent.\n case 'widget.dragStart':\n if (this.inline) break;\n this.dragBase = this.cornerOffset();\n break;\n\n case 'widget.dragMove':\n if (this.inline) break;\n this.dragTo(msg.dx, msg.dy);\n break;\n\n case 'widget.dragEnd':\n if (this.inline) break;\n this.dragBase = null;\n this.writePos(this.pos);\n break;\n\n case 'widget.setMenu':\n if (this.inline) break;\n // Make room for the launcher's menu. Only meaningful while collapsed — open,\n // the popup is already taller than any menu.\n if (this.iframe && !this.open) {\n this.iframe.style.height = msg.open ? `${64 + msg.height}px` : '';\n }\n break;\n\n case 'widget.resetPos':\n if (this.inline) break;\n this.resetPos();\n break;\n\n case 'widget.hide':\n // Inline: hiding is the host's panel to hide. Blanking their drawer from in\n // here would leave them with an empty box and no way to get it back.\n if (this.inline) break;\n if (this.hostEl) this.hostEl.style.display = 'none';\n break;\n\n case 'widget.needsAuth':\n void this.provideAuth();\n break;\n }\n };\n\n /**\n * Own a drag for its lifetime.\n *\n * The widget reports the press and then goes quiet: a cross-origin iframe only gets\n * pointer events while the pointer is over it, and a drag leaves that box immediately.\n * So we lay a transparent layer over the whole viewport and track the gesture in the\n * host document, where it can't be lost. The layer also stops the pointer landing on\n * the customer's own UI mid-drag (text selection, hover states, stray clicks).\n *\n * We are the dumb half on purpose — see `widget.dragMove` in the protocol for why the\n * widget has to own the gesture. All we do is take a delta and place the element.\n */\n private cornerOffset(): DragPos {\n const rect = this.hostEl!.getBoundingClientRect();\n return {\n right: window.innerWidth - rect.right,\n bottom: window.innerHeight - rect.bottom,\n };\n }\n\n private dragTo(dx: number, dy: number) {\n if (!this.dragBase || !this.hostEl) return;\n const rect = this.hostEl.getBoundingClientRect();\n // Clamp to the viewport: the position persists, so letting someone drop the launcher\n // off-screen would strand it there across reloads with no way back to it.\n const maxRight = Math.max(0, window.innerWidth - rect.width);\n const maxBottom = Math.max(0, window.innerHeight - rect.height);\n const right = Math.min(Math.max(0, this.dragBase.right - dx), maxRight);\n const bottom = Math.min(Math.max(0, this.dragBase.bottom - dy), maxBottom);\n this.pos = { right, bottom };\n this.hostEl.style.right = `${right}px`;\n this.hostEl.style.bottom = `${bottom}px`;\n }\n\n /** Reset to the default corner (a menu action — the drag is otherwise sticky). */\n private resetPos() {\n this.pos = null;\n this.writePos(null);\n if (this.hostEl) {\n this.hostEl.style.right = '20px';\n this.hostEl.style.bottom = '20px';\n }\n }\n\n private readPos(): DragPos | null {\n // First-party storage on the CUSTOMER's origin, so each site remembers its own spot.\n // Never throws: storage is unavailable in some embedding contexts, and a widget that\n // can't remember where it was put is fine — one that fails to mount is not.\n try {\n const raw = localStorage.getItem(POS_KEY);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<DragPos>;\n return typeof p?.right === 'number' && typeof p?.bottom === 'number'\n ? { right: p.right, bottom: p.bottom }\n : null;\n } catch {\n return null;\n }\n }\n\n private writePos(pos: DragPos | null) {\n try {\n if (pos) localStorage.setItem(POS_KEY, JSON.stringify(pos));\n else localStorage.removeItem(POS_KEY);\n } catch {\n /* storage denied — the position just won't survive the reload */\n }\n }\n\n /**\n * Answer `widget.needsAuth`. If a trusted first-party host has an auth-token provider,\n * call it and hand the token straight to the widget via `host.auth` — no popup. The\n * provider comes from EITHER the programmatic config (the React `<MatterfactAgent\n * getAuthToken>` prop) OR a global the host page sets for the `<script>` loader:\n *\n * window.matterfact = { getEmbedAuthToken: () => getIdToken(user) };\n *\n * Read fresh at call time (not at readConfig), so a global set after the loader booted\n * — e.g. once the host's auth is ready — is still picked up. Otherwise fall back to the\n * hosted-login popup. `expiresAt: 0`: the widget doesn't cache it, it exchanges the\n * token for a rotating embed session anyway.\n */\n private async provideAuth() {\n const provider =\n this.config.authTokenProvider ??\n (globalThis as { matterfact?: { getEmbedAuthToken?: AuthTokenProvider } })\n .matterfact?.getEmbedAuthToken;\n if (provider) {\n try {\n const token = await provider();\n if (token) {\n this.send({ type: 'host.auth', token, expiresAt: 0 });\n return;\n }\n } catch {\n /* fall through to the popup */\n }\n }\n void this.loadContext().then((m) => m.beginAuth(this.config, this.send));\n }\n\n private loadContext() {\n // One chunk, one fetch, cached. Everything that can see the customer's page\n // lives behind this boundary.\n this.context ??= import('./context').then((m) => {\n m.start(this.send, this.config.origin);\n // start() emits the OS-preference theme. An explicit data-theme on the\n // script tag is the host's choice — resend it so it wins over auto-detect\n // (a light-branded site must be able to force a light widget on a dark-OS\n // visitor, and vice versa).\n if (this.config.theme !== 'auto') {\n this.send({ type: 'host.theme', mode: this.config.theme });\n }\n return m;\n });\n return this.context;\n }\n\n private send = (msg: HostToWidget) => {\n if (!this.ready) {\n this.queue.push(msg);\n return;\n }\n // targetOrigin is the widget's exact origin — never '*'. A '*' here would\n // broadcast the customer's page content to whatever happens to be listening.\n this.iframe?.contentWindow?.postMessage(envelope(msg), this.config.origin);\n };\n\n private flush() {\n const pending = this.queue;\n this.queue = [];\n for (const m of pending) this.send(m);\n }\n\n /** Tear down: stop listening and remove the host element. For the React wrapper's\n * unmount — the vanilla `<script>` loader lives for the page's lifetime and never\n * calls this. */\n destroy() {\n window.removeEventListener('message', this.onMessage);\n this.hostEl?.remove();\n this.hostEl = null;\n this.iframe = null;\n this.shadow = null;\n this.ready = false;\n }\n}\n\n/**\n * Programmatic entry — mount the widget from a config object instead of the DOM\n * `<script data-*>`. This is what the React wrapper (`@matterfact/embed/react`) drives;\n * the vanilla loader below reads the script tag and calls this same class.\n */\nexport function mount(config: LoaderConfig): EmbedHost {\n const host = new EmbedHost(config);\n host.mount();\n return host;\n}\n\nexport { EmbedHost, CHANNEL, readConfig };\n"]}