@matterfact/embed 0.3.0 → 0.4.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 (42) hide show
  1. package/README.md +20 -0
  2. package/dist/{chunk-33LPVL2R.js → chunk-523BCS2Z.js} +3 -3
  3. package/dist/{chunk-33LPVL2R.js.map → chunk-523BCS2Z.js.map} +3 -3
  4. package/dist/{chunk-SQJX27LT.js → chunk-SBNMM3ZV.js} +85 -28
  5. package/dist/chunk-SBNMM3ZV.js.map +1 -0
  6. package/dist/chunk-URIBHOOQ.js +2 -0
  7. package/dist/chunk-XLQ36ZMV.js +2 -0
  8. package/dist/chunk-XLQ36ZMV.js.map +7 -0
  9. package/dist/{chunk-CHPADW72.js → chunk-Z4WT3TIZ.js} +86 -30
  10. package/dist/chunk-Z4WT3TIZ.js.map +1 -0
  11. package/dist/{context-MORDASRH.js → context-432WQST4.js} +6 -4
  12. package/dist/context-KZAUOIR6.js +3 -0
  13. package/dist/{context-BFNFFHC2.js.map → context-KZAUOIR6.js.map} +1 -1
  14. package/dist/embed.js +1 -1
  15. package/dist/embed.js.map +3 -3
  16. package/dist/index.cjs +100 -32
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +16 -0
  19. package/dist/index.d.ts +16 -0
  20. package/dist/index.js +11 -4
  21. package/dist/index.js.map +1 -1
  22. package/dist/react.cjs +102 -34
  23. package/dist/react.cjs.map +1 -1
  24. package/dist/react.d.cts +14 -1
  25. package/dist/react.d.ts +14 -1
  26. package/dist/react.js +13 -6
  27. package/dist/react.js.map +1 -1
  28. package/dist/{snapshot-QBV7DTJP.js → snapshot-Q3CALMHD.js} +7 -4
  29. package/dist/snapshot-Q3CALMHD.js.map +1 -0
  30. package/dist/{snapshot-IWVXLE4G.js → snapshot-SOMSG2OF.js} +6 -2
  31. package/dist/snapshot-SOMSG2OF.js.map +1 -0
  32. package/package.json +1 -1
  33. package/dist/chunk-CHPADW72.js.map +0 -1
  34. package/dist/chunk-F7DLOR7F.js +0 -2
  35. package/dist/chunk-F7DLOR7F.js.map +0 -7
  36. package/dist/chunk-FBIJZJGL.js +0 -2
  37. package/dist/chunk-SQJX27LT.js.map +0 -1
  38. package/dist/context-BFNFFHC2.js +0 -3
  39. package/dist/snapshot-IWVXLE4G.js.map +0 -1
  40. package/dist/snapshot-QBV7DTJP.js.map +0 -1
  41. /package/dist/{chunk-FBIJZJGL.js.map → chunk-URIBHOOQ.js.map} +0 -0
  42. /package/dist/{context-MORDASRH.js.map → context-432WQST4.js.map} +0 -0
@@ -7,6 +7,12 @@ var send = null;
7
7
  var activitySeq = 0;
8
8
  var activity = [];
9
9
  var lastUrl = "";
10
+ var pageContextOn = true;
11
+ var navFire = null;
12
+ var origPushState = null;
13
+ var origReplaceState = null;
14
+ var pendingAuthListener = null;
15
+ var snapshotModule = null;
10
16
  var PII = [
11
17
  /\b[\w.+-]+@[\w-]+\.[\w.]{2,}\b/g,
12
18
  // email
@@ -193,8 +199,11 @@ function watchNavigation() {
193
199
  publishContext();
194
200
  publishArtifactGrants();
195
201
  };
202
+ navFire = fire;
196
203
  for (const name of ["pushState", "replaceState"]) {
197
204
  const orig = history[name];
205
+ if (name === "pushState") origPushState = orig;
206
+ else origReplaceState = orig;
198
207
  history[name] = function(...args) {
199
208
  const r = orig.apply(this, args);
200
209
  fire();
@@ -216,7 +225,7 @@ async function readFocus() {
216
225
  }
217
226
  const active = document.activeElement;
218
227
  if (active && active !== document.body && !isPrivate(active) && !active.closest("[data-mf-private]")) {
219
- const { snapshot } = await import("./snapshot-IWVXLE4G.js");
228
+ const { snapshot } = await loadSnapshotModule();
220
229
  void snapshot;
221
230
  focus.focused = {
222
231
  label: redact(describeControl(active)),
@@ -231,6 +240,11 @@ async function readFocus() {
231
240
  function describeControl(el) {
232
241
  return describe(el);
233
242
  }
243
+ async function loadSnapshotModule() {
244
+ const m = await import("./snapshot-SOMSG2OF.js");
245
+ snapshotModule = m;
246
+ return m;
247
+ }
234
248
  var focusTimer = null;
235
249
  function scheduleFocus() {
236
250
  if (focusTimer) return;
@@ -242,7 +256,8 @@ function scheduleFocus() {
242
256
  }
243
257
  var snapshotSeq = 0;
244
258
  async function sendSnapshot(emit) {
245
- const { snapshot } = await import("./snapshot-IWVXLE4G.js");
259
+ if (!pageContextOn) return;
260
+ const { snapshot } = await loadSnapshotModule();
246
261
  const { yaml, truncated, visibleRefs } = snapshot();
247
262
  emit({
248
263
  type: "host.snapshot",
@@ -252,7 +267,8 @@ async function sendSnapshot(emit) {
252
267
  emit({ type: "host.focus", focus: lastFocus });
253
268
  }
254
269
  async function sendRegion(ref, emit) {
255
- const { snapshotRegion, resolveRef } = await import("./snapshot-IWVXLE4G.js");
270
+ if (!pageContextOn) return;
271
+ const { snapshotRegion, resolveRef } = await loadSnapshotModule();
256
272
  const el = resolveRef(ref);
257
273
  if (!el) {
258
274
  emit({
@@ -282,42 +298,82 @@ function beginAuth(config, emit) {
282
298
  "width=460,height=640"
283
299
  );
284
300
  if (!w) return;
301
+ if (pendingAuthListener) window.removeEventListener("message", pendingAuthListener);
285
302
  const onMsg = (event) => {
286
303
  if (event.origin !== config.origin) return;
287
304
  const d = event.data;
288
305
  if (d?.type !== "mf:embed:auth") return;
289
306
  window.removeEventListener("message", onMsg);
307
+ pendingAuthListener = null;
290
308
  emit({ type: "host.auth", token: d.token, expiresAt: d.expiresAt });
291
309
  };
310
+ pendingAuthListener = onMsg;
292
311
  window.addEventListener("message", onMsg);
293
312
  }
294
- function start(emit, origin) {
313
+ function stop() {
314
+ document.removeEventListener("click", onClick, { capture: true });
315
+ document.removeEventListener("submit", onSubmit, { capture: true });
316
+ document.removeEventListener("change", onChange, { capture: true });
317
+ document.removeEventListener("selectionchange", scheduleFocus);
318
+ document.removeEventListener("focusin", scheduleFocus, { capture: true });
319
+ window.removeEventListener("scroll", scheduleFocus, { capture: true });
320
+ if (navFire) {
321
+ window.removeEventListener("popstate", navFire);
322
+ navFire = null;
323
+ }
324
+ if (origPushState) {
325
+ history.pushState = origPushState;
326
+ origPushState = null;
327
+ }
328
+ if (origReplaceState) {
329
+ history.replaceState = origReplaceState;
330
+ origReplaceState = null;
331
+ }
332
+ if (pendingAuthListener) {
333
+ window.removeEventListener("message", pendingAuthListener);
334
+ pendingAuthListener = null;
335
+ }
336
+ if (focusTimer) {
337
+ clearTimeout(focusTimer);
338
+ focusTimer = null;
339
+ }
340
+ send = null;
341
+ activity.length = 0;
342
+ lastFocus = {};
343
+ widgetOrigin = "";
344
+ snapshotModule?.clearRefs();
345
+ }
346
+ function start(emit, origin, pageContext = true) {
347
+ stop();
295
348
  send = emit;
296
349
  widgetOrigin = origin || "";
297
350
  lastUrl = location.pathname;
298
- publishContext();
299
- publishArtifactGrants();
300
- watchNavigation();
301
- document.addEventListener("click", onClick, { capture: true, passive: true });
302
- document.addEventListener("submit", onSubmit, {
303
- capture: true,
304
- passive: true
305
- });
306
- document.addEventListener("change", onChange, {
307
- capture: true,
308
- passive: true
309
- });
310
- document.addEventListener("selectionchange", scheduleFocus, {
311
- passive: true
312
- });
313
- document.addEventListener("focusin", scheduleFocus, {
314
- capture: true,
315
- passive: true
316
- });
317
- window.addEventListener("scroll", scheduleFocus, {
318
- capture: true,
319
- passive: true
320
- });
351
+ pageContextOn = pageContext;
352
+ if (pageContextOn) {
353
+ publishContext();
354
+ publishArtifactGrants();
355
+ watchNavigation();
356
+ document.addEventListener("click", onClick, { capture: true, passive: true });
357
+ document.addEventListener("submit", onSubmit, {
358
+ capture: true,
359
+ passive: true
360
+ });
361
+ document.addEventListener("change", onChange, {
362
+ capture: true,
363
+ passive: true
364
+ });
365
+ document.addEventListener("selectionchange", scheduleFocus, {
366
+ passive: true
367
+ });
368
+ document.addEventListener("focusin", scheduleFocus, {
369
+ capture: true,
370
+ passive: true
371
+ });
372
+ window.addEventListener("scroll", scheduleFocus, {
373
+ capture: true,
374
+ passive: true
375
+ });
376
+ }
321
377
  const theme = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
322
378
  emit({ type: "host.theme", mode: theme });
323
379
  }
@@ -332,6 +388,7 @@ export {
332
388
  sendRegion,
333
389
  callTool,
334
390
  beginAuth,
391
+ stop,
335
392
  start
336
393
  };
337
- //# sourceMappingURL=chunk-SQJX27LT.js.map
394
+ //# sourceMappingURL=chunk-SBNMM3ZV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context.ts"],"sourcesContent":["import type {\n ActivityEvent,\n FocusContext,\n HostToWidget,\n PageContext,\n PageEntity,\n ToolCall,\n} from './protocol';\n\n/** The origin serving our chat — how we tell OUR embedded content from the host's own\n * iframes. Set by start(); empty until then, which just means we spot nothing. */\nlet widgetOrigin = '';\n\n/**\n * The eye.\n *\n * Everything in this module can see the customer's page. It is a SEPARATE CHUNK,\n * loaded only when someone actually opens the chat — so a page whose visitors never\n * click the widget pays nothing for any of it, and a security reviewer can read\n * exactly one file to know what we look at.\n *\n * The rules, which are not negotiable:\n *\n * NEVER captured — no config enables it: the value of any <input>, <textarea> or\n * contenteditable; anything inside a password field; cookies; localStorage;\n * sessionStorage; the raw DOM; screenshots; network traffic; anything inside an\n * element marked `data-mf-private`.\n *\n * The agent never gets a selector and never touches the DOM. It gets refs. A ref\n * is resolved to an element HERE, in the page, by us.\n */\n\ntype Send = (msg: HostToWidget) => void;\n\nconst MAX_ACTIVITY = 40;\n\nlet send: Send | null = null;\nlet activitySeq = 0;\nconst activity: ActivityEvent[] = [];\nlet lastUrl = '';\n/** Set once by `start()`. False ⇒ the host opted out of ALL page observation — every\n * exported entry point below that would otherwise read or send the page checks this. */\nlet pageContextOn = true;\n\n/* ─────────────────────────── teardown state ───────────────────────────── */\n\n/**\n * Everything below is module-global bookkeeping so `stop()` (see `start()`, bottom of\n * file) can undo exactly what `start()`/`watchNavigation()`/`beginAuth()` installed —\n * remove every listener, restore `history` to what it was before we wrapped it, and\n * forget any DOM-walk module we pulled in. All of this outlives a single `EmbedHost`;\n * see `stop()`'s doc comment for why that's the bug this exists to close.\n */\n\n/** The `fire` closure `watchNavigation()` handed to `popstate` — the only handle we\n * have to remove that listener again. */\nlet navFire: (() => void) | null = null;\n/** The `history.pushState`/`replaceState` this module wrapped, captured so `stop()`\n * can restore them EXACTLY rather than re-wrapping (which is how the old code\n * double-fired navigation on a second `start()`). */\nlet origPushState: History['pushState'] | null = null;\nlet origReplaceState: History['replaceState'] | null = null;\n/** The `message` listener `beginAuth()` is currently waiting on, if any. */\nlet pendingAuthListener: ((event: MessageEvent) => void) | null = null;\n/** Set once `sendSnapshot`/`sendRegion`/`readFocus` actually pull in the DOM-walk\n * chunk (`./dom/snapshot`) — never imported eagerly, so `stop()` doesn't pay for a\n * chunk that a host who only ever opted out (and never opened a snapshot) never\n * loaded in the first place. */\nlet snapshotModule: { clearRefs: () => void } | null = null;\n\n/* ─────────────────────────── redaction ────────────────────────────────── */\n\nconst PII = [\n /\\b[\\w.+-]+@[\\w-]+\\.[\\w.]{2,}\\b/g, // email\n /\\b(?:\\d[ -]?){13,19}\\b/g, // card-ish\n /\\b\\d{3}[- ]?\\d{2}[- ]?\\d{4}\\b/g, // ssn — dashed, spaced, OR bare 9 digits\n /\\b\\d{9,}\\b/g, // long bare digit runs: account / MRN / routing numbers\n /(?:\\+?\\d{1,2}[\\s.-]?)?\\(?\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}\\b/g, // us phone\n /\\b(?:sk|pk|rk|ak)_(?:live|test)_[A-Za-z0-9]{8,}\\b/g, // stripe-style api keys\n /\\beyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+\\b/g, // jwt\n];\n\n/**\n * Scrub before anything leaves the page — not after it arrives.\n *\n * A compromised widget, or a bug in ours, must not be able to retroactively obtain\n * a customer's users' email addresses. The only way to guarantee that is to never\n * put them on the wire.\n */\nexport function redact(text: string): string {\n let out = text;\n for (const re of PII) out = out.replace(re, '[redacted]');\n return out;\n}\n\n/** Anything the host has marked private, or that is inherently sensitive, is out. */\nexport function isPrivate(el: Element): boolean {\n if (el.closest('[data-mf-private]')) return true;\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const t = (el as HTMLInputElement).type;\n if (t === 'password' || t === 'hidden') return true;\n }\n return false;\n}\n\n/* ───────────────────────── page context ───────────────────────────────── */\n\n/**\n * What the page says about itself.\n *\n * A host that declares nothing still gets URL + title, which is what every other\n * embeddable assistant on the market offers in total. The interesting fields\n * (`route`, `description`, `entities`) are host-declared, because only the host\n * knows that `/o/8813` is \"the Acme Corp order, 3 items, unpaid\".\n *\n * Declared via a global the host sets before we load:\n * window.matterfact = { context: { route: '/orders/:id', description: '...', entities: [...] } }\n */\n/**\n * matterfact content embedded IN the host page — today, artifact iframes.\n *\n * A cross-origin iframe is opaque: `contentDocument` throws, so the DOM snapshot walks\n * straight past an embedded artifact and the agent is blind to the very thing the page\n * is built around. It reads the page as empty and asks which URL you mean.\n *\n * We don't need to see inside, and shouldn't want to. The artifact's ID is right there\n * in the src, and the agent can already resolve `artifacts/<id>/` in its session — the\n * same path an `@`-mention uses. So we report the ID and let the backend fetch the real\n * thing, which beats scraping a rendering of it: it gets the data, not the picture.\n *\n * Matched by ORIGIN, not by path shape: a customer is perfectly entitled to their own\n * /artifacts/ route, and it isn't ours.\n */\n/** The artifact slug from a matterfact artifact path, or null. Matches both the\n * chrome-free embed route (/embed/artifacts/<slug>) and the bare /artifacts/<slug>. */\nexport function artifactIdFromPath(pathname: string): string | null {\n const m = pathname.match(/^\\/(?:embed\\/)?artifacts\\/(.+?)\\/?$/);\n return m ? decodeURIComponent(m[1]) : null;\n}\n\nfunction embeddedMatterfactEntities(): PageEntity[] {\n if (!widgetOrigin) return [];\n const out: PageEntity[] = [];\n for (const frame of Array.from(document.querySelectorAll('iframe'))) {\n let u: URL;\n try {\n u = new URL(frame.getAttribute('src') || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== widgetOrigin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n if (out.some((e) => e.id === id)) continue; // same artifact twice = once\n // No url field: the agent reaches an artifact by ID (`artifacts/<id>/`), never by\n // fetching the page, and an artifact URL can carry a share token we've no business\n // forwarding. The id is the whole useful payload.\n out.push({\n kind: 'artifact',\n id,\n label: redact(frame.getAttribute('title') || '') || id,\n });\n }\n return out;\n}\n\n/**\n * Frames we can see the existence of but nothing inside — someone else's cross-origin\n * embed. Worth one line: \"there is a thing here I cannot read\" is a true and useful\n * statement, and much better than the agent confidently describing a page while missing\n * the widget the user is actually asking about.\n */\nfunction opaqueFrameCount(): number {\n return Array.from(document.querySelectorAll('iframe')).filter((f) => {\n try {\n const u = new URL(f.getAttribute('src') || '', location.href);\n return u.origin !== location.origin && u.origin !== widgetOrigin;\n } catch {\n return false;\n }\n }).length;\n}\n\nexport function readPageContext(): PageContext {\n const declared =\n (window as { matterfact?: { context?: PageContext } }).matterfact\n ?.context ?? {};\n\n const found = embeddedMatterfactEntities();\n const opaque = opaqueFrameCount();\n\n return {\n // Path only. A query string is where session ids, tokens and email addresses\n // live; it is not ours to take.\n url: location.origin + location.pathname,\n path: location.pathname,\n title: redact(document.title),\n locale: document.documentElement.lang || undefined,\n ...declared,\n // After the spread: what we FOUND is additive to what the host DECLARED, never a\n // replacement. A host that declares its own entities still gets the artifacts we\n // spotted, and vice versa.\n entities: [...(declared.entities ?? []), ...found],\n data: {\n ...(declared.data ?? {}),\n ...(opaque ? { opaque_frames: opaque } : {}),\n },\n };\n}\n\nfunction publishContext() {\n send?.({ type: 'host.context', context: readPageContext() });\n}\n\n/* ─────────────────────── artifact grants (backend-only) ────────────────── */\n\nexport interface ArtifactGrantSrc {\n id: string;\n owner: string;\n token: string;\n}\n\n/** Read-only capability grants from co-embedded artifact iframes, for the backend to\n * materialize their data. Separate from entities on purpose: the token must never ride\n * ambient (rendered) context, only this backend-only channel. */\nexport function grantsFromIframeSrcs(\n srcs: string[],\n origin: string,\n): ArtifactGrantSrc[] {\n const out: ArtifactGrantSrc[] = [];\n for (const raw of srcs) {\n let u: URL;\n try {\n u = new URL(raw || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== origin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n const owner = u.searchParams.get('owner') || '';\n const token = u.searchParams.get('t') || '';\n if (!owner || !token) continue;\n if (out.some((g) => g.id === id)) continue;\n out.push({ id, owner, token });\n }\n return out;\n}\n\nfunction readArtifactGrants(): ArtifactGrantSrc[] {\n if (!widgetOrigin) return [];\n const srcs = Array.from(document.querySelectorAll('iframe')).map(\n (f) => f.getAttribute('src') || '',\n );\n return grantsFromIframeSrcs(srcs, widgetOrigin);\n}\n\nfunction publishArtifactGrants() {\n send?.({ type: 'host.artifactGrants', grants: readArtifactGrants() });\n}\n\n/* ────────────────────────── activity ──────────────────────────────────── */\n\nfunction pushActivity(e: Omit<ActivityEvent, 'seq' | 'ts'>) {\n activity.push({ ...e, seq: ++activitySeq, ts: Date.now() });\n if (activity.length > MAX_ACTIVITY) activity.shift();\n send?.({ type: 'host.activity', events: [activity[activity.length - 1]] });\n}\n\n/**\n * A short, human-readable label for what got clicked.\n *\n * Shaped after PostHog's autocapture, not after a session-replay frame: rrweb would\n * give us `{source:2, type:2, id:417, x:210, y:88}` — no text, no role, no href,\n * meaningless to a model without the full DOM snapshot it deltas against. One line\n * of \"clicked button 'Export CSV'\" is worth more and costs less.\n */\n/**\n * The accessible NAME of a form control — never its value.\n *\n * A control has no `innerText`, so the generic path below misses it. We look where a\n * control's name actually lives: `aria-label`, then a `<label for>` or a wrapping\n * `<label>`, then `placeholder`. `placeholder` is a LABEL, not a value — it is the\n * hint shown when the field is empty (\"Order number or customer\"), so it is safe.\n */\nfunction controlLabel(el: Element): string {\n const aria = el.getAttribute('aria-label');\n if (aria) return aria;\n\n const id = el.id;\n if (id) {\n const forLabel = document.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n const t = forLabel?.textContent?.trim();\n if (t) return t;\n }\n const wrapping = el.closest('label')?.textContent?.trim();\n if (wrapping) return wrapping;\n\n const placeholder = el.getAttribute('placeholder');\n if (placeholder) return placeholder;\n\n return '';\n}\n\nconst FORM_CONTROLS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);\n\nfunction describe(el: Element): string {\n const role = el.getAttribute('role') || el.tagName.toLowerCase();\n const label =\n el.getAttribute('aria-label') ||\n (FORM_CONTROLS.has(el.tagName)\n ? controlLabel(el)\n : (el as HTMLElement).innerText?.trim().slice(0, 60)) ||\n el.getAttribute('title') ||\n '';\n return label ? `${role} \"${redact(label)}\"` : role;\n}\n\n/**\n * Elements a click is worth recording. Deliberately tight: the point of the activity\n * stream is INTENT (\"the user chose to export\"), and a click on a heading, a label,\n * a card gutter, or blank page is not intent, it is noise. We only log a click that\n * lands on something actionable.\n */\nconst ACTIONABLE =\n 'a[href],button,input,select,textarea,summary,' +\n '[role=\"button\"],[role=\"link\"],[role=\"menuitem\"],[role=\"tab\"],[role=\"option\"],' +\n '[role=\"checkbox\"],[role=\"switch\"],[role=\"radio\"],[onclick],[tabindex]';\n\nfunction onClick(ev: Event) {\n const target = ev.target as Element | null;\n if (!target || !(target instanceof Element)) return;\n\n // Clicking a <label> operates the control it labels — record THAT, not \"clicked\n // label\", so the event reads as the user's actual intent.\n const label = target.closest('label');\n const labelled = label\n ? (label.getAttribute('for') &&\n document.getElementById(label.getAttribute('for')!)) ||\n label.querySelector('input,select,textarea')\n : null;\n\n const actionable = labelled ?? target.closest(ACTIONABLE);\n // No actionable target — a click on text, a gutter, or blank space. That is not an\n // action; dropping it is the whole fix for the click-log noise.\n if (!actionable || isPrivate(actionable)) return;\n\n pushActivity({ type: 'click', summary: `clicked ${describe(actionable)}` });\n}\n\nfunction onSubmit(ev: Event) {\n const el = ev.target as Element | null;\n if (!el || isPrivate(el)) return;\n // The FORM was submitted — never its values.\n pushActivity({ type: 'submit', summary: `submitted ${describe(el)}` });\n}\n\n/**\n * A form field changed.\n *\n * The rule is the same as everywhere else and the temptation here is sharpest:\n * record THAT a field changed and WHICH field (its label), never WHAT it was\n * changed to. `change` fires on exactly the elements whose values are off-limits.\n *\n * One safe exception: a <select>, a checkbox, or a radio chose from a fixed, visible\n * set of options the agent can already see in the snapshot — \"Unpaid\", \"Shipped\".\n * That is a user *choice*, not typed data, so the chosen option's LABEL is fair to\n * include and is the useful part (\"filtered status to Shipped\"). Free-text and\n * numeric inputs get their label only.\n */\nfunction onChange(ev: Event) {\n const el = ev.target as (HTMLElement & { type?: string }) | null;\n if (!el || !(el instanceof Element) || isPrivate(el)) return;\n\n const tag = el.tagName;\n const type = (el as HTMLInputElement).type;\n\n // Never a password/hidden field, and isPrivate already covered data-mf-private.\n if (tag === 'INPUT' && (type === 'password' || type === 'hidden')) return;\n\n let summary = `changed ${describe(el)}`;\n\n if (tag === 'SELECT') {\n const opt = (el as HTMLSelectElement).selectedOptions[0]?.text;\n if (opt) summary = `${describe(el)} → \"${redact(opt)}\"`;\n } else if (type === 'checkbox' || type === 'radio') {\n summary = `${(el as HTMLInputElement).checked ? 'checked' : 'unchecked'} ${describe(el)}`;\n }\n\n pushActivity({ type: 'input', summary });\n}\n\n/**\n * SPA navigation. There is no event for `pushState`, so we wrap it — a 20-line job\n * that no library does better.\n */\nfunction watchNavigation() {\n const fire = () => {\n const url = location.pathname;\n if (url === lastUrl) return;\n lastUrl = url;\n pushActivity({ type: 'nav', summary: `navigated to ${url}` });\n publishContext();\n publishArtifactGrants();\n };\n // Captured so stop() can remove exactly this listener, and so history.pushState/\n // replaceState get restored to what they were before we wrapped them — never\n // re-wrapped on top of an existing wrap (that was the pre-existing bug: a second\n // start() used to wrap the ALREADY-wrapped methods, double-firing every nav).\n navFire = fire;\n\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = history[name];\n if (name === 'pushState') origPushState = orig as History['pushState'];\n else origReplaceState = orig as History['replaceState'];\n history[name] = function (\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const r = orig.apply(this, args);\n fire();\n return r;\n } as History[typeof name];\n }\n window.addEventListener('popstate', fire);\n}\n\n/* ─────────────────────────── focal context ────────────────────────────── */\n\n/**\n * Where the user's attention is, right now.\n *\n * This is the \"knows what you're doing\" layer, and it is deliberately small so it can\n * ride on every turn — where the full snapshot cannot. It is also the most sensitive:\n * `selection` is whatever the user highlighted, which could be their own email, so it\n * is redacted and respects data-mf-private like everything else. Focus and the\n * viewport are labels and refs — never a value.\n *\n * Held so the last-known focus can travel with a turn even between the (throttled)\n * push updates.\n */\nlet lastFocus: FocusContext = {};\n\nasync function readFocus(): Promise<FocusContext> {\n const focus: FocusContext = {};\n\n // Selection — the single strongest \"this is what I'm asking about\" signal.\n const sel = window.getSelection?.();\n if (sel && !sel.isCollapsed) {\n const anchor = sel.anchorNode?.parentElement ?? null;\n // Don't lift a selection out of a private region, and cap it — a user can select\n // the whole page.\n if (!anchor || !anchor.closest('[data-mf-private]')) {\n const text = sel.toString().trim().slice(0, 500);\n if (text) focus.selection = redact(text);\n }\n }\n\n // The control they're working in — its label, never its contents.\n const active = document.activeElement;\n if (\n active &&\n active !== document.body &&\n !isPrivate(active) &&\n !active.closest('[data-mf-private]')\n ) {\n const { snapshot } = await loadSnapshotModule();\n void snapshot; // ensure the chunk that owns refFor is loaded before we describe\n focus.focused = {\n label: redact(describeControl(active)),\n role: active.getAttribute('role') || active.tagName.toLowerCase(),\n };\n }\n\n const doc = document.documentElement;\n const scrollable = doc.scrollHeight - doc.clientHeight;\n focus.scroll =\n scrollable > 0 ? Math.round((doc.scrollTop / scrollable) * 100) / 100 : 0;\n\n return focus;\n}\n\n/** A label for whatever is focused, reusing the same value-blind rules as activity. */\nfunction describeControl(el: Element): string {\n return describe(el);\n}\n\n/** The one place any of the three call sites below reach into the DOM-walk chunk —\n * so `stop()` has a single `snapshotModule` to check without importing anything\n * itself (see the teardown-state block above). */\nasync function loadSnapshotModule() {\n const m = await import('./dom/snapshot');\n snapshotModule = m;\n return m;\n}\n\nlet focusTimer: ReturnType<typeof setTimeout> | null = null;\n\n/** Coalesce a burst of selection/focus/scroll events into one push. */\nfunction scheduleFocus() {\n if (focusTimer) return;\n focusTimer = setTimeout(async () => {\n focusTimer = null;\n lastFocus = await readFocus();\n send?.({ type: 'host.focus', focus: lastFocus });\n }, 250);\n}\n\n/* ───────────────────────────── snapshot ───────────────────────────────── */\n\nlet snapshotSeq = 0;\n\nexport async function sendSnapshot(emit: Send) {\n // pageContext: false ⇒ no snapshot, ever — a `widget.requestSnapshot` must not be\n // able to reintroduce the page observation the host explicitly turned off.\n if (!pageContextOn) return;\n // The a11y walk is itself lazily imported: a host that only ever declares\n // PageContext and never lets the agent look at the page never downloads it.\n const { snapshot } = await loadSnapshotModule();\n const { yaml, truncated, visibleRefs } = snapshot();\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // The viewport slice rides with the focus context so the agent can tell the few\n // things on screen from the whole tree it just received.\n lastFocus = { ...lastFocus, visibleRefs };\n emit({ type: 'host.focus', focus: lastFocus });\n}\n\n/**\n * Zoom in on one ref — the pull half of the model. The agent asks; we resolve the ref\n * to a live element and return just its sub-tree.\n */\nexport async function sendRegion(ref: string, emit: Send) {\n // Mirrors sendSnapshot's guard: a `widget.readRegion` for a ref minted before\n // opt-out must not pull a live DOM subtree just because the ref is still\n // resolvable (see refs.ts's `clearRefs`, which `stop()` also uses as a backstop).\n if (!pageContextOn) return;\n const { snapshotRegion, resolveRef } = await loadSnapshotModule();\n const el = resolveRef(ref);\n if (!el) {\n emit({\n type: 'host.region',\n ref,\n yaml: '(this element is no longer on the page)',\n });\n return;\n }\n const { yaml } = snapshotRegion(el);\n emit({ type: 'host.region', ref, yaml: redact(yaml) });\n}\n\n/* ───────────────────────────── tools ──────────────────────────────────── */\n\n/**\n * v1 IS READ-ONLY.\n *\n * The page's content is untrusted — text on it can try to instruct the agent — and\n * the moment the agent can act, a bad answer becomes a bad ACTION. So no tool here\n * mutates the page yet. The call path exists, and the enforcement point is HERE (in\n * the page, where we control what actually happens) rather than in the widget, which\n * can be lied to.\n *\n * When write tools land: anything not `readOnly` gets a user confirmation, on every\n * call. Not \"unless the host opts out\" — every call, because the trigger may have\n * been written by the page.\n */\nexport async function callTool(call: ToolCall, emit: Send) {\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: false,\n error: 'Host tools are read-only in this version; no action was taken.',\n });\n}\n\n/* ───────────────────────────── auth ───────────────────────────────────── */\n\n/**\n * Hosted login, in a POPUP — and the popup is not a UX preference.\n *\n * Our iframe on acme.com gets a PARTITIONED cookie jar: it cannot see the user's\n * existing matterfact session, no matter that it is served from our own origin.\n * A popup, however, is a TOP-LEVEL window on app.matterfact.com — first-party, real\n * cookies, silent SSO if they are already signed in. It hands the token back by\n * postMessage and we forward it into the iframe.\n */\nexport function beginAuth(\n config: { origin: string; publishableKey: string },\n emit: Send,\n) {\n const w = window.open(\n `${config.origin}/embed/authorize?k=${encodeURIComponent(\n config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}`,\n 'mf_auth',\n 'width=460,height=640',\n );\n if (!w) return; // popup blocked; the widget shows its own \"sign in\" affordance\n\n // At most one pending popup at a time: a second beginAuth() (a re-click of \"sign\n // in\" before the first popup resolved) would otherwise leave the FIRST listener\n // dangling right alongside this one — tracked at module scope so stop() can also\n // remove it on teardown, same as every other listener this module installs.\n if (pendingAuthListener) window.removeEventListener('message', pendingAuthListener);\n\n const onMsg = (event: MessageEvent) => {\n if (event.origin !== config.origin) return;\n const d = event.data;\n if (d?.type !== 'mf:embed:auth') return;\n window.removeEventListener('message', onMsg);\n pendingAuthListener = null;\n emit({ type: 'host.auth', token: d.token, expiresAt: d.expiresAt });\n };\n pendingAuthListener = onMsg;\n window.addEventListener('message', onMsg);\n}\n\n/* ───────────────────────────── stop / start ───────────────────────────── */\n\n/**\n * The opposite number of `start()` — remove every listener it (or `watchNavigation`,\n * or `beginAuth`) installed, restore `history.pushState`/`replaceState` to what they\n * were before we wrapped them, and forget the module-level `send`/`activity`/focus\n * state. Nothing here is a filter over what gets sent afterward — there is simply\n * nothing left installed to send anything.\n *\n * Why this has to exist at all: everything `start()` installs is MODULE-GLOBAL, and\n * this module outlives any single `EmbedHost`. React remounts `EmbedHost` whenever\n * ANY of its identity-defining props change (react.tsx's effect deps: publishableKey,\n * widgetOrigin, surface, theme, inline, pageContext, dev) — including just a theme\n * swap, not only a deliberate opt-out. Before this fix, a remount's `start()` call\n * only ever ADDED listeners; the previous mount's were still attached and kept firing\n * into the module `send`, which the new `start()` had just repointed at the NEW\n * widget. Net effect: open once with pageContext on, then remount for any reason\n * (including `pageContext: false`) and the new widget silently keeps receiving\n * clicks/nav/focus collected by the old mount's still-live listeners.\n *\n * Called from two places: the top of `start()` (idempotency — a second `start()`\n * never doubles up, which also fixes the pre-existing double history-wrap /\n * double-`fire()`-per-navigation bug), and `EmbedHost.destroy()` in loader.ts (a\n * plain unmount with no remount still has to stop, not just wait for a `start()`\n * that may never come).\n */\nexport function stop(): void {\n document.removeEventListener('click', onClick, { capture: true });\n document.removeEventListener('submit', onSubmit, { capture: true });\n document.removeEventListener('change', onChange, { capture: true });\n document.removeEventListener('selectionchange', scheduleFocus);\n document.removeEventListener('focusin', scheduleFocus, { capture: true });\n window.removeEventListener('scroll', scheduleFocus, { capture: true });\n\n if (navFire) {\n window.removeEventListener('popstate', navFire);\n navFire = null;\n }\n // Restore, don't re-wrap: this is what stops a repeated start() from wrapping an\n // already-wrapped pushState/replaceState (the old double-fire-per-nav bug).\n if (origPushState) {\n history.pushState = origPushState;\n origPushState = null;\n }\n if (origReplaceState) {\n history.replaceState = origReplaceState;\n origReplaceState = null;\n }\n\n if (pendingAuthListener) {\n window.removeEventListener('message', pendingAuthListener);\n pendingAuthListener = null;\n }\n\n if (focusTimer) {\n clearTimeout(focusTimer);\n focusTimer = null;\n }\n\n send = null;\n activity.length = 0;\n lastFocus = {};\n widgetOrigin = '';\n\n // Belt-and-suspenders alongside sendRegion's own pageContextOn check (see above):\n // an old ref minted while observation was on must not stay resolvable afterward.\n // Only touches the DOM-walk chunk if it was ever actually loaded — see\n // loadSnapshotModule's doc comment.\n snapshotModule?.clearRefs();\n}\n\n/**\n * @param pageContext Whether to observe the host page at all. Default `true`. False is\n * the loader's `pageContext: false` opt-out reaching all the way down here: skip every\n * bit of page reading below — no declared/found context, no artifact grants, no nav/\n * click/submit/change/focus observers — so there is nothing to send and nothing that\n * could later be asked for (see `widget.requestSnapshot` in loader.ts). Theme detection\n * is unaffected: it reads an OS media query, never the page, so it isn't page context.\n */\nexport function start(emit: Send, origin?: string, pageContext = true) {\n // Idempotent: undo whatever a PREVIOUS start() installed before this one installs\n // anything. Without this, a remount (see stop()'s doc comment) leaves the old\n // mount's listeners live, writing into the `send` this call is about to reassign.\n stop();\n\n send = emit;\n widgetOrigin = origin || '';\n lastUrl = location.pathname;\n pageContextOn = pageContext;\n\n if (pageContextOn) {\n publishContext();\n publishArtifactGrants();\n watchNavigation();\n\n // Passive + capture: we observe, we never interfere with the host's own handling.\n document.addEventListener('click', onClick, { capture: true, passive: true });\n document.addEventListener('submit', onSubmit, {\n capture: true,\n passive: true,\n });\n // `change` fires on blur/commit for text inputs and immediately for select/\n // checkbox/radio — not on every keystroke, which is what we want: a settled\n // choice, not a stream of partial values.\n document.addEventListener('change', onChange, {\n capture: true,\n passive: true,\n });\n\n // Focal context: what the user is attending to. Coalesced (scheduleFocus), because\n // selectionchange and scroll fire in torrents.\n document.addEventListener('selectionchange', scheduleFocus, {\n passive: true,\n });\n document.addEventListener('focusin', scheduleFocus, {\n capture: true,\n passive: true,\n });\n window.addEventListener('scroll', scheduleFocus, {\n capture: true,\n passive: true,\n });\n }\n\n const theme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light';\n emit({ type: 'host.theme', mode: theme });\n}\n"],"mappings":";;;AAWA,IAAI,eAAe;AAuBnB,IAAM,eAAe;AAErB,IAAI,OAAoB;AACxB,IAAI,cAAc;AAClB,IAAM,WAA4B,CAAC;AACnC,IAAI,UAAU;AAGd,IAAI,gBAAgB;AAcpB,IAAI,UAA+B;AAInC,IAAI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W,8BAA8B,EAAE,UACrD,SACA;AACJ,OAAK,EAAE,MAAM,cAAc,MAAM,MAAM,CAAC;AAC1C;","names":[]}
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e,f,g,h,i,j,k}from"./chunk-XLQ36ZMV.js";export{c as artifactIdFromPath,i as beginAuth,h as callTool,e as grantsFromIframeSrcs,b as isPrivate,d as readPageContext,a as redact,g as sendRegion,f as sendSnapshot,k as start,j as stop};
2
+ //# sourceMappingURL=chunk-URIBHOOQ.js.map
@@ -0,0 +1,2 @@
1
+ var l="";var g=null,M=0,u=[],S="",b=!0,h=null,y=null,v=null,c=null,x=null,$=[/\b[\w.+-]+@[\w-]+\.[\w.]{2,}\b/g,/\b(?:\d[ -]?){13,19}\b/g,/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,/\b\d{9,}\b/g,/(?:\+?\d{1,2}[\s.-]?)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}\b/g,/\b(?:sk|pk|rk|ak)_(?:live|test)_[A-Za-z0-9]{8,}\b/g,/\beyJ[\w-]+\.[\w-]+\.[\w-]+\b/g];function a(t){let e=t;for(let n of $)e=e.replace(n,"[redacted]");return e}function E(t){if(t.closest("[data-mf-private]"))return!0;if(t.tagName==="INPUT"){let n=t.type;if(n==="password"||n==="hidden")return!0}return!1}function C(t){let e=t.match(/^\/(?:embed\/)?artifacts\/(.+?)\/?$/);return e?decodeURIComponent(e[1]):null}function q(){if(!l)return[];let t=[];for(let e of Array.from(document.querySelectorAll("iframe"))){let n;try{n=new URL(e.getAttribute("src")||"",location.href)}catch{continue}if(n.origin!==l)continue;let o=C(n.pathname);o&&(t.some(r=>r.id===o)||t.push({kind:"artifact",id:o,label:a(e.getAttribute("title")||"")||o}))}return t}function F(){return Array.from(document.querySelectorAll("iframe")).filter(t=>{try{let e=new URL(t.getAttribute("src")||"",location.href);return e.origin!==location.origin&&e.origin!==l}catch{return!1}}).length}function N(){let t=window.matterfact?.context??{},e=q(),n=F();return{url:location.origin+location.pathname,path:location.pathname,title:a(document.title),locale:document.documentElement.lang||void 0,...t,entities:[...t.entities??[],...e],data:{...t.data??{},...n?{opaque_frames:n}:{}}}}function T(){g?.({type:"host.context",context:N()})}function U(t,e){let n=[];for(let o of t){let r;try{r=new URL(o||"",location.href)}catch{continue}if(r.origin!==e)continue;let i=C(r.pathname);if(!i)continue;let s=r.searchParams.get("owner")||"",L=r.searchParams.get("t")||"";!s||!L||n.some(P=>P.id===i)||n.push({id:i,owner:s,token:L})}return n}function O(){if(!l)return[];let t=Array.from(document.querySelectorAll("iframe")).map(e=>e.getAttribute("src")||"");return U(t,l)}function k(){g?.({type:"host.artifactGrants",grants:O()})}function w(t){u.push({...t,seq:++M,ts:Date.now()}),u.length>40&&u.shift(),g?.({type:"host.activity",events:[u[u.length-1]]})}function G(t){let e=t.getAttribute("aria-label");if(e)return e;let n=t.id;if(n){let s=document.querySelector(`label[for="${CSS.escape(n)}"]`)?.textContent?.trim();if(s)return s}let o=t.closest("label")?.textContent?.trim();if(o)return o;let r=t.getAttribute("placeholder");return r||""}var _=new Set(["INPUT","SELECT","TEXTAREA"]);function d(t){let e=t.getAttribute("role")||t.tagName.toLowerCase(),n=t.getAttribute("aria-label")||(_.has(t.tagName)?G(t):t.innerText?.trim().slice(0,60))||t.getAttribute("title")||"";return n?`${e} "${a(n)}"`:e}var X='a[href],button,input,select,textarea,summary,[role="button"],[role="link"],[role="menuitem"],[role="tab"],[role="option"],[role="checkbox"],[role="switch"],[role="radio"],[onclick],[tabindex]';function I(t){let e=t.target;if(!e||!(e instanceof Element))return;let n=e.closest("label"),r=(n?n.getAttribute("for")&&document.getElementById(n.getAttribute("for"))||n.querySelector("input,select,textarea"):null)??e.closest(X);!r||E(r)||w({type:"click",summary:`clicked ${d(r)}`})}function R(t){let e=t.target;!e||E(e)||w({type:"submit",summary:`submitted ${d(e)}`})}function H(t){let e=t.target;if(!e||!(e instanceof Element)||E(e))return;let n=e.tagName,o=e.type;if(n==="INPUT"&&(o==="password"||o==="hidden"))return;let r=`changed ${d(e)}`;if(n==="SELECT"){let i=e.selectedOptions[0]?.text;i&&(r=`${d(e)} \u2192 "${a(i)}"`)}else(o==="checkbox"||o==="radio")&&(r=`${e.checked?"checked":"unchecked"} ${d(e)}`);w({type:"input",summary:r})}function z(){let t=()=>{let e=location.pathname;e!==S&&(S=e,w({type:"nav",summary:`navigated to ${e}`}),T(),k())};h=t;for(let e of["pushState","replaceState"]){let n=history[e];e==="pushState"?y=n:v=n,history[e]=function(...o){let r=n.apply(this,o);return t(),r}}window.addEventListener("popstate",t)}var m={};async function B(){let t={},e=window.getSelection?.();if(e&&!e.isCollapsed){let i=e.anchorNode?.parentElement??null;if(!i||!i.closest("[data-mf-private]")){let s=e.toString().trim().slice(0,500);s&&(t.selection=a(s))}}let n=document.activeElement;if(n&&n!==document.body&&!E(n)&&!n.closest("[data-mf-private]")){let{snapshot:i}=await A();t.focused={label:a(K(n)),role:n.getAttribute("role")||n.tagName.toLowerCase()}}let o=document.documentElement,r=o.scrollHeight-o.clientHeight;return t.scroll=r>0?Math.round(o.scrollTop/r*100)/100:0,t}function K(t){return d(t)}async function A(){let t=await import("./chunk-523BCS2Z.js");return x=t,t}var f=null;function p(){f||(f=setTimeout(async()=>{f=null,m=await B(),g?.({type:"host.focus",focus:m})},250))}var V=0;async function Y(t){if(!b)return;let{snapshot:e}=await A(),{yaml:n,truncated:o,visibleRefs:r}=e();t({type:"host.snapshot",snapshot:{yaml:a(n),seq:++V,truncated:o}}),m={...m,visibleRefs:r},t({type:"host.focus",focus:m})}async function D(t,e){if(!b)return;let{snapshotRegion:n,resolveRef:o}=await A(),r=o(t);if(!r){e({type:"host.region",ref:t,yaml:"(this element is no longer on the page)"});return}let{yaml:i}=n(r);e({type:"host.region",ref:t,yaml:a(i)})}async function J(t,e){e({type:"host.toolResult",callId:t.callId,ok:!1,error:"Host tools are read-only in this version; no action was taken."})}function Z(t,e){if(!window.open(`${t.origin}/embed/authorize?k=${encodeURIComponent(t.publishableKey)}&o=${encodeURIComponent(location.origin)}`,"mf_auth","width=460,height=640"))return;c&&window.removeEventListener("message",c);let o=r=>{if(r.origin!==t.origin)return;let i=r.data;i?.type==="mf:embed:auth"&&(window.removeEventListener("message",o),c=null,e({type:"host.auth",token:i.token,expiresAt:i.expiresAt}))};c=o,window.addEventListener("message",o)}function W(){document.removeEventListener("click",I,{capture:!0}),document.removeEventListener("submit",R,{capture:!0}),document.removeEventListener("change",H,{capture:!0}),document.removeEventListener("selectionchange",p),document.removeEventListener("focusin",p,{capture:!0}),window.removeEventListener("scroll",p,{capture:!0}),h&&(window.removeEventListener("popstate",h),h=null),y&&(history.pushState=y,y=null),v&&(history.replaceState=v,v=null),c&&(window.removeEventListener("message",c),c=null),f&&(clearTimeout(f),f=null),g=null,u.length=0,m={},l="",x?.clearRefs()}function j(t,e,n=!0){W(),g=t,l=e||"",S=location.pathname,b=n,b&&(T(),k(),z(),document.addEventListener("click",I,{capture:!0,passive:!0}),document.addEventListener("submit",R,{capture:!0,passive:!0}),document.addEventListener("change",H,{capture:!0,passive:!0}),document.addEventListener("selectionchange",p,{passive:!0}),document.addEventListener("focusin",p,{capture:!0,passive:!0}),window.addEventListener("scroll",p,{capture:!0,passive:!0}));let o=matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";t({type:"host.theme",mode:o})}export{a,E as b,C as c,N as d,U as e,Y as f,D as g,J as h,Z as i,W as j,j as k};
2
+ //# sourceMappingURL=chunk-XLQ36ZMV.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/context.ts"],
4
+ "sourcesContent": ["import type {\n ActivityEvent,\n FocusContext,\n HostToWidget,\n PageContext,\n PageEntity,\n ToolCall,\n} from './protocol';\n\n/** The origin serving our chat \u2014 how we tell OUR embedded content from the host's own\n * iframes. Set by start(); empty until then, which just means we spot nothing. */\nlet widgetOrigin = '';\n\n/**\n * The eye.\n *\n * Everything in this module can see the customer's page. It is a SEPARATE CHUNK,\n * loaded only when someone actually opens the chat \u2014 so a page whose visitors never\n * click the widget pays nothing for any of it, and a security reviewer can read\n * exactly one file to know what we look at.\n *\n * The rules, which are not negotiable:\n *\n * NEVER captured \u2014 no config enables it: the value of any <input>, <textarea> or\n * contenteditable; anything inside a password field; cookies; localStorage;\n * sessionStorage; the raw DOM; screenshots; network traffic; anything inside an\n * element marked `data-mf-private`.\n *\n * The agent never gets a selector and never touches the DOM. It gets refs. A ref\n * is resolved to an element HERE, in the page, by us.\n */\n\ntype Send = (msg: HostToWidget) => void;\n\nconst MAX_ACTIVITY = 40;\n\nlet send: Send | null = null;\nlet activitySeq = 0;\nconst activity: ActivityEvent[] = [];\nlet lastUrl = '';\n/** Set once by `start()`. False \u21D2 the host opted out of ALL page observation \u2014 every\n * exported entry point below that would otherwise read or send the page checks this. */\nlet pageContextOn = true;\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 teardown state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\n/**\n * Everything below is module-global bookkeeping so `stop()` (see `start()`, bottom of\n * file) can undo exactly what `start()`/`watchNavigation()`/`beginAuth()` installed \u2014\n * remove every listener, restore `history` to what it was before we wrapped it, and\n * forget any DOM-walk module we pulled in. All of this outlives a single `EmbedHost`;\n * see `stop()`'s doc comment for why that's the bug this exists to close.\n */\n\n/** The `fire` closure `watchNavigation()` handed to `popstate` \u2014 the only handle we\n * have to remove that listener again. */\nlet navFire: (() => void) | null = null;\n/** The `history.pushState`/`replaceState` this module wrapped, captured so `stop()`\n * can restore them EXACTLY rather than re-wrapping (which is how the old code\n * double-fired navigation on a second `start()`). */\nlet origPushState: History['pushState'] | null = null;\nlet origReplaceState: History['replaceState'] | null = null;\n/** The `message` listener `beginAuth()` is currently waiting on, if any. */\nlet pendingAuthListener: ((event: MessageEvent) => void) | null = null;\n/** Set once `sendSnapshot`/`sendRegion`/`readFocus` actually pull in the DOM-walk\n * chunk (`./dom/snapshot`) \u2014 never imported eagerly, so `stop()` doesn't pay for a\n * chunk that a host who only ever opted out (and never opened a snapshot) never\n * loaded in the first place. */\nlet snapshotModule: { clearRefs: () => void } | null = null;\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 redaction \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\nconst PII = [\n /\\b[\\w.+-]+@[\\w-]+\\.[\\w.]{2,}\\b/g, // email\n /\\b(?:\\d[ -]?){13,19}\\b/g, // card-ish\n /\\b\\d{3}[- ]?\\d{2}[- ]?\\d{4}\\b/g, // ssn \u2014 dashed, spaced, OR bare 9 digits\n /\\b\\d{9,}\\b/g, // long bare digit runs: account / MRN / routing numbers\n /(?:\\+?\\d{1,2}[\\s.-]?)?\\(?\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}\\b/g, // us phone\n /\\b(?:sk|pk|rk|ak)_(?:live|test)_[A-Za-z0-9]{8,}\\b/g, // stripe-style api keys\n /\\beyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+\\b/g, // jwt\n];\n\n/**\n * Scrub before anything leaves the page \u2014 not after it arrives.\n *\n * A compromised widget, or a bug in ours, must not be able to retroactively obtain\n * a customer's users' email addresses. The only way to guarantee that is to never\n * put them on the wire.\n */\nexport function redact(text: string): string {\n let out = text;\n for (const re of PII) out = out.replace(re, '[redacted]');\n return out;\n}\n\n/** Anything the host has marked private, or that is inherently sensitive, is out. */\nexport function isPrivate(el: Element): boolean {\n if (el.closest('[data-mf-private]')) return true;\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const t = (el as HTMLInputElement).type;\n if (t === 'password' || t === 'hidden') return true;\n }\n return false;\n}\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 page context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\n/**\n * What the page says about itself.\n *\n * A host that declares nothing still gets URL + title, which is what every other\n * embeddable assistant on the market offers in total. The interesting fields\n * (`route`, `description`, `entities`) are host-declared, because only the host\n * knows that `/o/8813` is \"the Acme Corp order, 3 items, unpaid\".\n *\n * Declared via a global the host sets before we load:\n * window.matterfact = { context: { route: '/orders/:id', description: '...', entities: [...] } }\n */\n/**\n * matterfact content embedded IN the host page \u2014 today, artifact iframes.\n *\n * A cross-origin iframe is opaque: `contentDocument` throws, so the DOM snapshot walks\n * straight past an embedded artifact and the agent is blind to the very thing the page\n * is built around. It reads the page as empty and asks which URL you mean.\n *\n * We don't need to see inside, and shouldn't want to. The artifact's ID is right there\n * in the src, and the agent can already resolve `artifacts/<id>/` in its session \u2014 the\n * same path an `@`-mention uses. So we report the ID and let the backend fetch the real\n * thing, which beats scraping a rendering of it: it gets the data, not the picture.\n *\n * Matched by ORIGIN, not by path shape: a customer is perfectly entitled to their own\n * /artifacts/ route, and it isn't ours.\n */\n/** The artifact slug from a matterfact artifact path, or null. Matches both the\n * chrome-free embed route (/embed/artifacts/<slug>) and the bare /artifacts/<slug>. */\nexport function artifactIdFromPath(pathname: string): string | null {\n const m = pathname.match(/^\\/(?:embed\\/)?artifacts\\/(.+?)\\/?$/);\n return m ? decodeURIComponent(m[1]) : null;\n}\n\nfunction embeddedMatterfactEntities(): PageEntity[] {\n if (!widgetOrigin) return [];\n const out: PageEntity[] = [];\n for (const frame of Array.from(document.querySelectorAll('iframe'))) {\n let u: URL;\n try {\n u = new URL(frame.getAttribute('src') || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== widgetOrigin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n if (out.some((e) => e.id === id)) continue; // same artifact twice = once\n // No url field: the agent reaches an artifact by ID (`artifacts/<id>/`), never by\n // fetching the page, and an artifact URL can carry a share token we've no business\n // forwarding. The id is the whole useful payload.\n out.push({\n kind: 'artifact',\n id,\n label: redact(frame.getAttribute('title') || '') || id,\n });\n }\n return out;\n}\n\n/**\n * Frames we can see the existence of but nothing inside \u2014 someone else's cross-origin\n * embed. Worth one line: \"there is a thing here I cannot read\" is a true and useful\n * statement, and much better than the agent confidently describing a page while missing\n * the widget the user is actually asking about.\n */\nfunction opaqueFrameCount(): number {\n return Array.from(document.querySelectorAll('iframe')).filter((f) => {\n try {\n const u = new URL(f.getAttribute('src') || '', location.href);\n return u.origin !== location.origin && u.origin !== widgetOrigin;\n } catch {\n return false;\n }\n }).length;\n}\n\nexport function readPageContext(): PageContext {\n const declared =\n (window as { matterfact?: { context?: PageContext } }).matterfact\n ?.context ?? {};\n\n const found = embeddedMatterfactEntities();\n const opaque = opaqueFrameCount();\n\n return {\n // Path only. A query string is where session ids, tokens and email addresses\n // live; it is not ours to take.\n url: location.origin + location.pathname,\n path: location.pathname,\n title: redact(document.title),\n locale: document.documentElement.lang || undefined,\n ...declared,\n // After the spread: what we FOUND is additive to what the host DECLARED, never a\n // replacement. A host that declares its own entities still gets the artifacts we\n // spotted, and vice versa.\n entities: [...(declared.entities ?? []), ...found],\n data: {\n ...(declared.data ?? {}),\n ...(opaque ? { opaque_frames: opaque } : {}),\n },\n };\n}\n\nfunction publishContext() {\n send?.({ type: 'host.context', context: readPageContext() });\n}\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 artifact grants (backend-only) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\nexport interface ArtifactGrantSrc {\n id: string;\n owner: string;\n token: string;\n}\n\n/** Read-only capability grants from co-embedded artifact iframes, for the backend to\n * materialize their data. Separate from entities on purpose: the token must never ride\n * ambient (rendered) context, only this backend-only channel. */\nexport function grantsFromIframeSrcs(\n srcs: string[],\n origin: string,\n): ArtifactGrantSrc[] {\n const out: ArtifactGrantSrc[] = [];\n for (const raw of srcs) {\n let u: URL;\n try {\n u = new URL(raw || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== origin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n const owner = u.searchParams.get('owner') || '';\n const token = u.searchParams.get('t') || '';\n if (!owner || !token) continue;\n if (out.some((g) => g.id === id)) continue;\n out.push({ id, owner, token });\n }\n return out;\n}\n\nfunction readArtifactGrants(): ArtifactGrantSrc[] {\n if (!widgetOrigin) return [];\n const srcs = Array.from(document.querySelectorAll('iframe')).map(\n (f) => f.getAttribute('src') || '',\n );\n return grantsFromIframeSrcs(srcs, widgetOrigin);\n}\n\nfunction publishArtifactGrants() {\n send?.({ type: 'host.artifactGrants', grants: readArtifactGrants() });\n}\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 activity \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\nfunction pushActivity(e: Omit<ActivityEvent, 'seq' | 'ts'>) {\n activity.push({ ...e, seq: ++activitySeq, ts: Date.now() });\n if (activity.length > MAX_ACTIVITY) activity.shift();\n send?.({ type: 'host.activity', events: [activity[activity.length - 1]] });\n}\n\n/**\n * A short, human-readable label for what got clicked.\n *\n * Shaped after PostHog's autocapture, not after a session-replay frame: rrweb would\n * give us `{source:2, type:2, id:417, x:210, y:88}` \u2014 no text, no role, no href,\n * meaningless to a model without the full DOM snapshot it deltas against. One line\n * of \"clicked button 'Export CSV'\" is worth more and costs less.\n */\n/**\n * The accessible NAME of a form control \u2014 never its value.\n *\n * A control has no `innerText`, so the generic path below misses it. We look where a\n * control's name actually lives: `aria-label`, then a `<label for>` or a wrapping\n * `<label>`, then `placeholder`. `placeholder` is a LABEL, not a value \u2014 it is the\n * hint shown when the field is empty (\"Order number or customer\"), so it is safe.\n */\nfunction controlLabel(el: Element): string {\n const aria = el.getAttribute('aria-label');\n if (aria) return aria;\n\n const id = el.id;\n if (id) {\n const forLabel = document.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n const t = forLabel?.textContent?.trim();\n if (t) return t;\n }\n const wrapping = el.closest('label')?.textContent?.trim();\n if (wrapping) return wrapping;\n\n const placeholder = el.getAttribute('placeholder');\n if (placeholder) return placeholder;\n\n return '';\n}\n\nconst FORM_CONTROLS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);\n\nfunction describe(el: Element): string {\n const role = el.getAttribute('role') || el.tagName.toLowerCase();\n const label =\n el.getAttribute('aria-label') ||\n (FORM_CONTROLS.has(el.tagName)\n ? controlLabel(el)\n : (el as HTMLElement).innerText?.trim().slice(0, 60)) ||\n el.getAttribute('title') ||\n '';\n return label ? `${role} \"${redact(label)}\"` : role;\n}\n\n/**\n * Elements a click is worth recording. Deliberately tight: the point of the activity\n * stream is INTENT (\"the user chose to export\"), and a click on a heading, a label,\n * a card gutter, or blank page is not intent, it is noise. We only log a click that\n * lands on something actionable.\n */\nconst ACTIONABLE =\n 'a[href],button,input,select,textarea,summary,' +\n '[role=\"button\"],[role=\"link\"],[role=\"menuitem\"],[role=\"tab\"],[role=\"option\"],' +\n '[role=\"checkbox\"],[role=\"switch\"],[role=\"radio\"],[onclick],[tabindex]';\n\nfunction onClick(ev: Event) {\n const target = ev.target as Element | null;\n if (!target || !(target instanceof Element)) return;\n\n // Clicking a <label> operates the control it labels \u2014 record THAT, not \"clicked\n // label\", so the event reads as the user's actual intent.\n const label = target.closest('label');\n const labelled = label\n ? (label.getAttribute('for') &&\n document.getElementById(label.getAttribute('for')!)) ||\n label.querySelector('input,select,textarea')\n : null;\n\n const actionable = labelled ?? target.closest(ACTIONABLE);\n // No actionable target \u2014 a click on text, a gutter, or blank space. That is not an\n // action; dropping it is the whole fix for the click-log noise.\n if (!actionable || isPrivate(actionable)) return;\n\n pushActivity({ type: 'click', summary: `clicked ${describe(actionable)}` });\n}\n\nfunction onSubmit(ev: Event) {\n const el = ev.target as Element | null;\n if (!el || isPrivate(el)) return;\n // The FORM was submitted \u2014 never its values.\n pushActivity({ type: 'submit', summary: `submitted ${describe(el)}` });\n}\n\n/**\n * A form field changed.\n *\n * The rule is the same as everywhere else and the temptation here is sharpest:\n * record THAT a field changed and WHICH field (its label), never WHAT it was\n * changed to. `change` fires on exactly the elements whose values are off-limits.\n *\n * One safe exception: a <select>, a checkbox, or a radio chose from a fixed, visible\n * set of options the agent can already see in the snapshot \u2014 \"Unpaid\", \"Shipped\".\n * That is a user *choice*, not typed data, so the chosen option's LABEL is fair to\n * include and is the useful part (\"filtered status to Shipped\"). Free-text and\n * numeric inputs get their label only.\n */\nfunction onChange(ev: Event) {\n const el = ev.target as (HTMLElement & { type?: string }) | null;\n if (!el || !(el instanceof Element) || isPrivate(el)) return;\n\n const tag = el.tagName;\n const type = (el as HTMLInputElement).type;\n\n // Never a password/hidden field, and isPrivate already covered data-mf-private.\n if (tag === 'INPUT' && (type === 'password' || type === 'hidden')) return;\n\n let summary = `changed ${describe(el)}`;\n\n if (tag === 'SELECT') {\n const opt = (el as HTMLSelectElement).selectedOptions[0]?.text;\n if (opt) summary = `${describe(el)} \u2192 \"${redact(opt)}\"`;\n } else if (type === 'checkbox' || type === 'radio') {\n summary = `${(el as HTMLInputElement).checked ? 'checked' : 'unchecked'} ${describe(el)}`;\n }\n\n pushActivity({ type: 'input', summary });\n}\n\n/**\n * SPA navigation. There is no event for `pushState`, so we wrap it \u2014 a 20-line job\n * that no library does better.\n */\nfunction watchNavigation() {\n const fire = () => {\n const url = location.pathname;\n if (url === lastUrl) return;\n lastUrl = url;\n pushActivity({ type: 'nav', summary: `navigated to ${url}` });\n publishContext();\n publishArtifactGrants();\n };\n // Captured so stop() can remove exactly this listener, and so history.pushState/\n // replaceState get restored to what they were before we wrapped them \u2014 never\n // re-wrapped on top of an existing wrap (that was the pre-existing bug: a second\n // start() used to wrap the ALREADY-wrapped methods, double-firing every nav).\n navFire = fire;\n\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = history[name];\n if (name === 'pushState') origPushState = orig as History['pushState'];\n else origReplaceState = orig as History['replaceState'];\n history[name] = function (\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const r = orig.apply(this, args);\n fire();\n return r;\n } as History[typeof name];\n }\n window.addEventListener('popstate', fire);\n}\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 focal context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\n/**\n * Where the user's attention is, right now.\n *\n * This is the \"knows what you're doing\" layer, and it is deliberately small so it can\n * ride on every turn \u2014 where the full snapshot cannot. It is also the most sensitive:\n * `selection` is whatever the user highlighted, which could be their own email, so it\n * is redacted and respects data-mf-private like everything else. Focus and the\n * viewport are labels and refs \u2014 never a value.\n *\n * Held so the last-known focus can travel with a turn even between the (throttled)\n * push updates.\n */\nlet lastFocus: FocusContext = {};\n\nasync function readFocus(): Promise<FocusContext> {\n const focus: FocusContext = {};\n\n // Selection \u2014 the single strongest \"this is what I'm asking about\" signal.\n const sel = window.getSelection?.();\n if (sel && !sel.isCollapsed) {\n const anchor = sel.anchorNode?.parentElement ?? null;\n // Don't lift a selection out of a private region, and cap it \u2014 a user can select\n // the whole page.\n if (!anchor || !anchor.closest('[data-mf-private]')) {\n const text = sel.toString().trim().slice(0, 500);\n if (text) focus.selection = redact(text);\n }\n }\n\n // The control they're working in \u2014 its label, never its contents.\n const active = document.activeElement;\n if (\n active &&\n active !== document.body &&\n !isPrivate(active) &&\n !active.closest('[data-mf-private]')\n ) {\n const { snapshot } = await loadSnapshotModule();\n void snapshot; // ensure the chunk that owns refFor is loaded before we describe\n focus.focused = {\n label: redact(describeControl(active)),\n role: active.getAttribute('role') || active.tagName.toLowerCase(),\n };\n }\n\n const doc = document.documentElement;\n const scrollable = doc.scrollHeight - doc.clientHeight;\n focus.scroll =\n scrollable > 0 ? Math.round((doc.scrollTop / scrollable) * 100) / 100 : 0;\n\n return focus;\n}\n\n/** A label for whatever is focused, reusing the same value-blind rules as activity. */\nfunction describeControl(el: Element): string {\n return describe(el);\n}\n\n/** The one place any of the three call sites below reach into the DOM-walk chunk \u2014\n * so `stop()` has a single `snapshotModule` to check without importing anything\n * itself (see the teardown-state block above). */\nasync function loadSnapshotModule() {\n const m = await import('./dom/snapshot');\n snapshotModule = m;\n return m;\n}\n\nlet focusTimer: ReturnType<typeof setTimeout> | null = null;\n\n/** Coalesce a burst of selection/focus/scroll events into one push. */\nfunction scheduleFocus() {\n if (focusTimer) return;\n focusTimer = setTimeout(async () => {\n focusTimer = null;\n lastFocus = await readFocus();\n send?.({ type: 'host.focus', focus: lastFocus });\n }, 250);\n}\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 snapshot \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\nlet snapshotSeq = 0;\n\nexport async function sendSnapshot(emit: Send) {\n // pageContext: false \u21D2 no snapshot, ever \u2014 a `widget.requestSnapshot` must not be\n // able to reintroduce the page observation the host explicitly turned off.\n if (!pageContextOn) return;\n // The a11y walk is itself lazily imported: a host that only ever declares\n // PageContext and never lets the agent look at the page never downloads it.\n const { snapshot } = await loadSnapshotModule();\n const { yaml, truncated, visibleRefs } = snapshot();\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // The viewport slice rides with the focus context so the agent can tell the few\n // things on screen from the whole tree it just received.\n lastFocus = { ...lastFocus, visibleRefs };\n emit({ type: 'host.focus', focus: lastFocus });\n}\n\n/**\n * Zoom in on one ref \u2014 the pull half of the model. The agent asks; we resolve the ref\n * to a live element and return just its sub-tree.\n */\nexport async function sendRegion(ref: string, emit: Send) {\n // Mirrors sendSnapshot's guard: a `widget.readRegion` for a ref minted before\n // opt-out must not pull a live DOM subtree just because the ref is still\n // resolvable (see refs.ts's `clearRefs`, which `stop()` also uses as a backstop).\n if (!pageContextOn) return;\n const { snapshotRegion, resolveRef } = await loadSnapshotModule();\n const el = resolveRef(ref);\n if (!el) {\n emit({\n type: 'host.region',\n ref,\n yaml: '(this element is no longer on the page)',\n });\n return;\n }\n const { yaml } = snapshotRegion(el);\n emit({ type: 'host.region', ref, yaml: redact(yaml) });\n}\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 tools \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\n/**\n * v1 IS READ-ONLY.\n *\n * The page's content is untrusted \u2014 text on it can try to instruct the agent \u2014 and\n * the moment the agent can act, a bad answer becomes a bad ACTION. So no tool here\n * mutates the page yet. The call path exists, and the enforcement point is HERE (in\n * the page, where we control what actually happens) rather than in the widget, which\n * can be lied to.\n *\n * When write tools land: anything not `readOnly` gets a user confirmation, on every\n * call. Not \"unless the host opts out\" \u2014 every call, because the trigger may have\n * been written by the page.\n */\nexport async function callTool(call: ToolCall, emit: Send) {\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: false,\n error: 'Host tools are read-only in this version; no action was taken.',\n });\n}\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 auth \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\u2500 */\n\n/**\n * Hosted login, in a POPUP \u2014 and the popup is not a UX preference.\n *\n * Our iframe on acme.com gets a PARTITIONED cookie jar: it cannot see the user's\n * existing matterfact session, no matter that it is served from our own origin.\n * A popup, however, is a TOP-LEVEL window on app.matterfact.com \u2014 first-party, real\n * cookies, silent SSO if they are already signed in. It hands the token back by\n * postMessage and we forward it into the iframe.\n */\nexport function beginAuth(\n config: { origin: string; publishableKey: string },\n emit: Send,\n) {\n const w = window.open(\n `${config.origin}/embed/authorize?k=${encodeURIComponent(\n config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}`,\n 'mf_auth',\n 'width=460,height=640',\n );\n if (!w) return; // popup blocked; the widget shows its own \"sign in\" affordance\n\n // At most one pending popup at a time: a second beginAuth() (a re-click of \"sign\n // in\" before the first popup resolved) would otherwise leave the FIRST listener\n // dangling right alongside this one \u2014 tracked at module scope so stop() can also\n // remove it on teardown, same as every other listener this module installs.\n if (pendingAuthListener) window.removeEventListener('message', pendingAuthListener);\n\n const onMsg = (event: MessageEvent) => {\n if (event.origin !== config.origin) return;\n const d = event.data;\n if (d?.type !== 'mf:embed:auth') return;\n window.removeEventListener('message', onMsg);\n pendingAuthListener = null;\n emit({ type: 'host.auth', token: d.token, expiresAt: d.expiresAt });\n };\n pendingAuthListener = onMsg;\n window.addEventListener('message', onMsg);\n}\n\n/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 stop / start \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */\n\n/**\n * The opposite number of `start()` \u2014 remove every listener it (or `watchNavigation`,\n * or `beginAuth`) installed, restore `history.pushState`/`replaceState` to what they\n * were before we wrapped them, and forget the module-level `send`/`activity`/focus\n * state. Nothing here is a filter over what gets sent afterward \u2014 there is simply\n * nothing left installed to send anything.\n *\n * Why this has to exist at all: everything `start()` installs is MODULE-GLOBAL, and\n * this module outlives any single `EmbedHost`. React remounts `EmbedHost` whenever\n * ANY of its identity-defining props change (react.tsx's effect deps: publishableKey,\n * widgetOrigin, surface, theme, inline, pageContext, dev) \u2014 including just a theme\n * swap, not only a deliberate opt-out. Before this fix, a remount's `start()` call\n * only ever ADDED listeners; the previous mount's were still attached and kept firing\n * into the module `send`, which the new `start()` had just repointed at the NEW\n * widget. Net effect: open once with pageContext on, then remount for any reason\n * (including `pageContext: false`) and the new widget silently keeps receiving\n * clicks/nav/focus collected by the old mount's still-live listeners.\n *\n * Called from two places: the top of `start()` (idempotency \u2014 a second `start()`\n * never doubles up, which also fixes the pre-existing double history-wrap /\n * double-`fire()`-per-navigation bug), and `EmbedHost.destroy()` in loader.ts (a\n * plain unmount with no remount still has to stop, not just wait for a `start()`\n * that may never come).\n */\nexport function stop(): void {\n document.removeEventListener('click', onClick, { capture: true });\n document.removeEventListener('submit', onSubmit, { capture: true });\n document.removeEventListener('change', onChange, { capture: true });\n document.removeEventListener('selectionchange', scheduleFocus);\n document.removeEventListener('focusin', scheduleFocus, { capture: true });\n window.removeEventListener('scroll', scheduleFocus, { capture: true });\n\n if (navFire) {\n window.removeEventListener('popstate', navFire);\n navFire = null;\n }\n // Restore, don't re-wrap: this is what stops a repeated start() from wrapping an\n // already-wrapped pushState/replaceState (the old double-fire-per-nav bug).\n if (origPushState) {\n history.pushState = origPushState;\n origPushState = null;\n }\n if (origReplaceState) {\n history.replaceState = origReplaceState;\n origReplaceState = null;\n }\n\n if (pendingAuthListener) {\n window.removeEventListener('message', pendingAuthListener);\n pendingAuthListener = null;\n }\n\n if (focusTimer) {\n clearTimeout(focusTimer);\n focusTimer = null;\n }\n\n send = null;\n activity.length = 0;\n lastFocus = {};\n widgetOrigin = '';\n\n // Belt-and-suspenders alongside sendRegion's own pageContextOn check (see above):\n // an old ref minted while observation was on must not stay resolvable afterward.\n // Only touches the DOM-walk chunk if it was ever actually loaded \u2014 see\n // loadSnapshotModule's doc comment.\n snapshotModule?.clearRefs();\n}\n\n/**\n * @param pageContext Whether to observe the host page at all. Default `true`. False is\n * the loader's `pageContext: false` opt-out reaching all the way down here: skip every\n * bit of page reading below \u2014 no declared/found context, no artifact grants, no nav/\n * click/submit/change/focus observers \u2014 so there is nothing to send and nothing that\n * could later be asked for (see `widget.requestSnapshot` in loader.ts). Theme detection\n * is unaffected: it reads an OS media query, never the page, so it isn't page context.\n */\nexport function start(emit: Send, origin?: string, pageContext = true) {\n // Idempotent: undo whatever a PREVIOUS start() installed before this one installs\n // anything. Without this, a remount (see stop()'s doc comment) leaves the old\n // mount's listeners live, writing into the `send` this call is about to reassign.\n stop();\n\n send = emit;\n widgetOrigin = origin || '';\n lastUrl = location.pathname;\n pageContextOn = pageContext;\n\n if (pageContextOn) {\n publishContext();\n publishArtifactGrants();\n watchNavigation();\n\n // Passive + capture: we observe, we never interfere with the host's own handling.\n document.addEventListener('click', onClick, { capture: true, passive: true });\n document.addEventListener('submit', onSubmit, {\n capture: true,\n passive: true,\n });\n // `change` fires on blur/commit for text inputs and immediately for select/\n // checkbox/radio \u2014 not on every keystroke, which is what we want: a settled\n // choice, not a stream of partial values.\n document.addEventListener('change', onChange, {\n capture: true,\n passive: true,\n });\n\n // Focal context: what the user is attending to. Coalesced (scheduleFocus), because\n // selectionchange and scroll fire in torrents.\n document.addEventListener('selectionchange', scheduleFocus, {\n passive: true,\n });\n document.addEventListener('focusin', scheduleFocus, {\n capture: true,\n passive: true,\n });\n window.addEventListener('scroll', scheduleFocus, {\n capture: true,\n passive: true,\n });\n }\n\n const theme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light';\n emit({ type: 'host.theme', mode: theme });\n}\n"],
5
+ "mappings": "AAWA,IAAIA,EAAe,GAyBnB,IAAIC,EAAoB,KACpBC,EAAc,EACZC,EAA4B,CAAC,EAC/BC,EAAU,GAGVC,EAAgB,GAchBC,EAA+B,KAI/BC,EAA6C,KAC7CC,EAAmD,KAEnDC,EAA8D,KAK9DC,EAAmD,KAIjDC,EAAM,CACV,kCACA,0BACA,iCACA,cACA,6DACA,qDACA,gCACF,EASO,SAASC,EAAOC,EAAsB,CAC3C,IAAIC,EAAM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fb,GAAgB,UAAU,CAC5B,CAUO,SAAS2F,EAAMhB,EAAYhD,EAAiBiE,EAAc,GAAM,CAIrEF,EAAK,EAELnG,EAAOoF,EACP9D,EAAec,GAAU,GACzBjC,EAAU,SAAS,SACnBC,EAAgBiG,EAEZjG,IACF6B,EAAe,EACfS,EAAsB,EACtBqB,EAAgB,EAGhB,SAAS,iBAAiB,QAASV,EAAS,CAAE,QAAS,GAAM,QAAS,EAAK,CAAC,EAC5E,SAAS,iBAAiB,SAAUI,EAAU,CAC5C,QAAS,GACT,QAAS,EACX,CAAC,EAID,SAAS,iBAAiB,SAAUC,EAAU,CAC5C,QAAS,GACT,QAAS,EACX,CAAC,EAID,SAAS,iBAAiB,kBAAmBuB,EAAe,CAC1D,QAAS,EACX,CAAC,EACD,SAAS,iBAAiB,UAAWA,EAAe,CAClD,QAAS,GACT,QAAS,EACX,CAAC,EACD,OAAO,iBAAiB,SAAUA,EAAe,CAC/C,QAAS,GACT,QAAS,EACX,CAAC,GAGH,IAAMqB,EAAQ,WAAW,8BAA8B,EAAE,QACrD,OACA,QACJlB,EAAK,CAAE,KAAM,aAAc,KAAMkB,CAAM,CAAC,CAC1C",
6
+ "names": ["widgetOrigin", "send", "activitySeq", "activity", "lastUrl", "pageContextOn", "navFire", "origPushState", "origReplaceState", "pendingAuthListener", "snapshotModule", "PII", "redact", "text", "out", "re", "isPrivate", "el", "t", "artifactIdFromPath", "pathname", "m", "embeddedMatterfactEntities", "widgetOrigin", "frame", "u", "id", "e", "opaqueFrameCount", "f", "readPageContext", "declared", "found", "opaque", "publishContext", "grantsFromIframeSrcs", "srcs", "origin", "raw", "owner", "token", "g", "readArtifactGrants", "publishArtifactGrants", "pushActivity", "controlLabel", "aria", "wrapping", "placeholder", "FORM_CONTROLS", "describe", "role", "label", "ACTIONABLE", "onClick", "ev", "target", "actionable", "onSubmit", "onChange", "tag", "type", "summary", "opt", "watchNavigation", "fire", "url", "name", "orig", "args", "lastFocus", "readFocus", "focus", "sel", "anchor", "active", "snapshot", "loadSnapshotModule", "describeControl", "doc", "scrollable", "focusTimer", "scheduleFocus", "snapshotSeq", "sendSnapshot", "emit", "yaml", "truncated", "visibleRefs", "sendRegion", "ref", "snapshotRegion", "resolveRef", "callTool", "call", "beginAuth", "config", "onMsg", "event", "d", "stop", "start", "pageContext", "theme"]
7
+ }
@@ -5,6 +5,12 @@ var send = null;
5
5
  var activitySeq = 0;
6
6
  var activity = [];
7
7
  var lastUrl = "";
8
+ var pageContextOn = true;
9
+ var navFire = null;
10
+ var origPushState = null;
11
+ var origReplaceState = null;
12
+ var pendingAuthListener = null;
13
+ var snapshotModule = null;
8
14
  var PII = [
9
15
  /\b[\w.+-]+@[\w-]+\.[\w.]{2,}\b/g,
10
16
  // email
@@ -191,8 +197,11 @@ function watchNavigation() {
191
197
  publishContext();
192
198
  publishArtifactGrants();
193
199
  };
200
+ navFire = fire;
194
201
  for (const name of ["pushState", "replaceState"]) {
195
202
  const orig = history[name];
203
+ if (name === "pushState") origPushState = orig;
204
+ else origReplaceState = orig;
196
205
  history[name] = function(...args) {
197
206
  const r = orig.apply(this, args);
198
207
  fire();
@@ -214,7 +223,7 @@ async function readFocus() {
214
223
  }
215
224
  const active = document.activeElement;
216
225
  if (active && active !== document.body && !isPrivate(active) && !active.closest("[data-mf-private]")) {
217
- const { snapshot } = await import('./snapshot-QBV7DTJP.js');
226
+ const { snapshot } = await loadSnapshotModule();
218
227
  focus.focused = {
219
228
  label: redact(describeControl(active)),
220
229
  role: active.getAttribute("role") || active.tagName.toLowerCase()
@@ -228,6 +237,11 @@ async function readFocus() {
228
237
  function describeControl(el) {
229
238
  return describe(el);
230
239
  }
240
+ async function loadSnapshotModule() {
241
+ const m = await import('./snapshot-Q3CALMHD.js');
242
+ snapshotModule = m;
243
+ return m;
244
+ }
231
245
  var focusTimer = null;
232
246
  function scheduleFocus() {
233
247
  if (focusTimer) return;
@@ -239,7 +253,8 @@ function scheduleFocus() {
239
253
  }
240
254
  var snapshotSeq = 0;
241
255
  async function sendSnapshot(emit) {
242
- const { snapshot } = await import('./snapshot-QBV7DTJP.js');
256
+ if (!pageContextOn) return;
257
+ const { snapshot } = await loadSnapshotModule();
243
258
  const { yaml, truncated, visibleRefs } = snapshot();
244
259
  emit({
245
260
  type: "host.snapshot",
@@ -249,7 +264,8 @@ async function sendSnapshot(emit) {
249
264
  emit({ type: "host.focus", focus: lastFocus });
250
265
  }
251
266
  async function sendRegion(ref, emit) {
252
- const { snapshotRegion, resolveRef } = await import('./snapshot-QBV7DTJP.js');
267
+ if (!pageContextOn) return;
268
+ const { snapshotRegion, resolveRef } = await loadSnapshotModule();
253
269
  const el = resolveRef(ref);
254
270
  if (!el) {
255
271
  emit({
@@ -279,46 +295,86 @@ function beginAuth(config, emit) {
279
295
  "width=460,height=640"
280
296
  );
281
297
  if (!w) return;
298
+ if (pendingAuthListener) window.removeEventListener("message", pendingAuthListener);
282
299
  const onMsg = (event) => {
283
300
  if (event.origin !== config.origin) return;
284
301
  const d = event.data;
285
302
  if (d?.type !== "mf:embed:auth") return;
286
303
  window.removeEventListener("message", onMsg);
304
+ pendingAuthListener = null;
287
305
  emit({ type: "host.auth", token: d.token, expiresAt: d.expiresAt });
288
306
  };
307
+ pendingAuthListener = onMsg;
289
308
  window.addEventListener("message", onMsg);
290
309
  }
291
- function start(emit, origin) {
310
+ function stop() {
311
+ document.removeEventListener("click", onClick, { capture: true });
312
+ document.removeEventListener("submit", onSubmit, { capture: true });
313
+ document.removeEventListener("change", onChange, { capture: true });
314
+ document.removeEventListener("selectionchange", scheduleFocus);
315
+ document.removeEventListener("focusin", scheduleFocus, { capture: true });
316
+ window.removeEventListener("scroll", scheduleFocus, { capture: true });
317
+ if (navFire) {
318
+ window.removeEventListener("popstate", navFire);
319
+ navFire = null;
320
+ }
321
+ if (origPushState) {
322
+ history.pushState = origPushState;
323
+ origPushState = null;
324
+ }
325
+ if (origReplaceState) {
326
+ history.replaceState = origReplaceState;
327
+ origReplaceState = null;
328
+ }
329
+ if (pendingAuthListener) {
330
+ window.removeEventListener("message", pendingAuthListener);
331
+ pendingAuthListener = null;
332
+ }
333
+ if (focusTimer) {
334
+ clearTimeout(focusTimer);
335
+ focusTimer = null;
336
+ }
337
+ send = null;
338
+ activity.length = 0;
339
+ lastFocus = {};
340
+ widgetOrigin = "";
341
+ snapshotModule?.clearRefs();
342
+ }
343
+ function start(emit, origin, pageContext = true) {
344
+ stop();
292
345
  send = emit;
293
346
  widgetOrigin = origin || "";
294
347
  lastUrl = location.pathname;
295
- publishContext();
296
- publishArtifactGrants();
297
- watchNavigation();
298
- document.addEventListener("click", onClick, { capture: true, passive: true });
299
- document.addEventListener("submit", onSubmit, {
300
- capture: true,
301
- passive: true
302
- });
303
- document.addEventListener("change", onChange, {
304
- capture: true,
305
- passive: true
306
- });
307
- document.addEventListener("selectionchange", scheduleFocus, {
308
- passive: true
309
- });
310
- document.addEventListener("focusin", scheduleFocus, {
311
- capture: true,
312
- passive: true
313
- });
314
- window.addEventListener("scroll", scheduleFocus, {
315
- capture: true,
316
- passive: true
317
- });
348
+ pageContextOn = pageContext;
349
+ if (pageContextOn) {
350
+ publishContext();
351
+ publishArtifactGrants();
352
+ watchNavigation();
353
+ document.addEventListener("click", onClick, { capture: true, passive: true });
354
+ document.addEventListener("submit", onSubmit, {
355
+ capture: true,
356
+ passive: true
357
+ });
358
+ document.addEventListener("change", onChange, {
359
+ capture: true,
360
+ passive: true
361
+ });
362
+ document.addEventListener("selectionchange", scheduleFocus, {
363
+ passive: true
364
+ });
365
+ document.addEventListener("focusin", scheduleFocus, {
366
+ capture: true,
367
+ passive: true
368
+ });
369
+ window.addEventListener("scroll", scheduleFocus, {
370
+ capture: true,
371
+ passive: true
372
+ });
373
+ }
318
374
  const theme = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
319
375
  emit({ type: "host.theme", mode: theme });
320
376
  }
321
377
 
322
- export { artifactIdFromPath, beginAuth, callTool, grantsFromIframeSrcs, isPrivate, readPageContext, redact, sendRegion, sendSnapshot, start };
323
- //# sourceMappingURL=chunk-CHPADW72.js.map
324
- //# sourceMappingURL=chunk-CHPADW72.js.map
378
+ export { artifactIdFromPath, beginAuth, callTool, grantsFromIframeSrcs, isPrivate, readPageContext, redact, sendRegion, sendSnapshot, start, stop };
379
+ //# sourceMappingURL=chunk-Z4WT3TIZ.js.map
380
+ //# sourceMappingURL=chunk-Z4WT3TIZ.js.map