@matterfact/embed 0.4.0 → 0.6.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 (54) hide show
  1. package/README.md +62 -6
  2. package/dist/{chunk-523BCS2Z.js → chunk-4Q2ROXLR.js} +2 -2
  3. package/dist/chunk-7I37ZFAJ.js +2 -0
  4. package/dist/{chunk-Z4WT3TIZ.js → chunk-AXKXNYRT.js} +39 -38
  5. package/dist/chunk-AXKXNYRT.js.map +1 -0
  6. package/dist/chunk-D7R6WVHG.js +2 -0
  7. package/dist/chunk-D7R6WVHG.js.map +7 -0
  8. package/dist/{chunk-SBNMM3ZV.js → chunk-RS6RMZ77.js} +39 -37
  9. package/dist/chunk-RS6RMZ77.js.map +1 -0
  10. package/dist/{context-432WQST4.js → context-WU2F5CBC.js} +6 -4
  11. package/dist/context-YX2KXFLI.js +3 -0
  12. package/dist/{context-KZAUOIR6.js.map → context-YX2KXFLI.js.map} +1 -1
  13. package/dist/embed.js +1 -1
  14. package/dist/embed.js.map +2 -2
  15. package/dist/index.cjs +58 -50
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +37 -3
  18. package/dist/index.d.ts +37 -3
  19. package/dist/index.js +22 -15
  20. package/dist/index.js.map +1 -1
  21. package/dist/react.cjs +64 -50
  22. package/dist/react.cjs.map +1 -1
  23. package/dist/react.d.cts +35 -1
  24. package/dist/react.d.ts +35 -1
  25. package/dist/react.js +28 -15
  26. package/dist/react.js.map +1 -1
  27. package/dist/{snapshot-SOMSG2OF.js → snapshot-JOGZWESK.js} +2 -2
  28. package/dist/{snapshot-Q3CALMHD.js → snapshot-MUXE7KXX.js} +3 -3
  29. package/dist/{snapshot-Q3CALMHD.js.map → snapshot-MUXE7KXX.js.map} +1 -1
  30. package/examples/README.md +46 -0
  31. package/examples/demo-host/index.html +163 -0
  32. package/examples/demo-host/serve.mjs +62 -0
  33. package/examples/embed-demo/.env.example +24 -0
  34. package/examples/embed-demo/README.md +72 -0
  35. package/examples/embed-demo/index.html +12 -0
  36. package/examples/embed-demo/package.json +25 -0
  37. package/examples/embed-demo/src/App.tsx +239 -0
  38. package/examples/embed-demo/src/config.ts +43 -0
  39. package/examples/embed-demo/src/main.tsx +10 -0
  40. package/examples/embed-demo/src/styles.css +354 -0
  41. package/examples/embed-demo/tsconfig.json +16 -0
  42. package/examples/embed-demo/vite.config.ts +11 -0
  43. package/examples/host-panel.html +259 -0
  44. package/package.json +3 -2
  45. package/dist/chunk-SBNMM3ZV.js.map +0 -1
  46. package/dist/chunk-URIBHOOQ.js +0 -2
  47. package/dist/chunk-XLQ36ZMV.js +0 -2
  48. package/dist/chunk-XLQ36ZMV.js.map +0 -7
  49. package/dist/chunk-Z4WT3TIZ.js.map +0 -1
  50. package/dist/context-KZAUOIR6.js +0 -3
  51. /package/dist/{chunk-523BCS2Z.js.map → chunk-4Q2ROXLR.js.map} +0 -0
  52. /package/dist/{chunk-URIBHOOQ.js.map → chunk-7I37ZFAJ.js.map} +0 -0
  53. /package/dist/{context-432WQST4.js.map → context-WU2F5CBC.js.map} +0 -0
  54. /package/dist/{snapshot-SOMSG2OF.js.map → snapshot-JOGZWESK.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/context.ts"],
4
+ "sourcesContent": ["import type {\n ActivityEvent,\n FocusContext,\n HostToWidget,\n PageContext,\n PageEntity,\n ToolCall,\n} from './protocol';\n\n/** The origin serving our chat \u2014 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 \u2014 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 \u2014 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/** Set once by `start()`. False \u21D2 the host opted out of ALL page observation \u2014 every\n * exported entry point below that would otherwise read or send the page checks this. */\nlet pageContextOn = true;\n\n/**\n * A host callback that returns the DECLARED page context on demand \u2014 the pull-based\n * counterpart to the static `window.matterfact.context` global. Symmetric with\n * `AuthTokenProvider`: the React `<MatterfactAgent getPageContext>` prop supplies it; the\n * `<script>` loader uses `window.matterfact.getPageContext` instead (see resolveDeclaredContext).\n */\nexport type PageContextProvider = () =>\n | PageContext\n | null\n | undefined\n | Promise<PageContext | null | undefined>;\n/** The programmatic pull callback, set by `start()`. Read fresh on every publish. */\nlet contextProvider: PageContextProvider | undefined;\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 teardown state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\n/**\n * Everything below is module-global bookkeeping so `stop()` (see `start()`, bottom of\n * file) can undo exactly what `start()`/`watchNavigation()` installed \u2014 remove every\n * listener, restore `history` to what it was before we wrapped it, and forget any\n * DOM-walk module we pulled in. All of this outlives a single `EmbedHost`; see\n * `stop()`'s doc comment for why that's the bug this exists to close.\n */\n\n/** The `fire` closure `watchNavigation()` handed to `popstate` \u2014 the only handle we\n * have to remove that listener again. */\nlet navFire: (() => void) | null = null;\n/** The `history.pushState`/`replaceState` this module wrapped, captured so `stop()`\n * can restore them EXACTLY rather than re-wrapping (which is how the old code\n * double-fired navigation on a second `start()`). */\nlet origPushState: History['pushState'] | null = null;\nlet origReplaceState: History['replaceState'] | null = null;\n/** Set once `sendSnapshot`/`sendRegion`/`readFocus` actually pull in the DOM-walk\n * chunk (`./dom/snapshot`) \u2014 never imported eagerly, so `stop()` doesn't pay for a\n * chunk that a host who only ever opted out (and never opened a snapshot) never\n * loaded in the first place. */\nlet snapshotModule: { clearRefs: () => void } | null = null;\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 redaction \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\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 \u2014 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 \u2014 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/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 page context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\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 \u2014 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 \u2014 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 \u2014 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\n/**\n * Merge the host's DECLARED context with what we auto-detect. Auto-detected fields\n * (url/path/title/locale, co-embedded artifact entities, opaque-frame count) are additive:\n * a declared value wins where they overlap (the `...declared` spread), and found entities\n * append to declared ones.\n */\nexport function buildPageContext(declared: PageContext): PageContext {\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\n/** Back-compat: build context from the static `window.matterfact.context` global only (sync). */\nexport function readPageContext(): PageContext {\n return buildPageContext(\n (window as { matterfact?: { context?: PageContext } }).matterfact\n ?.context ?? {},\n );\n}\n\n/**\n * Resolve the host's DECLARED context, preferring a pull callback over the static global so\n * a virtualized SPA can hand us fresh context per turn. First non-null wins:\n * 1. the programmatic `getPageContext` provider (React `<MatterfactAgent getPageContext>`),\n * 2. the `<script>`-loader global `window.matterfact.getPageContext()`,\n * 3. the static `window.matterfact.context`.\n */\nasync function resolveDeclaredContext(): Promise<PageContext> {\n const mf = (\n window as {\n matterfact?: {\n context?: PageContext;\n getPageContext?: PageContextProvider;\n };\n }\n ).matterfact;\n if (contextProvider) {\n const c = await contextProvider();\n if (c) return c;\n }\n if (mf?.getPageContext) {\n const c = await mf.getPageContext();\n if (c) return c;\n }\n return mf?.context ?? {};\n}\n\n/**\n * Publish the current declared+detected context as `host.context`. Async because the pull\n * callback may be (a host might read a store). Rapid calls just re-publish \u2014 for idempotent\n * context, last-writer-wins is fine. No-op when the host opted out of page observation.\n */\nasync function publishContext() {\n if (!pageContextOn) return;\n const declared = await resolveDeclaredContext();\n send?.({ type: 'host.context', context: buildPageContext(declared) });\n}\n\n/**\n * Answer a `widget.requestContext` (the pull path): publish context NOW, so a turn assembled\n * right after carries the current context rather than the context as of the last route\n * change. No-op when page observation is off.\n */\nexport function provideContext() {\n void publishContext();\n}\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 artifact grants (backend-only) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\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/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 activity \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\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}` \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 \"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)} \u2192 \"${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 \u2014 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 void publishContext();\n publishArtifactGrants();\n };\n // Captured so stop() can remove exactly this listener, and so history.pushState/\n // replaceState get restored to what they were before we wrapped them \u2014 never\n // re-wrapped on top of an existing wrap (that was the pre-existing bug: a second\n // start() used to wrap the ALREADY-wrapped methods, double-firing every nav).\n navFire = fire;\n\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = history[name];\n if (name === 'pushState') origPushState = orig as History['pushState'];\n else origReplaceState = orig as History['replaceState'];\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/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 focal context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 loadSnapshotModule();\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\n/** The one place any of the three call sites below reach into the DOM-walk chunk \u2014\n * so `stop()` has a single `snapshotModule` to check without importing anything\n * itself (see the teardown-state block above). */\nasync function loadSnapshotModule() {\n const m = await import('./dom/snapshot');\n snapshotModule = m;\n return m;\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/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 snapshot \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\nlet snapshotSeq = 0;\n\nexport async function sendSnapshot(emit: Send) {\n // pageContext: false \u21D2 no snapshot, ever \u2014 a `widget.requestSnapshot` must not be\n // able to reintroduce the page observation the host explicitly turned off.\n if (!pageContextOn) return;\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 loadSnapshotModule();\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 \u2014 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 // Mirrors sendSnapshot's guard: a `widget.readRegion` for a ref minted before\n // opt-out must not pull a live DOM subtree just because the ref is still\n // resolvable (see refs.ts's `clearRefs`, which `stop()` also uses as a backstop).\n if (!pageContextOn) return;\n const { snapshotRegion, resolveRef } = await loadSnapshotModule();\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/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 tools \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\n/**\n * v1 IS READ-ONLY.\n *\n * The page's content is untrusted \u2014 text on it can try to instruct the agent \u2014 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\" \u2014 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/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 stop / start \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\n/**\n * The opposite number of `start()` \u2014 remove every listener it (or `watchNavigation`)\n * installed, restore `history.pushState`/`replaceState` to what they were before we\n * wrapped them, and forget the module-level `send`/`activity`/focus state. Nothing\n * here is a filter over what gets sent afterward \u2014 there is simply nothing left\n * installed to send anything.\n *\n * Why this has to exist at all: everything `start()` installs is MODULE-GLOBAL, and\n * this module outlives any single `EmbedHost`. React remounts `EmbedHost` whenever\n * ANY of its identity-defining props change (react.tsx's effect deps: publishableKey,\n * widgetOrigin, surface, theme, inline, pageContext, dev) \u2014 including just a theme\n * swap, not only a deliberate opt-out. Before this fix, a remount's `start()` call\n * only ever ADDED listeners; the previous mount's were still attached and kept firing\n * into the module `send`, which the new `start()` had just repointed at the NEW\n * widget. Net effect: open once with pageContext on, then remount for any reason\n * (including `pageContext: false`) and the new widget silently keeps receiving\n * clicks/nav/focus collected by the old mount's still-live listeners.\n *\n * Called from two places: the top of `start()` (idempotency \u2014 a second `start()`\n * never doubles up, which also fixes the pre-existing double history-wrap /\n * double-`fire()`-per-navigation bug), and `EmbedHost.destroy()` in loader.ts (a\n * plain unmount with no remount still has to stop, not just wait for a `start()`\n * that may never come).\n */\nexport function stop(): void {\n document.removeEventListener('click', onClick, { capture: true });\n document.removeEventListener('submit', onSubmit, { capture: true });\n document.removeEventListener('change', onChange, { capture: true });\n document.removeEventListener('selectionchange', scheduleFocus);\n document.removeEventListener('focusin', scheduleFocus, { capture: true });\n window.removeEventListener('scroll', scheduleFocus, { capture: true });\n\n if (navFire) {\n window.removeEventListener('popstate', navFire);\n navFire = null;\n }\n // Restore, don't re-wrap: this is what stops a repeated start() from wrapping an\n // already-wrapped pushState/replaceState (the old double-fire-per-nav bug).\n if (origPushState) {\n history.pushState = origPushState;\n origPushState = null;\n }\n if (origReplaceState) {\n history.replaceState = origReplaceState;\n origReplaceState = null;\n }\n\n if (focusTimer) {\n clearTimeout(focusTimer);\n focusTimer = null;\n }\n\n send = null;\n contextProvider = undefined;\n activity.length = 0;\n lastFocus = {};\n widgetOrigin = '';\n\n // Belt-and-suspenders alongside sendRegion's own pageContextOn check (see above):\n // an old ref minted while observation was on must not stay resolvable afterward.\n // Only touches the DOM-walk chunk if it was ever actually loaded \u2014 see\n // loadSnapshotModule's doc comment.\n snapshotModule?.clearRefs();\n}\n\n/**\n * @param pageContext Whether to observe the host page at all. Default `true`. False is\n * the loader's `pageContext: false` opt-out reaching all the way down here: skip every\n * bit of page reading below \u2014 no declared/found context, no artifact grants, no nav/\n * click/submit/change/focus observers \u2014 so there is nothing to send and nothing that\n * could later be asked for (see `widget.requestSnapshot` in loader.ts). Theme detection\n * is unaffected: it reads an OS media query, never the page, so it isn't page context.\n */\nexport function start(\n emit: Send,\n origin?: string,\n pageContext = true,\n provider?: PageContextProvider,\n) {\n // Idempotent: undo whatever a PREVIOUS start() installed before this one installs\n // anything. Without this, a remount (see stop()'s doc comment) leaves the old\n // mount's listeners live, writing into the `send` this call is about to reassign.\n stop();\n\n send = emit;\n widgetOrigin = origin || '';\n lastUrl = location.pathname;\n pageContextOn = pageContext;\n contextProvider = provider;\n\n if (pageContextOn) {\n void 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, {\n capture: true,\n passive: true,\n });\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 \u2014 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\n const theme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light';\n emit({ type: 'host.theme', mode: theme });\n}\n"],
5
+ "mappings": "AAWA,IAAIA,EAAe,GAyBnB,IAAIC,EAAoB,KACpBC,EAAc,EACZC,EAA4B,CAAC,EAC/BC,EAAU,GAGVC,EAAgB,GAchBC,EAcAC,EAA+B,KAI/BC,EAA6C,KAC7CC,EAAmD,KAKnDC,EAAmD,KAIjDC,EAAM,CACV,kCACA,0BACA,iCACA,cACA,6DACA,qDACA,gCACF,EASO,SAASC,EAAOC,EAAsB,CAC3C,IAAIC,EAAMD,EACV,QAAWE,KAAMJ,EAAKG,EAAMA,EAAI,QAAQC,EAAI,YAAY,EACxD,OAAOD,CACT,CAGO,SAASE,EAAUC,EAAsB,CAC9C,GAAIA,EAAG,QAAQ,mBAAmB,EAAG,MAAO,GAE5C,GADYA,EAAG,UACH,QAAS,CACnB,IAAMC,EAAKD,EAAwB,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U,CAC5C,QAAS,GACT,QAAS,EACX,CAAC,EAID,SAAS,iBAAiB,SAAUC,EAAU,CAC5C,QAAS,GACT,QAAS,EACX,CAAC,EAID,SAAS,iBAAiB,kBAAmBwB,EAAe,CAC1D,QAAS,EACX,CAAC,EACD,SAAS,iBAAiB,UAAWA,EAAe,CAClD,QAAS,GACT,QAAS,EACX,CAAC,EACD,OAAO,iBAAiB,SAAUA,EAAe,CAC/C,QAAS,GACT,QAAS,EACX,CAAC,GAGH,IAAMiB,EAAQ,WAAW,8BAA8B,EAAE,QACrD,OACA,QACJd,EAAK,CAAE,KAAM,aAAc,KAAMc,CAAM,CAAC,CAC1C",
6
+ "names": ["widgetOrigin", "send", "activitySeq", "activity", "lastUrl", "pageContextOn", "contextProvider", "navFire", "origPushState", "origReplaceState", "snapshotModule", "PII", "redact", "text", "out", "re", "isPrivate", "el", "t", "artifactIdFromPath", "pathname", "m", "embeddedMatterfactEntities", "widgetOrigin", "frame", "u", "id", "e", "opaqueFrameCount", "f", "buildPageContext", "declared", "found", "opaque", "readPageContext", "resolveDeclaredContext", "mf", "c", "publishContext", "provideContext", "grantsFromIframeSrcs", "srcs", "origin", "raw", "owner", "token", "g", "readArtifactGrants", "publishArtifactGrants", "pushActivity", "controlLabel", "aria", "wrapping", "placeholder", "FORM_CONTROLS", "describe", "role", "label", "ACTIONABLE", "onClick", "ev", "target", "actionable", "onSubmit", "onChange", "tag", "type", "summary", "opt", "watchNavigation", "fire", "url", "name", "orig", "args", "r", "lastFocus", "readFocus", "focus", "sel", "anchor", "active", "snapshot", "loadSnapshotModule", "describeControl", "doc", "scrollable", "focusTimer", "scheduleFocus", "snapshotSeq", "sendSnapshot", "emit", "yaml", "truncated", "visibleRefs", "sendRegion", "ref", "snapshotRegion", "resolveRef", "callTool", "call", "stop", "start", "pageContext", "provider", "theme"]
7
+ }
@@ -8,10 +8,10 @@ var activitySeq = 0;
8
8
  var activity = [];
9
9
  var lastUrl = "";
10
10
  var pageContextOn = true;
11
+ var contextProvider;
11
12
  var navFire = null;
12
13
  var origPushState = null;
13
14
  var origReplaceState = null;
14
- var pendingAuthListener = null;
15
15
  var snapshotModule = null;
16
16
  var PII = [
17
17
  /\b[\w.+-]+@[\w-]+\.[\w.]{2,}\b/g,
@@ -79,8 +79,7 @@ function opaqueFrameCount() {
79
79
  }
80
80
  }).length;
81
81
  }
82
- function readPageContext() {
83
- const declared = window.matterfact?.context ?? {};
82
+ function buildPageContext(declared) {
84
83
  const found = embeddedMatterfactEntities();
85
84
  const opaque = opaqueFrameCount();
86
85
  return {
@@ -101,8 +100,30 @@ function readPageContext() {
101
100
  }
102
101
  };
103
102
  }
104
- function publishContext() {
105
- send?.({ type: "host.context", context: readPageContext() });
103
+ function readPageContext() {
104
+ return buildPageContext(
105
+ window.matterfact?.context ?? {}
106
+ );
107
+ }
108
+ async function resolveDeclaredContext() {
109
+ const mf = window.matterfact;
110
+ if (contextProvider) {
111
+ const c = await contextProvider();
112
+ if (c) return c;
113
+ }
114
+ if (mf?.getPageContext) {
115
+ const c = await mf.getPageContext();
116
+ if (c) return c;
117
+ }
118
+ return mf?.context ?? {};
119
+ }
120
+ async function publishContext() {
121
+ if (!pageContextOn) return;
122
+ const declared = await resolveDeclaredContext();
123
+ send?.({ type: "host.context", context: buildPageContext(declared) });
124
+ }
125
+ function provideContext() {
126
+ void publishContext();
106
127
  }
107
128
  function grantsFromIframeSrcs(srcs, origin) {
108
129
  const out = [];
@@ -196,7 +217,7 @@ function watchNavigation() {
196
217
  if (url === lastUrl) return;
197
218
  lastUrl = url;
198
219
  pushActivity({ type: "nav", summary: `navigated to ${url}` });
199
- publishContext();
220
+ void publishContext();
200
221
  publishArtifactGrants();
201
222
  };
202
223
  navFire = fire;
@@ -241,7 +262,7 @@ function describeControl(el) {
241
262
  return describe(el);
242
263
  }
243
264
  async function loadSnapshotModule() {
244
- const m = await import("./snapshot-SOMSG2OF.js");
265
+ const m = await import("./snapshot-JOGZWESK.js");
245
266
  snapshotModule = m;
246
267
  return m;
247
268
  }
@@ -289,27 +310,6 @@ async function callTool(call, emit) {
289
310
  error: "Host tools are read-only in this version; no action was taken."
290
311
  });
291
312
  }
292
- function beginAuth(config, emit) {
293
- const w = window.open(
294
- `${config.origin}/embed/authorize?k=${encodeURIComponent(
295
- config.publishableKey
296
- )}&o=${encodeURIComponent(location.origin)}`,
297
- "mf_auth",
298
- "width=460,height=640"
299
- );
300
- if (!w) return;
301
- if (pendingAuthListener) window.removeEventListener("message", pendingAuthListener);
302
- const onMsg = (event) => {
303
- if (event.origin !== config.origin) return;
304
- const d = event.data;
305
- if (d?.type !== "mf:embed:auth") return;
306
- window.removeEventListener("message", onMsg);
307
- pendingAuthListener = null;
308
- emit({ type: "host.auth", token: d.token, expiresAt: d.expiresAt });
309
- };
310
- pendingAuthListener = onMsg;
311
- window.addEventListener("message", onMsg);
312
- }
313
313
  function stop() {
314
314
  document.removeEventListener("click", onClick, { capture: true });
315
315
  document.removeEventListener("submit", onSubmit, { capture: true });
@@ -329,31 +329,32 @@ function stop() {
329
329
  history.replaceState = origReplaceState;
330
330
  origReplaceState = null;
331
331
  }
332
- if (pendingAuthListener) {
333
- window.removeEventListener("message", pendingAuthListener);
334
- pendingAuthListener = null;
335
- }
336
332
  if (focusTimer) {
337
333
  clearTimeout(focusTimer);
338
334
  focusTimer = null;
339
335
  }
340
336
  send = null;
337
+ contextProvider = void 0;
341
338
  activity.length = 0;
342
339
  lastFocus = {};
343
340
  widgetOrigin = "";
344
341
  snapshotModule?.clearRefs();
345
342
  }
346
- function start(emit, origin, pageContext = true) {
343
+ function start(emit, origin, pageContext = true, provider) {
347
344
  stop();
348
345
  send = emit;
349
346
  widgetOrigin = origin || "";
350
347
  lastUrl = location.pathname;
351
348
  pageContextOn = pageContext;
349
+ contextProvider = provider;
352
350
  if (pageContextOn) {
353
- publishContext();
351
+ void publishContext();
354
352
  publishArtifactGrants();
355
353
  watchNavigation();
356
- document.addEventListener("click", onClick, { capture: true, passive: true });
354
+ document.addEventListener("click", onClick, {
355
+ capture: true,
356
+ passive: true
357
+ });
357
358
  document.addEventListener("submit", onSubmit, {
358
359
  capture: true,
359
360
  passive: true
@@ -382,13 +383,14 @@ export {
382
383
  redact,
383
384
  isPrivate,
384
385
  artifactIdFromPath,
386
+ buildPageContext,
385
387
  readPageContext,
388
+ provideContext,
386
389
  grantsFromIframeSrcs,
387
390
  sendSnapshot,
388
391
  sendRegion,
389
392
  callTool,
390
- beginAuth,
391
393
  stop,
392
394
  start
393
395
  };
394
- //# sourceMappingURL=chunk-SBNMM3ZV.js.map
396
+ //# sourceMappingURL=chunk-RS6RMZ77.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context.ts"],"sourcesContent":["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/** Set once by `start()`. False ⇒ the host opted out of ALL page observation — every\n * exported entry point below that would otherwise read or send the page checks this. */\nlet pageContextOn = true;\n\n/**\n * A host callback that returns the DECLARED page context on demand — the pull-based\n * counterpart to the static `window.matterfact.context` global. Symmetric with\n * `AuthTokenProvider`: the React `<MatterfactAgent getPageContext>` prop supplies it; the\n * `<script>` loader uses `window.matterfact.getPageContext` instead (see resolveDeclaredContext).\n */\nexport type PageContextProvider = () =>\n | PageContext\n | null\n | undefined\n | Promise<PageContext | null | undefined>;\n/** The programmatic pull callback, set by `start()`. Read fresh on every publish. */\nlet contextProvider: PageContextProvider | undefined;\n\n/* ─────────────────────────── teardown state ───────────────────────────── */\n\n/**\n * Everything below is module-global bookkeeping so `stop()` (see `start()`, bottom of\n * file) can undo exactly what `start()`/`watchNavigation()` installed — remove every\n * listener, restore `history` to what it was before we wrapped it, and forget any\n * DOM-walk module we pulled in. All of this outlives a single `EmbedHost`; see\n * `stop()`'s doc comment for why that's the bug this exists to close.\n */\n\n/** The `fire` closure `watchNavigation()` handed to `popstate` — the only handle we\n * have to remove that listener again. */\nlet navFire: (() => void) | null = null;\n/** The `history.pushState`/`replaceState` this module wrapped, captured so `stop()`\n * can restore them EXACTLY rather than re-wrapping (which is how the old code\n * double-fired navigation on a second `start()`). */\nlet origPushState: History['pushState'] | null = null;\nlet origReplaceState: History['replaceState'] | null = null;\n/** Set once `sendSnapshot`/`sendRegion`/`readFocus` actually pull in the DOM-walk\n * chunk (`./dom/snapshot`) — never imported eagerly, so `stop()` doesn't pay for a\n * chunk that a host who only ever opted out (and never opened a snapshot) never\n * loaded in the first place. */\nlet snapshotModule: { clearRefs: () => void } | null = null;\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\n/**\n * Merge the host's DECLARED context with what we auto-detect. Auto-detected fields\n * (url/path/title/locale, co-embedded artifact entities, opaque-frame count) are additive:\n * a declared value wins where they overlap (the `...declared` spread), and found entities\n * append to declared ones.\n */\nexport function buildPageContext(declared: PageContext): PageContext {\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\n/** Back-compat: build context from the static `window.matterfact.context` global only (sync). */\nexport function readPageContext(): PageContext {\n return buildPageContext(\n (window as { matterfact?: { context?: PageContext } }).matterfact\n ?.context ?? {},\n );\n}\n\n/**\n * Resolve the host's DECLARED context, preferring a pull callback over the static global so\n * a virtualized SPA can hand us fresh context per turn. First non-null wins:\n * 1. the programmatic `getPageContext` provider (React `<MatterfactAgent getPageContext>`),\n * 2. the `<script>`-loader global `window.matterfact.getPageContext()`,\n * 3. the static `window.matterfact.context`.\n */\nasync function resolveDeclaredContext(): Promise<PageContext> {\n const mf = (\n window as {\n matterfact?: {\n context?: PageContext;\n getPageContext?: PageContextProvider;\n };\n }\n ).matterfact;\n if (contextProvider) {\n const c = await contextProvider();\n if (c) return c;\n }\n if (mf?.getPageContext) {\n const c = await mf.getPageContext();\n if (c) return c;\n }\n return mf?.context ?? {};\n}\n\n/**\n * Publish the current declared+detected context as `host.context`. Async because the pull\n * callback may be (a host might read a store). Rapid calls just re-publish — for idempotent\n * context, last-writer-wins is fine. No-op when the host opted out of page observation.\n */\nasync function publishContext() {\n if (!pageContextOn) return;\n const declared = await resolveDeclaredContext();\n send?.({ type: 'host.context', context: buildPageContext(declared) });\n}\n\n/**\n * Answer a `widget.requestContext` (the pull path): publish context NOW, so a turn assembled\n * right after carries the current context rather than the context as of the last route\n * change. No-op when page observation is off.\n */\nexport function provideContext() {\n void publishContext();\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 void publishContext();\n publishArtifactGrants();\n };\n // Captured so stop() can remove exactly this listener, and so history.pushState/\n // replaceState get restored to what they were before we wrapped them — never\n // re-wrapped on top of an existing wrap (that was the pre-existing bug: a second\n // start() used to wrap the ALREADY-wrapped methods, double-firing every nav).\n navFire = fire;\n\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = history[name];\n if (name === 'pushState') origPushState = orig as History['pushState'];\n else origReplaceState = orig as History['replaceState'];\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 loadSnapshotModule();\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\n/** The one place any of the three call sites below reach into the DOM-walk chunk —\n * so `stop()` has a single `snapshotModule` to check without importing anything\n * itself (see the teardown-state block above). */\nasync function loadSnapshotModule() {\n const m = await import('./dom/snapshot');\n snapshotModule = m;\n return m;\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 // pageContext: false ⇒ no snapshot, ever — a `widget.requestSnapshot` must not be\n // able to reintroduce the page observation the host explicitly turned off.\n if (!pageContextOn) return;\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 loadSnapshotModule();\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 // Mirrors sendSnapshot's guard: a `widget.readRegion` for a ref minted before\n // opt-out must not pull a live DOM subtree just because the ref is still\n // resolvable (see refs.ts's `clearRefs`, which `stop()` also uses as a backstop).\n if (!pageContextOn) return;\n const { snapshotRegion, resolveRef } = await loadSnapshotModule();\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/* ───────────────────────────── stop / start ───────────────────────────── */\n\n/**\n * The opposite number of `start()` — remove every listener it (or `watchNavigation`)\n * installed, restore `history.pushState`/`replaceState` to what they were before we\n * wrapped them, and forget the module-level `send`/`activity`/focus state. Nothing\n * here is a filter over what gets sent afterward — there is simply nothing left\n * installed to send anything.\n *\n * Why this has to exist at all: everything `start()` installs is MODULE-GLOBAL, and\n * this module outlives any single `EmbedHost`. React remounts `EmbedHost` whenever\n * ANY of its identity-defining props change (react.tsx's effect deps: publishableKey,\n * widgetOrigin, surface, theme, inline, pageContext, dev) — including just a theme\n * swap, not only a deliberate opt-out. Before this fix, a remount's `start()` call\n * only ever ADDED listeners; the previous mount's were still attached and kept firing\n * into the module `send`, which the new `start()` had just repointed at the NEW\n * widget. Net effect: open once with pageContext on, then remount for any reason\n * (including `pageContext: false`) and the new widget silently keeps receiving\n * clicks/nav/focus collected by the old mount's still-live listeners.\n *\n * Called from two places: the top of `start()` (idempotency — a second `start()`\n * never doubles up, which also fixes the pre-existing double history-wrap /\n * double-`fire()`-per-navigation bug), and `EmbedHost.destroy()` in loader.ts (a\n * plain unmount with no remount still has to stop, not just wait for a `start()`\n * that may never come).\n */\nexport function stop(): void {\n document.removeEventListener('click', onClick, { capture: true });\n document.removeEventListener('submit', onSubmit, { capture: true });\n document.removeEventListener('change', onChange, { capture: true });\n document.removeEventListener('selectionchange', scheduleFocus);\n document.removeEventListener('focusin', scheduleFocus, { capture: true });\n window.removeEventListener('scroll', scheduleFocus, { capture: true });\n\n if (navFire) {\n window.removeEventListener('popstate', navFire);\n navFire = null;\n }\n // Restore, don't re-wrap: this is what stops a repeated start() from wrapping an\n // already-wrapped pushState/replaceState (the old double-fire-per-nav bug).\n if (origPushState) {\n history.pushState = origPushState;\n origPushState = null;\n }\n if (origReplaceState) {\n history.replaceState = origReplaceState;\n origReplaceState = null;\n }\n\n if (focusTimer) {\n clearTimeout(focusTimer);\n focusTimer = null;\n }\n\n send = null;\n contextProvider = undefined;\n activity.length = 0;\n lastFocus = {};\n widgetOrigin = '';\n\n // Belt-and-suspenders alongside sendRegion's own pageContextOn check (see above):\n // an old ref minted while observation was on must not stay resolvable afterward.\n // Only touches the DOM-walk chunk if it was ever actually loaded — see\n // loadSnapshotModule's doc comment.\n snapshotModule?.clearRefs();\n}\n\n/**\n * @param pageContext Whether to observe the host page at all. Default `true`. False is\n * the loader's `pageContext: false` opt-out reaching all the way down here: skip every\n * bit of page reading below — no declared/found context, no artifact grants, no nav/\n * click/submit/change/focus observers — so there is nothing to send and nothing that\n * could later be asked for (see `widget.requestSnapshot` in loader.ts). Theme detection\n * is unaffected: it reads an OS media query, never the page, so it isn't page context.\n */\nexport function start(\n emit: Send,\n origin?: string,\n pageContext = true,\n provider?: PageContextProvider,\n) {\n // Idempotent: undo whatever a PREVIOUS start() installed before this one installs\n // anything. Without this, a remount (see stop()'s doc comment) leaves the old\n // mount's listeners live, writing into the `send` this call is about to reassign.\n stop();\n\n send = emit;\n widgetOrigin = origin || '';\n lastUrl = location.pathname;\n pageContextOn = pageContext;\n contextProvider = provider;\n\n if (pageContextOn) {\n void 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, {\n capture: true,\n passive: true,\n });\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\n const theme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light';\n emit({ type: 'host.theme', mode: theme });\n}\n"],"mappings":";;;AAWA,IAAI,eAAe;AAuBnB,IAAM,eAAe;AAErB,IAAI,OAAoB;AACxB,IAAI,cAAc;AAClB,IAAM,WAA4B,CAAC;AACnC,IAAI,UAAU;AAGd,IAAI,gBAAgB;AAcpB,IAAI;AAcJ,IAAI,UAA+B;AAInC,IAAI,gBAA6C;AACjD,IAAI,mBAAmD;AAKvD,IAAI,iBAAmD;AAIvD,IAAM,MAAM;AAAA,EACV;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF;AASO,SAAS,OAAO,MAAsB;AAC3C,MAAI,MAAM;AACV,aAAW,MAAM,IAAK,OAAM,IAAI,QAAQ,IAAI,YAAY;AACxD,SAAO;AACT;AAGO,SAAS,UAAU,IAAsB;AAC9C,MAAI,GAAG,QAAQ,mBAAmB,EAAG,QAAO;AAC5C,QAAM,MAAM,GAAG;AACf,MAAI,QAAQ,SAAS;AACnB,UAAM,IAAK,GAAwB;AACnC,QAAI,MAAM,cAAc,MAAM,SAAU,QAAO;AAAA,EACjD;AACA,SAAO;AACT;AAgCO,SAAS,mBAAmB,UAAiC;AAClE,QAAM,IAAI,SAAS,MAAM,qCAAqC;AAC9D,SAAO,IAAI,mBAAmB,EAAE,CAAC,CAAC,IAAI;AACxC;AAEA,SAAS,6BAA2C;AAClD,MAAI,CAAC,aAAc,QAAO,CAAC;AAC3B,QAAM,MAAoB,CAAC;AAC3B,aAAW,SAAS,MAAM,KAAK,SA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ID,aAAS,iBAAiB,mBAAmB,eAAe;AAAA,MAC1D,SAAS;AAAA,IACX,CAAC;AACD,aAAS,iBAAiB,WAAW,eAAe;AAAA,MAClD,SAAS;AAAA,MACT,SAAS;AAAA,IACX,CAAC;AACD,WAAO,iBAAiB,UAAU,eAAe;AAAA,MAC/C,SAAS;AAAA,MACT,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ,WAAW,8BAA8B,EAAE,UACrD,SACA;AACJ,OAAK,EAAE,MAAM,cAAc,MAAM,MAAM,CAAC;AAC1C;","names":[]}
@@ -1,23 +1,25 @@
1
1
  "use client";
2
2
  import {
3
3
  artifactIdFromPath,
4
- beginAuth,
4
+ buildPageContext,
5
5
  callTool,
6
6
  grantsFromIframeSrcs,
7
7
  isPrivate,
8
+ provideContext,
8
9
  readPageContext,
9
10
  redact,
10
11
  sendRegion,
11
12
  sendSnapshot,
12
13
  start,
13
14
  stop
14
- } from "./chunk-SBNMM3ZV.js";
15
+ } from "./chunk-RS6RMZ77.js";
15
16
  export {
16
17
  artifactIdFromPath,
17
- beginAuth,
18
+ buildPageContext,
18
19
  callTool,
19
20
  grantsFromIframeSrcs,
20
21
  isPrivate,
22
+ provideContext,
21
23
  readPageContext,
22
24
  redact,
23
25
  sendRegion,
@@ -25,4 +27,4 @@ export {
25
27
  start,
26
28
  stop
27
29
  };
28
- //# sourceMappingURL=context-432WQST4.js.map
30
+ //# sourceMappingURL=context-WU2F5CBC.js.map
@@ -0,0 +1,3 @@
1
+ export { artifactIdFromPath, buildPageContext, callTool, grantsFromIframeSrcs, isPrivate, provideContext, readPageContext, redact, sendRegion, sendSnapshot, start, stop } from './chunk-AXKXNYRT.js';
2
+ //# sourceMappingURL=context-YX2KXFLI.js.map
3
+ //# sourceMappingURL=context-YX2KXFLI.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"context-KZAUOIR6.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"context-YX2KXFLI.js"}
package/dist/embed.js CHANGED
@@ -1,2 +1,2 @@
1
- var s="mf-embed";function d(i,t){return{channel:s,protocol:1,...t?{id:t}:{},payload:i}}function c(i){return typeof i=="object"&&i!==null&&i.channel===s}var b="https://app.matterfact.com";function y(){try{return new URLSearchParams(location.search).get("mfdev")==="1"}catch{return!1}}function p(){let i=document.currentScript??document.querySelector('script[data-key][src*="embed"]'),t=i?.dataset.key;if(!t)return console.error("[matterfact] missing data-key on the embed script tag"),null;let e=i?.dataset.container,n=e?document.querySelector(e):null;e&&!n&&console.error(`[matterfact] data-container="${e}" matched nothing; falling back to the corner`);let o=i?.dataset.pageContext?.toLowerCase();return{publishableKey:t,origin:i?.dataset.origin||b,theme:i?.dataset.theme||"auto",surface:i?.dataset.surface||"",container:n,pageContext:o!=="off"&&o!=="false"&&o!=="0"}}var r="mf.embed.pos",a=class{constructor(t){this.config=t;this.iframe=null;this.shadow=null;this.queue=[];this.ready=!1;this.open=!1;this.expanded=!1;this.pos=null;this.dragBase=null;this.context=null;this.hostEl=null;this.onMessage=t=>{if(t.origin!==this.config.origin||t.source!==this.iframe?.contentWindow||!c(t.data))return;let e=t.data.payload;switch(e.type){case"widget.ready":this.ready=!0,this.send({type:"host.ready",protocol:1,origin:location.origin}),this.flush(),this.inline&&this.loadContext();break;case"widget.setOpen":if(this.inline)break;this.open=e.open,this.iframe?.setAttribute("data-open",String(e.open)),e.open||(this.expanded=!1,this.iframe?.setAttribute("data-expanded","false")),e.open&&this.loadContext();break;case"widget.setExpanded":if(this.inline)break;this.expanded=e.expanded,this.iframe?.setAttribute("data-expanded",String(e.expanded)),this.iframe&&(this.iframe.style.height="");break;case"widget.resize":if(this.inline)break;this.iframe&&this.open&&!this.expanded&&(this.iframe.style.height=`${Math.min(e.height,window.innerHeight-40)}px`);break;case"widget.requestSnapshot":this.loadContext().then(n=>n.sendSnapshot(this.send));break;case"widget.readRegion":this.loadContext().then(n=>n.sendRegion(e.ref,this.send));break;case"widget.callTool":this.loadContext().then(n=>n.callTool(e.call,this.send));break;case"widget.dragStart":if(this.inline)break;this.dragBase=this.cornerOffset();break;case"widget.dragMove":if(this.inline)break;this.dragTo(e.dx,e.dy);break;case"widget.dragEnd":if(this.inline)break;this.dragBase=null,this.writePos(this.pos);break;case"widget.setMenu":if(this.inline)break;this.iframe&&!this.open&&(this.iframe.style.height=e.open?`${64+e.height}px`:"");break;case"widget.resetPos":if(this.inline)break;this.resetPos();break;case"widget.hide":if(this.inline)break;this.hostEl&&(this.hostEl.style.display="none");break;case"widget.needsAuth":this.provideAuth();break}};this.send=t=>{if(!this.ready){this.queue.push(t);return}this.iframe?.contentWindow?.postMessage(d(t),this.config.origin)};this.inline=!!t.container}mount(){let t=document.createElement("div");this.hostEl=t,t.id="matterfact-embed",this.inline?(t.style.cssText=["all: initial","position: relative","display: block","width: 100%","height: 100%","contain: layout style"].join(";"),this.config.container.appendChild(t)):(this.pos=this.readPos(),t.style.cssText=["all: initial","position: fixed",`right: ${this.pos?this.pos.right:20}px`,`bottom: ${this.pos?this.pos.bottom:20}px`,"z-index: 2147483000","contain: layout style"].join(";"),document.body.appendChild(t)),this.shadow=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=":host{all:initial}iframe{border:0;display:block;color-scheme:light dark;}"+(this.inline?"iframe{width:100%;height:100%}":'iframe{border-radius:12px;box-shadow:0 0 0 1px #00000014,0 8px 40px #00000029;width:400px;height:64px;transition:height .18s ease,width .18s ease}iframe[data-open="true"]{width:420px;height:640px}iframe[data-open="true"][data-expanded="true"]{width:min(600px,calc(100vw - 40px));height:calc(100vh - 40px)}'),this.shadow.appendChild(e);let n=document.createElement("iframe");n.title="matterfact assistant",n.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),n.setAttribute("allow","microphone"),n.src=`${this.config.origin}/embed/chat?k=${encodeURIComponent(this.config.publishableKey)}&o=${encodeURIComponent(location.origin)}`+(this.config.surface?`&s=${encodeURIComponent(this.config.surface)}`:"")+(y()||this.config.dev?"&dev=1":"")+(this.inline?"&inline=1":""),this.iframe=n,this.shadow.appendChild(n),window.addEventListener("message",this.onMessage)}cornerOffset(){let t=this.hostEl.getBoundingClientRect();return{right:window.innerWidth-t.right,bottom:window.innerHeight-t.bottom}}dragTo(t,e){if(!this.dragBase||!this.hostEl)return;let n=this.hostEl.getBoundingClientRect(),o=Math.max(0,window.innerWidth-n.width),m=Math.max(0,window.innerHeight-n.height),l=Math.min(Math.max(0,this.dragBase.right-t),o),h=Math.min(Math.max(0,this.dragBase.bottom-e),m);this.pos={right:l,bottom:h},this.hostEl.style.right=`${l}px`,this.hostEl.style.bottom=`${h}px`}resetPos(){this.pos=null,this.writePos(null),this.hostEl&&(this.hostEl.style.right="20px",this.hostEl.style.bottom="20px")}readPos(){try{let t=localStorage.getItem(r);if(!t)return null;let e=JSON.parse(t);return typeof e?.right=="number"&&typeof e?.bottom=="number"?{right:e.right,bottom:e.bottom}:null}catch{return null}}writePos(t){try{t?localStorage.setItem(r,JSON.stringify(t)):localStorage.removeItem(r)}catch{}}async provideAuth(){let t=this.config.authTokenProvider??globalThis.matterfact?.getEmbedAuthToken;if(t)try{let e=await t();if(e){this.send({type:"host.auth",token:e,expiresAt:0});return}}catch{}this.loadContext().then(e=>e.beginAuth(this.config,this.send))}loadContext(){return this.context??(this.context=import("./chunk-URIBHOOQ.js").then(t=>(t.start(this.send,this.config.origin,this.config.pageContext),this.config.theme!=="auto"&&this.send({type:"host.theme",mode:this.config.theme}),t))),this.context}flush(){let t=this.queue;this.queue=[];for(let e of t)this.send(e)}destroy(){window.removeEventListener("message",this.onMessage),this.hostEl?.remove(),this.hostEl=null,this.iframe=null,this.shadow=null,this.ready=!1,this.context?.then(t=>t.stop())}};function g(i){let t=new a(i);return t.mount(),t}var u=p();if(u){let i=()=>g(u);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",i,{once:!0}):i()}
1
+ var s="mf-embed";function d(o,t){return{channel:s,protocol:1,...t?{id:t}:{},payload:o}}function p(o){return typeof o=="object"&&o!==null&&o.channel===s}var x="https://app.matterfact.com";function y(){try{return new URLSearchParams(location.search).get("mfdev")==="1"}catch{return!1}}function c(){let o=document.currentScript??document.querySelector('script[data-key][src*="embed"]'),t=o?.dataset.key;if(!t)return console.error("[matterfact] missing data-key on the embed script tag"),null;let e=o?.dataset.container,i=e?document.querySelector(e):null;e&&!i&&console.error(`[matterfact] data-container="${e}" matched nothing; falling back to the corner`);let n=o?.dataset.pageContext?.toLowerCase();return{publishableKey:t,origin:o?.dataset.origin||x,theme:o?.dataset.theme||"auto",surface:o?.dataset.surface||"",container:i,pageContext:n!=="off"&&n!=="false"&&n!=="0"}}var r="mf.embed.pos",a=class{constructor(t){this.config=t;this.iframe=null;this.shadow=null;this.queue=[];this.ready=!1;this.open=!1;this.expanded=!1;this.pos=null;this.dragBase=null;this.context=null;this.hostEl=null;this.onMessage=t=>{if(t.origin!==this.config.origin||t.source!==this.iframe?.contentWindow||!p(t.data))return;let e=t.data.payload;switch(e.type){case"widget.ready":this.ready=!0,this.send({type:"host.ready",protocol:1,origin:location.origin}),this.flush(),this.inline&&this.loadContext();break;case"widget.setOpen":if(this.inline)break;this.open=e.open,this.iframe?.setAttribute("data-open",String(e.open)),e.open||(this.expanded=!1,this.iframe?.setAttribute("data-expanded","false")),e.open&&this.loadContext();break;case"widget.setExpanded":if(this.inline)break;this.expanded=e.expanded,this.iframe?.setAttribute("data-expanded",String(e.expanded)),this.iframe&&(this.iframe.style.height="");break;case"widget.resize":if(this.inline)break;this.iframe&&this.open&&!this.expanded&&(this.iframe.style.height=`${Math.min(e.height,window.innerHeight-40)}px`);break;case"widget.requestContext":this.loadContext().then(i=>i.provideContext());break;case"widget.requestSnapshot":this.loadContext().then(i=>i.sendSnapshot(this.send));break;case"widget.readRegion":this.loadContext().then(i=>i.sendRegion(e.ref,this.send));break;case"widget.callTool":this.loadContext().then(i=>i.callTool(e.call,this.send));break;case"widget.dragStart":if(this.inline)break;this.dragBase=this.cornerOffset();break;case"widget.dragMove":if(this.inline)break;this.dragTo(e.dx,e.dy);break;case"widget.dragEnd":if(this.inline)break;this.dragBase=null,this.writePos(this.pos);break;case"widget.setMenu":if(this.inline)break;this.iframe&&!this.open&&(this.iframe.style.height=e.open?`${64+e.height}px`:"");break;case"widget.resetPos":if(this.inline)break;this.resetPos();break;case"widget.hide":if(this.inline)break;this.hostEl&&(this.hostEl.style.display="none");break;case"widget.needsAuth":this.provideAuth();break}};this.send=t=>{if(!this.ready){this.queue.push(t);return}this.iframe?.contentWindow?.postMessage(d(t),this.config.origin)};this.inline=!!t.container}mount(){let t=document.createElement("div");this.hostEl=t,t.id="matterfact-embed",this.inline?(t.style.cssText=["all: initial","position: relative","display: block","width: 100%","height: 100%","contain: layout style"].join(";"),this.config.container.appendChild(t)):(this.pos=this.readPos(),t.style.cssText=["all: initial","position: fixed",`right: ${this.pos?this.pos.right:20}px`,`bottom: ${this.pos?this.pos.bottom:20}px`,"z-index: 2147483000","contain: layout style"].join(";"),document.body.appendChild(t)),this.shadow=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=":host{all:initial}iframe{border:0;display:block;color-scheme:light dark;}"+(this.inline?"iframe{width:100%;height:100%}":'iframe{border-radius:12px;box-shadow:0 0 0 1px #00000014,0 8px 40px #00000029;width:400px;height:64px;transition:height .18s ease,width .18s ease}iframe[data-open="true"]{width:420px;height:640px}iframe[data-open="true"][data-expanded="true"]{width:min(600px,calc(100vw - 40px));height:calc(100vh - 40px)}'),this.shadow.appendChild(e);let i=document.createElement("iframe");i.title="matterfact assistant",i.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),i.setAttribute("allow","microphone"),i.src=`${this.config.origin}/embed/chat?k=${encodeURIComponent(this.config.publishableKey)}&o=${encodeURIComponent(location.origin)}`+(this.config.surface?`&s=${encodeURIComponent(this.config.surface)}`:"")+(y()||this.config.dev?"&dev=1":"")+(this.inline?"&inline=1":""),this.iframe=i,this.shadow.appendChild(i),window.addEventListener("message",this.onMessage)}cornerOffset(){let t=this.hostEl.getBoundingClientRect();return{right:window.innerWidth-t.right,bottom:window.innerHeight-t.bottom}}dragTo(t,e){if(!this.dragBase||!this.hostEl)return;let i=this.hostEl.getBoundingClientRect(),n=Math.max(0,window.innerWidth-i.width),m=Math.max(0,window.innerHeight-i.height),l=Math.min(Math.max(0,this.dragBase.right-t),n),h=Math.min(Math.max(0,this.dragBase.bottom-e),m);this.pos={right:l,bottom:h},this.hostEl.style.right=`${l}px`,this.hostEl.style.bottom=`${h}px`}resetPos(){this.pos=null,this.writePos(null),this.hostEl&&(this.hostEl.style.right="20px",this.hostEl.style.bottom="20px")}readPos(){try{let t=localStorage.getItem(r);if(!t)return null;let e=JSON.parse(t);return typeof e?.right=="number"&&typeof e?.bottom=="number"?{right:e.right,bottom:e.bottom}:null}catch{return null}}writePos(t){try{t?localStorage.setItem(r,JSON.stringify(t)):localStorage.removeItem(r)}catch{}}async provideAuth(){let t=this.config.authTokenProvider??globalThis.matterfact?.getEmbedAuthToken;if(t)try{let e=await t();e&&this.send({type:"host.auth",token:e,expiresAt:0})}catch{}}loadContext(){return this.context??(this.context=import("./chunk-7I37ZFAJ.js").then(t=>(t.start(this.send,this.config.origin,this.config.pageContext,this.config.pageContextProvider),this.config.theme!=="auto"&&this.send({type:"host.theme",mode:this.config.theme}),t))),this.context}flush(){let t=this.queue;this.queue=[];for(let e of t)this.send(e)}destroy(){window.removeEventListener("message",this.onMessage),this.hostEl?.remove(),this.hostEl=null,this.iframe=null,this.shadow=null,this.ready=!1,this.context?.then(t=>t.stop())}};function g(o){let t=new a(o);return t.mount(),t}var u=c();if(u){let o=()=>g(u);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",o,{once:!0}):o()}
2
2
  //# sourceMappingURL=embed.js.map