@mgamadeus/ddd-agents 0.5.15 → 0.5.17
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.
- package/README.md +7 -1
- package/dist/chunks/browser-request-interception-BdKjYz31.js +335 -0
- package/dist/chunks/browser-request-interception-BdKjYz31.js.map +1 -0
- package/dist/image-render.js +60 -33
- package/dist/image-render.js.map +1 -1
- package/dist/preview.js +17 -20
- package/dist/preview.js.map +1 -1
- package/dist/types/image-render/frozen-widget-requests.d.ts +11 -2
- package/dist/types/image-render/widget-image-google-map.d.ts +5 -0
- package/dist/types/image-render/widget-image-static-assets.d.ts +2 -0
- package/dist/types/preview/widget-preview-requests.d.ts +6 -5
- package/dist/types/request-interception/browser-request-interception.d.ts +48 -0
- package/dist/types/request-interception/intercepted-xml-http-request-upload.d.ts +15 -0
- package/package.json +1 -8
- package/dist/chunks/widget-image-readiness-signal-C58JkCQA.js +0 -25
- package/dist/chunks/widget-image-readiness-signal-C58JkCQA.js.map +0 -1
package/dist/image-render.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image-render.js","sources":["../src/image-render/WidgetImageRender.tsx","../src/image-render/widget-image-readiness.ts","../src/image-render/frozen-widget-requests.ts","../src/image-render/widget-image-google-map.ts","../src/image-render/live-widget-requests.ts"],"sourcesContent":["import React, { useEffect, useRef } from \"react\";\nimport { conversationWidgetRegistry } from \"../renderer/conversationWidgetRegistry\";\nimport { resolveWidgetName } from \"../renderer/widget-name-resolver\";\nimport { buildWidgetAgentSpaceKeyProps } from \"../renderer/_agent-space/widget-agent-space-key-attribute\";\nimport { ReadOnlyConversationWidgetProvider } from \"../renderer/ConversationWidgetContext\";\nimport { ConversationWidgetRenderContext } from \"../renderer/ConversationWidgetRenderContext\";\nimport {\n WidgetImageRenderContext,\n WidgetImageLiveHydrationContext,\n WidgetImageReadinessContext,\n} from \"./WidgetImageRenderContext\";\nimport type { WidgetImageRenderBootstrap } from \"./widget-image-render.types\";\nimport type { createWidgetImageReadiness } from \"./widget-image-readiness\";\nimport styles from \"./WidgetImageRender.module.scss\";\n\n/**\n * Capture-only components by wire name: a frozen render shows the widget's visual from its complete snapshot, without\n * mounting the live fetch / OAuth / polling wrappers. An app adds its own with `registerStaticWidgetImageComponents`.\n */\nexport const staticWidgetImageComponents: Record<string, React.ComponentType<Record<string, unknown>>> = {};\n\n/** Adds an app's capture-only components (wire name → component). Runs outside React, before the first render. */\nexport const registerStaticWidgetImageComponents = (\n components: Readonly<Record<string, React.ComponentType<Record<string, unknown>>>>,\n): void => {\n Object.assign(staticWidgetImageComponents, components);\n};\n\ntype Readiness = ReturnType<typeof createWidgetImageReadiness>;\ntype HostProps = { bootstrap: WidgetImageRenderBootstrap; readiness: Readiness };\n\n// React error boundaries require a class. Never log customer payloads or send telemetry from capture.\nexport class WidgetImageCaptureBoundary extends React.Component<\n { children: React.ReactNode; fail: Readiness[\"fail\"] },\n { failed: boolean }\n> {\n state = { failed: false };\n static getDerivedStateFromError() {\n return { failed: true };\n }\n componentDidCatch() {\n this.props.fail(\"WIDGET_RENDER_FAILED\");\n }\n render() {\n return this.state.failed ? null : this.props.children;\n }\n}\n\n/**\n * The static image render of one widget (the e-mail capture): the registered widget in its e-mail presentation, inside\n * the read-only widget context, with the capture's frozen or live hydration. A frozen render takes the widget's static\n * capture component when the app registered one (`registerStaticWidgetImageComponents`). The app mounts it inside its\n * own store and theme (`WidgetImageCaptureBoundary` around it).\n */\nexport const WidgetImageRender = (props: HostProps) => {\n const { bootstrap, readiness } = props;\n const ref = useRef<HTMLDivElement>(null);\n const name = resolveWidgetName(bootstrap.input.widgetName);\n const entry = conversationWidgetRegistry.widgets.find((widget) => widget.name === name);\n useEffect(() => {\n if (!entry) readiness.fail(\"UNKNOWN_WIDGET\");\n else if (ref.current) return readiness.observe(ref.current);\n }, [entry, readiness]);\n if (!entry) return null;\n const Component =\n bootstrap.input.mode === \"live\" ? entry.component : (staticWidgetImageComponents[name ?? \"\"] ?? entry.component);\n return (\n <div ref={ref} className={styles.root} inert>\n <ConversationWidgetRenderContext.Provider value=\"email\">\n <WidgetImageReadinessContext.Provider value={readiness}>\n <ReadOnlyConversationWidgetProvider agentSpaceKey={bootstrap.siteId}>\n <WidgetImageRenderContext.Provider value={bootstrap.input.hydration}>\n <WidgetImageLiveHydrationContext.Provider value={bootstrap.input.mode === \"live\"}>\n <Component\n {...bootstrap.input.props}\n {...buildWidgetAgentSpaceKeyProps(bootstrap.siteId)}\n interactive={false}\n fresh={false}\n justDelivered={false}\n openedByPage={false}\n />\n </WidgetImageLiveHydrationContext.Provider>\n </WidgetImageRenderContext.Provider>\n </ReadOnlyConversationWidgetProvider>\n </WidgetImageReadinessContext.Provider>\n </ConversationWidgetRenderContext.Provider>\n </div>\n );\n};\n\n/** The slice the capture reads its hydration state from; any store that carries it (the capture's, a spec's). */\ninterface StoreWithWidgetHydration {\n getState: () => { AIExtensionsWidgetHydration: { widgets: Record<string, { status: string }> } };\n subscribe: (listener: () => void) => () => void;\n}\n\n/**\n * Holds the capture's readiness open while any widget hydration is idle or loading, and fails it on a hydration error.\n * Every shared hydrator counts — a widget's own, and each `$source` binding of a `ComposedView` tree, which reads through\n * the same slice (`ComposedViewDataSource:<name>`), so the shot waits for the tree's mail-time rows.\n */\nexport const followWidgetHydrationReadiness = (store: StoreWithWidgetHydration, readiness: Readiness) =>\n store.subscribe(() => {\n const widgets = Object.values(store.getState().AIExtensionsWidgetHydration.widgets);\n if (widgets.some((widget) => widget.status === \"error\")) readiness.fail(\"WIDGET_HYDRATION_FAILED\");\n readiness.setHydrationPending(widgets.some((widget) => widget.status === \"loading\" || widget.status === \"idle\"));\n });\n","import { publishWidgetImageReadiness, readWidgetImageReadiness } from \"./widget-image-readiness-signal\";\nimport type { WidgetImageRenderBootstrap, WidgetImageReadiness } from \"./widget-image-render.types\";\n\nconst MAX_TIMER_DELAY_MS = 2 ** 31 - 1;\n\nexport const createWidgetImageReadiness = (bootstrap: WidgetImageRenderBootstrap) => {\n let failed = readWidgetImageReadiness()?.state === \"failed\";\n let requestsPending = 0;\n let hydrationPending = false;\n let notifyChanged = () => {};\n let observed: HTMLElement | null = null;\n const identity = {\n version: 1 as const,\n snapshot_id: bootstrap.snapshotId,\n attempt_id: bootstrap.attemptId,\n input_sha256: bootstrap.inputSha256,\n render_version: bootstrap.renderVersion,\n };\n const publish = (state: WidgetImageReadiness[\"state\"], extra: Partial<WidgetImageReadiness> = {}) => {\n publishWidgetImageReadiness({ ...identity, state, ...extra });\n // Mirror outside the observed widget subtree for browser checks without changing screenshot pixels.\n document.documentElement.dataset.widgetImageState = state;\n document.documentElement.dataset.widgetImageError = extra.error_code ?? \"\";\n };\n if (!failed) publish(\"loading\");\n const measure = (element: HTMLElement) => {\n const { x, y, width, height } = element.getBoundingClientRect();\n return { x, y, width, height };\n };\n // A failed state still reports the widget box so the renderer can capture it when the caller suppresses errors.\n const fail = (code: string) => {\n if (failed || readWidgetImageReadiness()?.state === \"failed\") return;\n failed = true;\n const rect = observed ? measure(observed) : undefined;\n publish(\"failed\", rect && rect.width > 0 && rect.height > 0 ? { error_code: code, rect } : { error_code: code });\n };\n const isFailed = () => failed || readWidgetImageReadiness()?.state === \"failed\";\n const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));\n\n const ready = async (element: HTMLElement, isCurrent: () => boolean = () => true) => {\n observed = element;\n try {\n // Effects and their state updates must commit before inspecting the final content.\n await frame();\n await frame();\n await document.fonts.ready;\n document.fonts.forEach((font) => {\n if (font.status === \"error\") throw new Error(\"FONT_FAILED\");\n });\n const images = Array.from(element.querySelectorAll(\"img\"));\n await Promise.all(\n images.map(async (img) => {\n // Empty decorative image slots have nothing to download or decode.\n if (!img.currentSrc && !img.getAttribute(\"src\") && !img.getAttribute(\"srcset\") && img.alt === \"\") return;\n if (img.loading !== \"eager\") img.loading = \"eager\";\n await img.decode();\n if (!img.naturalWidth) throw new Error(\"ASSET_FAILED\");\n }),\n );\n await frame();\n await frame();\n if (isFailed() || !isCurrent()) return;\n if (requestsPending > 0 || hydrationPending) return;\n if (Date.now() >= bootstrap.expiresAt * 1000) return fail(\"TOKEN_EXPIRED\");\n // Determinate bars visualize scores too; only indeterminate bars imply loading.\n if (\n element.querySelector(\n '[aria-busy=\"true\"], [role=\"progressbar\"]:not([aria-valuenow]), [class*=\"Skeleton\"], [class*=\"skeleton\"]',\n )\n ) {\n if (bootstrap.input.mode === \"live\") return;\n return fail(\"WIDGET_STILL_LOADING\");\n }\n const rect = element.getBoundingClientRect();\n const width = bootstrap.input.width ?? 528;\n const maxHeight = bootstrap.input.maxHeight ?? 1200;\n if (!element.textContent?.trim() && !element.querySelector(\"img,svg,canvas\")) return fail(\"EMPTY_WIDGET\");\n if (\n rect.width <= 0 ||\n rect.height <= 0 ||\n rect.width > width + 1 ||\n rect.height > maxHeight ||\n rect.x < 0 ||\n rect.y < 0 ||\n element.scrollWidth > Math.ceil(rect.width) ||\n element.scrollHeight > Math.ceil(rect.height)\n ) {\n return fail(\"WIDGET_BOUNDS_EXCEEDED\");\n }\n // The capture viewport may be smaller than the widget; the renderer sizes its viewport/clip from this rect.\n publish(\"ready\", { rect: measure(element) });\n } catch {\n if (isCurrent()) fail(\"REQUIRED_ASSET_FAILED\");\n }\n };\n const observe = (element: HTMLElement) => {\n observed = element;\n let revision = 0;\n let timer: ReturnType<typeof setTimeout>;\n let disposed = false;\n const changed = () => {\n if (disposed || isFailed()) return;\n revision += 1;\n const expected = revision;\n publish(\"loading\");\n clearTimeout(timer);\n // Frozen hydrators resolve synchronously; legacy frozen GET effects and chart layout may commit later.\n timer = setTimeout(() => void ready(element, () => !disposed && expected === revision), 250);\n };\n const observer = new MutationObserver(changed);\n notifyChanged = changed;\n observer.observe(element, { childList: true, subtree: true, attributes: true, characterData: true });\n const resize = new ResizeObserver(changed);\n resize.observe(element);\n changed();\n const remaining = bootstrap.expiresAt * 1000 - Date.now();\n // Browsers fire delays above 2^31-1 ms immediately; long-lived URLs cannot expire within the render deadline.\n const expiry =\n remaining <= MAX_TIMER_DELAY_MS ? setTimeout(() => fail(\"TOKEN_EXPIRED\"), Math.max(0, remaining)) : undefined;\n const deadline = setTimeout(() => {\n if (readWidgetImageReadiness()?.state !== \"ready\") fail(\"RENDER_DEADLINE_EXCEEDED\");\n }, 60000);\n return () => {\n disposed = true;\n observer.disconnect();\n resize.disconnect();\n clearTimeout(timer);\n if (expiry !== undefined) clearTimeout(expiry);\n clearTimeout(deadline);\n notifyChanged = () => {};\n };\n };\n const beginRequest = () => {\n requestsPending += 1;\n if (!isFailed()) publish(\"loading\");\n notifyChanged();\n return () => {\n requestsPending -= 1;\n notifyChanged();\n };\n };\n const setHydrationPending = (pending: boolean) => {\n if (hydrationPending === pending) return;\n hydrationPending = pending;\n if (!isFailed()) publish(\"loading\");\n notifyChanged();\n };\n return { ready, observe, fail, isFailed, beginRequest, setHydrationPending };\n};\n","import axios, { AxiosRequestConfig } from \"axios\";\n\n/** The capture page serves supplied GET results in memory. It never lends the render token to the SDK. */\nexport const installFrozenWidgetRequests = (responses: Record<string, unknown>, fail: (code: string) => void) => {\n const originalAdapter = axios.defaults.adapter;\n axios.defaults.adapter = async (config: AxiosRequestConfig) => {\n const url = new URL(axios.getUri(config), window.location.origin);\n url.searchParams.sort();\n const key = `${(config.method ?? \"get\").toUpperCase()} ${url.pathname}${url.search}`;\n if ((config.method ?? \"get\").toLowerCase() !== \"get\" || !Object.prototype.hasOwnProperty.call(responses, key)) {\n fail(\"MISSING_FROZEN_RESPONSE\");\n throw new Error(\"MISSING_FROZEN_RESPONSE\");\n }\n return { data: structuredClone(responses[key]), status: 200, statusText: \"OK\", config, headers: {} };\n };\n return () => {\n axios.defaults.adapter = originalAdapter;\n };\n};\n","import { getGoogleMapWidgetNames } from \"../provider/environment\";\n\n/** The deepest tree the walk follows — the backend decodes a block with the same depth (`json_decode(…, 32)`). */\nconst MAX_TREE_DEPTH = 32;\n\nconst isMapNodeInValue = (value: unknown, depth: number, googleMapWidgetNames: readonly string[]): boolean => {\n if (depth > MAX_TREE_DEPTH || typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return value.some((element) => isMapNodeInValue(element, depth + 1, googleMapWidgetNames));\n const wireObject = value as Record<string, unknown>;\n if (wireObject.type === \"Map\") return true;\n if (wireObject.type === \"Widget\" && typeof wireObject.widget === \"string\") {\n const embeddedWidgetName = wireObject.widget.replace(/Directive$/, \"\");\n if (googleMapWidgetNames.includes(embeddedWidgetName)) return true;\n }\n return Object.values(wireObject).some((nested) => isMapNodeInValue(nested, depth + 1, googleMapWidgetNames));\n};\n\n/**\n * Whether a capture renders a Google map and so may load the Maps SDK (the narrow CSP and transport exception).\n * The twin of the backend's check that opens the page's CSP: the app's map widgets themselves\n * (`AgentsEnvironment.googleMapWidgetNames`), and a `ComposedView` whose tree holds a `Map` node or embeds one of them.\n * The payload is read as written; a payload that does not parse renders no map.\n */\nexport const isGoogleMapCapture = (widgetName: string, props: Record<string, unknown>): boolean => {\n const googleMapWidgetNames = getGoogleMapWidgetNames();\n if (googleMapWidgetNames.includes(widgetName)) return true;\n if (widgetName !== \"ComposedView\" || typeof props.payload !== \"string\") return false;\n try {\n return isMapNodeInValue((JSON.parse(props.payload) as Record<string, unknown>)?.view, 0, googleMapWidgetNames);\n } catch {\n return false;\n }\n};\n","import axios, { AxiosRequestConfig } from \"axios\";\nimport type { WidgetImageRenderBootstrap } from \"./widget-image-render.types\";\nimport type { createWidgetImageReadiness } from \"./widget-image-readiness\";\nimport { isGoogleMapCapture } from \"./widget-image-google-map\";\nimport { getWidgetImageCaptureReadPathPrefix } from \"../provider/environment\";\n\nconst STATIC_ASSET_PATH =\n /^\\/react\\/(?:app-build|widget-image-build)\\/assets\\/(?:[\\w-]+\\/)*[\\w.-]+\\.(?:svg|png|jpe?g|webp|gif)$/;\n\n/** Loaded only by the capture entry. SDK signatures stay unchanged; no ambient credentials are sent. */\nexport const installLiveWidgetRequests = (\n bootstrap: WidgetImageRenderBootstrap,\n readiness: ReturnType<typeof createWidgetImageReadiness>,\n) => {\n const originalAdapter = axios.defaults.adapter;\n const originalFetch = window.fetch;\n const fetchRead = originalFetch.bind(window);\n // The one read a capture may make of the backend: a GET without body under the capture read path, with the\n // capture token and nothing of the page (cookies, debug/noCache) — through axios and through fetch alike.\n const isScopedRead = (url: URL, method: string, hasBody: boolean) =>\n Boolean(bootstrap.authToken) &&\n url.origin === window.location.origin &&\n url.pathname.startsWith(getWidgetImageCaptureReadPathPrefix()) &&\n method.toLowerCase() === \"get\" &&\n !hasBody &&\n !readiness.isFailed() &&\n Date.now() < bootstrap.expiresAt * 1000;\n const readScoped = async (url: URL, signal: AbortSignal | undefined) => {\n // The ordinary helper propagates debug/noCache from the page; capture requests never do.\n url.searchParams.delete(\"debug\");\n url.searchParams.delete(\"noCache\");\n const response = await fetchRead(url.toString(), {\n method: \"GET\",\n credentials: \"omit\",\n cache: \"no-store\",\n redirect: \"error\",\n referrerPolicy: \"no-referrer\",\n signal,\n headers: {\n Authorization: `Bearer ${bootstrap.authToken}`,\n jwtSource: \"internal_requests\",\n Accept: \"application/json\",\n },\n });\n if (!response.ok) throw new Error(\"RENDER_READ_FAILED\");\n return response;\n };\n // Captured widgets may import shared telemetry/helpers. They cannot bypass the scoped reads. Three reads pass:\n // the capture read path (as through axios: a client on fetch reads its data the same way), static bundle images\n // (useDynamicImport fetches icons such as review-source logos) and, for map captures only, the Google Maps SDK (a map\n // widget, or a ComposedView tree holding a map).\n window.fetch = async (input, init) => {\n const request = new Request(typeof input === \"string\" ? new URL(input, window.location.origin).href : input, init);\n const url = new URL(request.url, window.location.origin);\n const unavailable = readiness.isFailed() || Date.now() >= bootstrap.expiresAt * 1000;\n const isStaticAsset =\n url.origin === window.location.origin &&\n STATIC_ASSET_PATH.test(url.pathname) &&\n url.search === \"\" &&\n request.method === \"GET\";\n if (url.origin === window.location.origin && url.pathname.startsWith(getWidgetImageCaptureReadPathPrefix())) {\n const finish = readiness.beginRequest();\n try {\n if (!isScopedRead(url, request.method, request.body !== null)) throw new Error(\"RENDER_READ_DENIED\");\n return await readScoped(url, init?.signal ?? request.signal);\n } catch {\n readiness.fail(\"WIDGET_HYDRATION_FAILED\");\n // never the URL, the headers, the token or the remote body to the page's own error handling\n throw new TypeError(\"Widget hydration failed\");\n } finally {\n finish();\n }\n }\n if (isStaticAsset && !unavailable) {\n const finish = readiness.beginRequest();\n try {\n return await fetchRead(url.toString(), {\n credentials: \"omit\",\n redirect: \"error\",\n referrerPolicy: \"no-referrer\",\n });\n } finally {\n finish();\n }\n }\n const isMap = isGoogleMapCapture(bootstrap.input.widgetName, bootstrap.input.props);\n const isGoogleMapRequest =\n url.protocol === \"https:\" &&\n ((url.hostname === \"maps.googleapis.com\" &&\n (url.pathname.startsWith(\"/maps/\") || url.pathname.startsWith(\"/$rpc/\"))) ||\n (url.hostname === \"maps.gstatic.com\" && url.pathname.startsWith(\"/mapfiles/\")));\n if (!isMap || !isGoogleMapRequest || ![\"GET\", \"POST\"].includes(request.method) || unavailable) {\n readiness.fail(\"UNSCOPED_REQUEST\");\n throw new Error(\"Unscoped render request\");\n }\n const headers = new Headers();\n for (const name of [\"content-type\", \"x-goog-api-key\", \"x-goog-api-client\", \"x-user-agent\"]) {\n const value = request.headers.get(name);\n if (value) headers.set(name, value);\n }\n const finish = readiness.beginRequest();\n try {\n const response = await fetchRead(request, {\n credentials: \"omit\",\n referrerPolicy: \"no-referrer\",\n redirect: \"error\",\n headers,\n });\n if (!response.ok) throw new Error(\"Map request failed\");\n return response;\n } catch {\n readiness.fail(\"MAP_ASSET_FAILED\");\n throw new Error(\"Map request failed\");\n } finally {\n finish();\n }\n };\n axios.defaults.adapter = async (config: AxiosRequestConfig) => {\n const finish = readiness.beginRequest();\n try {\n const url = new URL(axios.getUri(config), window.location.origin);\n if (!isScopedRead(url, config.method ?? \"get\", config.data !== undefined)) throw new Error(\"RENDER_READ_DENIED\");\n const response = await readScoped(url, config.signal as AbortSignal | undefined);\n const data = await response.json();\n return { data, status: response.status, statusText: \"OK\", config: {}, headers: {} };\n } catch {\n readiness.fail(\"WIDGET_HYDRATION_FAILED\");\n // HttpStore logs errors and submits telemetry for status 500. Never expose the URL,\n // request headers, auth token or remote exception body to those shared interceptors.\n throw { message: \"Widget hydration failed\", response: { status: 0, data: { error: \"Widget hydration failed\" } } };\n } finally {\n finish();\n }\n };\n return () => {\n axios.defaults.adapter = originalAdapter;\n window.fetch = originalFetch;\n };\n};\n"],"names":["finish"],"mappings":";;;;;;;;;;;;;;;AAmBO,MAAM,8BAA4F,CAAA;AAGlG,MAAM,sCAAsC,CACjD,eACS;AACT,SAAO,OAAO,6BAA6B,UAAU;AACvD;AAMO,MAAM,mCAAmC,MAAM,UAGpD;AAAA,EAHK,cAAA;AAAA,UAAA,GAAA,SAAA;AAIL,SAAA,QAAQ,EAAE,QAAQ,MAAA;AAAA,EAAM;AAAA,EACxB,OAAO,2BAA2B;AAChC,WAAO,EAAE,QAAQ,KAAA;AAAA,EACnB;AAAA,EACA,oBAAoB;AAClB,SAAK,MAAM,KAAK,sBAAsB;AAAA,EACxC;AAAA,EACA,SAAS;AACP,WAAO,KAAK,MAAM,SAAS,OAAO,KAAK,MAAM;AAAA,EAC/C;AACF;AAQO,MAAM,oBAAoB,CAAC,UAAqB;AACrD,QAAM,EAAE,WAAW,UAAA,IAAc;AACjC,QAAM,MAAM,OAAuB,IAAI;AACvC,QAAM,OAAO,kBAAkB,UAAU,MAAM,UAAU;AACzD,QAAM,QAAQ,2BAA2B,QAAQ,KAAK,CAAC,WAAW,OAAO,SAAS,IAAI;AACtF,YAAU,MAAM;AACd,QAAI,CAAC,MAAO,WAAU,KAAK,gBAAgB;AAAA,aAClC,IAAI,QAAS,QAAO,UAAU,QAAQ,IAAI,OAAO;AAAA,EAC5D,GAAG,CAAC,OAAO,SAAS,CAAC;AACrB,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,YACJ,UAAU,MAAM,SAAS,SAAS,MAAM,YAAa,4BAA4B,QAAQ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["../src/image-render/WidgetImageRender.tsx","../src/image-render/widget-image-readiness.ts","../src/image-render/widget-image-google-map.ts","../src/image-render/widget-image-static-assets.ts","../src/image-render/frozen-widget-requests.ts","../src/image-render/live-widget-requests.ts"],"sourcesContent":["import React, { useEffect, useRef } from \"react\";\nimport { conversationWidgetRegistry } from \"../renderer/conversationWidgetRegistry\";\nimport { resolveWidgetName } from \"../renderer/widget-name-resolver\";\nimport { buildWidgetAgentSpaceKeyProps } from \"../renderer/_agent-space/widget-agent-space-key-attribute\";\nimport { ReadOnlyConversationWidgetProvider } from \"../renderer/ConversationWidgetContext\";\nimport { ConversationWidgetRenderContext } from \"../renderer/ConversationWidgetRenderContext\";\nimport {\n WidgetImageRenderContext,\n WidgetImageLiveHydrationContext,\n WidgetImageReadinessContext,\n} from \"./WidgetImageRenderContext\";\nimport type { WidgetImageRenderBootstrap } from \"./widget-image-render.types\";\nimport type { createWidgetImageReadiness } from \"./widget-image-readiness\";\nimport styles from \"./WidgetImageRender.module.scss\";\n\n/**\n * Capture-only components by wire name: a frozen render shows the widget's visual from its complete snapshot, without\n * mounting the live fetch / OAuth / polling wrappers. An app adds its own with `registerStaticWidgetImageComponents`.\n */\nexport const staticWidgetImageComponents: Record<string, React.ComponentType<Record<string, unknown>>> = {};\n\n/** Adds an app's capture-only components (wire name → component). Runs outside React, before the first render. */\nexport const registerStaticWidgetImageComponents = (\n components: Readonly<Record<string, React.ComponentType<Record<string, unknown>>>>,\n): void => {\n Object.assign(staticWidgetImageComponents, components);\n};\n\ntype Readiness = ReturnType<typeof createWidgetImageReadiness>;\ntype HostProps = { bootstrap: WidgetImageRenderBootstrap; readiness: Readiness };\n\n// React error boundaries require a class. Never log customer payloads or send telemetry from capture.\nexport class WidgetImageCaptureBoundary extends React.Component<\n { children: React.ReactNode; fail: Readiness[\"fail\"] },\n { failed: boolean }\n> {\n state = { failed: false };\n static getDerivedStateFromError() {\n return { failed: true };\n }\n componentDidCatch() {\n this.props.fail(\"WIDGET_RENDER_FAILED\");\n }\n render() {\n return this.state.failed ? null : this.props.children;\n }\n}\n\n/**\n * The static image render of one widget (the e-mail capture): the registered widget in its e-mail presentation, inside\n * the read-only widget context, with the capture's frozen or live hydration. A frozen render takes the widget's static\n * capture component when the app registered one (`registerStaticWidgetImageComponents`). The app mounts it inside its\n * own store and theme (`WidgetImageCaptureBoundary` around it).\n */\nexport const WidgetImageRender = (props: HostProps) => {\n const { bootstrap, readiness } = props;\n const ref = useRef<HTMLDivElement>(null);\n const name = resolveWidgetName(bootstrap.input.widgetName);\n const entry = conversationWidgetRegistry.widgets.find((widget) => widget.name === name);\n useEffect(() => {\n if (!entry) readiness.fail(\"UNKNOWN_WIDGET\");\n else if (ref.current) return readiness.observe(ref.current);\n }, [entry, readiness]);\n if (!entry) return null;\n const Component =\n bootstrap.input.mode === \"live\" ? entry.component : (staticWidgetImageComponents[name ?? \"\"] ?? entry.component);\n return (\n <div ref={ref} className={styles.root} inert>\n <ConversationWidgetRenderContext.Provider value=\"email\">\n <WidgetImageReadinessContext.Provider value={readiness}>\n <ReadOnlyConversationWidgetProvider agentSpaceKey={bootstrap.siteId}>\n <WidgetImageRenderContext.Provider value={bootstrap.input.hydration}>\n <WidgetImageLiveHydrationContext.Provider value={bootstrap.input.mode === \"live\"}>\n <Component\n {...bootstrap.input.props}\n {...buildWidgetAgentSpaceKeyProps(bootstrap.siteId)}\n interactive={false}\n fresh={false}\n justDelivered={false}\n openedByPage={false}\n />\n </WidgetImageLiveHydrationContext.Provider>\n </WidgetImageRenderContext.Provider>\n </ReadOnlyConversationWidgetProvider>\n </WidgetImageReadinessContext.Provider>\n </ConversationWidgetRenderContext.Provider>\n </div>\n );\n};\n\n/** The slice the capture reads its hydration state from; any store that carries it (the capture's, a spec's). */\ninterface StoreWithWidgetHydration {\n getState: () => { AIExtensionsWidgetHydration: { widgets: Record<string, { status: string }> } };\n subscribe: (listener: () => void) => () => void;\n}\n\n/**\n * Holds the capture's readiness open while any widget hydration is idle or loading, and fails it on a hydration error.\n * Every shared hydrator counts — a widget's own, and each `$source` binding of a `ComposedView` tree, which reads through\n * the same slice (`ComposedViewDataSource:<name>`), so the shot waits for the tree's mail-time rows.\n */\nexport const followWidgetHydrationReadiness = (store: StoreWithWidgetHydration, readiness: Readiness) =>\n store.subscribe(() => {\n const widgets = Object.values(store.getState().AIExtensionsWidgetHydration.widgets);\n if (widgets.some((widget) => widget.status === \"error\")) readiness.fail(\"WIDGET_HYDRATION_FAILED\");\n readiness.setHydrationPending(widgets.some((widget) => widget.status === \"loading\" || widget.status === \"idle\"));\n });\n","import { publishWidgetImageReadiness, readWidgetImageReadiness } from \"./widget-image-readiness-signal\";\nimport type { WidgetImageRenderBootstrap, WidgetImageReadiness } from \"./widget-image-render.types\";\n\nconst MAX_TIMER_DELAY_MS = 2 ** 31 - 1;\n\nexport const createWidgetImageReadiness = (bootstrap: WidgetImageRenderBootstrap) => {\n let failed = readWidgetImageReadiness()?.state === \"failed\";\n let requestsPending = 0;\n let hydrationPending = false;\n let notifyChanged = () => {};\n let observed: HTMLElement | null = null;\n const identity = {\n version: 1 as const,\n snapshot_id: bootstrap.snapshotId,\n attempt_id: bootstrap.attemptId,\n input_sha256: bootstrap.inputSha256,\n render_version: bootstrap.renderVersion,\n };\n const publish = (state: WidgetImageReadiness[\"state\"], extra: Partial<WidgetImageReadiness> = {}) => {\n publishWidgetImageReadiness({ ...identity, state, ...extra });\n // Mirror outside the observed widget subtree for browser checks without changing screenshot pixels.\n document.documentElement.dataset.widgetImageState = state;\n document.documentElement.dataset.widgetImageError = extra.error_code ?? \"\";\n };\n if (!failed) publish(\"loading\");\n const measure = (element: HTMLElement) => {\n const { x, y, width, height } = element.getBoundingClientRect();\n return { x, y, width, height };\n };\n // A failed state still reports the widget box so the renderer can capture it when the caller suppresses errors.\n const fail = (code: string) => {\n if (failed || readWidgetImageReadiness()?.state === \"failed\") return;\n failed = true;\n const rect = observed ? measure(observed) : undefined;\n publish(\"failed\", rect && rect.width > 0 && rect.height > 0 ? { error_code: code, rect } : { error_code: code });\n };\n const isFailed = () => failed || readWidgetImageReadiness()?.state === \"failed\";\n const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));\n\n const ready = async (element: HTMLElement, isCurrent: () => boolean = () => true) => {\n observed = element;\n try {\n // Effects and their state updates must commit before inspecting the final content.\n await frame();\n await frame();\n await document.fonts.ready;\n document.fonts.forEach((font) => {\n if (font.status === \"error\") throw new Error(\"FONT_FAILED\");\n });\n const images = Array.from(element.querySelectorAll(\"img\"));\n await Promise.all(\n images.map(async (img) => {\n // Empty decorative image slots have nothing to download or decode.\n if (!img.currentSrc && !img.getAttribute(\"src\") && !img.getAttribute(\"srcset\") && img.alt === \"\") return;\n if (img.loading !== \"eager\") img.loading = \"eager\";\n await img.decode();\n if (!img.naturalWidth) throw new Error(\"ASSET_FAILED\");\n }),\n );\n await frame();\n await frame();\n if (isFailed() || !isCurrent()) return;\n if (requestsPending > 0 || hydrationPending) return;\n if (Date.now() >= bootstrap.expiresAt * 1000) return fail(\"TOKEN_EXPIRED\");\n // Determinate bars visualize scores too; only indeterminate bars imply loading.\n if (\n element.querySelector(\n '[aria-busy=\"true\"], [role=\"progressbar\"]:not([aria-valuenow]), [class*=\"Skeleton\"], [class*=\"skeleton\"]',\n )\n ) {\n if (bootstrap.input.mode === \"live\") return;\n return fail(\"WIDGET_STILL_LOADING\");\n }\n const rect = element.getBoundingClientRect();\n const width = bootstrap.input.width ?? 528;\n const maxHeight = bootstrap.input.maxHeight ?? 1200;\n if (!element.textContent?.trim() && !element.querySelector(\"img,svg,canvas\")) return fail(\"EMPTY_WIDGET\");\n if (\n rect.width <= 0 ||\n rect.height <= 0 ||\n rect.width > width + 1 ||\n rect.height > maxHeight ||\n rect.x < 0 ||\n rect.y < 0 ||\n element.scrollWidth > Math.ceil(rect.width) ||\n element.scrollHeight > Math.ceil(rect.height)\n ) {\n return fail(\"WIDGET_BOUNDS_EXCEEDED\");\n }\n // The capture viewport may be smaller than the widget; the renderer sizes its viewport/clip from this rect.\n publish(\"ready\", { rect: measure(element) });\n } catch {\n if (isCurrent()) fail(\"REQUIRED_ASSET_FAILED\");\n }\n };\n const observe = (element: HTMLElement) => {\n observed = element;\n let revision = 0;\n let timer: ReturnType<typeof setTimeout>;\n let disposed = false;\n const changed = () => {\n if (disposed || isFailed()) return;\n revision += 1;\n const expected = revision;\n publish(\"loading\");\n clearTimeout(timer);\n // Frozen hydrators resolve synchronously; legacy frozen GET effects and chart layout may commit later.\n timer = setTimeout(() => void ready(element, () => !disposed && expected === revision), 250);\n };\n const observer = new MutationObserver(changed);\n notifyChanged = changed;\n observer.observe(element, { childList: true, subtree: true, attributes: true, characterData: true });\n const resize = new ResizeObserver(changed);\n resize.observe(element);\n changed();\n const remaining = bootstrap.expiresAt * 1000 - Date.now();\n // Browsers fire delays above 2^31-1 ms immediately; long-lived URLs cannot expire within the render deadline.\n const expiry =\n remaining <= MAX_TIMER_DELAY_MS ? setTimeout(() => fail(\"TOKEN_EXPIRED\"), Math.max(0, remaining)) : undefined;\n const deadline = setTimeout(() => {\n if (readWidgetImageReadiness()?.state !== \"ready\") fail(\"RENDER_DEADLINE_EXCEEDED\");\n }, 60000);\n return () => {\n disposed = true;\n observer.disconnect();\n resize.disconnect();\n clearTimeout(timer);\n if (expiry !== undefined) clearTimeout(expiry);\n clearTimeout(deadline);\n notifyChanged = () => {};\n };\n };\n const beginRequest = () => {\n requestsPending += 1;\n if (!isFailed()) publish(\"loading\");\n notifyChanged();\n return () => {\n requestsPending -= 1;\n notifyChanged();\n };\n };\n const setHydrationPending = (pending: boolean) => {\n if (hydrationPending === pending) return;\n hydrationPending = pending;\n if (!isFailed()) publish(\"loading\");\n notifyChanged();\n };\n return { ready, observe, fail, isFailed, beginRequest, setHydrationPending };\n};\n","import { getGoogleMapWidgetNames } from \"../provider/environment\";\n\n/** The deepest tree the walk follows — the backend decodes a block with the same depth (`json_decode(…, 32)`). */\nconst MAX_TREE_DEPTH = 32;\n\nconst isMapNodeInValue = (value: unknown, depth: number, googleMapWidgetNames: readonly string[]): boolean => {\n if (depth > MAX_TREE_DEPTH || typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return value.some((element) => isMapNodeInValue(element, depth + 1, googleMapWidgetNames));\n const wireObject = value as Record<string, unknown>;\n if (wireObject.type === \"Map\") return true;\n if (wireObject.type === \"Widget\" && typeof wireObject.widget === \"string\") {\n const embeddedWidgetName = wireObject.widget.replace(/Directive$/, \"\");\n if (googleMapWidgetNames.includes(embeddedWidgetName)) return true;\n }\n return Object.values(wireObject).some((nested) => isMapNodeInValue(nested, depth + 1, googleMapWidgetNames));\n};\n\n/**\n * Whether a capture renders a Google map and so may load the Maps SDK (the narrow CSP and transport exception).\n * The twin of the backend's check that opens the page's CSP: the app's map widgets themselves\n * (`AgentsEnvironment.googleMapWidgetNames`), and a `ComposedView` whose tree holds a `Map` node or embeds one of them.\n * The payload is read as written; a payload that does not parse renders no map.\n */\nexport const isGoogleMapCapture = (widgetName: string, props: Record<string, unknown>): boolean => {\n const googleMapWidgetNames = getGoogleMapWidgetNames();\n if (googleMapWidgetNames.includes(widgetName)) return true;\n if (widgetName !== \"ComposedView\" || typeof props.payload !== \"string\") return false;\n try {\n return isMapNodeInValue((JSON.parse(props.payload) as Record<string, unknown>)?.view, 0, googleMapWidgetNames);\n } catch {\n return false;\n }\n};\n\n/**\n * A request of the Google Maps SDK (its API and RPC paths, its static files) — the only other origin a map capture\n * may reach, through `fetch` and `XMLHttpRequest` alike.\n */\nexport const isGoogleMapsSdkRequestUrl = (url: URL): boolean =>\n url.protocol === \"https:\" &&\n ((url.hostname === \"maps.googleapis.com\" && (url.pathname.startsWith(\"/maps/\") || url.pathname.startsWith(\"/$rpc/\"))) ||\n (url.hostname === \"maps.gstatic.com\" && url.pathname.startsWith(\"/mapfiles/\")));\n","const STATIC_ASSET_PATH =\n /^\\/react\\/(?:app-build|widget-image-build)\\/assets\\/(?:[\\w-]+\\/)*[\\w.-]+\\.(?:svg|png|jpe?g|webp|gif)$/;\n\n/** A static bundle image of the page's origin (icons such as review-source logos that `useDynamicImport` fetches). */\nexport const isStaticBundleImageRequest = (url: URL, method: string): boolean =>\n url.origin === window.location.origin && STATIC_ASSET_PATH.test(url.pathname) && url.search === \"\" && method === \"GET\";\n","import {\n createHeaderlessResponse,\n interceptFetchRequests,\n interceptXMLHttpRequests,\n type InterceptedRequest,\n} from \"../request-interception/browser-request-interception\";\nimport { isGoogleMapsSdkRequestUrl } from \"./widget-image-google-map\";\nimport { isStaticBundleImageRequest } from \"./widget-image-static-assets\";\n\n/** The key a frozen response is stored under: method, path and the sorted query (`GET /api/keywords?a=1&b=2`). */\nconst frozenRequestKey = (request: InterceptedRequest): string => {\n const url = new URL(request.url.href);\n url.searchParams.sort();\n return `${request.method} ${url.pathname}${url.search}`;\n};\n\nconst findFrozenResponse = (responses: Record<string, unknown>, request: InterceptedRequest) => {\n const key = frozenRequestKey(request);\n return request.method === \"GET\" && Object.prototype.hasOwnProperty.call(responses, key)\n ? { value: responses[key] }\n : undefined;\n};\n\n/**\n * The capture page serves supplied GET results in memory. It never lends the render token to the SDK.\n *\n * `XMLHttpRequest` (the transport of axios's browser adapter) is always answered: a supplied GET with its result, any\n * other request fails with MISSING_FROZEN_RESPONSE. `fetch` is left alone unless `options.interceptFetch` is set; then\n * a `fetch` gets the same answers and the same failure, except that a static bundle image of the page's origin and a\n * request of the Google Maps SDK still go to the network unchanged; any other origin fails as well.\n */\nexport const installFrozenWidgetRequests = (\n responses: Record<string, unknown>,\n fail: (code: string) => void,\n options: { interceptFetch?: boolean } = {},\n) => {\n const refuse = (): never => {\n fail(\"MISSING_FROZEN_RESPONSE\");\n throw new Error(\"MISSING_FROZEN_RESPONSE\");\n };\n const restoreXMLHttpRequest = interceptXMLHttpRequests(async (request) => {\n const frozen = findFrozenResponse(responses, request);\n if (!frozen) return refuse();\n return createHeaderlessResponse(JSON.stringify(frozen.value), 200, \"OK\");\n });\n const restoreFetch = options.interceptFetch\n ? interceptFetchRequests(async (request) => {\n const frozen = findFrozenResponse(responses, request);\n if (frozen) {\n return new Response(JSON.stringify(frozen.value), {\n status: 200,\n statusText: \"OK\",\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n const passesUnanswered =\n isGoogleMapsSdkRequestUrl(request.url) || isStaticBundleImageRequest(request.url, request.method);\n return passesUnanswered ? request.forward() : refuse();\n })\n : () => {};\n return () => {\n restoreXMLHttpRequest();\n restoreFetch();\n };\n};\n","import type { WidgetImageRenderBootstrap } from \"./widget-image-render.types\";\nimport type { createWidgetImageReadiness } from \"./widget-image-readiness\";\nimport { isGoogleMapCapture, isGoogleMapsSdkRequestUrl } from \"./widget-image-google-map\";\nimport { isStaticBundleImageRequest } from \"./widget-image-static-assets\";\nimport { getWidgetImageCaptureReadPathPrefix } from \"../provider/environment\";\nimport {\n createHeaderlessResponse,\n interceptXMLHttpRequests,\n toSameRealmFetchInput,\n} from \"../request-interception/browser-request-interception\";\n\n/** Loaded only by the capture entry. SDK signatures stay unchanged; no ambient credentials are sent. */\nexport const installLiveWidgetRequests = (\n bootstrap: WidgetImageRenderBootstrap,\n readiness: ReturnType<typeof createWidgetImageReadiness>,\n) => {\n const originalFetch = window.fetch;\n const fetchRead = originalFetch.bind(window);\n // The one read a capture may make of the backend: a GET without body under the capture read path, with the\n // capture token and nothing of the page (cookies, debug/noCache) — through XMLHttpRequest and through fetch alike.\n const isScopedRead = (url: URL, method: string, hasBody: boolean) =>\n Boolean(bootstrap.authToken) &&\n url.origin === window.location.origin &&\n url.pathname.startsWith(getWidgetImageCaptureReadPathPrefix()) &&\n method.toLowerCase() === \"get\" &&\n !hasBody &&\n !readiness.isFailed() &&\n Date.now() < bootstrap.expiresAt * 1000;\n const readScoped = async (url: URL, signal: AbortSignal | undefined) => {\n // The ordinary helper propagates debug/noCache from the page; capture requests never do.\n url.searchParams.delete(\"debug\");\n url.searchParams.delete(\"noCache\");\n const response = await fetchRead(url.toString(), {\n method: \"GET\",\n credentials: \"omit\",\n cache: \"no-store\",\n redirect: \"error\",\n referrerPolicy: \"no-referrer\",\n signal,\n headers: {\n Authorization: `Bearer ${bootstrap.authToken}`,\n jwtSource: \"internal_requests\",\n Accept: \"application/json\",\n },\n });\n if (!response.ok) throw new Error(\"RENDER_READ_FAILED\");\n return response;\n };\n // Captured widgets may import shared telemetry/helpers. They cannot bypass the scoped reads. Three reads pass:\n // the capture read path (as through XMLHttpRequest: a client on fetch reads its data the same way), static bundle\n // images (useDynamicImport fetches icons such as review-source logos) and, for map captures only, the Google Maps SDK\n // (a map widget, or a ComposedView tree holding a map). A `Request` of another realm is read like one of this realm.\n window.fetch = async (input, init) => {\n const sameRealmInput = await toSameRealmFetchInput(input);\n const request = new Request(\n typeof sameRealmInput === \"string\" ? new URL(sameRealmInput, window.location.origin).href : sameRealmInput,\n init,\n );\n const url = new URL(request.url, window.location.origin);\n const unavailable = readiness.isFailed() || Date.now() >= bootstrap.expiresAt * 1000;\n const isStaticAsset = isStaticBundleImageRequest(url, request.method);\n if (url.origin === window.location.origin && url.pathname.startsWith(getWidgetImageCaptureReadPathPrefix())) {\n const finish = readiness.beginRequest();\n try {\n if (!isScopedRead(url, request.method, request.body !== null)) throw new Error(\"RENDER_READ_DENIED\");\n return await readScoped(url, init?.signal ?? request.signal);\n } catch {\n readiness.fail(\"WIDGET_HYDRATION_FAILED\");\n // never the URL, the headers, the token or the remote body to the page's own error handling\n throw new TypeError(\"Widget hydration failed\");\n } finally {\n finish();\n }\n }\n if (isStaticAsset && !unavailable) {\n const finish = readiness.beginRequest();\n try {\n return await fetchRead(url.toString(), {\n credentials: \"omit\",\n redirect: \"error\",\n referrerPolicy: \"no-referrer\",\n });\n } finally {\n finish();\n }\n }\n const isMap = isGoogleMapCapture(bootstrap.input.widgetName, bootstrap.input.props);\n const isGoogleMapRequest = isGoogleMapsSdkRequestUrl(url);\n if (!isMap || !isGoogleMapRequest || ![\"GET\", \"POST\"].includes(request.method) || unavailable) {\n readiness.fail(\"UNSCOPED_REQUEST\");\n throw new Error(\"Unscoped render request\");\n }\n const headers = new Headers();\n for (const name of [\"content-type\", \"x-goog-api-key\", \"x-goog-api-client\", \"x-user-agent\"]) {\n const value = request.headers.get(name);\n if (value) headers.set(name, value);\n }\n const finish = readiness.beginRequest();\n try {\n const response = await fetchRead(request, {\n credentials: \"omit\",\n referrerPolicy: \"no-referrer\",\n redirect: \"error\",\n headers,\n });\n if (!response.ok) throw new Error(\"Map request failed\");\n return response;\n } catch {\n readiness.fail(\"MAP_ASSET_FAILED\");\n throw new Error(\"Map request failed\");\n } finally {\n finish();\n }\n };\n // XMLHttpRequest (the transport of axios's browser adapter): the scoped capture read and, for a map capture, the\n // Google Maps SDK; everything else fails closed. A Maps SDK request goes through the fetch stand-in above (the page's\n // `fetch` at this install), so it gets exactly the rules of a fetch: no credentials, no referrer, the allowed headers.\n // A failure reaches the page as a network error — status 0, no header, no body: never the URL, request headers, auth\n // token or remote exception body to the page's shared interceptors (which log errors and submit telemetry).\n const isMapCapture = isGoogleMapCapture(bootstrap.input.widgetName, bootstrap.input.props);\n const restoreXMLHttpRequest = interceptXMLHttpRequests(async (request) => {\n if (isMapCapture && isGoogleMapsSdkRequestUrl(request.url)) return request.forward();\n const finish = readiness.beginRequest();\n try {\n if (!isScopedRead(request.url, request.method, request.body !== null)) throw new Error(\"RENDER_READ_DENIED\");\n const response = await readScoped(request.url, request.signal);\n const text = await response.text();\n JSON.parse(text);\n return createHeaderlessResponse(text, response.status, \"OK\");\n } catch {\n readiness.fail(\"WIDGET_HYDRATION_FAILED\");\n throw new TypeError(\"Widget hydration failed\");\n } finally {\n finish();\n }\n });\n return () => {\n restoreXMLHttpRequest();\n window.fetch = originalFetch;\n };\n};\n"],"names":["finish"],"mappings":";;;;;;;;;;;;;;AAmBO,MAAM,8BAA4F,CAAA;AAGlG,MAAM,sCAAsC,CACjD,eACS;AACT,SAAO,OAAO,6BAA6B,UAAU;AACvD;AAMO,MAAM,mCAAmC,MAAM,UAGpD;AAA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I;AAAA,IAC7D,QAAQ;AACN,gBAAU,KAAK,yBAAyB;AACxC,YAAM,IAAI,UAAU,yBAAyB;AAAA,IAC/C,UAAA;AACE,aAAA;AAAA,IACF;AAAA,EACF,CAAC;AACD,SAAO,MAAM;AACX,0BAAA;AACA,WAAO,QAAQ;AAAA,EACjB;AACF;"}
|
package/dist/preview.js
CHANGED
|
@@ -6,8 +6,7 @@ import { Q as buildComposedViewComponentRegistry, R as composedViewComponents, G
|
|
|
6
6
|
import { aE as WidgetSurface, Y as readWidgetAgentSpaceKeyAttribute, h as canvasBehaviourOf, W as WidgetRenderReportContext, z as buildWidgetAgentSpaceKeyProps, S as StandaloneConversationWidgetProvider, y as ConversationWidgetRenderContext, a7 as WidgetImageRenderContext, ac as CANVAS_VIABLE_MIN_WIDTH, l as listWidgetHydratorTypes, j as getWidgetHydrator, u as unregisterWidgetHydrator, g as registerWidgetHydrator } from "./chunks/WebSearchResultsConversationWidget-887v8Wen.js";
|
|
7
7
|
import { c as canvasBodies, E as EntityMentionAskButton } from "./chunks/canvasBodies-C7qqThc9.js";
|
|
8
8
|
import { f as decideCanvasOpen } from "./chunks/canvas-reducers-CwFA3rQ6.js";
|
|
9
|
-
import { p as publishWidgetImageReadiness } from "./chunks/
|
|
10
|
-
import axios from "axios";
|
|
9
|
+
import { p as publishWidgetImageReadiness, i as interceptXMLHttpRequests, d as isFetchRequest, c as createHeaderlessResponse } from "./chunks/browser-request-interception-BdKjYz31.js";
|
|
11
10
|
import { C as ConversationWidgetProvider, a as ConversationMessageInputComposerWidgets } from "./chunks/ConversationMessageInputComposerWidgets-B3Zf69rD.js";
|
|
12
11
|
const page$1 = "agents_page_5VMDeD";
|
|
13
12
|
const chatColumn = "agents_chatColumn_FWcgdJ";
|
|
@@ -631,36 +630,34 @@ const SILENTLY_ANSWERED_PATHS = ["/rest_api/v1/log"];
|
|
|
631
630
|
const isSilentlyAnswered = (url) => SILENTLY_ANSWERED_PATHS.includes(url.pathname);
|
|
632
631
|
const isStatusResponse = (response) => typeof response === "object" && response !== null && typeof response.__status === "number";
|
|
633
632
|
const isPendingResponse = (response) => typeof response === "object" && response !== null && response.__pending === true;
|
|
633
|
+
const xhrAnswer = (body, status) => {
|
|
634
|
+
if (status < 200 || status > 599) throw new TypeError(`preview response ${status}`);
|
|
635
|
+
if ([204, 205, 304].includes(status)) return createHeaderlessResponse(null, status);
|
|
636
|
+
return createHeaderlessResponse(JSON.stringify(body), status, status === 200 ? "OK" : "");
|
|
637
|
+
};
|
|
634
638
|
const installWidgetPreviewRequests = (responses, onMissingResponse, onFailedRequest = () => {
|
|
635
639
|
}) => {
|
|
636
|
-
const
|
|
637
|
-
|
|
638
|
-
const
|
|
639
|
-
const requestUrl = new URL(axios.getUri(config), window.location.origin);
|
|
640
|
-
if (isSilentlyAnswered(requestUrl)) return { data: {}, status: 200, statusText: "OK", config, headers: {} };
|
|
641
|
-
const requestKey = widgetPreviewRequestKey(method, requestUrl);
|
|
640
|
+
const restoreXMLHttpRequest = interceptXMLHttpRequests(async (request) => {
|
|
641
|
+
if (isSilentlyAnswered(request.url)) return xhrAnswer({}, 200);
|
|
642
|
+
const requestKey = widgetPreviewRequestKey(request.method, request.url);
|
|
642
643
|
const response = Object.prototype.hasOwnProperty.call(responses, requestKey) ? responses[requestKey] : void 0;
|
|
643
644
|
if (response === void 0) {
|
|
644
645
|
onMissingResponse(requestKey);
|
|
645
|
-
|
|
646
|
+
throw new Error(`no preview response for ${requestKey}`);
|
|
646
647
|
}
|
|
647
648
|
if (isPendingResponse(response)) return new Promise(() => {
|
|
648
649
|
});
|
|
649
650
|
if (isStatusResponse(response)) {
|
|
650
651
|
if (response.__status >= 400) onFailedRequest(requestKey);
|
|
651
|
-
return
|
|
652
|
-
Object.assign(new Error(`preview response ${response.__status}`), {
|
|
653
|
-
config,
|
|
654
|
-
response: { status: response.__status, data: response.__body ?? null, config, headers: {} }
|
|
655
|
-
})
|
|
656
|
-
);
|
|
652
|
+
return xhrAnswer(response.__body ?? null, response.__status);
|
|
657
653
|
}
|
|
658
|
-
return
|
|
659
|
-
};
|
|
654
|
+
return xhrAnswer(response, 200);
|
|
655
|
+
});
|
|
660
656
|
const originalFetch = window.fetch;
|
|
661
657
|
window.fetch = async (input, init) => {
|
|
662
|
-
const
|
|
663
|
-
const
|
|
658
|
+
const fromRequest = isFetchRequest(input) ? input : void 0;
|
|
659
|
+
const method = (init?.method ?? (fromRequest ? fromRequest.method : "GET")).toLowerCase();
|
|
660
|
+
const url = new URL(fromRequest ? fromRequest.url : String(input), window.location.origin);
|
|
664
661
|
if (isSilentlyAnswered(url)) return new Response("{}", { status: 200 });
|
|
665
662
|
const requestKey = widgetPreviewRequestKey(method, url);
|
|
666
663
|
const response = Object.prototype.hasOwnProperty.call(responses, requestKey) ? responses[requestKey] : void 0;
|
|
@@ -677,7 +674,7 @@ const installWidgetPreviewRequests = (responses, onMissingResponse, onFailedRequ
|
|
|
677
674
|
return new Response(JSON.stringify(response), { status: 200, headers: { "Content-Type": "application/json" } });
|
|
678
675
|
};
|
|
679
676
|
return () => {
|
|
680
|
-
|
|
677
|
+
restoreXMLHttpRequest();
|
|
681
678
|
window.fetch = originalFetch;
|
|
682
679
|
};
|
|
683
680
|
};
|
package/dist/preview.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preview.js","sources":["../src/preview/preview-stub-components.tsx","../src/renderer/_agent-space/declared-agent-space-key-field-name.ts","../src/preview/widget-preview-fixtures.ts","../src/preview/WidgetPreviewHost.tsx","../src/preview/widget-preview-signal.ts","../src/preview/widget-preview-readiness.ts","../src/preview/widget-preview-requests.ts","../src/preview/widget-preview-hydration.ts","../src/widgets/EntityMentionConversationWidget/stories/EntityMentionAskFlowStory.tsx"],"sourcesContent":["import { Text } from \"../provider/components\";\nimport type {\n ComposedViewComponentDefinition,\n ComposedViewComponentProps,\n} from \"../kit/composed-view-component-types\";\nimport {\n buildComposedViewComponentRegistry,\n composedViewComponents,\n} from \"../kit/composed-view-components\";\nimport { WidgetSurface } from \"../widgets/_shared/modern\";\nimport styles from \"./WidgetPreview.module.scss\";\n\n/**\n * Stand-ins for kit node types that have a schema but no component yet — only the preview uses\n * them, and only for a fixture that asks (`stubComposedViewComponents`). A real component always wins.\n */\nconst formatDuration = (durationSeconds: unknown): string | null => {\n if (typeof durationSeconds !== \"number\" || !Number.isFinite(durationSeconds) || durationSeconds < 0) return null;\n const minutes = Math.floor(durationSeconds / 60);\n const seconds = Math.floor(durationSeconds % 60);\n return `${minutes}:${String(seconds).padStart(2, \"0\")}`;\n};\n\nconst StubVideo = ({ props }: ComposedViewComponentProps) => {\n const duration = formatDuration(props.durationSeconds);\n return (\n <WidgetSurface level=\"flat\" compact>\n <div className={styles.stubVideo}>\n {typeof props.thumbnail === \"string\" ? (\n <img className={styles.stubVideoThumbnail} src={props.thumbnail} alt=\"\" />\n ) : null}\n <div className={styles.stubVideoText}>\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {typeof props.title === \"string\" ? props.title : \"\"}\n </Text>\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {[typeof props.channel === \"string\" ? props.channel : null, duration].filter(Boolean).join(\" · \")}\n </Text>\n </div>\n </div>\n </WidgetSurface>\n );\n};\n\nconst PREVIEW_STUB_COMPONENTS: ComposedViewComponentDefinition[] = [{ nodeType: \"Video\", component: StubVideo }];\n\n/** The folder registry with a stub for every node type that has no component of its own. */\nexport const buildPreviewComposedViewComponents = () =>\n buildComposedViewComponentRegistry([\n ...Object.values(composedViewComponents),\n ...PREVIEW_STUB_COMPONENTS.filter(\n (stub) => !Object.prototype.hasOwnProperty.call(composedViewComponents, stub.nodeType),\n ),\n ]);\n","import {\n DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME,\n getWidgetSelfHydrationKeyFieldName,\n} from \"../../provider/environment\";\n\nconst DEFAULT_FIELD_NAME_PATTERN = new RegExp(`\\\\b${DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME}\\\\b`, \"g\");\n\n/**\n * A fixture of the package as the app reads it. The package's fixtures name the key of a block's agent space with the\n * package default field (`agentSpaceId`): as a key of an object, as a field in a block's JSON, as an attribute of a\n * block's markdown. An app that declares another field name (`AgentsEnvironment.widgetSelfHydrationKeyFieldName`)\n * reads every occurrence under its own name, so a fixture is mapped once, when it is loaded. Without a declaration\n * the fixture is returned as it is.\n */\nexport const mapFixtureToDeclaredAgentSpaceKeyFieldName = <Fixture>(fixture: Fixture): Fixture => {\n const declaredFieldName = getWidgetSelfHydrationKeyFieldName();\n if (declaredFieldName === DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME || fixture === undefined) return fixture;\n return JSON.parse(JSON.stringify(fixture).replace(DEFAULT_FIELD_NAME_PATTERN, declaredFieldName)) as Fixture;\n};\n","import { mapFixtureToDeclaredAgentSpaceKeyFieldName } from \"../renderer/_agent-space/declared-agent-space-key-field-name\";\nimport type { WidgetPreviewFixture, WidgetPreviewFixtureFile } from \"./widget-preview.types\";\n\n/**\n * Every `*.preview-fixtures.json` below the package's `widgets/` and `kit/`, by wire name — read by folder glob, so the\n * fixtures of a widget are added as one new file next to it; an app adds the fixtures of its widgets with\n * `registerWidgetPreviewFixtureFiles`. Imports nothing from the app, so the preview entry can read it before the\n * request transport is installed.\n */\nconst fixtureModules = import.meta.glob<WidgetPreviewFixtureFile>(\n [\"../widgets/**/*.preview-fixtures.json\", \"../kit/**/*.preview-fixtures.json\"],\n {\n eager: true,\n import: \"default\",\n },\n);\n\nconst sortByWireName = (fixtureFiles: WidgetPreviewFixtureFile[]): WidgetPreviewFixtureFile[] =>\n fixtureFiles.sort((first, second) => first.wireName.localeCompare(second.wireName));\n\n/** Every fixture file, sorted by wire name; filled in place by `registerWidgetPreviewFixtureFiles`. */\nexport const widgetPreviewFixtureFiles: WidgetPreviewFixtureFile[] = sortByWireName(Object.values(fixtureModules));\n\n/** Adds an app's fixture files (its glob stays in its code). Runs before the preview reads a fixture. */\nexport const registerWidgetPreviewFixtureFiles = (fixtureFiles: readonly WidgetPreviewFixtureFile[]): void => {\n widgetPreviewFixtureFiles.push(...fixtureFiles);\n sortByWireName(widgetPreviewFixtureFiles);\n};\n\n/**\n * The fixtures of a widget from EVERY file naming it — a `ComposedView` component can add its own file next to it\n * instead of editing the widget's — or an empty list. A fixture an app registers under the name of a package fixture\n * of the same widget replaces it in place (an app's copy with its own entity types and endpoints). Each is read under\n * the agent space key field the app declares (`mapFixtureToDeclaredAgentSpaceKeyFieldName`; the package's files name\n * `agentSpaceId`), at call time: an app installs its environment after this module is loaded.\n */\nexport const findWidgetPreviewFixtures = (widgetName: string): readonly WidgetPreviewFixture[] => {\n const fixturesByName = new Map<string, WidgetPreviewFixture>();\n for (const fixtureFile of widgetPreviewFixtureFiles) {\n if (fixtureFile.wireName !== widgetName) continue;\n for (const fixture of fixtureFile.fixtures) fixturesByName.set(fixture.name, fixture);\n }\n return [...fixturesByName.values()].map(mapFixtureToDeclaredAgentSpaceKeyFieldName);\n};\n\n/** One named fixture, or undefined. */\nexport const findWidgetPreviewFixture = (widgetName: string, fixtureName: string): WidgetPreviewFixture | undefined =>\n findWidgetPreviewFixtures(widgetName).find((fixture) => fixture.name === fixtureName);\n\n/** The fence the fixture stands for — what a canvas body re-reads as its anchor message. */\nexport const buildWidgetPreviewFence = (widgetName: string, fixture: WidgetPreviewFixture): string =>\n \"```widget\\n\" + JSON.stringify({ type: widgetName, ...fixture.payload }) + \"\\n```\";\n","import { Text } from \"../provider/components\";\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { conversationWidgetRegistry } from \"../renderer/conversationWidgetRegistry\";\nimport { resolveWidgetName } from \"../renderer/widget-name-resolver\";\nimport {\n buildWidgetAgentSpaceKeyProps,\n readWidgetAgentSpaceKeyAttribute,\n} from \"../renderer/_agent-space/widget-agent-space-key-attribute\";\nimport {\n CanvasOpenRequestFromOpener,\n ConversationWidgetCallbacks,\n StandaloneConversationWidgetProvider,\n} from \"../renderer/ConversationWidgetContext\";\nimport { ConversationWidgetRenderContext } from \"../renderer/ConversationWidgetRenderContext\";\nimport { ConversationWidgetErrorBoundary } from \"../renderer/ConversationWidgetErrorBoundary\";\nimport {\n WidgetRenderReporter,\n WidgetRenderReportContext,\n} from \"../renderer/render-report/widget-render-report\";\nimport type { CanvasState } from \"../renderer/canvas/canvas-state\";\nimport { canvasBodies } from \"../renderer/canvas/canvasBodies\";\nimport { canvasBehaviourOf } from \"../renderer/canvas/canvas-behaviours\";\nimport { decideCanvasOpen } from \"../renderer/canvas/decide-canvas-open\";\nimport { CANVAS_VIABLE_MIN_WIDTH } from \"../widgets/CanvasLauncherWidget/use-canvas-viable\";\nimport { WidgetImageRenderContext } from \"../image-render/WidgetImageRenderContext\";\nimport { ComposedViewComponentsContext } from \"../kit/composed-view-components\";\nimport { buildPreviewComposedViewComponents } from \"./preview-stub-components\";\nimport { buildWidgetPreviewFence } from \"./widget-preview-fixtures\";\nimport type { WidgetPreviewReadiness } from \"./widget-preview-readiness\";\nimport type { WidgetPreviewBootstrap, WidgetPreviewFixture } from \"./widget-preview.types\";\nimport styles from \"./WidgetPreview.module.scss\";\n\n/**\n * The widget preview host: ONE widget from ONE fixture, outside the chat, in the mode the script\n * asks for. Unlike the e-mail capture host it keeps a working canvas pane (an `openCanvas` request mounts the canvas\n * body beside the widget, its anchor message being the fixture's fence) and a composer log (what the widget sent,\n * prefilled or signalled), so the interactions of the ChatGPT reference can be driven and checked. The app mounts it in\n * its store (the capture's store state); every request is served from the fixture (`widget-preview-requests.ts`). The fixture's\n * `hydration` is the capture's frozen hydration only in `email` mode; `interactive` and `replay` serve it through the\n * preview's hydrators (`widget-preview-hydration.ts`), so the widget runs as in the chat (a canvas auto-opens).\n */\n\n/** The key of the agent space a fixture without its own renders for. */\nexport const PREVIEW_AGENT_SPACE_KEY = 1;\nconst PREVIEW_MESSAGE_ID = 1;\n\ninterface ComposerLogEntry {\n kind: \"message\" | \"prefill\" | \"signal\";\n text: string;\n}\n\nexport interface WidgetPreviewProps {\n bootstrap: WidgetPreviewBootstrap;\n fixture: WidgetPreviewFixture;\n readiness: WidgetPreviewReadiness;\n hasHydrationError: () => boolean;\n}\n\nexport const WidgetPreview = (props: WidgetPreviewProps) => {\n const { bootstrap, fixture, readiness, hasHydrationError } = props;\n const widgetRef = useRef<HTMLDivElement>(null);\n const widgetName = resolveWidgetName(bootstrap.widgetName);\n const entry = conversationWidgetRegistry.widgets.find((widget) => widget.name === widgetName);\n const [canvas, setCanvas] = useState<CanvasState | null>(null);\n const [composerLog, setComposerLog] = useState<ComposerLogEntry[]>([]);\n const agentSpaceKey = Number(readWidgetAgentSpaceKeyAttribute(fixture) ?? PREVIEW_AGENT_SPACE_KEY);\n const fence = useMemo(\n () => buildWidgetPreviewFence(widgetName ?? bootstrap.widgetName, fixture),\n [widgetName, bootstrap.widgetName, fixture],\n );\n const isEmail = bootstrap.mode === \"email\";\n const isInteractive = bootstrap.mode === \"interactive\";\n // The capture context switches every widget to its static e-mail branch (no canvas, no auto-open): e-mail mode only.\n const frozenHydration =\n isEmail && fixture.hydration && Object.keys(fixture.hydration).length > 0 ? fixture.hydration : null;\n\n useEffect(() => {\n if (!entry) readiness.fail(\"UNKNOWN_WIDGET\");\n // The whole page document: the canvas pane and a modal (the lightbox renders into the modal root) settle too.\n else if (widgetRef.current) return readiness.observe(document.body, widgetRef.current, hasHydrationError);\n }, [entry, readiness, hasHydrationError]);\n // The block's render report reaches the readiness as in the chat it reaches the collector.\n const renderReporter = useMemo<WidgetRenderReporter>(() => ({ report: readiness.recordRenderReport }), [readiness]);\n\n const appendComposerLog = useCallback(\n (kind: ComposerLogEntry[\"kind\"], text: string) => setComposerLog((entries) => [...entries, { kind, text }]),\n [],\n );\n // The chat's opening rule decides, as in the conversation slice: a live delivery on a narrow window does not take\n // over for a canvas without an overlay, so the narrow shot shows the inline rows and the \"Open in canvas\" card.\n const openCanvas = useCallback((request: CanvasOpenRequestFromOpener) => {\n setCanvas((current) => {\n const decision = decideCanvasOpen(canvasBehaviourOf(request.canvasId), current, null, {\n ...request,\n viewportViable: window.innerWidth >= CANVAS_VIABLE_MIN_WIDTH,\n hostHasCanvasSurface: true,\n });\n if (decision.kind === \"ignore\") return current;\n return {\n canvasId: request.canvasId,\n instanceId: request.instanceId,\n anchor: request.anchor,\n origin: request.origin,\n mountGeneration: (current?.mountGeneration ?? 0) + 1,\n };\n });\n }, []);\n const callbacks = useMemo<Partial<ConversationWidgetCallbacks>>(\n () => ({\n canvas,\n hostHasCanvasSurface: !isEmail,\n openCanvas: isEmail ? () => {} : openCanvas,\n closeCanvas: () => setCanvas(null),\n chatAgentSpaceKey: agentSpaceKey,\n messages: [],\n sendMessageToChat: (text: string) => appendComposerLog(\"message\", text),\n prefillComposer: (text: string) => appendComposerLog(\"prefill\", text),\n injectSignal: (text: string) => {\n appendComposerLog(\"signal\", text);\n return Promise.resolve(true);\n },\n }),\n [canvas, isEmail, openCanvas, agentSpaceKey, appendComposerLog],\n );\n\n if (!entry) return null;\n const WidgetComponent = entry.component;\n const CanvasBody = canvas ? canvasBodies[canvas.canvasId] : null;\n const widget = (\n <ConversationWidgetErrorBoundary widgetName={entry.name} onCrash={readiness.recordWidgetCrash}>\n <WidgetRenderReportContext.Provider value={renderReporter}>\n <WidgetComponent\n payload={JSON.stringify(fixture.payload)}\n {...buildWidgetAgentSpaceKeyProps(String(agentSpaceKey))}\n interactive={isInteractive}\n fresh={isInteractive}\n justDelivered={isInteractive}\n messageId={String(PREVIEW_MESSAGE_ID)}\n openedByPage={false}\n />\n </WidgetRenderReportContext.Provider>\n </ConversationWidgetErrorBoundary>\n );\n return (\n <StandaloneConversationWidgetProvider callbacks={callbacks}>\n <ConversationWidgetRenderContext.Provider value={isEmail ? \"email\" : \"conversation\"}>\n <WidgetImageRenderContext.Provider value={frozenHydration}>\n <div className={styles.page} data-testid=\"widget-preview-page\">\n <div className={styles.chatColumn} data-testid=\"widget-preview-frame\">\n <div\n ref={widgetRef}\n className={styles.widget}\n data-testid=\"widget-preview-widget\"\n inert={isEmail || undefined}\n >\n {fixture.stubComposedViewComponents ? (\n <ComposedViewComponentsContext.Provider value={buildPreviewComposedViewComponents()}>\n {widget}\n </ComposedViewComponentsContext.Provider>\n ) : (\n widget\n )}\n </div>\n {composerLog.length > 0 ? (\n <div className={styles.composerLog} data-testid=\"widget-preview-composer-log\">\n {composerLog.map((composerEntry, entryIndex) => (\n <Text\n key={entryIndex}\n role=\"caption\"\n translate={false}\n className={styles.composerEntry}\n >\n {`${composerEntry.kind}: ${composerEntry.text}`}\n </Text>\n ))}\n </div>\n ) : null}\n </div>\n {canvas && CanvasBody ? (\n <div className={styles.canvasPane} data-testid=\"widget-preview-canvas\" data-canvas-id={canvas.canvasId}>\n <CanvasBody\n key={`${canvas.instanceId}#${canvas.mountGeneration}`}\n canvas={canvas}\n agentSpaceKey={agentSpaceKey}\n anchorMessageMarkdown={fence}\n />\n </div>\n ) : null}\n </div>\n </WidgetImageRenderContext.Provider>\n </ConversationWidgetRenderContext.Provider>\n </StandaloneConversationWidgetProvider>\n );\n};\n","import { getSandboxLegacyAliases } from \"../provider/environment\";\nimport type { WidgetPreviewSignal } from \"./widget-preview.types\";\n\n/** The `window` property a preview script waits on. */\nexport const WIDGET_PREVIEW_SIGNAL_GLOBAL_NAME = \"__AGENTS_WIDGET_PREVIEW_V1__\";\n\ntype WindowSignals = Record<string, WidgetPreviewSignal | undefined>;\n\n/**\n * Every name the preview signal is published under: the package's own, then each name the app declares\n * (`AgentsEnvironment.sandboxLegacyAliases.previewReadinessGlobalNames`), read at each publish.\n */\nexport const readWidgetPreviewSignalGlobalNames = (): string[] => [\n WIDGET_PREVIEW_SIGNAL_GLOBAL_NAME,\n ...(getSandboxLegacyAliases().previewReadinessGlobalNames ?? []).filter(\n (aliasName) => aliasName !== WIDGET_PREVIEW_SIGNAL_GLOBAL_NAME,\n ),\n];\n\n/** Publishes (or with `undefined` clears) the preview signal under every name. */\nexport const publishWidgetPreviewSignal = (signal: WidgetPreviewSignal | undefined): void => {\n const windowSignals = window as unknown as WindowSignals;\n for (const globalName of readWidgetPreviewSignalGlobalNames()) windowSignals[globalName] = signal;\n};\n","import { publishWidgetImageReadiness } from \"../image-render/widget-image-readiness-signal\";\nimport type { WidgetRenderReportEntry } from \"../renderer/render-report/widget-render-report\";\nimport { publishWidgetPreviewSignal } from \"./widget-preview-signal\";\nimport type { WidgetPreviewExpectedState, WidgetPreviewSignal } from \"./widget-preview.types\";\n\n/** A loading placeholder: the component library's `Skeleton` (its test id; its class is a hashed module name) and the kit's own. */\nconst SKELETON_SELECTOR = '[data-testid=\"Skeleton\"], [class*=\"Skeleton\"], [class*=\"skeleton\"]';\nconst LOADING_SELECTOR = `[aria-busy=\"true\"], [role=\"progressbar\"]:not([aria-valuenow]), ${SKELETON_SELECTOR}`;\n/** The DOM must stay unchanged this long before the preview counts as settled. */\nconst SETTLE_MS = 400;\n\n/**\n * Whether a loading marker is actually rendered: the component library's `ImgWithLoader` keeps its Skeleton in the DOM inside a\n * `display: none` wrapper once the image has loaded, so a marker under a hidden ancestor is no loading state. Without\n * a layout engine (jsdom: no client rects for any element) every marker counts as before.\n */\nconst hasRenderedLoadingMarker = (element: HTMLElement): boolean => {\n const markers = Array.from(element.querySelectorAll(LOADING_SELECTOR));\n if (markers.length === 0) return false;\n const hasLayout = element.getClientRects().length > 0;\n return !hasLayout || markers.some((marker) => marker.getClientRects().length > 0);\n};\n\n/**\n * The state an element shows — the same loading markers the e-mail capture refuses to shoot. `hasError` is true when\n * the widget is known to be in an error: a failed hydration, a crash caught by the error boundary, or a request the\n * fixture failed on purpose — a widget that renders nothing on an error would otherwise read as `empty`.\n * `renderReport` is the block's own render report when the widget sent one: `failed` reads as `error`,\n * `pending` as `loading` and `empty` as `empty` — a widget that shows one muted line (\"No data to show.\") for its empty\n * state is empty, whatever text the line holds.\n */\nexport const observeWidgetPreviewState = (\n element: HTMLElement,\n hasError: boolean,\n renderReport?: WidgetRenderReportEntry,\n): WidgetPreviewExpectedState => {\n if (hasError || renderReport?.status === \"failed\") return \"error\";\n if (renderReport?.status === \"pending\") return \"loading\";\n if (hasRenderedLoadingMarker(element)) return \"loading\";\n if (renderReport?.status === \"empty\") return \"empty\";\n if (!element.textContent?.trim() && !element.querySelector(\"img,svg,canvas,iframe\")) return \"empty\";\n return \"data\";\n};\n\n/**\n * A mutation the settle ignores: a style or attribute change inside a loading placeholder — the component library's `Skeleton`\n * animates its shimmer by rewriting its style every frame, so a loading fixture would never be still otherwise.\n */\nconst isSkeletonAnimation = (mutation: MutationRecord): boolean => {\n if (mutation.type !== \"attributes\") return false;\n const target = mutation.target;\n return target instanceof Element && target.closest(SKELETON_SELECTOR) !== null;\n};\n\n/**\n * The preview's ready signal: after every change it waits until the DOM is still for `SETTLE_MS`, then publishes what\n * it shows — `window.__AGENTS_WIDGET_PREVIEW_V1__` (observed against the fixture's expected state, with every request\n * the fixture had no response for) and the e-mail capture's `window.__AGENTS_WIDGET_IMAGE_V1__` (`ready` when the\n * expected state was reached), so the same script conventions work for both. Both are also published under the names\n * the app declares (`AgentsEnvironment.sandboxLegacyAliases`).\n */\nexport const createWidgetPreviewReadiness = (expectedState: WidgetPreviewExpectedState) => {\n const missingResponses: string[] = [];\n const failedRequests: string[] = [];\n let widgetCrashed = false;\n let renderReport: WidgetRenderReportEntry | undefined;\n let scheduleSettleAgain: () => void = () => {};\n let revision = 0;\n const publish = (\n signal: Omit<\n WidgetPreviewSignal,\n \"version\" | \"missingResponses\" | \"failedRequests\" | \"widgetCrashed\" | \"expectedState\"\n >,\n ) => {\n publishWidgetPreviewSignal({\n version: 1,\n expectedState,\n missingResponses: [...missingResponses],\n failedRequests: [...failedRequests],\n widgetCrashed,\n ...(renderReport ? { renderReport } : {}),\n ...signal,\n });\n document.documentElement.dataset.widgetPreviewState = signal.state;\n };\n publish({ state: \"loading\", revision });\n\n const fail = (errorCode: string) => {\n publish({ state: \"failed\", revision, error_code: errorCode });\n publishWidgetImageReadiness({ version: 1, state: \"failed\", error_code: errorCode });\n };\n\n const recordMissingResponse = (requestKey: string) => {\n if (!missingResponses.includes(requestKey)) missingResponses.push(requestKey);\n };\n\n /** A request (or a preview hydration) the fixture answered with a failing `__status`. */\n const recordFailedRequest = (requestKey: string) => {\n if (!failedRequests.includes(requestKey)) failedRequests.push(requestKey);\n };\n\n /** The error boundary caught the widget (`ConversationWidgetErrorBoundary` `onCrash`). */\n const recordWidgetCrash = () => {\n widgetCrashed = true;\n };\n\n /** The block's render report (`WidgetRenderReportContext` of the host); a new status settles again. */\n const recordRenderReport = (entry: WidgetRenderReportEntry) => {\n renderReport = entry;\n scheduleSettleAgain();\n };\n\n const settle = (element: HTMLElement, hasHydrationError: () => boolean) => {\n const hasError = hasHydrationError() || widgetCrashed || failedRequests.length > 0;\n const observedState = observeWidgetPreviewState(element, hasError, renderReport);\n const { x, y, width, height } = element.getBoundingClientRect();\n const rect = { x, y, width, height };\n revision += 1;\n const expectedStateReached = observedState === expectedState;\n publish({ state: \"settled\", revision, observedState, expectedStateReached, rect });\n publishWidgetImageReadiness(\n expectedStateReached\n ? { version: 1, state: \"ready\", rect }\n : {\n version: 1,\n state: \"failed\",\n error_code: `EXPECTED_${expectedState.toUpperCase()}_SAW_${observedState.toUpperCase()}`,\n rect,\n },\n );\n };\n\n /**\n * Watches `watchedElement` (the whole preview document, so an interaction that changes only the canvas pane or opens\n * a modal settles too)\n * and classifies `widgetElement` (the widget alone, the screenshot); returns the disposer.\n */\n const observe = (watchedElement: HTMLElement, widgetElement: HTMLElement, hasHydrationError: () => boolean) => {\n let settleTimer: ReturnType<typeof setTimeout> | null = null;\n const scheduleSettle = () => {\n if (settleTimer !== null) clearTimeout(settleTimer);\n settleTimer = setTimeout(() => settle(widgetElement, hasHydrationError), SETTLE_MS);\n };\n const mutationObserver = new MutationObserver((mutations) => {\n if (mutations.some((mutation) => !isSkeletonAnimation(mutation))) scheduleSettle();\n });\n mutationObserver.observe(watchedElement, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n scheduleSettleAgain = scheduleSettle;\n scheduleSettle();\n return () => {\n mutationObserver.disconnect();\n scheduleSettleAgain = () => {};\n if (settleTimer !== null) clearTimeout(settleTimer);\n };\n };\n\n return { observe, fail, recordMissingResponse, recordFailedRequest, recordWidgetCrash, recordRenderReport };\n};\n\nexport type WidgetPreviewReadiness = ReturnType<typeof createWidgetPreviewReadiness>;\n","import axios, { AxiosRequestConfig } from \"axios\";\nimport type { WidgetPreviewResponse } from \"./widget-preview.types\";\n\n/** The key a fixture response is stored under: method, path and the sorted query (`GET /api/example/…?a=1&b=2`). */\nexport const widgetPreviewRequestKey = (method: string, url: URL): string => {\n const sortedUrl = new URL(url.toString());\n sortedUrl.searchParams.sort();\n return `${method.toUpperCase()} ${sortedUrl.pathname}${sortedUrl.search}`;\n};\n\n/** The app's own error log: answered empty and never reported — a fixture's error state must not count as a gap. */\nconst SILENTLY_ANSWERED_PATHS = [\"/rest_api/v1/log\"];\nconst isSilentlyAnswered = (url: URL): boolean => SILENTLY_ANSWERED_PATHS.includes(url.pathname);\n\nexport const isStatusResponse = (response: unknown): response is { __status: number; __body?: unknown } =>\n typeof response === \"object\" &&\n response !== null &&\n typeof (response as { __status?: unknown }).__status === \"number\";\nexport const isPendingResponse = (response: unknown): boolean =>\n typeof response === \"object\" && response !== null && (response as { __pending?: unknown }).__pending === true;\n\n/**\n * Serves every request of the preview — axios and `fetch` — from the fixture: a known request gets its body (a copy), a\n * `__status` entry fails with that status (a status of 400 or more is reported as a failed request — the error state the\n * fixture asked for), a `__pending` entry never answers (the loading state), and anything else — an unknown read, a\n * write the fixture does not answer — fails as a missing response and is reported. A write is answered only when the\n * fixture names it (`\"POST /api/example/…\"`, e.g. a widget's fire-and-forget measurement event). Nothing reaches a server.\n */\nexport const installWidgetPreviewRequests = (\n responses: Record<string, WidgetPreviewResponse>,\n onMissingResponse: (requestKey: string) => void,\n onFailedRequest: (requestKey: string) => void = () => {},\n): (() => void) => {\n const originalAdapter = axios.defaults.adapter;\n axios.defaults.adapter = async (config: AxiosRequestConfig) => {\n const method = (config.method ?? \"get\").toLowerCase();\n const requestUrl = new URL(axios.getUri(config), window.location.origin);\n if (isSilentlyAnswered(requestUrl)) return { data: {}, status: 200, statusText: \"OK\", config, headers: {} };\n const requestKey = widgetPreviewRequestKey(method, requestUrl);\n const response = Object.prototype.hasOwnProperty.call(responses, requestKey) ? responses[requestKey] : undefined;\n if (response === undefined) {\n onMissingResponse(requestKey);\n return Promise.reject(Object.assign(new Error(`no preview response for ${requestKey}`), { config }));\n }\n if (isPendingResponse(response)) return new Promise(() => {});\n if (isStatusResponse(response)) {\n if (response.__status >= 400) onFailedRequest(requestKey);\n return Promise.reject(\n Object.assign(new Error(`preview response ${response.__status}`), {\n config,\n response: { status: response.__status, data: response.__body ?? null, config, headers: {} },\n }),\n );\n }\n return { data: structuredClone(response), status: 200, statusText: \"OK\", config, headers: {} };\n };\n // `fetch` is answered the same way (a few modules bypass axios); a missing response is a 404, reported.\n const originalFetch = window.fetch;\n window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {\n const method = (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toLowerCase();\n const url = new URL(input instanceof Request ? input.url : String(input), window.location.origin);\n if (isSilentlyAnswered(url)) return new Response(\"{}\", { status: 200 });\n const requestKey = widgetPreviewRequestKey(method, url);\n const response = Object.prototype.hasOwnProperty.call(responses, requestKey) ? responses[requestKey] : undefined;\n if (response === undefined) {\n onMissingResponse(requestKey);\n return new Response(null, { status: 404 });\n }\n if (isPendingResponse(response)) return new Promise<Response>(() => {});\n if (isStatusResponse(response)) {\n if (response.__status >= 400) onFailedRequest(requestKey);\n return new Response(JSON.stringify(response.__body ?? null), { status: response.__status });\n }\n return new Response(JSON.stringify(response), { status: 200, headers: { \"Content-Type\": \"application/json\" } });\n };\n return () => {\n axios.defaults.adapter = originalAdapter;\n window.fetch = originalFetch;\n };\n};\n","import {\n getWidgetHydrator,\n listWidgetHydratorTypes,\n registerWidgetHydrator,\n unregisterWidgetHydrator,\n} from \"../renderer/widget-hydration/widget-hydration.registry\";\nimport type { RegisteredWidget } from \"../renderer/widget-hydration/widget-hydration.types\";\nimport { isPendingResponse, isStatusResponse } from \"./widget-preview-requests\";\nimport type { WidgetPreviewResponse } from \"./widget-preview.types\";\n\n/** The fixture's entry for one hydration: the exact derived key first, then the hydrator type (as the capture reads). */\nconst findFixtureHydration = (\n hydration: Record<string, WidgetPreviewResponse>,\n type: string,\n key: string,\n): { found: boolean; value?: WidgetPreviewResponse; hydrationKey: string } => {\n if (Object.prototype.hasOwnProperty.call(hydration, key))\n return { found: true, value: hydration[key], hydrationKey: key };\n if (Object.prototype.hasOwnProperty.call(hydration, type))\n return { found: true, value: hydration[type], hydrationKey: type };\n return { found: false, hydrationKey: key };\n};\n\n/** One fixture value as a hydrator result: a copy of the body, a failing `__status`, or a `__pending` that never ends. */\nconst answerFromFixture = (\n value: WidgetPreviewResponse,\n hydrationKey: string,\n onFailedRequest: (requestKey: string) => void,\n): Promise<unknown> => {\n if (isPendingResponse(value)) return new Promise(() => {});\n if (isStatusResponse(value)) {\n onFailedRequest(`HYDRATION ${hydrationKey}`);\n return Promise.reject(new Error(`preview hydration ${value.__status}`));\n }\n return Promise.resolve(structuredClone(value));\n};\n\n/**\n * The preview's hydration transport for the `interactive` and `replay` modes: every registered hydrator is replaced by\n * one that answers from the fixture's `hydration` (by derived key, else by type) and otherwise runs the real hydrator,\n * whose requests the request transport answers from `responses`. The widget therefore runs its live code path —\n * `useWidgetHydration` with the store's hydration slice, no frozen capture context — so a self-hydrating canvas widget\n * auto-opens its canvas like in the chat (`CanvasLauncherWidget`). The `email` mode keeps the capture's frozen hydration.\n * Returns the disposer that puts the real hydrators back.\n */\nexport const installWidgetPreviewHydration = (\n hydration: Record<string, WidgetPreviewResponse>,\n onFailedRequest: (requestKey: string) => void,\n): (() => void) => {\n const replacedHydrators = new Map<string, RegisteredWidget<unknown, unknown>>();\n for (const type of listWidgetHydratorTypes()) {\n const registered = getWidgetHydrator<unknown, unknown>(type);\n if (!registered) continue;\n replacedHydrators.set(type, registered);\n unregisterWidgetHydrator(type);\n registerWidgetHydrator<unknown, unknown>(type, {\n ...registered,\n hydrator: (payload, context) => {\n const fixtureHydration = findFixtureHydration(hydration, type, registered.deriveKey(type, payload));\n return fixtureHydration.found\n ? answerFromFixture(fixtureHydration.value, fixtureHydration.hydrationKey, onFailedRequest)\n : registered.hydrator(payload, context);\n },\n });\n }\n return () => {\n for (const [type, registered] of replacedHydrators) {\n unregisterWidgetHydrator(type);\n registerWidgetHydrator(type, registered);\n }\n };\n};\n","import { Text } from \"../../../provider/components\";\nimport { ConversationWidgetProvider } from \"../../../renderer/ConversationWidgetContext\";\nimport { ConversationMessageInputComposerWidgets } from \"../../../chat/ConversationMessageInput/ConversationMessageInputComposerWidgets/ConversationMessageInputComposerWidgets\";\nimport { EntityMentionAskButton } from \"../EntityMentionAskButton/EntityMentionAskButton\";\nimport styles from \"./EntityMentionAskFlowStory.module.scss\";\n\nconst ENTITIES = [\n { entityType: \"competitor\", entityId: \"8812\", label: \"Altes Gasthaus Leve\", agentSpaceKey: 1 },\n { entityType: \"competitor\", entityId: \"9001\", label: \"Kleiner Kiepenkerl\", agentSpaceKey: 1 },\n];\n\n/**\n * The \"Ask about this\" flow for the story and the browser check: a stand-in for the detail panel's\n * footer (the `entityDetail` shell is the canvas shell's, the bodies come from the entity types) with the real button, and the real\n * composer strip of the chat input, so a click shows the chip where the owner types.\n */\nexport const EntityMentionAskFlowStory = (props: { maxWidth?: number }) => (\n <ConversationWidgetProvider callbacks={{}}>\n <div className={styles.page} style={{ maxWidth: props.maxWidth ?? 720 }}>\n {ENTITIES.map((entity) => (\n <div key={entity.entityId} className={styles.panel}>\n <Text role=\"intro\" weight=\"bold\" translate={false}>\n {entity.label}\n </Text>\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false}>\n {\"detail panel body\"}\n </Text>\n <div className={styles.footer}>\n <EntityMentionAskButton {...entity} testId={`entity-mention-ask-${entity.entityId}`} />\n </div>\n </div>\n ))}\n <div className={styles.composer} data-testid=\"story-composer\">\n <ConversationMessageInputComposerWidgets testId=\"story-input\" />\n <Text role=\"help\" color=\"var(--agents-fg-lightest)\" translate={false}>\n {\"Ask anything…\"}\n </Text>\n </div>\n </div>\n </ConversationWidgetProvider>\n);\n"],"names":["styles","widget","composerLog","composerEntry"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,MAAM,iBAAiB,CAAC,oBAA4C;AAClE,MAAI,OAAO,oBAAoB,YAAY,CAAC,OAAO,SAAS,eAAe,KAAK,kBAAkB,EAAG,QAAO;AAC5G,QAAM,UAAU,KAAK,MAAM,kBAAkB,EAAE;AAC/C,QAAM,UAAU,KAAK,MAAM,kBAAkB,EAAE;AAC/C,SAAO,GAAG,OAAO,IAAI,OAAO,OAAO,EAAE,SAAS,GAAG,GAAG,CAAC;AACvD;AAEA,MAAM,YAAY,CAAC,EAAE,YAAwC;AAC3D,QAAM,WAAW,eAAe,MAAM,eAAe;AACrD,SACE,oBAAC,eAAA,EAAc,OAAM,QAAO,SAAO,MACjC,UAAA,qBAAC,OAAA,EAAI,WAAWA,SAAO,WACpB,UAAA;AAAA,IAAA,OAAO,MAAM,cAAc,WAC1B,oBAAC,OAAA,EAAI,WAAWA,SAAO,oBAAoB,KAAK,MAAM,WAAW,KAAI,IAAG,IACtE;AAAA,IACJ,qBAAC,OAAA,EAAI,WAAWA,SAAO,eACrB,UAAA;AAAA,MAAA,oBAAC,MAAA,EAAK,MAAK,QAAO,QAAO,QAAO,WAAW,OACxC,UAAA,OAAO,MAAM,UAAU,WAAW,MAAM,QAAQ,IACnD;AAAA,MACA,oBAAC,QAAK,MAAK,WAAU,OAAM,0BAAyB,WAAW,OAC5D,UAAA,CAAC,OAAO,MAAM,YAAY,WAAW,MAAM,UAAU,MAAM,QAAQ,EAAE,OAAO,OAAO,EAAE,KAAK,KAAK,EAAA,CAClG;AAA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,eAAe,EAAA;AAAA,EAC3F,EAAE,YAAY,cAAc,UAAU,QAAQ,OAAO,sBAAsB,eAAe,EAAA;AAC5F;AAOO,MAAM,4BAA4B,CAAC,8BACvC,4BAAA,EAA2B,WAAW,CAAA,GACrC,UAAA,qBAAC,SAAI,WAAW,OAAO,MAAM,OAAO,EAAE,UAAU,MAAM,YAAY,OAC/D,UAAA;AAAA,EAAA,SAAS,IAAI,CAAC,gCACZ,OAAA,EAA0B,WAAW,OAAO,OAC3C,UAAA;AAAA,IAAA,oBAAC,MAAA,EAAK,MAAK,SAAQ,QAAO,QAAO,WAAW,OACzC,iBAAO,MAAA,CACV;AAAA,IACA,oBAAC,QAAK,MAAK,QAAO,OAAM,0BAAyB,WAAW,OACzD,UAAA,oBAAA,CACH;AAAA,IACA,oBAAC,OAAA,EAAI,WAAW,OAAO,QACrB,UAAA,oBAAC,wBAAA,EAAwB,GAAG,QAAQ,QAAQ,sBAAsB,OAAO,QAAQ,IAAI,EAAA,CACvF;AAAA,EAAA,KATQ,OAAO,QAUjB,CACD;AAAA,uBACA,OAAA,EAAI,WAAW,OAAO,UAAU,eAAY,kBAC3C,UAAA;AAAA,IAAA,oBAAC,yCAAA,EAAwC,QAAO,cAAA,CAAc;AAAA,IAC9D,oBAAC,QAAK,MAAK,QAAO,OAAM,6BAA4B,WAAW,OAC5D,UAAA,gBAAA,CACH;AAAA,EAAA,EAAA,CACF;AAAA,EAAA,CACF,EAAA,CACF;"}
|
|
1
|
+
{"version":3,"file":"preview.js","sources":["../src/preview/preview-stub-components.tsx","../src/renderer/_agent-space/declared-agent-space-key-field-name.ts","../src/preview/widget-preview-fixtures.ts","../src/preview/WidgetPreviewHost.tsx","../src/preview/widget-preview-signal.ts","../src/preview/widget-preview-readiness.ts","../src/preview/widget-preview-requests.ts","../src/preview/widget-preview-hydration.ts","../src/widgets/EntityMentionConversationWidget/stories/EntityMentionAskFlowStory.tsx"],"sourcesContent":["import { Text } from \"../provider/components\";\nimport type {\n ComposedViewComponentDefinition,\n ComposedViewComponentProps,\n} from \"../kit/composed-view-component-types\";\nimport {\n buildComposedViewComponentRegistry,\n composedViewComponents,\n} from \"../kit/composed-view-components\";\nimport { WidgetSurface } from \"../widgets/_shared/modern\";\nimport styles from \"./WidgetPreview.module.scss\";\n\n/**\n * Stand-ins for kit node types that have a schema but no component yet — only the preview uses\n * them, and only for a fixture that asks (`stubComposedViewComponents`). A real component always wins.\n */\nconst formatDuration = (durationSeconds: unknown): string | null => {\n if (typeof durationSeconds !== \"number\" || !Number.isFinite(durationSeconds) || durationSeconds < 0) return null;\n const minutes = Math.floor(durationSeconds / 60);\n const seconds = Math.floor(durationSeconds % 60);\n return `${minutes}:${String(seconds).padStart(2, \"0\")}`;\n};\n\nconst StubVideo = ({ props }: ComposedViewComponentProps) => {\n const duration = formatDuration(props.durationSeconds);\n return (\n <WidgetSurface level=\"flat\" compact>\n <div className={styles.stubVideo}>\n {typeof props.thumbnail === \"string\" ? (\n <img className={styles.stubVideoThumbnail} src={props.thumbnail} alt=\"\" />\n ) : null}\n <div className={styles.stubVideoText}>\n <Text role=\"body\" weight=\"bold\" translate={false}>\n {typeof props.title === \"string\" ? props.title : \"\"}\n </Text>\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" translate={false}>\n {[typeof props.channel === \"string\" ? props.channel : null, duration].filter(Boolean).join(\" · \")}\n </Text>\n </div>\n </div>\n </WidgetSurface>\n );\n};\n\nconst PREVIEW_STUB_COMPONENTS: ComposedViewComponentDefinition[] = [{ nodeType: \"Video\", component: StubVideo }];\n\n/** The folder registry with a stub for every node type that has no component of its own. */\nexport const buildPreviewComposedViewComponents = () =>\n buildComposedViewComponentRegistry([\n ...Object.values(composedViewComponents),\n ...PREVIEW_STUB_COMPONENTS.filter(\n (stub) => !Object.prototype.hasOwnProperty.call(composedViewComponents, stub.nodeType),\n ),\n ]);\n","import {\n DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME,\n getWidgetSelfHydrationKeyFieldName,\n} from \"../../provider/environment\";\n\nconst DEFAULT_FIELD_NAME_PATTERN = new RegExp(`\\\\b${DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME}\\\\b`, \"g\");\n\n/**\n * A fixture of the package as the app reads it. The package's fixtures name the key of a block's agent space with the\n * package default field (`agentSpaceId`): as a key of an object, as a field in a block's JSON, as an attribute of a\n * block's markdown. An app that declares another field name (`AgentsEnvironment.widgetSelfHydrationKeyFieldName`)\n * reads every occurrence under its own name, so a fixture is mapped once, when it is loaded. Without a declaration\n * the fixture is returned as it is.\n */\nexport const mapFixtureToDeclaredAgentSpaceKeyFieldName = <Fixture>(fixture: Fixture): Fixture => {\n const declaredFieldName = getWidgetSelfHydrationKeyFieldName();\n if (declaredFieldName === DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME || fixture === undefined) return fixture;\n return JSON.parse(JSON.stringify(fixture).replace(DEFAULT_FIELD_NAME_PATTERN, declaredFieldName)) as Fixture;\n};\n","import { mapFixtureToDeclaredAgentSpaceKeyFieldName } from \"../renderer/_agent-space/declared-agent-space-key-field-name\";\nimport type { WidgetPreviewFixture, WidgetPreviewFixtureFile } from \"./widget-preview.types\";\n\n/**\n * Every `*.preview-fixtures.json` below the package's `widgets/` and `kit/`, by wire name — read by folder glob, so the\n * fixtures of a widget are added as one new file next to it; an app adds the fixtures of its widgets with\n * `registerWidgetPreviewFixtureFiles`. Imports nothing from the app, so the preview entry can read it before the\n * request transport is installed.\n */\nconst fixtureModules = import.meta.glob<WidgetPreviewFixtureFile>(\n [\"../widgets/**/*.preview-fixtures.json\", \"../kit/**/*.preview-fixtures.json\"],\n {\n eager: true,\n import: \"default\",\n },\n);\n\nconst sortByWireName = (fixtureFiles: WidgetPreviewFixtureFile[]): WidgetPreviewFixtureFile[] =>\n fixtureFiles.sort((first, second) => first.wireName.localeCompare(second.wireName));\n\n/** Every fixture file, sorted by wire name; filled in place by `registerWidgetPreviewFixtureFiles`. */\nexport const widgetPreviewFixtureFiles: WidgetPreviewFixtureFile[] = sortByWireName(Object.values(fixtureModules));\n\n/** Adds an app's fixture files (its glob stays in its code). Runs before the preview reads a fixture. */\nexport const registerWidgetPreviewFixtureFiles = (fixtureFiles: readonly WidgetPreviewFixtureFile[]): void => {\n widgetPreviewFixtureFiles.push(...fixtureFiles);\n sortByWireName(widgetPreviewFixtureFiles);\n};\n\n/**\n * The fixtures of a widget from EVERY file naming it — a `ComposedView` component can add its own file next to it\n * instead of editing the widget's — or an empty list. A fixture an app registers under the name of a package fixture\n * of the same widget replaces it in place (an app's copy with its own entity types and endpoints). Each is read under\n * the agent space key field the app declares (`mapFixtureToDeclaredAgentSpaceKeyFieldName`; the package's files name\n * `agentSpaceId`), at call time: an app installs its environment after this module is loaded.\n */\nexport const findWidgetPreviewFixtures = (widgetName: string): readonly WidgetPreviewFixture[] => {\n const fixturesByName = new Map<string, WidgetPreviewFixture>();\n for (const fixtureFile of widgetPreviewFixtureFiles) {\n if (fixtureFile.wireName !== widgetName) continue;\n for (const fixture of fixtureFile.fixtures) fixturesByName.set(fixture.name, fixture);\n }\n return [...fixturesByName.values()].map(mapFixtureToDeclaredAgentSpaceKeyFieldName);\n};\n\n/** One named fixture, or undefined. */\nexport const findWidgetPreviewFixture = (widgetName: string, fixtureName: string): WidgetPreviewFixture | undefined =>\n findWidgetPreviewFixtures(widgetName).find((fixture) => fixture.name === fixtureName);\n\n/** The fence the fixture stands for — what a canvas body re-reads as its anchor message. */\nexport const buildWidgetPreviewFence = (widgetName: string, fixture: WidgetPreviewFixture): string =>\n \"```widget\\n\" + JSON.stringify({ type: widgetName, ...fixture.payload }) + \"\\n```\";\n","import { Text } from \"../provider/components\";\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { conversationWidgetRegistry } from \"../renderer/conversationWidgetRegistry\";\nimport { resolveWidgetName } from \"../renderer/widget-name-resolver\";\nimport {\n buildWidgetAgentSpaceKeyProps,\n readWidgetAgentSpaceKeyAttribute,\n} from \"../renderer/_agent-space/widget-agent-space-key-attribute\";\nimport {\n CanvasOpenRequestFromOpener,\n ConversationWidgetCallbacks,\n StandaloneConversationWidgetProvider,\n} from \"../renderer/ConversationWidgetContext\";\nimport { ConversationWidgetRenderContext } from \"../renderer/ConversationWidgetRenderContext\";\nimport { ConversationWidgetErrorBoundary } from \"../renderer/ConversationWidgetErrorBoundary\";\nimport {\n WidgetRenderReporter,\n WidgetRenderReportContext,\n} from \"../renderer/render-report/widget-render-report\";\nimport type { CanvasState } from \"../renderer/canvas/canvas-state\";\nimport { canvasBodies } from \"../renderer/canvas/canvasBodies\";\nimport { canvasBehaviourOf } from \"../renderer/canvas/canvas-behaviours\";\nimport { decideCanvasOpen } from \"../renderer/canvas/decide-canvas-open\";\nimport { CANVAS_VIABLE_MIN_WIDTH } from \"../widgets/CanvasLauncherWidget/use-canvas-viable\";\nimport { WidgetImageRenderContext } from \"../image-render/WidgetImageRenderContext\";\nimport { ComposedViewComponentsContext } from \"../kit/composed-view-components\";\nimport { buildPreviewComposedViewComponents } from \"./preview-stub-components\";\nimport { buildWidgetPreviewFence } from \"./widget-preview-fixtures\";\nimport type { WidgetPreviewReadiness } from \"./widget-preview-readiness\";\nimport type { WidgetPreviewBootstrap, WidgetPreviewFixture } from \"./widget-preview.types\";\nimport styles from \"./WidgetPreview.module.scss\";\n\n/**\n * The widget preview host: ONE widget from ONE fixture, outside the chat, in the mode the script\n * asks for. Unlike the e-mail capture host it keeps a working canvas pane (an `openCanvas` request mounts the canvas\n * body beside the widget, its anchor message being the fixture's fence) and a composer log (what the widget sent,\n * prefilled or signalled), so the interactions of the ChatGPT reference can be driven and checked. The app mounts it in\n * its store (the capture's store state); every request is served from the fixture (`widget-preview-requests.ts`). The fixture's\n * `hydration` is the capture's frozen hydration only in `email` mode; `interactive` and `replay` serve it through the\n * preview's hydrators (`widget-preview-hydration.ts`), so the widget runs as in the chat (a canvas auto-opens).\n */\n\n/** The key of the agent space a fixture without its own renders for. */\nexport const PREVIEW_AGENT_SPACE_KEY = 1;\nconst PREVIEW_MESSAGE_ID = 1;\n\ninterface ComposerLogEntry {\n kind: \"message\" | \"prefill\" | \"signal\";\n text: string;\n}\n\nexport interface WidgetPreviewProps {\n bootstrap: WidgetPreviewBootstrap;\n fixture: WidgetPreviewFixture;\n readiness: WidgetPreviewReadiness;\n hasHydrationError: () => boolean;\n}\n\nexport const WidgetPreview = (props: WidgetPreviewProps) => {\n const { bootstrap, fixture, readiness, hasHydrationError } = props;\n const widgetRef = useRef<HTMLDivElement>(null);\n const widgetName = resolveWidgetName(bootstrap.widgetName);\n const entry = conversationWidgetRegistry.widgets.find((widget) => widget.name === widgetName);\n const [canvas, setCanvas] = useState<CanvasState | null>(null);\n const [composerLog, setComposerLog] = useState<ComposerLogEntry[]>([]);\n const agentSpaceKey = Number(readWidgetAgentSpaceKeyAttribute(fixture) ?? PREVIEW_AGENT_SPACE_KEY);\n const fence = useMemo(\n () => buildWidgetPreviewFence(widgetName ?? bootstrap.widgetName, fixture),\n [widgetName, bootstrap.widgetName, fixture],\n );\n const isEmail = bootstrap.mode === \"email\";\n const isInteractive = bootstrap.mode === \"interactive\";\n // The capture context switches every widget to its static e-mail branch (no canvas, no auto-open): e-mail mode only.\n const frozenHydration =\n isEmail && fixture.hydration && Object.keys(fixture.hydration).length > 0 ? fixture.hydration : null;\n\n useEffect(() => {\n if (!entry) readiness.fail(\"UNKNOWN_WIDGET\");\n // The whole page document: the canvas pane and a modal (the lightbox renders into the modal root) settle too.\n else if (widgetRef.current) return readiness.observe(document.body, widgetRef.current, hasHydrationError);\n }, [entry, readiness, hasHydrationError]);\n // The block's render report reaches the readiness as in the chat it reaches the collector.\n const renderReporter = useMemo<WidgetRenderReporter>(() => ({ report: readiness.recordRenderReport }), [readiness]);\n\n const appendComposerLog = useCallback(\n (kind: ComposerLogEntry[\"kind\"], text: string) => setComposerLog((entries) => [...entries, { kind, text }]),\n [],\n );\n // The chat's opening rule decides, as in the conversation slice: a live delivery on a narrow window does not take\n // over for a canvas without an overlay, so the narrow shot shows the inline rows and the \"Open in canvas\" card.\n const openCanvas = useCallback((request: CanvasOpenRequestFromOpener) => {\n setCanvas((current) => {\n const decision = decideCanvasOpen(canvasBehaviourOf(request.canvasId), current, null, {\n ...request,\n viewportViable: window.innerWidth >= CANVAS_VIABLE_MIN_WIDTH,\n hostHasCanvasSurface: true,\n });\n if (decision.kind === \"ignore\") return current;\n return {\n canvasId: request.canvasId,\n instanceId: request.instanceId,\n anchor: request.anchor,\n origin: request.origin,\n mountGeneration: (current?.mountGeneration ?? 0) + 1,\n };\n });\n }, []);\n const callbacks = useMemo<Partial<ConversationWidgetCallbacks>>(\n () => ({\n canvas,\n hostHasCanvasSurface: !isEmail,\n openCanvas: isEmail ? () => {} : openCanvas,\n closeCanvas: () => setCanvas(null),\n chatAgentSpaceKey: agentSpaceKey,\n messages: [],\n sendMessageToChat: (text: string) => appendComposerLog(\"message\", text),\n prefillComposer: (text: string) => appendComposerLog(\"prefill\", text),\n injectSignal: (text: string) => {\n appendComposerLog(\"signal\", text);\n return Promise.resolve(true);\n },\n }),\n [canvas, isEmail, openCanvas, agentSpaceKey, appendComposerLog],\n );\n\n if (!entry) return null;\n const WidgetComponent = entry.component;\n const CanvasBody = canvas ? canvasBodies[canvas.canvasId] : null;\n const widget = (\n <ConversationWidgetErrorBoundary widgetName={entry.name} onCrash={readiness.recordWidgetCrash}>\n <WidgetRenderReportContext.Provider value={renderReporter}>\n <WidgetComponent\n payload={JSON.stringify(fixture.payload)}\n {...buildWidgetAgentSpaceKeyProps(String(agentSpaceKey))}\n interactive={isInteractive}\n fresh={isInteractive}\n justDelivered={isInteractive}\n messageId={String(PREVIEW_MESSAGE_ID)}\n openedByPage={false}\n />\n </WidgetRenderReportContext.Provider>\n </ConversationWidgetErrorBoundary>\n );\n return (\n <StandaloneConversationWidgetProvider callbacks={callbacks}>\n <ConversationWidgetRenderContext.Provider value={isEmail ? \"email\" : \"conversation\"}>\n <WidgetImageRenderContext.Provider value={frozenHydration}>\n <div className={styles.page} data-testid=\"widget-preview-page\">\n <div className={styles.chatColumn} data-testid=\"widget-preview-frame\">\n <div\n ref={widgetRef}\n className={styles.widget}\n data-testid=\"widget-preview-widget\"\n inert={isEmail || undefined}\n >\n {fixture.stubComposedViewComponents ? (\n <ComposedViewComponentsContext.Provider value={buildPreviewComposedViewComponents()}>\n {widget}\n </ComposedViewComponentsContext.Provider>\n ) : (\n widget\n )}\n </div>\n {composerLog.length > 0 ? (\n <div className={styles.composerLog} data-testid=\"widget-preview-composer-log\">\n {composerLog.map((composerEntry, entryIndex) => (\n <Text\n key={entryIndex}\n role=\"caption\"\n translate={false}\n className={styles.composerEntry}\n >\n {`${composerEntry.kind}: ${composerEntry.text}`}\n </Text>\n ))}\n </div>\n ) : null}\n </div>\n {canvas && CanvasBody ? (\n <div className={styles.canvasPane} data-testid=\"widget-preview-canvas\" data-canvas-id={canvas.canvasId}>\n <CanvasBody\n key={`${canvas.instanceId}#${canvas.mountGeneration}`}\n canvas={canvas}\n agentSpaceKey={agentSpaceKey}\n anchorMessageMarkdown={fence}\n />\n </div>\n ) : null}\n </div>\n </WidgetImageRenderContext.Provider>\n </ConversationWidgetRenderContext.Provider>\n </StandaloneConversationWidgetProvider>\n );\n};\n","import { getSandboxLegacyAliases } from \"../provider/environment\";\nimport type { WidgetPreviewSignal } from \"./widget-preview.types\";\n\n/** The `window` property a preview script waits on. */\nexport const WIDGET_PREVIEW_SIGNAL_GLOBAL_NAME = \"__AGENTS_WIDGET_PREVIEW_V1__\";\n\ntype WindowSignals = Record<string, WidgetPreviewSignal | undefined>;\n\n/**\n * Every name the preview signal is published under: the package's own, then each name the app declares\n * (`AgentsEnvironment.sandboxLegacyAliases.previewReadinessGlobalNames`), read at each publish.\n */\nexport const readWidgetPreviewSignalGlobalNames = (): string[] => [\n WIDGET_PREVIEW_SIGNAL_GLOBAL_NAME,\n ...(getSandboxLegacyAliases().previewReadinessGlobalNames ?? []).filter(\n (aliasName) => aliasName !== WIDGET_PREVIEW_SIGNAL_GLOBAL_NAME,\n ),\n];\n\n/** Publishes (or with `undefined` clears) the preview signal under every name. */\nexport const publishWidgetPreviewSignal = (signal: WidgetPreviewSignal | undefined): void => {\n const windowSignals = window as unknown as WindowSignals;\n for (const globalName of readWidgetPreviewSignalGlobalNames()) windowSignals[globalName] = signal;\n};\n","import { publishWidgetImageReadiness } from \"../image-render/widget-image-readiness-signal\";\nimport type { WidgetRenderReportEntry } from \"../renderer/render-report/widget-render-report\";\nimport { publishWidgetPreviewSignal } from \"./widget-preview-signal\";\nimport type { WidgetPreviewExpectedState, WidgetPreviewSignal } from \"./widget-preview.types\";\n\n/** A loading placeholder: the component library's `Skeleton` (its test id; its class is a hashed module name) and the kit's own. */\nconst SKELETON_SELECTOR = '[data-testid=\"Skeleton\"], [class*=\"Skeleton\"], [class*=\"skeleton\"]';\nconst LOADING_SELECTOR = `[aria-busy=\"true\"], [role=\"progressbar\"]:not([aria-valuenow]), ${SKELETON_SELECTOR}`;\n/** The DOM must stay unchanged this long before the preview counts as settled. */\nconst SETTLE_MS = 400;\n\n/**\n * Whether a loading marker is actually rendered: the component library's `ImgWithLoader` keeps its Skeleton in the DOM inside a\n * `display: none` wrapper once the image has loaded, so a marker under a hidden ancestor is no loading state. Without\n * a layout engine (jsdom: no client rects for any element) every marker counts as before.\n */\nconst hasRenderedLoadingMarker = (element: HTMLElement): boolean => {\n const markers = Array.from(element.querySelectorAll(LOADING_SELECTOR));\n if (markers.length === 0) return false;\n const hasLayout = element.getClientRects().length > 0;\n return !hasLayout || markers.some((marker) => marker.getClientRects().length > 0);\n};\n\n/**\n * The state an element shows — the same loading markers the e-mail capture refuses to shoot. `hasError` is true when\n * the widget is known to be in an error: a failed hydration, a crash caught by the error boundary, or a request the\n * fixture failed on purpose — a widget that renders nothing on an error would otherwise read as `empty`.\n * `renderReport` is the block's own render report when the widget sent one: `failed` reads as `error`,\n * `pending` as `loading` and `empty` as `empty` — a widget that shows one muted line (\"No data to show.\") for its empty\n * state is empty, whatever text the line holds.\n */\nexport const observeWidgetPreviewState = (\n element: HTMLElement,\n hasError: boolean,\n renderReport?: WidgetRenderReportEntry,\n): WidgetPreviewExpectedState => {\n if (hasError || renderReport?.status === \"failed\") return \"error\";\n if (renderReport?.status === \"pending\") return \"loading\";\n if (hasRenderedLoadingMarker(element)) return \"loading\";\n if (renderReport?.status === \"empty\") return \"empty\";\n if (!element.textContent?.trim() && !element.querySelector(\"img,svg,canvas,iframe\")) return \"empty\";\n return \"data\";\n};\n\n/**\n * A mutation the settle ignores: a style or attribute change inside a loading placeholder — the component library's `Skeleton`\n * animates its shimmer by rewriting its style every frame, so a loading fixture would never be still otherwise.\n */\nconst isSkeletonAnimation = (mutation: MutationRecord): boolean => {\n if (mutation.type !== \"attributes\") return false;\n const target = mutation.target;\n return target instanceof Element && target.closest(SKELETON_SELECTOR) !== null;\n};\n\n/**\n * The preview's ready signal: after every change it waits until the DOM is still for `SETTLE_MS`, then publishes what\n * it shows — `window.__AGENTS_WIDGET_PREVIEW_V1__` (observed against the fixture's expected state, with every request\n * the fixture had no response for) and the e-mail capture's `window.__AGENTS_WIDGET_IMAGE_V1__` (`ready` when the\n * expected state was reached), so the same script conventions work for both. Both are also published under the names\n * the app declares (`AgentsEnvironment.sandboxLegacyAliases`).\n */\nexport const createWidgetPreviewReadiness = (expectedState: WidgetPreviewExpectedState) => {\n const missingResponses: string[] = [];\n const failedRequests: string[] = [];\n let widgetCrashed = false;\n let renderReport: WidgetRenderReportEntry | undefined;\n let scheduleSettleAgain: () => void = () => {};\n let revision = 0;\n const publish = (\n signal: Omit<\n WidgetPreviewSignal,\n \"version\" | \"missingResponses\" | \"failedRequests\" | \"widgetCrashed\" | \"expectedState\"\n >,\n ) => {\n publishWidgetPreviewSignal({\n version: 1,\n expectedState,\n missingResponses: [...missingResponses],\n failedRequests: [...failedRequests],\n widgetCrashed,\n ...(renderReport ? { renderReport } : {}),\n ...signal,\n });\n document.documentElement.dataset.widgetPreviewState = signal.state;\n };\n publish({ state: \"loading\", revision });\n\n const fail = (errorCode: string) => {\n publish({ state: \"failed\", revision, error_code: errorCode });\n publishWidgetImageReadiness({ version: 1, state: \"failed\", error_code: errorCode });\n };\n\n const recordMissingResponse = (requestKey: string) => {\n if (!missingResponses.includes(requestKey)) missingResponses.push(requestKey);\n };\n\n /** A request (or a preview hydration) the fixture answered with a failing `__status`. */\n const recordFailedRequest = (requestKey: string) => {\n if (!failedRequests.includes(requestKey)) failedRequests.push(requestKey);\n };\n\n /** The error boundary caught the widget (`ConversationWidgetErrorBoundary` `onCrash`). */\n const recordWidgetCrash = () => {\n widgetCrashed = true;\n };\n\n /** The block's render report (`WidgetRenderReportContext` of the host); a new status settles again. */\n const recordRenderReport = (entry: WidgetRenderReportEntry) => {\n renderReport = entry;\n scheduleSettleAgain();\n };\n\n const settle = (element: HTMLElement, hasHydrationError: () => boolean) => {\n const hasError = hasHydrationError() || widgetCrashed || failedRequests.length > 0;\n const observedState = observeWidgetPreviewState(element, hasError, renderReport);\n const { x, y, width, height } = element.getBoundingClientRect();\n const rect = { x, y, width, height };\n revision += 1;\n const expectedStateReached = observedState === expectedState;\n publish({ state: \"settled\", revision, observedState, expectedStateReached, rect });\n publishWidgetImageReadiness(\n expectedStateReached\n ? { version: 1, state: \"ready\", rect }\n : {\n version: 1,\n state: \"failed\",\n error_code: `EXPECTED_${expectedState.toUpperCase()}_SAW_${observedState.toUpperCase()}`,\n rect,\n },\n );\n };\n\n /**\n * Watches `watchedElement` (the whole preview document, so an interaction that changes only the canvas pane or opens\n * a modal settles too)\n * and classifies `widgetElement` (the widget alone, the screenshot); returns the disposer.\n */\n const observe = (watchedElement: HTMLElement, widgetElement: HTMLElement, hasHydrationError: () => boolean) => {\n let settleTimer: ReturnType<typeof setTimeout> | null = null;\n const scheduleSettle = () => {\n if (settleTimer !== null) clearTimeout(settleTimer);\n settleTimer = setTimeout(() => settle(widgetElement, hasHydrationError), SETTLE_MS);\n };\n const mutationObserver = new MutationObserver((mutations) => {\n if (mutations.some((mutation) => !isSkeletonAnimation(mutation))) scheduleSettle();\n });\n mutationObserver.observe(watchedElement, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n scheduleSettleAgain = scheduleSettle;\n scheduleSettle();\n return () => {\n mutationObserver.disconnect();\n scheduleSettleAgain = () => {};\n if (settleTimer !== null) clearTimeout(settleTimer);\n };\n };\n\n return { observe, fail, recordMissingResponse, recordFailedRequest, recordWidgetCrash, recordRenderReport };\n};\n\nexport type WidgetPreviewReadiness = ReturnType<typeof createWidgetPreviewReadiness>;\n","import { createHeaderlessResponse, interceptXMLHttpRequests, isFetchRequest } from \"../request-interception/browser-request-interception\";\nimport type { WidgetPreviewResponse } from \"./widget-preview.types\";\n\n/** The key a fixture response is stored under: method, path and the sorted query (`GET /api/example/…?a=1&b=2`). */\nexport const widgetPreviewRequestKey = (method: string, url: URL): string => {\n const sortedUrl = new URL(url.toString());\n sortedUrl.searchParams.sort();\n return `${method.toUpperCase()} ${sortedUrl.pathname}${sortedUrl.search}`;\n};\n\n/** The app's own error log: answered empty and never reported — a fixture's error state must not count as a gap. */\nconst SILENTLY_ANSWERED_PATHS = [\"/rest_api/v1/log\"];\nconst isSilentlyAnswered = (url: URL): boolean => SILENTLY_ANSWERED_PATHS.includes(url.pathname);\n\nexport const isStatusResponse = (response: unknown): response is { __status: number; __body?: unknown } =>\n typeof response === \"object\" &&\n response !== null &&\n typeof (response as { __status?: unknown }).__status === \"number\";\nexport const isPendingResponse = (response: unknown): boolean =>\n typeof response === \"object\" && response !== null && (response as { __pending?: unknown }).__pending === true;\n\n/** A fixture answer as an `XMLHttpRequest` reads it; a status a `Response` cannot carry fails like a network error. */\nconst xhrAnswer = (body: unknown, status: number): Response => {\n if (status < 200 || status > 599) throw new TypeError(`preview response ${status}`);\n if ([204, 205, 304].includes(status)) return createHeaderlessResponse(null, status);\n return createHeaderlessResponse(JSON.stringify(body), status, status === 200 ? \"OK\" : \"\");\n};\n\n/**\n * Serves every request of the preview — `XMLHttpRequest` (the transport of axios's browser adapter) and `fetch` — from\n * the fixture: a known request gets its body (a copy), a `__status` entry fails with that status (a status of 400 or\n * more is reported as a failed request — the error state the fixture asked for), a `__pending` entry never answers (the\n * loading state), and anything else — an unknown read, a write the fixture does not answer — fails as a missing\n * response and is reported. A write is answered only when the fixture names it (`\"POST /api/example/…\"`, e.g. a\n * widget's fire-and-forget measurement event). Nothing reaches a server.\n */\nexport const installWidgetPreviewRequests = (\n responses: Record<string, WidgetPreviewResponse>,\n onMissingResponse: (requestKey: string) => void,\n onFailedRequest: (requestKey: string) => void = () => {},\n): (() => void) => {\n // XMLHttpRequest: a missing response fails like a network error (no response), a `__status` entry answers with its\n // status and `__body`.\n const restoreXMLHttpRequest = interceptXMLHttpRequests(async (request) => {\n if (isSilentlyAnswered(request.url)) return xhrAnswer({}, 200);\n const requestKey = widgetPreviewRequestKey(request.method, request.url);\n const response = Object.prototype.hasOwnProperty.call(responses, requestKey) ? responses[requestKey] : undefined;\n if (response === undefined) {\n onMissingResponse(requestKey);\n throw new Error(`no preview response for ${requestKey}`);\n }\n if (isPendingResponse(response)) return new Promise<Response>(() => {});\n if (isStatusResponse(response)) {\n if (response.__status >= 400) onFailedRequest(requestKey);\n return xhrAnswer(response.__body ?? null, response.__status);\n }\n return xhrAnswer(response, 200);\n });\n // `fetch` is answered the same way (a few modules bypass the XMLHttpRequest client); a missing response is a 404,\n // reported. A `Request` of another realm is read by its brand, not by `instanceof`.\n const originalFetch = window.fetch;\n window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {\n const fromRequest = isFetchRequest(input) ? input : undefined;\n const method = (init?.method ?? (fromRequest ? fromRequest.method : \"GET\")).toLowerCase();\n const url = new URL(fromRequest ? fromRequest.url : String(input), window.location.origin);\n if (isSilentlyAnswered(url)) return new Response(\"{}\", { status: 200 });\n const requestKey = widgetPreviewRequestKey(method, url);\n const response = Object.prototype.hasOwnProperty.call(responses, requestKey) ? responses[requestKey] : undefined;\n if (response === undefined) {\n onMissingResponse(requestKey);\n return new Response(null, { status: 404 });\n }\n if (isPendingResponse(response)) return new Promise<Response>(() => {});\n if (isStatusResponse(response)) {\n if (response.__status >= 400) onFailedRequest(requestKey);\n return new Response(JSON.stringify(response.__body ?? null), { status: response.__status });\n }\n return new Response(JSON.stringify(response), { status: 200, headers: { \"Content-Type\": \"application/json\" } });\n };\n return () => {\n restoreXMLHttpRequest();\n window.fetch = originalFetch;\n };\n};\n","import {\n getWidgetHydrator,\n listWidgetHydratorTypes,\n registerWidgetHydrator,\n unregisterWidgetHydrator,\n} from \"../renderer/widget-hydration/widget-hydration.registry\";\nimport type { RegisteredWidget } from \"../renderer/widget-hydration/widget-hydration.types\";\nimport { isPendingResponse, isStatusResponse } from \"./widget-preview-requests\";\nimport type { WidgetPreviewResponse } from \"./widget-preview.types\";\n\n/** The fixture's entry for one hydration: the exact derived key first, then the hydrator type (as the capture reads). */\nconst findFixtureHydration = (\n hydration: Record<string, WidgetPreviewResponse>,\n type: string,\n key: string,\n): { found: boolean; value?: WidgetPreviewResponse; hydrationKey: string } => {\n if (Object.prototype.hasOwnProperty.call(hydration, key))\n return { found: true, value: hydration[key], hydrationKey: key };\n if (Object.prototype.hasOwnProperty.call(hydration, type))\n return { found: true, value: hydration[type], hydrationKey: type };\n return { found: false, hydrationKey: key };\n};\n\n/** One fixture value as a hydrator result: a copy of the body, a failing `__status`, or a `__pending` that never ends. */\nconst answerFromFixture = (\n value: WidgetPreviewResponse,\n hydrationKey: string,\n onFailedRequest: (requestKey: string) => void,\n): Promise<unknown> => {\n if (isPendingResponse(value)) return new Promise(() => {});\n if (isStatusResponse(value)) {\n onFailedRequest(`HYDRATION ${hydrationKey}`);\n return Promise.reject(new Error(`preview hydration ${value.__status}`));\n }\n return Promise.resolve(structuredClone(value));\n};\n\n/**\n * The preview's hydration transport for the `interactive` and `replay` modes: every registered hydrator is replaced by\n * one that answers from the fixture's `hydration` (by derived key, else by type) and otherwise runs the real hydrator,\n * whose requests the request transport answers from `responses`. The widget therefore runs its live code path —\n * `useWidgetHydration` with the store's hydration slice, no frozen capture context — so a self-hydrating canvas widget\n * auto-opens its canvas like in the chat (`CanvasLauncherWidget`). The `email` mode keeps the capture's frozen hydration.\n * Returns the disposer that puts the real hydrators back.\n */\nexport const installWidgetPreviewHydration = (\n hydration: Record<string, WidgetPreviewResponse>,\n onFailedRequest: (requestKey: string) => void,\n): (() => void) => {\n const replacedHydrators = new Map<string, RegisteredWidget<unknown, unknown>>();\n for (const type of listWidgetHydratorTypes()) {\n const registered = getWidgetHydrator<unknown, unknown>(type);\n if (!registered) continue;\n replacedHydrators.set(type, registered);\n unregisterWidgetHydrator(type);\n registerWidgetHydrator<unknown, unknown>(type, {\n ...registered,\n hydrator: (payload, context) => {\n const fixtureHydration = findFixtureHydration(hydration, type, registered.deriveKey(type, payload));\n return fixtureHydration.found\n ? answerFromFixture(fixtureHydration.value, fixtureHydration.hydrationKey, onFailedRequest)\n : registered.hydrator(payload, context);\n },\n });\n }\n return () => {\n for (const [type, registered] of replacedHydrators) {\n unregisterWidgetHydrator(type);\n registerWidgetHydrator(type, registered);\n }\n };\n};\n","import { Text } from \"../../../provider/components\";\nimport { ConversationWidgetProvider } from \"../../../renderer/ConversationWidgetContext\";\nimport { ConversationMessageInputComposerWidgets } from \"../../../chat/ConversationMessageInput/ConversationMessageInputComposerWidgets/ConversationMessageInputComposerWidgets\";\nimport { EntityMentionAskButton } from \"../EntityMentionAskButton/EntityMentionAskButton\";\nimport styles from \"./EntityMentionAskFlowStory.module.scss\";\n\nconst ENTITIES = [\n { entityType: \"competitor\", entityId: \"8812\", label: \"Altes Gasthaus Leve\", agentSpaceKey: 1 },\n { entityType: \"competitor\", entityId: \"9001\", label: \"Kleiner Kiepenkerl\", agentSpaceKey: 1 },\n];\n\n/**\n * The \"Ask about this\" flow for the story and the browser check: a stand-in for the detail panel's\n * footer (the `entityDetail` shell is the canvas shell's, the bodies come from the entity types) with the real button, and the real\n * composer strip of the chat input, so a click shows the chip where the owner types.\n */\nexport const EntityMentionAskFlowStory = (props: { maxWidth?: number }) => (\n <ConversationWidgetProvider callbacks={{}}>\n <div className={styles.page} style={{ maxWidth: props.maxWidth ?? 720 }}>\n {ENTITIES.map((entity) => (\n <div key={entity.entityId} className={styles.panel}>\n <Text role=\"intro\" weight=\"bold\" translate={false}>\n {entity.label}\n </Text>\n <Text role=\"help\" color=\"var(--agents-fg-light)\" translate={false}>\n {\"detail panel body\"}\n </Text>\n <div className={styles.footer}>\n <EntityMentionAskButton {...entity} testId={`entity-mention-ask-${entity.entityId}`} />\n </div>\n </div>\n ))}\n <div className={styles.composer} data-testid=\"story-composer\">\n <ConversationMessageInputComposerWidgets testId=\"story-input\" />\n <Text role=\"help\" color=\"var(--agents-fg-lightest)\" translate={false}>\n {\"Ask anything…\"}\n </Text>\n </div>\n </div>\n </ConversationWidgetProvider>\n);\n"],"names":["styles","widget","composerLog","composerEntry"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,MAAM,iBAAiB,CAAC,oBAA4C;AAClE,MAAI,OAAO,oBAAoB,YAAY,CAAC,OAAO,SAAS,eAAe,KAAK,kBAAkB,EAAG,QAAO;AAC5G,QAAM,UAAU,KAAK,MAAM,kBAAkB,EAAE;AAC/C,QAAM,UAAU,KAAK,MAAM,kBAAkB,EAAE;AAC/C,SAAO,GAAG,OAAO,IAAI,OAAO,OAAO,EAAE,SAAS,GAAG,GAAG,CAAC;AACvD;AAEA,MAAM,YAAY,CAAC,EAAE,YAAwC;AAC3D,QAAM,WAAW,eAAe,MAAM,eAAe;AACrD,SACE,oBAAC,eAAA,EAAc,OAAM,QAAO,SAAO,MACjC,UAAA,qBAAC,OAAA,EAAI,WAAWA,SAAO,WACpB,UAAA;AAAA,IAAA,OAAO,MAAM,cAAc,WAC1B,oBAAC,OAAA,EAAI,WAAWA,SAAO,oBAAoB,KAAK,MAAM,WAAW,KAAI,IAAG,IACtE;AAAA,IACJ,qBAAC,OAA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yB,IAAI;AAC7B,6BAAuB,MAAM,UAAU;AAAA,IACzC;AAAA,EACF;AACF;;;;;;;;;;;ACjEA,MAAM,WAAW;AAAA,EACf,EAAE,YAAY,cAAc,UAAU,QAAQ,OAAO,uBAAuB,eAAe,EAAA;AAAA,EAC3F,EAAE,YAAY,cAAc,UAAU,QAAQ,OAAO,sBAAsB,eAAe,EAAA;AAC5F;AAOO,MAAM,4BAA4B,CAAC,8BACvC,4BAAA,EAA2B,WAAW,CAAA,GACrC,UAAA,qBAAC,SAAI,WAAW,OAAO,MAAM,OAAO,EAAE,UAAU,MAAM,YAAY,OAC/D,UAAA;AAAA,EAAA,SAAS,IAAI,CAAC,gCACZ,OAAA,EAA0B,WAAW,OAAO,OAC3C,UAAA;AAAA,IAAA,oBAAC,MAAA,EAAK,MAAK,SAAQ,QAAO,QAAO,WAAW,OACzC,iBAAO,MAAA,CACV;AAAA,IACA,oBAAC,QAAK,MAAK,QAAO,OAAM,0BAAyB,WAAW,OACzD,UAAA,oBAAA,CACH;AAAA,IACA,oBAAC,OAAA,EAAI,WAAW,OAAO,QACrB,UAAA,oBAAC,wBAAA,EAAwB,GAAG,QAAQ,QAAQ,sBAAsB,OAAO,QAAQ,IAAI,EAAA,CACvF;AAAA,EAAA,KATQ,OAAO,QAUjB,CACD;AAAA,uBACA,OAAA,EAAI,WAAW,OAAO,UAAU,eAAY,kBAC3C,UAAA;AAAA,IAAA,oBAAC,yCAAA,EAAwC,QAAO,cAAA,CAAc;AAAA,IAC9D,oBAAC,QAAK,MAAK,QAAO,OAAM,6BAA4B,WAAW,OAC5D,UAAA,gBAAA,CACH;AAAA,EAAA,EAAA,CACF;AAAA,EAAA,CACF,EAAA,CACF;"}
|
|
@@ -1,2 +1,11 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* The capture page serves supplied GET results in memory. It never lends the render token to the SDK.
|
|
3
|
+
*
|
|
4
|
+
* `XMLHttpRequest` (the transport of axios's browser adapter) is always answered: a supplied GET with its result, any
|
|
5
|
+
* other request fails with MISSING_FROZEN_RESPONSE. `fetch` is left alone unless `options.interceptFetch` is set; then
|
|
6
|
+
* a `fetch` gets the same answers and the same failure, except that a static bundle image of the page's origin and a
|
|
7
|
+
* request of the Google Maps SDK still go to the network unchanged; any other origin fails as well.
|
|
8
|
+
*/
|
|
9
|
+
export declare const installFrozenWidgetRequests: (responses: Record<string, unknown>, fail: (code: string) => void, options?: {
|
|
10
|
+
interceptFetch?: boolean;
|
|
11
|
+
}) => () => void;
|
|
@@ -5,3 +5,8 @@
|
|
|
5
5
|
* The payload is read as written; a payload that does not parse renders no map.
|
|
6
6
|
*/
|
|
7
7
|
export declare const isGoogleMapCapture: (widgetName: string, props: Record<string, unknown>) => boolean;
|
|
8
|
+
/**
|
|
9
|
+
* A request of the Google Maps SDK (its API and RPC paths, its static files) — the only other origin a map capture
|
|
10
|
+
* may reach, through `fetch` and `XMLHttpRequest` alike.
|
|
11
|
+
*/
|
|
12
|
+
export declare const isGoogleMapsSdkRequestUrl: (url: URL) => boolean;
|
|
@@ -7,10 +7,11 @@ export declare const isStatusResponse: (response: unknown) => response is {
|
|
|
7
7
|
};
|
|
8
8
|
export declare const isPendingResponse: (response: unknown) => boolean;
|
|
9
9
|
/**
|
|
10
|
-
* Serves every request of the preview —
|
|
11
|
-
* `__status` entry fails with that status (a status of 400 or
|
|
12
|
-
* fixture asked for), a `__pending` entry never answers (the
|
|
13
|
-
* write the fixture does not answer — fails as a missing
|
|
14
|
-
* fixture names it (`"POST /api/example/…"`, e.g. a
|
|
10
|
+
* Serves every request of the preview — `XMLHttpRequest` (the transport of axios's browser adapter) and `fetch` — from
|
|
11
|
+
* the fixture: a known request gets its body (a copy), a `__status` entry fails with that status (a status of 400 or
|
|
12
|
+
* more is reported as a failed request — the error state the fixture asked for), a `__pending` entry never answers (the
|
|
13
|
+
* loading state), and anything else — an unknown read, a write the fixture does not answer — fails as a missing
|
|
14
|
+
* response and is reported. A write is answered only when the fixture names it (`"POST /api/example/…"`, e.g. a
|
|
15
|
+
* widget's fire-and-forget measurement event). Nothing reaches a server.
|
|
15
16
|
*/
|
|
16
17
|
export declare const installWidgetPreviewRequests: (responses: Record<string, WidgetPreviewResponse>, onMissingResponse: (requestKey: string) => void, onFailedRequest?: (requestKey: string) => void) => (() => void);
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser-level request stand-in of the capture and preview pages: `XMLHttpRequest` (the transport of axios's
|
|
3
|
+
* browser adapter and of uploads with progress) and, where an install asks for it, `window.fetch` are replaced for the
|
|
4
|
+
* duration of an install and send every request into one handler, whatever HTTP client the application uses.
|
|
5
|
+
*
|
|
6
|
+
* The handler answers with a `Response` or throws: `fetch` then rejects with the thrown error, an `XMLHttpRequest`
|
|
7
|
+
* fails like a network error (status 0, `error` and `loadend`, no body, no header). A handler that never settles
|
|
8
|
+
* leaves the request pending. Nothing of the request reaches the network unless the handler sends it itself
|
|
9
|
+
* (`forward()`, or its own copy of the original `fetch`).
|
|
10
|
+
*/
|
|
11
|
+
/** A request as the handler sees it, the same for `fetch` and `XMLHttpRequest`. */
|
|
12
|
+
export interface InterceptedRequest {
|
|
13
|
+
/** Upper case (`GET`, `POST`, …). */
|
|
14
|
+
method: string;
|
|
15
|
+
/** Absolute, resolved against the page's origin. A fresh object per request; the handler may change it. */
|
|
16
|
+
url: URL;
|
|
17
|
+
headers: Headers;
|
|
18
|
+
/** The body the client passed (`fetch`'s, or the argument of `XMLHttpRequest.send`, also for a GET), or null. */
|
|
19
|
+
body: BodyInit | null;
|
|
20
|
+
signal: AbortSignal | undefined;
|
|
21
|
+
transport: "fetch" | "xhr";
|
|
22
|
+
/** Sends the request unchanged through the original `fetch` (an `XMLHttpRequest` with its own credentials mode). */
|
|
23
|
+
forward: () => Promise<Response>;
|
|
24
|
+
}
|
|
25
|
+
export type InterceptedRequestHandler = (request: InterceptedRequest) => Promise<Response>;
|
|
26
|
+
type FetchInput = RequestInfo | URL;
|
|
27
|
+
/**
|
|
28
|
+
* An answer without any header, as the former axios adapters answered (`headers: {}`): a string body would add a
|
|
29
|
+
* `Content-Type`, the bytes of it do not.
|
|
30
|
+
*/
|
|
31
|
+
export declare const createHeaderlessResponse: (body: string | null, status: number, statusText?: string) => Response;
|
|
32
|
+
/** A `Request` of any realm (an iframe's, jsdom's, Node's) — never `instanceof`, which holds only for this realm. */
|
|
33
|
+
export declare const isFetchRequest: (input: unknown) => input is Request;
|
|
34
|
+
/** The `fetch` arguments as one request: a `Request` of any realm, a `URL` or a string, with `init` taking precedence. */
|
|
35
|
+
export declare const readFetchRequest: (input: FetchInput, init: RequestInit | undefined, originalFetch: typeof fetch) => Promise<InterceptedRequest>;
|
|
36
|
+
/**
|
|
37
|
+
* Replaces `XMLHttpRequest` on the page until the returned function is called; `fetch` stays as it is. A handler's
|
|
38
|
+
* `forward()` goes through the page's `fetch` as it was at the install.
|
|
39
|
+
*/
|
|
40
|
+
export declare const interceptXMLHttpRequests: (handle: InterceptedRequestHandler) => (() => void);
|
|
41
|
+
/** Replaces `fetch` on the page until the returned function is called; `XMLHttpRequest` stays as it is. */
|
|
42
|
+
export declare const interceptFetchRequests: (handle: InterceptedRequestHandler) => (() => void);
|
|
43
|
+
/**
|
|
44
|
+
* A `fetch` input this realm's `Request` constructor reads correctly: a `Request` of another realm becomes one of this
|
|
45
|
+
* realm with the same URL, method, headers, body and signal; anything else is returned as it is.
|
|
46
|
+
*/
|
|
47
|
+
export declare const toSameRealmFetchInput: (input: FetchInput) => Promise<FetchInput>;
|
|
48
|
+
export {};
|