@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
package/dist/embed.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/protocol.ts", "../src/loader.ts", "../src/embed.ts"],
4
- "sourcesContent": ["/**\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 \u2014 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 \u2014 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/* \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 refs \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 * 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 \u2014 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/* \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 host \u2192 widget \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/** 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 \u2014 it tells the agent what KIND of page this is. */\n route?: string;\n path?: string;\n title?: string;\n locale?: string;\n /** 1\u20132 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 \u2014 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 \u2014 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 \u2014\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\" \u2014 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 \u2014 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 \u2014 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\u20131. A cheap proxy for \"which part am I reading\". */\n scroll?: number;\n}\n\n/** Something the user did. Shaped after PostHog's autocapture \u2014 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 \u2014 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/* \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 widget \u2192 host \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 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\" \u2014 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 \u2014 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 \u2014 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 \u2014 `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 \u2014 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 \u2014 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 \u2014 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/* \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 envelope \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 * 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 \u2014 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, \u2026). 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, \u2026); 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 \u2014 this only skips a redundant second sign-in.\n * Called on demand (so tokens can refresh). Absent \u21D2 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 \u2014 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 \u2014 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 * Turn off ALL host-page observation \u2014 no `host.context`, no `host.focus`, no\n * `host.snapshot`, no `host.activity`, no `host.artifactGrants`. Not a filter on what\n * gets sent: when this is false the loader never installs the DOM/nav/focus/activity\n * observers in the first place, and an inbound `widget.requestSnapshot` is ignored\n * rather than answered. Default `true` \u2014 seeing the page is the widget's whole value\n * proposition; this is the escape hatch for a host that wants agent chat with nothing\n * about the page ever reaching it.\n */\n pageContext?: boolean;\n /**\n * Force dev mode (see `devRequested()` below) without needing `?mfdev=1` on the host\n * URL. This is the programmatic equivalent of that trigger, not a replacement for it \u2014\n * the URL param still works untouched; `mount()` ORs the two together.\n */\n dev?: boolean;\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 \u2014 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 \u2014 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 // `data-page-context=\"off\"` (also \"false\" / \"0\") disables all page observation.\n // Anything else \u2014 including the attribute being absent \u2014 leaves it on. Lowercased\n // once before comparing: a privacy toggle that silently stays ON for \"Off\" or\n // \"FALSE\" (a customer's templating/CMS can easily produce either, unintentionally)\n // is exactly the wrong direction for this to fail in.\n const pageContextAttr = el?.dataset.pageContext?.toLowerCase();\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 pageContext:\n pageContextAttr !== 'off' &&\n pageContextAttr !== 'false' &&\n pageContextAttr !== '0',\n // No `data-dev` \u2014 see the `dev` field's doc comment: the URL trigger is the\n // point for the script-tag path, so there is deliberately no script-tag knob here.\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 \u2014 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 \u2014 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 \u2014 no session, no auth, ever.\n //\n // The familiar warning \u2014 \"allow-scripts + allow-same-origin lets the frame escape\n // its sandbox\" \u2014 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 \u2014 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 // Either trigger works: the URL param (no redeploy needed) OR the config's\n // programmatic `dev` (the React prop). See both doc comments above.\n (devRequested() || this.config.dev ? '&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 \u2014 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 \u2014 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 \u2014 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 \u2014 the first time someone actually opens the\n // chat \u2014 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 // pageContext: false \u21D2 `sendSnapshot` itself no-ops (see context.ts) rather\n // than gating here \u2014 this file is the size-budgeted stub, and the check\n // costs nothing extra in the lazy chunk that already owns the DOM read.\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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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` \u2014 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 * \u2014 e.g. once the host's auth is ready \u2014 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 // The single place the eye actually starts: when pageContext is off, `start()`\n // skips installing every DOM/nav/focus/activity observer \u2014 not a filter over\n // what gets sent afterward, nothing is collected in the first place. Passed\n // through raw: `start`'s default parameter is what turns `undefined` (the\n // option omitted) into \"on\".\n m.start(this.send, this.config.origin, this.config.pageContext);\n // start() emits the OS-preference theme. An explicit data-theme on the\n // script tag is the host's choice \u2014 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 \u2014 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 \u2014 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 // context.ts's listeners/history-patch/ref-registry are module-global and\n // outlive this instance \u2014 stop() undoes exactly what start() installed. A no-op\n // if the eye was never loaded (chat never opened, so nothing was ever started).\n // This is the unmount-with-no-remount case; start()'s own stop()-first call\n // (see context.ts) is what protects a REMOUNT, which is why both exist.\n void this.context?.then((m) => m.stop());\n }\n}\n\n/**\n * Programmatic entry \u2014 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", "/**\n * The vanilla `<script>` loader entry \u2014 the browser stub hosted on a CDN and dropped\n * onto any page:\n *\n * <script src=\"https://cdn.matterfact.com/embed.js\" data-key=\"pk_live_\u2026\" defer></script>\n *\n * This is the ONLY module with the DOM auto-run side-effect. The reusable core\n * (`./loader`), the npm `.` entry (`./index`), and the React wrapper (`./react`) never\n * import it, so they stay SSR-safe \u2014 importing them touches no `document`.\n */\nimport { mount, readConfig } from './loader';\n\nconst config = readConfig();\nif (config) {\n const boot = () => mount(config);\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', boot, { once: true });\n } else {\n boot();\n }\n}\n"],
5
- "mappings": "AAwBO,IAAMA,EAAU,WAsPhB,SAASC,EAAYC,EAAYC,EAA0B,CAChE,MAAO,CACL,QAASH,EACT,SAAU,EACV,GAAIG,EAAK,CAAE,GAAAA,CAAG,EAAI,CAAC,EACnB,QAAAD,CACF,CACF,CAEO,SAASE,EAAWC,EAA0C,CACnE,OACE,OAAOA,GAAS,UAChBA,IAAS,MACRA,EAA+B,UAAYL,CAEhD,CCrMA,IAAMM,EAAiB,6BAcvB,SAASC,GAAwB,CAC/B,GAAI,CACF,OAAO,IAAI,gBAAgB,SAAS,MAAM,EAAE,IAAI,OAAO,IAAM,GAC/D,MAAQ,CACN,MAAO,EACT,CACF,CAEA,SAASC,GAAkC,CAGzC,IAAMC,EACH,SAAS,eACV,SAAS,cAAiC,gCAAgC,EAEtEC,EAAiBD,GAAI,QAAQ,IACnC,GAAI,CAACC,EACH,eAAQ,MAAM,uDAAuD,EAC9D,KAMT,IAAMC,EAAMF,GAAI,QAAQ,UAClBG,EAAYD,EAAM,SAAS,cAA2BA,CAAG,EAAI,KAC/DA,GAAO,CAACC,GACV,QAAQ,MACN,gCAAgCD,CAAG,+CACrC,EAQF,IAAME,EAAkBJ,GAAI,QAAQ,aAAa,YAAY,EAE7D,MAAO,CACL,eAAAC,EACA,OAAQD,GAAI,QAAQ,QAAUH,EAC9B,MAAQG,GAAI,QAAQ,OAAmC,OACvD,QAASA,GAAI,QAAQ,SAAW,GAChC,UAAAG,EACA,YACEC,IAAoB,OACpBA,IAAoB,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,CAEG,KAAK,YAAY,EAAE,KAAMhB,GAAMA,EAAE,UAAU,KAAK,OAAQ,KAAK,IAAI,CAAC,CACzE,CAEQ,aAAc,CAGpB,YAAK,UAAL,KAAK,QAAY,OAAO,qBAAW,EAAE,KAAMA,IAMzCA,EAAE,MAAM,KAAK,KAAM,KAAK,OAAO,OAAQ,KAAK,OAAO,WAAW,EAK1D,KAAK,OAAO,QAAU,QACxB,KAAK,KAAK,CAAE,KAAM,aAAc,KAAM,KAAK,OAAO,KAAM,CAAC,EAEpDA,EACR,GACM,KAAK,OACd,CAYQ,OAAQ,CACd,IAAMiB,EAAU,KAAK,MACrB,KAAK,MAAQ,CAAC,EACd,QAAWjB,KAAKiB,EAAS,KAAK,KAAKjB,CAAC,CACtC,CAKA,SAAU,CACR,OAAO,oBAAoB,UAAW,KAAK,SAAS,EACpD,KAAK,QAAQ,OAAO,EACpB,KAAK,OAAS,KACd,KAAK,OAAS,KACd,KAAK,OAAS,KACd,KAAK,MAAQ,GAMR,KAAK,SAAS,KAAMA,GAAMA,EAAE,KAAK,CAAC,CACzC,CACF,EAOO,SAASkB,EAAMtB,EAAiC,CACrD,IAAMM,EAAO,IAAIP,EAAUC,CAAM,EACjC,OAAAM,EAAK,MAAM,EACJA,CACT,CClkBA,IAAMiB,EAASC,EAAW,EAC1B,GAAID,EAAQ,CACV,IAAME,EAAO,IAAMC,EAAMH,CAAM,EAC3B,SAAS,aAAe,UAC1B,SAAS,iBAAiB,mBAAoBE,EAAM,CAAE,KAAM,EAAK,CAAC,EAElEA,EAAK,CAET",
4
+ "sourcesContent": ["/**\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 \u2014 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 \u2014 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/* \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 refs \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 * 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 \u2014 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/* \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 host \u2192 widget \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/** 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 \u2014 it tells the agent what KIND of page this is. */\n route?: string;\n path?: string;\n title?: string;\n locale?: string;\n /** 1\u20132 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 \u2014 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 \u2014 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 \u2014\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\" \u2014 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 \u2014 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 \u2014 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\u20131. A cheap proxy for \"which part am I reading\". */\n scroll?: number;\n}\n\n/** Something the user did. Shaped after PostHog's autocapture \u2014 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 \u2014 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/* \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 widget \u2192 host \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 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\" \u2014 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 \u2014 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 /**\n * Pull the DECLARED page context fresh, right now. The host answers with `host.context`.\n *\n * Declared context (`window.matterfact.context`, or a `getPageContext()` callback) is\n * otherwise only published on load and on URL navigation, so in a virtualized SPA it goes\n * stale on any non-navigation state change (a team switch, a filter edit, a selection).\n * The widget pulls it at turn-assembly time \u2014 symmetric with `widget.requestSnapshot` \u2014\n * so every turn carries the current context, not the context as of the last route change.\n */\n | { type: 'widget.requestContext' }\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 \u2014 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 \u2014 `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 \u2014 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 \u2014 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 \u2014 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/* \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 envelope \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 * 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 \u2014 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// Type-only: erased at build, so it does NOT pull the lazy ./context chunk eagerly.\nimport type { PageContextProvider } from './context';\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, \u2026). 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, \u2026); 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 \u2014 this only skips a redundant second sign-in.\n * Called on demand (so tokens can refresh). Absent \u21D2 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 * OPTIONAL pull callback for DECLARED page context, for a host whose context changes\n * without a URL navigation (a virtualized SPA: team switch, filter edit, selection). The\n * widget calls it at turn-assembly time (via `widget.requestContext`), so every turn\n * carries current context instead of context as of the last route change. Symmetric with\n * `authTokenProvider`. The `<script>` loader has no config here; it reads\n * `window.matterfact.getPageContext` instead (see resolveDeclaredContext in context.ts).\n * Absent \u21D2 falls back to the static `window.matterfact.context`.\n */\n pageContextProvider?: PageContextProvider;\n /**\n * Render INTO this element instead of floating in the corner \u2014 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 \u2014 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 * Turn off ALL host-page observation \u2014 no `host.context`, no `host.focus`, no\n * `host.snapshot`, no `host.activity`, no `host.artifactGrants`. Not a filter on what\n * gets sent: when this is false the loader never installs the DOM/nav/focus/activity\n * observers in the first place, and an inbound `widget.requestSnapshot` is ignored\n * rather than answered. Default `true` \u2014 seeing the page is the widget's whole value\n * proposition; this is the escape hatch for a host that wants agent chat with nothing\n * about the page ever reaching it.\n */\n pageContext?: boolean;\n /**\n * Force dev mode (see `devRequested()` below) without needing `?mfdev=1` on the host\n * URL. This is the programmatic equivalent of that trigger, not a replacement for it \u2014\n * the URL param still works untouched; `mount()` ORs the two together.\n */\n dev?: boolean;\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 \u2014 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 \u2014 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 // `data-page-context=\"off\"` (also \"false\" / \"0\") disables all page observation.\n // Anything else \u2014 including the attribute being absent \u2014 leaves it on. Lowercased\n // once before comparing: a privacy toggle that silently stays ON for \"Off\" or\n // \"FALSE\" (a customer's templating/CMS can easily produce either, unintentionally)\n // is exactly the wrong direction for this to fail in.\n const pageContextAttr = el?.dataset.pageContext?.toLowerCase();\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 pageContext:\n pageContextAttr !== 'off' &&\n pageContextAttr !== 'false' &&\n pageContextAttr !== '0',\n // No `data-dev` \u2014 see the `dev` field's doc comment: the URL trigger is the\n // point for the script-tag path, so there is deliberately no script-tag knob here.\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 \u2014 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 \u2014 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 \u2014 no session, no auth, ever.\n //\n // The familiar warning \u2014 \"allow-scripts + allow-same-origin lets the frame escape\n // its sandbox\" \u2014 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 \u2014 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 // Either trigger works: the URL param (no redeploy needed) OR the config's\n // programmatic `dev` (the React prop). See both doc comments above.\n (devRequested() || this.config.dev ? '&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 \u2014 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 \u2014 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 \u2014 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 \u2014 the first time someone actually opens the\n // chat \u2014 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.requestContext':\n // The pull path for declared context \u2014 re-read it now (via getPageContext if the\n // host supplied one) and re-publish `host.context`. No-op if pageContext is off.\n void this.loadContext().then((m) => m.provideContext());\n break;\n\n case 'widget.requestSnapshot':\n // pageContext: false \u21D2 `sendSnapshot` itself no-ops (see context.ts) rather\n // than gating here \u2014 this file is the size-budgeted stub, and the check\n // costs nothing extra in the lazy chunk that already owns the DOM read.\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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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` \u2014 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 * \u2014 e.g. once the host's auth is ready \u2014 is still picked up. `expiresAt: 0`: the widget\n * doesn't cache it, it exchanges the token for a rotating embed session anyway.\n *\n * No provider \u21D2 this does nothing. The loader never opens a sign-in popup \u2014 the widget\n * owns interactive sign-in (inline Firebase/email, and Microsoft's own MSAL login popup\n * for Entra, then the PKCE token exchange), so the loader must not also fire its stale\n * `/embed/authorize?k=&o=` popup, which the deployed authorize page no longer accepts.\n */\n private async provideAuth() {\n const provider =\n this.config.authTokenProvider ??\n (globalThis as { matterfact?: { getEmbedAuthToken?: AuthTokenProvider } })\n .matterfact?.getEmbedAuthToken;\n if (!provider) return; // the widget owns interactive sign-in; the loader never opens it\n try {\n const token = await provider();\n if (token) this.send({ type: 'host.auth', token, expiresAt: 0 });\n } catch {\n /* no token this time; the widget falls back to its own inline / popup sign-in */\n }\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 // The single place the eye actually starts: when pageContext is off, `start()`\n // skips installing every DOM/nav/focus/activity observer \u2014 not a filter over\n // what gets sent afterward, nothing is collected in the first place. Passed\n // through raw: `start`'s default parameter is what turns `undefined` (the\n // option omitted) into \"on\".\n m.start(\n this.send,\n this.config.origin,\n this.config.pageContext,\n this.config.pageContextProvider,\n );\n // start() emits the OS-preference theme. An explicit data-theme on the\n // script tag is the host's choice \u2014 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 \u2014 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 \u2014 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 // context.ts's listeners/history-patch/ref-registry are module-global and\n // outlive this instance \u2014 stop() undoes exactly what start() installed. A no-op\n // if the eye was never loaded (chat never opened, so nothing was ever started).\n // This is the unmount-with-no-remount case; start()'s own stop()-first call\n // (see context.ts) is what protects a REMOUNT, which is why both exist.\n void this.context?.then((m) => m.stop());\n }\n}\n\n/**\n * Programmatic entry \u2014 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", "/**\n * The vanilla `<script>` loader entry \u2014 the browser stub hosted on a CDN and dropped\n * onto any page:\n *\n * <script src=\"https://cdn.matterfact.com/embed.js\" data-key=\"pk_live_\u2026\" defer></script>\n *\n * This is the ONLY module with the DOM auto-run side-effect. The reusable core\n * (`./loader`), the npm `.` entry (`./index`), and the React wrapper (`./react`) never\n * import it, so they stay SSR-safe \u2014 importing them touches no `document`.\n */\nimport { mount, readConfig } from './loader';\n\nconst config = readConfig();\nif (config) {\n const boot = () => mount(config);\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', boot, { once: true });\n } else {\n boot();\n }\n}\n"],
5
+ "mappings": "AAwBO,IAAMA,EAAU,WAgQhB,SAASC,EAAYC,EAAYC,EAA0B,CAChE,MAAO,CACL,QAASH,EACT,SAAU,EACV,GAAIG,EAAK,CAAE,GAAAA,CAAG,EAAI,CAAC,EACnB,QAAAD,CACF,CACF,CAEO,SAASE,EAAWC,EAA0C,CACnE,OACE,OAAOA,GAAS,UAChBA,IAAS,MACRA,EAA+B,UAAYL,CAEhD,CCnMA,IAAMM,EAAiB,6BAcvB,SAASC,GAAwB,CAC/B,GAAI,CACF,OAAO,IAAI,gBAAgB,SAAS,MAAM,EAAE,IAAI,OAAO,IAAM,GAC/D,MAAQ,CACN,MAAO,EACT,CACF,CAEA,SAASC,GAAkC,CAGzC,IAAMC,EACH,SAAS,eACV,SAAS,cAAiC,gCAAgC,EAEtEC,EAAiBD,GAAI,QAAQ,IACnC,GAAI,CAACC,EACH,eAAQ,MAAM,uDAAuD,EAC9D,KAMT,IAAMC,EAAMF,GAAI,QAAQ,UAClBG,EAAYD,EAAM,SAAS,cAA2BA,CAAG,EAAI,KAC/DA,GAAO,CAACC,GACV,QAAQ,MACN,gCAAgCD,CAAG,+CACrC,EAQF,IAAME,EAAkBJ,GAAI,QAAQ,aAAa,YAAY,EAE7D,MAAO,CACL,eAAAC,EACA,OAAQD,GAAI,QAAQ,QAAUH,EAC9B,MAAQG,GAAI,QAAQ,OAAmC,OACvD,QAASA,GAAI,QAAQ,SAAW,GAChC,UAAAG,EACA,YACEC,IAAoB,OACpBA,IAAoB,SACpBA,IAAoB,GAGxB,CACF,CAQA,IAAMC,EAAU,eAEVC,EAAN,KAAgB,CAmBd,YAAoBC,EAAsB,CAAtB,YAAAA,EAlBpB,KAAQ,OAAmC,KAC3C,KAAQ,OAA4B,KAEpC,KAAQ,MAAwB,CAAC,EACjC,KAAQ,MAAQ,GAChB,KAAQ,KA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mBACd,EAKI,KAAK,OAAO,QAAU,QACxB,KAAK,KAAK,CAAE,KAAM,aAAc,KAAM,KAAK,OAAO,KAAM,CAAC,EAEpDA,EACR,GACM,KAAK,OACd,CAYQ,OAAQ,CACd,IAAMiB,EAAU,KAAK,MACrB,KAAK,MAAQ,CAAC,EACd,QAAWjB,KAAKiB,EAAS,KAAK,KAAKjB,CAAC,CACtC,CAKA,SAAU,CACR,OAAO,oBAAoB,UAAW,KAAK,SAAS,EACpD,KAAK,QAAQ,OAAO,EACpB,KAAK,OAAS,KACd,KAAK,OAAS,KACd,KAAK,OAAS,KACd,KAAK,MAAQ,GAMR,KAAK,SAAS,KAAMA,GAAMA,EAAE,KAAK,CAAC,CACzC,CACF,EAOO,SAASkB,EAAMtB,EAAiC,CACrD,IAAMM,EAAO,IAAIP,EAAUC,CAAM,EACjC,OAAAM,EAAK,MAAM,EACJA,CACT,CCxlBA,IAAMiB,EAASC,EAAW,EAC1B,GAAID,EAAQ,CACV,IAAME,EAAO,IAAMC,EAAMH,CAAM,EAC3B,SAAS,aAAe,UAC1B,SAAS,iBAAiB,mBAAoBE,EAAM,CAAE,KAAM,EAAK,CAAC,EAElEA,EAAK,CAET",
6
6
  "names": ["CHANNEL", "envelope", "payload", "id", "isEnvelope", "data", "DEFAULT_ORIGIN", "devRequested", "readConfig", "el", "publishableKey", "sel", "container", "pageContextAttr", "POS_KEY", "EmbedHost", "config", "event", "isEnvelope", "msg", "m", "envelope", "host", "style", "iframe", "rect", "dx", "dy", "maxRight", "maxBottom", "right", "bottom", "raw", "p", "pos", "provider", "token", "pending", "mount", "config", "readConfig", "boot", "mount"]
7
7
  }
package/dist/index.cjs CHANGED
@@ -482,10 +482,11 @@ var init_snapshot = __esm({
482
482
  var context_exports = {};
483
483
  __export(context_exports, {
484
484
  artifactIdFromPath: () => artifactIdFromPath,
485
- beginAuth: () => beginAuth,
485
+ buildPageContext: () => buildPageContext,
486
486
  callTool: () => callTool,
487
487
  grantsFromIframeSrcs: () => grantsFromIframeSrcs,
488
488
  isPrivate: () => isPrivate,
489
+ provideContext: () => provideContext,
489
490
  readPageContext: () => readPageContext,
490
491
  redact: () => redact,
491
492
  sendRegion: () => sendRegion,
@@ -543,8 +544,7 @@ function opaqueFrameCount() {
543
544
  }
544
545
  }).length;
545
546
  }
546
- function readPageContext() {
547
- const declared = window.matterfact?.context ?? {};
547
+ function buildPageContext(declared) {
548
548
  const found = embeddedMatterfactEntities();
549
549
  const opaque = opaqueFrameCount();
550
550
  return {
@@ -565,8 +565,30 @@ function readPageContext() {
565
565
  }
566
566
  };
567
567
  }
568
- function publishContext() {
569
- send?.({ type: "host.context", context: readPageContext() });
568
+ function readPageContext() {
569
+ return buildPageContext(
570
+ window.matterfact?.context ?? {}
571
+ );
572
+ }
573
+ async function resolveDeclaredContext() {
574
+ const mf = window.matterfact;
575
+ if (contextProvider) {
576
+ const c = await contextProvider();
577
+ if (c) return c;
578
+ }
579
+ if (mf?.getPageContext) {
580
+ const c = await mf.getPageContext();
581
+ if (c) return c;
582
+ }
583
+ return mf?.context ?? {};
584
+ }
585
+ async function publishContext() {
586
+ if (!pageContextOn) return;
587
+ const declared = await resolveDeclaredContext();
588
+ send?.({ type: "host.context", context: buildPageContext(declared) });
589
+ }
590
+ function provideContext() {
591
+ void publishContext();
570
592
  }
571
593
  function grantsFromIframeSrcs(srcs, origin) {
572
594
  const out = [];
@@ -658,7 +680,7 @@ function watchNavigation() {
658
680
  if (url === lastUrl) return;
659
681
  lastUrl = url;
660
682
  pushActivity({ type: "nav", summary: `navigated to ${url}` });
661
- publishContext();
683
+ void publishContext();
662
684
  publishArtifactGrants();
663
685
  };
664
686
  navFire = fire;
@@ -747,27 +769,6 @@ async function callTool(call, emit) {
747
769
  error: "Host tools are read-only in this version; no action was taken."
748
770
  });
749
771
  }
750
- function beginAuth(config, emit) {
751
- const w = window.open(
752
- `${config.origin}/embed/authorize?k=${encodeURIComponent(
753
- config.publishableKey
754
- )}&o=${encodeURIComponent(location.origin)}`,
755
- "mf_auth",
756
- "width=460,height=640"
757
- );
758
- if (!w) return;
759
- if (pendingAuthListener) window.removeEventListener("message", pendingAuthListener);
760
- const onMsg = (event) => {
761
- if (event.origin !== config.origin) return;
762
- const d = event.data;
763
- if (d?.type !== "mf:embed:auth") return;
764
- window.removeEventListener("message", onMsg);
765
- pendingAuthListener = null;
766
- emit({ type: "host.auth", token: d.token, expiresAt: d.expiresAt });
767
- };
768
- pendingAuthListener = onMsg;
769
- window.addEventListener("message", onMsg);
770
- }
771
772
  function stop() {
772
773
  document.removeEventListener("click", onClick, { capture: true });
773
774
  document.removeEventListener("submit", onSubmit, { capture: true });
@@ -787,31 +788,32 @@ function stop() {
787
788
  history.replaceState = origReplaceState;
788
789
  origReplaceState = null;
789
790
  }
790
- if (pendingAuthListener) {
791
- window.removeEventListener("message", pendingAuthListener);
792
- pendingAuthListener = null;
793
- }
794
791
  if (focusTimer) {
795
792
  clearTimeout(focusTimer);
796
793
  focusTimer = null;
797
794
  }
798
795
  send = null;
796
+ contextProvider = void 0;
799
797
  activity.length = 0;
800
798
  lastFocus = {};
801
799
  widgetOrigin = "";
802
800
  snapshotModule?.clearRefs();
803
801
  }
804
- function start(emit, origin, pageContext = true) {
802
+ function start(emit, origin, pageContext = true, provider) {
805
803
  stop();
806
804
  send = emit;
807
805
  widgetOrigin = origin || "";
808
806
  lastUrl = location.pathname;
809
807
  pageContextOn = pageContext;
808
+ contextProvider = provider;
810
809
  if (pageContextOn) {
811
- publishContext();
810
+ void publishContext();
812
811
  publishArtifactGrants();
813
812
  watchNavigation();
814
- document.addEventListener("click", onClick, { capture: true, passive: true });
813
+ document.addEventListener("click", onClick, {
814
+ capture: true,
815
+ passive: true
816
+ });
815
817
  document.addEventListener("submit", onSubmit, {
816
818
  capture: true,
817
819
  passive: true
@@ -835,7 +837,7 @@ function start(emit, origin, pageContext = true) {
835
837
  const theme = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
836
838
  emit({ type: "host.theme", mode: theme });
837
839
  }
838
- var widgetOrigin, MAX_ACTIVITY, send, activitySeq, activity, lastUrl, pageContextOn, navFire, origPushState, origReplaceState, pendingAuthListener, snapshotModule, PII, FORM_CONTROLS, ACTIONABLE, lastFocus, focusTimer, snapshotSeq;
840
+ var widgetOrigin, MAX_ACTIVITY, send, activitySeq, activity, lastUrl, pageContextOn, contextProvider, navFire, origPushState, origReplaceState, snapshotModule, PII, FORM_CONTROLS, ACTIONABLE, lastFocus, focusTimer, snapshotSeq;
839
841
  var init_context = __esm({
840
842
  "src/context.ts"() {
841
843
  widgetOrigin = "";
@@ -848,7 +850,6 @@ var init_context = __esm({
848
850
  navFire = null;
849
851
  origPushState = null;
850
852
  origReplaceState = null;
851
- pendingAuthListener = null;
852
853
  snapshotModule = null;
853
854
  PII = [
854
855
  /\b[\w.+-]+@[\w-]+\.[\w.]{2,}\b/g,
@@ -988,6 +989,9 @@ var EmbedHost = class {
988
989
  this.iframe.style.height = `${Math.min(msg.height, window.innerHeight - 40)}px`;
989
990
  }
990
991
  break;
992
+ case "widget.requestContext":
993
+ void this.loadContext().then((m) => m.provideContext());
994
+ break;
991
995
  case "widget.requestSnapshot":
992
996
  void this.loadContext().then((m) => m.sendSnapshot(this.send));
993
997
  break;
@@ -1159,27 +1163,31 @@ var EmbedHost = class {
1159
1163
  * window.matterfact = { getEmbedAuthToken: () => getIdToken(user) };
1160
1164
  *
1161
1165
  * Read fresh at call time (not at readConfig), so a global set after the loader booted
1162
- * — e.g. once the host's auth is ready — is still picked up. Otherwise fall back to the
1163
- * hosted-login popup. `expiresAt: 0`: the widget doesn't cache it, it exchanges the
1164
- * token for a rotating embed session anyway.
1166
+ * — e.g. once the host's auth is ready — is still picked up. `expiresAt: 0`: the widget
1167
+ * doesn't cache it, it exchanges the token for a rotating embed session anyway.
1168
+ *
1169
+ * No provider ⇒ this does nothing. The loader never opens a sign-in popup — the widget
1170
+ * owns interactive sign-in (inline Firebase/email, and Microsoft's own MSAL login popup
1171
+ * for Entra, then the PKCE token exchange), so the loader must not also fire its stale
1172
+ * `/embed/authorize?k=&o=` popup, which the deployed authorize page no longer accepts.
1165
1173
  */
1166
1174
  async provideAuth() {
1167
1175
  const provider = this.config.authTokenProvider ?? globalThis.matterfact?.getEmbedAuthToken;
1168
- if (provider) {
1169
- try {
1170
- const token = await provider();
1171
- if (token) {
1172
- this.send({ type: "host.auth", token, expiresAt: 0 });
1173
- return;
1174
- }
1175
- } catch {
1176
- }
1176
+ if (!provider) return;
1177
+ try {
1178
+ const token = await provider();
1179
+ if (token) this.send({ type: "host.auth", token, expiresAt: 0 });
1180
+ } catch {
1177
1181
  }
1178
- void this.loadContext().then((m) => m.beginAuth(this.config, this.send));
1179
1182
  }
1180
1183
  loadContext() {
1181
1184
  this.context ?? (this.context = Promise.resolve().then(() => (init_context(), context_exports)).then((m) => {
1182
- m.start(this.send, this.config.origin, this.config.pageContext);
1185
+ m.start(
1186
+ this.send,
1187
+ this.config.origin,
1188
+ this.config.pageContext,
1189
+ this.config.pageContextProvider
1190
+ );
1183
1191
  if (this.config.theme !== "auto") {
1184
1192
  this.send({ type: "host.theme", mode: this.config.theme });
1185
1193
  }