tempo-sdk 0.0.99 → 0.0.102
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 +3 -403
- package/dist/assets/editor.d.ts +43 -65
- package/dist/assets/editor.js +1 -573
- package/dist/assets/index.d.ts +11 -61
- package/dist/assets/index.js +1 -338
- package/dist/assets/parser.d.ts +68 -78
- package/dist/assets/parser.js +1 -33
- package/dist/astro/asset-preview-client.d.ts +3 -2
- package/dist/astro/asset-preview-client.js +1 -93
- package/dist/astro/controls.d.ts +1 -3
- package/dist/astro/controls.js +1 -7
- package/dist/astro/document-client.d.ts +5 -6
- package/dist/astro/document-client.js +1 -78
- package/dist/astro/runtime.d.ts +23 -11
- package/dist/astro/runtime.js +1 -86
- package/dist/astro.d.ts +19 -13
- package/dist/astro.js +1 -818
- package/dist/canvas/astro-contract.d.ts +0 -3
- package/dist/canvas/astro-contract.js +1 -9
- package/dist/canvas/astro.d.ts +3 -4
- package/dist/canvas/astro.js +1 -42
- package/dist/canvas/editor.d.ts +187 -183
- package/dist/canvas/editor.js +1 -1094
- package/dist/canvas/flutter-preview.d.ts +0 -1
- package/dist/canvas/flutter-preview.js +1 -9
- package/dist/canvas/index.d.ts +46 -100
- package/dist/canvas/index.js +1 -3926
- package/dist/canvas/interact-projection.d.ts +7 -5
- package/dist/canvas/interact-projection.js +1 -12
- package/dist/canvas/parser.d.ts +10 -303
- package/dist/canvas/parser.js +1 -30
- package/dist/canvas/svelte.d.ts +6 -7
- package/dist/canvas/svelte.js +1 -91
- package/dist/canvas/vue.d.ts +9 -49
- package/dist/canvas/vue.js +1 -264
- package/dist/chunk-CXCUJCXD.js +1 -0
- package/dist/chunk-FH6TMWFA.js +1 -0
- package/dist/chunk-FL7FSJSL.js +1 -0
- package/dist/chunk-GQIOB5SV.js +1 -0
- package/dist/chunk-HBQ7FFH7.js +1 -0
- package/dist/chunk-JRJOWLCN.js +1 -0
- package/dist/chunk-LJCBFTMP.js +1 -0
- package/dist/chunk-M3GN2KUH.js +1 -0
- package/dist/chunk-MPIHFFML.js +1 -0
- package/dist/chunk-T5TY3U2H.js +1 -0
- package/dist/chunk-XO2BSHWM.js +1 -0
- package/dist/chunk-XUSV3KOD.js +1 -0
- package/dist/chunk-ZXBMP6RV.js +1 -0
- package/dist/{controls-uCaQ3CNX.d.ts → controls-DKslABtM.d.ts} +0 -3
- package/dist/expo/plugin.cjs +1 -1928
- package/dist/expo/plugin.js +1 -8
- package/dist/expo-babel-plugin.cjs +1 -1928
- package/dist/expo-babel-plugin.d.cts +46 -40
- package/dist/expo-babel-plugin.d.ts +46 -40
- package/dist/expo-babel-plugin.js +1 -8
- package/dist/flutter-preview-path.d.ts +23 -7
- package/dist/flutter-preview-path.js +1 -16
- package/dist/index.d.ts +33 -45
- package/dist/index.js +1 -20
- package/dist/nextjs/plugin.cjs +1 -413
- package/dist/nextjs/plugin.js +1 -7
- package/dist/nextjs-loader.cjs +1 -2277
- package/dist/nextjs.cjs +1 -484
- package/dist/nextjs.d.cts +2 -58
- package/dist/nextjs.d.ts +2 -58
- package/dist/nextjs.js +1 -17
- package/dist/nuxt/runtime/identity.d.ts +2 -4
- package/dist/nuxt/runtime/identity.js +1 -18
- package/dist/nuxt.d.ts +31 -92
- package/dist/nuxt.js +1 -5854
- package/dist/{page-DwLnOM5d.d.ts → page-Bc8PekIX.d.ts} +1 -5
- package/dist/parser.d-MO5ciJ5n.d.ts +236 -0
- package/dist/{storyboard-CMJVBSXn.d.ts → storyboard.contract.d-UQ4MUYN5.d.ts} +3 -25
- package/dist/svelte.d.ts +8 -18
- package/dist/svelte.js +1 -917
- package/dist/types-CfUgM2w4.d.ts +57 -0
- package/dist/v1-client-compat-n0E0XxuX.d.ts +5 -0
- package/dist/vue.d.ts +17 -58
- package/dist/vue.js +1 -1501
- package/package.json +12 -62
- package/dist/assets/editor.js.map +0 -1
- package/dist/assets/index.js.map +0 -1
- package/dist/assets/parser.js.map +0 -1
- package/dist/astro/asset-preview-client.js.map +0 -1
- package/dist/astro/controls.js.map +0 -1
- package/dist/astro/document-client.js.map +0 -1
- package/dist/astro/runtime.js.map +0 -1
- package/dist/astro.js.map +0 -1
- package/dist/canvas/astro-contract.js.map +0 -1
- package/dist/canvas/astro.js.map +0 -1
- package/dist/canvas/editor.js.map +0 -1
- package/dist/canvas/flutter-preview.js.map +0 -1
- package/dist/canvas/index.js.map +0 -1
- package/dist/canvas/interact-projection.js.map +0 -1
- package/dist/canvas/parser.js.map +0 -1
- package/dist/canvas/svelte.js.map +0 -1
- package/dist/canvas/vue.js.map +0 -1
- package/dist/chunk-27WT3XUG.js +0 -455
- package/dist/chunk-27WT3XUG.js.map +0 -1
- package/dist/chunk-5HIIF354.js +0 -67
- package/dist/chunk-5HIIF354.js.map +0 -1
- package/dist/chunk-65B52AR7.js +0 -11
- package/dist/chunk-65B52AR7.js.map +0 -1
- package/dist/chunk-6HYKKP5N.js +0 -2658
- package/dist/chunk-6HYKKP5N.js.map +0 -1
- package/dist/chunk-6SOP4XU6.js +0 -1891
- package/dist/chunk-6SOP4XU6.js.map +0 -1
- package/dist/chunk-AFXE462X.js +0 -1253
- package/dist/chunk-AFXE462X.js.map +0 -1
- package/dist/chunk-BQPKOVI5.js +0 -115
- package/dist/chunk-BQPKOVI5.js.map +0 -1
- package/dist/chunk-CYDF4LYJ.js +0 -342
- package/dist/chunk-CYDF4LYJ.js.map +0 -1
- package/dist/chunk-CYQE3TLC.js +0 -37
- package/dist/chunk-CYQE3TLC.js.map +0 -1
- package/dist/chunk-DI2ZFAWL.js +0 -14
- package/dist/chunk-DI2ZFAWL.js.map +0 -1
- package/dist/chunk-EGRHWZRV.js +0 -1
- package/dist/chunk-EGRHWZRV.js.map +0 -1
- package/dist/chunk-FGWGY3G3.js +0 -157
- package/dist/chunk-FGWGY3G3.js.map +0 -1
- package/dist/chunk-HOBTDB6G.js +0 -112
- package/dist/chunk-HOBTDB6G.js.map +0 -1
- package/dist/chunk-I7VF4ZOV.js +0 -630
- package/dist/chunk-I7VF4ZOV.js.map +0 -1
- package/dist/chunk-JVVHU3A7.js +0 -1077
- package/dist/chunk-JVVHU3A7.js.map +0 -1
- package/dist/chunk-MIXQVPDH.js +0 -8606
- package/dist/chunk-MIXQVPDH.js.map +0 -1
- package/dist/chunk-MU7S7NU7.js +0 -183
- package/dist/chunk-MU7S7NU7.js.map +0 -1
- package/dist/chunk-OX2YKYSL.js +0 -13
- package/dist/chunk-OX2YKYSL.js.map +0 -1
- package/dist/chunk-PYAJHLXO.js +0 -903
- package/dist/chunk-PYAJHLXO.js.map +0 -1
- package/dist/chunk-SGN7BDRE.js +0 -16
- package/dist/chunk-SGN7BDRE.js.map +0 -1
- package/dist/chunk-SGTGDLOX.js +0 -285
- package/dist/chunk-SGTGDLOX.js.map +0 -1
- package/dist/chunk-T364NBR3.js +0 -1440
- package/dist/chunk-T364NBR3.js.map +0 -1
- package/dist/chunk-U66QI3EN.js +0 -1524
- package/dist/chunk-U66QI3EN.js.map +0 -1
- package/dist/chunk-WTXOWQ7N.js +0 -47
- package/dist/chunk-WTXOWQ7N.js.map +0 -1
- package/dist/chunk-X5DJKVBT.js +0 -1308
- package/dist/chunk-X5DJKVBT.js.map +0 -1
- package/dist/chunk-ZT7HJ6YU.js +0 -38
- package/dist/chunk-ZT7HJ6YU.js.map +0 -1
- package/dist/chunk-ZW26VZHX.js +0 -3169
- package/dist/chunk-ZW26VZHX.js.map +0 -1
- package/dist/controls-reader-5MFHYBZZ.js +0 -192
- package/dist/controls-reader-5MFHYBZZ.js.map +0 -1
- package/dist/expo/plugin.cjs.map +0 -1
- package/dist/expo/plugin.js.map +0 -1
- package/dist/expo-babel-plugin.cjs.map +0 -1
- package/dist/expo-babel-plugin.js.map +0 -1
- package/dist/flutter-preview-path.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/nextjs/plugin.cjs.map +0 -1
- package/dist/nextjs/plugin.js.map +0 -1
- package/dist/nextjs-loader.cjs.map +0 -1
- package/dist/nextjs.cjs.map +0 -1
- package/dist/nextjs.js.map +0 -1
- package/dist/nuxt/runtime/identity.js.map +0 -1
- package/dist/nuxt.js.map +0 -1
- package/dist/svelte.js.map +0 -1
- package/dist/types-C8OIU-kc.d.ts +0 -106
- package/dist/v1-client-compat-qxaXEDm_.d.ts +0 -23
- package/dist/vue.js.map +0 -1
package/dist/canvas/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../canvas/canvas-host.tsx","../../canvas/canvas-import-boundary.tsx","../../canvas/host-recovery-feed.ts","../../canvas/interact-projection-fallback.ts","../../canvas/use-canvas-host-postmessage.ts","../../../../modules/frame-pool/capture-discard.ts","../../canvas/canvas-host-runtime.ts","../../canvas/canvas-host-operations.ts","../../canvas/canvas-host-legacy-compat.ts","../../canvas/canvas-host-protocol.ts","../../canvas/canvas-host-render-state.ts","../../canvas/fresh-mounts.ts","../../canvas/source-identity.ts","../../canvas/runtime-problems.ts","../../canvas/flutter-layers.ts","../../canvas/flutter-view-sizing.ts","../../canvas/flutter-runtime.ts","../../canvas/flutter.tsx","../../canvas/host-capability.ts"],"sourcesContent":["import {\n type ReactNode,\n useEffect,\n useCallback,\n useLayoutEffect,\n useRef,\n useState,\n useMemo,\n useSyncExternalStore,\n} from \"react\";\n\nimport { getCanvasStoryboardRenderId } from \"./canvas\";\nimport {\n CanvasImportBoundary,\n type CanvasModule,\n} from \"./canvas-import-boundary\";\nimport { normalizeId } from \"./ids\";\nimport { installTempoInteractProjectionFallback } from \"./interact-projection-fallback\";\nimport type { CanvasHostRuntimeSize } from \"./runtime-context\";\nimport { CanvasHostContext } from \"./runtime-context\";\nimport { useCanvasHostPostMessage } from \"./use-canvas-host-postmessage\";\nimport { isV1CanvasClient, v1DirectUrlSize } from \"./v1-client-compat\";\nimport { isPreV3CanvasClient } from \"./v2-client-compat\";\n\n// Vite injects an earlier owner only after its projection module loads. Other\n// generated hosts (notably Next.js), or a Vite document whose optional client\n// failed to load, reach this module with no owner. Claiming here guarantees\n// every CanvasHost can produce the readiness commit without a timer fallback.\ninstallTempoInteractProjectionFallback(\"canvas-host\");\n\n/**\n * Live document title of every component-host page. AI agents connected over\n * CDP identify Tempo-internal frames by the leading \"INTERNAL\" marker and\n * leave them alone. Only the runtime title changes: the static\n * `<title>tempo-host</title>` in the harness HTML must stay untouched because\n * tempo-devserver's HTTP host detector matches on that exact body text.\n */\nexport const CANVAS_HOST_DOCUMENT_TITLE =\n \"INTERNAL tempo-host — Tempo component host, do not interact\";\n\nexport function protectCanvasHostDocumentTitle(doc: Document): () => void {\n const restoreTitle = () => {\n if (doc.title !== CANVAS_HOST_DOCUMENT_TITLE) {\n doc.title = CANVAS_HOST_DOCUMENT_TITLE;\n }\n };\n restoreTitle();\n\n const Observer = doc.defaultView?.MutationObserver;\n const observer = Observer ? new Observer(restoreTitle) : null;\n observer?.observe(doc.head ?? doc.documentElement, {\n childList: true,\n subtree: true,\n characterData: true,\n });\n // MutationObserver is the immediate path in browsers. The low-frequency\n // check also covers DOM implementations that special-case document.title\n // without surfacing a title-node mutation.\n const interval = doc.defaultView?.setInterval(restoreTitle, 250);\n return () => {\n observer?.disconnect();\n if (interval !== undefined) doc.defaultView?.clearInterval(interval);\n };\n}\n\n/**\n * Holds the shared component host document at scroll (0, 0). Every storyboard\n * in this document renders its slot at the origin, and each mirror resolves\n * coordinates in its own frame, so viewport coordinates equal board\n * coordinates only while this document is unscrolled. A library that measures\n * the viewport (a fixed-strategy popover writing `getBoundingClientRect`\n * pixels) writes pixels that are right only under that condition. Nothing\n * displays this document, so its scroll position means nothing by itself.\n *\n * The reset is `instant` because an app stylesheet with\n * `html { scroll-behavior: smooth }` would otherwise animate it and leave the\n * document scrolled for the length of the animation. The listener is on the\n * window and not capturing: element scroll events do not bubble, so it sees\n * only the document's own scroll and scroll containers inside a storyboard\n * keep scrolling.\n */\nexport function keepSharedHostUnscrolled(view: Window): () => void {\n const reset = () => {\n if (view.scrollX !== 0 || view.scrollY !== 0) {\n view.scrollTo({ left: 0, top: 0, behavior: \"instant\" });\n }\n };\n reset();\n view.addEventListener(\"scroll\", reset);\n return () => view.removeEventListener(\"scroll\", reset);\n}\n\ntype DirectUrlRender = {\n canvasPath: string;\n renderId: string;\n size?: CanvasHostRuntimeSize;\n};\n\nexport type CanvasHostModule = {\n canvasPath: string;\n load: () => Promise<CanvasModule>;\n};\n\nexport class CanvasHostContractError extends Error {\n override name = \"CanvasHostContractError\";\n}\n\nfunction readDirectUrlDimension(value: string): number | string {\n const match = value.trim().match(/^([0-9]*\\.?[0-9]+)(px|vw|vh)?$/);\n if (!match) {\n throw new Error(\n \"Direct URL dimensions must be positive finite numbers, optionally with px, vw, or vh units\",\n );\n }\n const numberPart = match[1] ?? \"\";\n const unit = match[2] ?? \"\";\n const numberValue = Number(numberPart);\n if (!numberPart || !Number.isFinite(numberValue) || numberValue <= 0) {\n throw new Error(\n \"Direct URL dimensions must be positive finite numbers, optionally with px, vw, or vh units\",\n );\n }\n return unit && unit !== \"px\" ? `${numberValue}${unit}` : numberValue;\n}\n\nfunction readDirectUrlSize(\n params: URLSearchParams,\n): CanvasHostRuntimeSize | undefined {\n if (isV1CanvasClient())\n return v1DirectUrlSize(params, readDirectUrlDimension);\n const width = params.get(\"width\")?.trim();\n const height = params.get(\"height\")?.trim();\n // Missing or malformed pairs leave the URL-owned slot responsive.\n if (!width || !height) return { revision: 1 };\n return {\n width: readDirectUrlDimension(width),\n height: readDirectUrlDimension(height),\n revision: 1,\n };\n}\n\nfunction readDirectUrlRender(): DirectUrlRender | null {\n if (typeof window === \"undefined\") return null;\n const params = new URLSearchParams(window.location.search);\n const canvasPath =\n params.get(\"canvasPath\")?.trim() ??\n params.get(\"pageFile\")?.trim() ??\n params.get(\"importPath\")?.trim() ??\n \"\";\n const storyboardId =\n params.get(\"storyboardId\")?.trim() ??\n params.get(\"exportName\")?.trim() ??\n params.get(\"importName\")?.trim() ??\n \"\";\n if (!canvasPath || !storyboardId) return null;\n return {\n canvasPath,\n renderId: getCanvasStoryboardRenderId(canvasPath, storyboardId),\n size: readDirectUrlSize(params),\n };\n}\n\nfunction subscribeDirectUrlSearch(onChange: () => void): () => void {\n window.addEventListener(\"popstate\", onChange);\n return () => window.removeEventListener(\"popstate\", onChange);\n}\n\nfunction readDirectUrlSearch(): string {\n return window.location.search;\n}\n\nexport function CanvasHost({\n children,\n canvasModules,\n incremental = false,\n activeStoryboardIds,\n isStoryboardActive,\n}: {\n children?: ReactNode;\n canvasModules?: readonly CanvasHostModule[];\n /** Generated Vite hosts admit requested canvases without replacing the document. */\n incremental?: boolean;\n activeStoryboardIds?: ReadonlySet<string> | readonly string[];\n isStoryboardActive?: (storyboardId: string) => boolean;\n}) {\n if (children !== undefined && canvasModules !== undefined) {\n throw new CanvasHostContractError(\n \"CanvasHost cannot receive both children and canvasModules.\",\n );\n }\n const [admitted, setAdmitted] = useState<readonly CanvasHostModule[]>([]);\n const pendingAdmissions = useRef(\n new Map<string, { resolve(): void; reject(error: Error): void }[]>(),\n );\n const admittedRef = useRef(admitted);\n const modules = useMemo(() => {\n const all = new Map(\n canvasModules?.map((module) => [module.canvasPath, module]),\n );\n for (const module of admitted)\n if (!all.has(module.canvasPath)) all.set(module.canvasPath, module);\n return [...all.values()];\n }, [canvasModules, admitted]);\n const registerCanvas = useCallback((canvasPath: string, rawUrl: string) => {\n const url = new URL(rawUrl, window.location.href);\n // Vite serves `@fs/` under its public base: `/@fs/` on a Vite host,\n // `/_nuxt/@fs/` in the Nuxt sidecar.\n const isViteFsModule = url.pathname.includes(\"/@fs/\");\n if (url.origin !== window.location.origin || !isViteFsModule) {\n return Promise.reject(\n new Error(\"Canvas registration requires a same-origin Vite module URL\"),\n );\n }\n if (admittedRef.current.some((module) => module.canvasPath === canvasPath))\n return Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const pending = pendingAdmissions.current.get(canvasPath) ?? [];\n pending.push({ resolve, reject });\n pendingAdmissions.current.set(canvasPath, pending);\n setAdmitted((current) =>\n current.some((module) => module.canvasPath === canvasPath)\n ? current\n : [\n ...current,\n // Vite-only registration stays a runtime import. Expo also\n // bundles this shared host, and must not resolve a variable URL.\n {\n canvasPath,\n load: () => import(/* @vite-ignore @metro-ignore */ url.href),\n },\n ],\n );\n });\n }, []);\n useLayoutEffect(() => {\n admittedRef.current = admitted;\n for (const module of admitted) {\n const pending = pendingAdmissions.current.get(module.canvasPath);\n pendingAdmissions.current.delete(module.canvasPath);\n pending?.forEach(({ resolve }) => resolve());\n }\n }, [admitted]);\n useEffect(\n () => () => {\n for (const pending of pendingAdmissions.current.values())\n pending.forEach(({ reject }) =>\n reject(new Error(\"Canvas host disposed during registration\")),\n );\n pendingAdmissions.current.clear();\n },\n [],\n );\n const directUrlSearch = useSyncExternalStore(\n subscribeDirectUrlSearch,\n readDirectUrlSearch,\n () => \"\",\n );\n const demandRegistration =\n incremental &&\n new URLSearchParams(directUrlSearch).get(\"canvasRegistration\") ===\n \"incremental\";\n const registeredCanvasPaths = useMemo(\n () =>\n [\n ...new Set(\n (demandRegistration ? admitted : modules).map(({ canvasPath }) =>\n canvasPath.trim(),\n ),\n ),\n ].filter(Boolean),\n [modules, admitted, demandRegistration],\n );\n const directUrlRender = useMemo(() => {\n return readDirectUrlRender();\n }, [directUrlSearch]);\n const {\n renderStatusById,\n renderSizeById,\n markStoryboardRendered,\n markStoryboardUnmounted,\n reportStoryboardError,\n clearStoryboardError,\n reportCanvasImportError,\n clearCanvasImportError,\n registerCanvasProblemScope,\n } = useCanvasHostPostMessage(\n registeredCanvasPaths,\n directUrlRender?.renderId ?? null,\n incremental ? registerCanvas : undefined,\n );\n useEffect(() => {\n if (typeof document === \"undefined\") return;\n return protectCanvasHostDocumentTitle(document);\n }, []);\n // A direct-render document mounts one storyboard and the user really\n // scrolls it. Released V1 and protocol-2 clients place slots at layout\n // positions and measure the scrolled document themselves.\n const isSharedHost = directUrlRender === null && !isPreV3CanvasClient();\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n if (!isSharedHost) return;\n return keepSharedHostUnscrolled(window);\n }, [isSharedHost]);\n\n const propActiveIds = useMemo(\n () => new Set(activeStoryboardIds ?? []),\n [activeStoryboardIds],\n );\n const directUrlIdle = useMemo(\n () => new URLSearchParams(directUrlSearch).has(\"tempoCaptureIdle\"),\n [directUrlSearch],\n );\n const mountedCanvasModules = useMemo(\n () =>\n directUrlIdle\n ? []\n : directUrlRender\n ? modules.filter(\n ({ canvasPath }) =>\n canvasPath.trim() === directUrlRender.canvasPath,\n )\n : demandRegistration\n ? modules.filter((module) =>\n admitted.some(\n (entry) => entry.canvasPath === module.canvasPath,\n ),\n )\n : modules,\n [modules, admitted, demandRegistration, directUrlIdle, directUrlRender],\n );\n\n const runtime = useMemo(\n () => ({\n getStoryboardStatus(storyboardId: string) {\n const normalizedId = normalizeId(storyboardId, \"Storyboard id\");\n if (\n propActiveIds.has(normalizedId) ||\n directUrlRender?.renderId === normalizedId ||\n (isStoryboardActive ? isStoryboardActive(normalizedId) : false)\n ) {\n return \"active\" as const;\n }\n return renderStatusById.get(normalizedId) ?? \"unmounted\";\n },\n getStoryboardSize(storyboardId: string) {\n const normalizedId = normalizeId(storyboardId, \"Storyboard id\");\n if (directUrlRender?.renderId === normalizedId) {\n return directUrlRender.size;\n }\n return renderSizeById.get(normalizedId);\n },\n getStoryboardPlacement(storyboardId: string) {\n const normalizedId = normalizeId(storyboardId, \"Storyboard id\");\n return directUrlRender?.renderId === normalizedId\n ? { left: 0, top: 0 }\n : undefined;\n },\n prepareStoryboardCapture(storyboardId: string) {\n if (directUrlRender?.renderId !== storyboardId) return;\n const captureGlobal = globalThis as typeof globalThis & {\n __tempoResetCaptureDeterminism?: () => void;\n };\n captureGlobal.__tempoResetCaptureDeterminism?.();\n },\n markStoryboardRendered,\n markStoryboardUnmounted,\n reportStoryboardError,\n clearStoryboardError,\n reportCanvasImportError,\n clearCanvasImportError,\n registerCanvasProblemScope,\n }),\n [\n clearStoryboardError,\n clearCanvasImportError,\n directUrlRender,\n isStoryboardActive,\n markStoryboardRendered,\n markStoryboardUnmounted,\n propActiveIds,\n registerCanvasProblemScope,\n reportCanvasImportError,\n reportStoryboardError,\n renderSizeById,\n renderStatusById,\n ],\n );\n\n // The host re-renders on every lease change; the canvas modules only\n // when the module list does, so a capture borrowing a render cannot\n // re-render the user's canvas file.\n const canvasBoundaries = useMemo(\n () =>\n mountedCanvasModules?.map(({ canvasPath, load }) => (\n <CanvasImportBoundary\n key={canvasPath}\n canvasPath={canvasPath}\n load={load}\n />\n )),\n [mountedCanvasModules],\n );\n\n return (\n <CanvasHostContext.Provider value={runtime}>\n {children}\n {canvasBoundaries}\n </CanvasHostContext.Provider>\n );\n}\n","import {\n Component,\n type ComponentType,\n type ErrorInfo,\n lazy,\n type ReactNode,\n Suspense,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { CanvasContext } from \"./canvas\";\nimport { CanvasPendingMarker } from \"./canvas-pending-marker\";\nimport { getCanvasHostRecoveryFeed } from \"./host-recovery-feed\";\nimport { useRenderErrorRecovery } from \"./render-error-recovery\";\nimport {\n type CanvasHostRuntimeError,\n useRequiredCanvasHost,\n} from \"./runtime-context\";\n\nexport type CanvasModule = {\n default: ComponentType;\n};\n\ntype ErrorBoundaryProps = {\n children: ReactNode;\n reportError(error: CanvasHostRuntimeError): void;\n};\n\nclass CanvasImportErrorBoundary extends Component<\n ErrorBoundaryProps,\n { hasError: boolean }\n> {\n state = { hasError: false };\n\n static getDerivedStateFromError() {\n return { hasError: true };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo) {\n this.props.reportError({\n message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n componentStack: info.componentStack ?? undefined,\n });\n }\n\n render() {\n return this.state.hasError ? null : this.props.children;\n }\n}\n\nfunction CanvasCommitSignal({ onCommit }: { onCommit(): void }) {\n const onCommitRef = useRef(onCommit);\n const didCommitRef = useRef(false);\n onCommitRef.current = onCommit;\n useLayoutEffect(() => {\n if (didCommitRef.current) return;\n didCommitRef.current = true;\n onCommitRef.current();\n }, []);\n return null;\n}\n\nexport function CanvasImportBoundary({\n canvasPath,\n load,\n}: {\n canvasPath: string;\n load: () => Promise<CanvasModule>;\n}) {\n const {\n clearCanvasImportError,\n registerCanvasProblemScope,\n reportCanvasImportError,\n } = useRequiredCanvasHost();\n const failedRef = useRef(false);\n const importRejectedRef = useRef(false);\n const loadRef = useRef(load);\n const currentExportRef = useRef<ComponentType | null>(null);\n const [replacement, setReplacement] = useState<ComponentType | null>(null);\n const loadGenerationRef = useRef(0);\n const previousLoadRef = useRef(load);\n loadRef.current = load;\n const [retryRevision, setRetryRevision] = useState(0);\n const retryRenderNow = useCallback(() => {\n if (!failedRef.current || importRejectedRef.current) return false;\n currentExportRef.current = null;\n setReplacement(null);\n setRetryRevision((revision) => revision + 1);\n return true;\n }, []);\n // A canvas can throw before its storyboards mount. That unmounted tree\n // needs the same render retry as a storyboard; its loader does not change\n // identity when Vite refreshes only the canvas module (TEM-2262).\n const { noteRenderError, noteRecovered } =\n useRenderErrorRecovery(retryRenderNow);\n const lazyIdentity = `${canvasPath}:${retryRevision}`;\n const LazyCanvas = useMemo(() => {\n void lazyIdentity;\n return lazy(() =>\n Promise.resolve()\n .then(() => {\n importRejectedRef.current = false;\n return loadRef.current();\n })\n .then((module) => {\n const current = module;\n if (currentExportRef.current === null) {\n currentExportRef.current = module.default;\n }\n // Keep the lazy boundary and this resolved wrapper stable. The\n // actual export remains an ordinary child React can reconcile by\n // its Fast Refresh family when a new module value arrives.\n return {\n default: function LoadedCanvas({\n replacement,\n }: {\n replacement: ComponentType | null;\n }) {\n const Component = replacement ?? current.default;\n return <Component />;\n },\n };\n })\n .catch((error: unknown) => {\n importRejectedRef.current = true;\n // A rejected canvas import means a module this document needs\n // failed to load or evaluate. Vite cannot be assumed to repair it\n // in place (a module whose evaluation threw never registered its\n // Fast Refresh accept callbacks), so the recovery adapter's\n // document latch must arm. Render errors deliberately never reach\n // this path — Fast Refresh and boundary retries repair those\n // without any document reload.\n getCanvasHostRecoveryFeed().publish({\n type: \"module-load-failure\",\n path: canvasPath,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }),\n );\n }, [lazyIdentity, canvasPath]);\n\n const reportError = useCallback(\n (error: CanvasHostRuntimeError) => {\n failedRef.current = true;\n // An import rejection ends any render-retry episode; the document\n // recovery adapter owns it. Only a successful commit clears the\n // canvas's reported problem.\n if (importRejectedRef.current) noteRecovered();\n else noteRenderError();\n reportCanvasImportError(canvasPath, error);\n },\n [canvasPath, noteRecovered, noteRenderError, reportCanvasImportError],\n );\n const markCommitted = useCallback(() => {\n failedRef.current = false;\n noteRecovered();\n clearCanvasImportError(canvasPath);\n }, [canvasPath, clearCanvasImportError, noteRecovered]);\n\n useEffect(() => {\n const loadChanged = previousLoadRef.current !== load;\n previousLoadRef.current = load;\n const generation = ++loadGenerationRef.current;\n if (!loadChanged) return;\n if (failedRef.current) {\n currentExportRef.current = null;\n setReplacement(null);\n setRetryRevision((revision) => revision + 1);\n return;\n }\n // Reload the import, preserving this boundary and its resolved wrapper.\n // React retains an unchanged export (and its Fast Refresh family). A\n // forwarded replacement becomes the wrapper's new child, not a new lazy\n // boundary. Obsolete loader completions cannot replace the current owner.\n Promise.resolve()\n .then(load)\n .then(\n (module) => {\n if (generation !== loadGenerationRef.current) return;\n const getFamily = (globalThis as Record<symbol, unknown>)[\n Symbol.for(\"tempo.react-refresh.family\")\n ];\n if (typeof getFamily === \"function\") {\n const family = getFamily(currentExportRef.current);\n // React Refresh owns updates within a registered family. Adopting\n // its newly evaluated function before performReactRefresh installs\n // the renderer mapping would remount the retained canvas state.\n if (family && family === getFamily(module.default)) {\n // An explicit loader can evaluate fresh source without an HMR\n // accept event to flush the queued family. Let the same Refresh\n // runtime install its mapping now; retaining the old export\n // before that would leave the canvas on its previous revision.\n const flush = (globalThis as Record<symbol, unknown>)[\n Symbol.for(\"tempo.react-refresh.flush\")\n ];\n if (typeof flush === \"function\") flush();\n return;\n }\n }\n currentExportRef.current = module.default;\n setReplacement(() => module.default);\n },\n (error: unknown) => {\n if (generation !== loadGenerationRef.current) return;\n getCanvasHostRecoveryFeed().publish({\n type: \"module-load-failure\",\n path: canvasPath,\n message: error instanceof Error ? error.message : String(error),\n });\n },\n );\n return () => {\n ++loadGenerationRef.current;\n };\n }, [load, canvasPath]);\n\n useEffect(\n () => () => {\n clearCanvasImportError(canvasPath);\n },\n [canvasPath, clearCanvasImportError],\n );\n\n // While this boundary is mounted its canvas is an attribution candidate:\n // a host-level Vite diagnostic uniquely naming this canvas's source is\n // scoped here instead of surfacing host-wide on healthy sibling canvases.\n useEffect(\n () => registerCanvasProblemScope(canvasPath),\n [canvasPath, registerCanvasProblemScope],\n );\n\n // This boundary consumes the host context for diagnostics. Lease/size\n // updates change that context, but must not execute the user's canvas file:\n // its inline component functions would become new types and remount every\n // retained storyboard. Actual loader replacements and Fast Refresh still\n // own updates to the canvas export.\n const canvasElement = useMemo(\n () => <LazyCanvas replacement={replacement} />,\n [LazyCanvas, replacement],\n );\n\n return (\n <CanvasImportErrorBoundary key={retryRevision} reportError={reportError}>\n <Suspense fallback={<CanvasPendingMarker />}>\n <CanvasContext path={canvasPath}>\n {canvasElement}\n <CanvasCommitSignal onCommit={markCommitted} />\n </CanvasContext>\n </Suspense>\n </CanvasImportErrorBoundary>\n );\n}\n","/**\n * In-document recovery feed shared between the SDK runtime and the\n * devserver-generated CanvasHost recovery adapter.\n *\n * The generated host document contains two cooperating parties that must not\n * import each other:\n *\n * - the SDK (problem tracking), which observes the product fact \"a module\n * evaluation failed in this document\"; and\n * - the devserver-generated Vite recovery adapter, which owns\n * `import.meta.hot` and decides when a failed host document may reload.\n *\n * The feed is a tiny window-global event bus with create-if-absent semantics\n * on both sides, so evaluation order between the SDK and the generated\n * adapter never matters. It carries product facts about failed module loads —\n * never Vite contexts, cycle numbers, owner success, or reload commands.\n * Which canvases show which problems is the SDK problem tracker's job; the\n * adapter's repair (a document reload) is document-scoped and needs no owner\n * identity.\n */\n\nexport type CanvasHostRecoveryEvent = {\n /** \"module-load-failure\": a module load or evaluation failed in a way Vite\n * cannot converge in place (evaluation threw and cleared the Fast Refresh\n * accepts, or a canvas's cold-start import rejected) — the adapter reloads\n * on the first later HMR cycle. \"module-update-dropped\": Vite dropped a\n * hot update whose module fetch failed — the adapter reloads only if a\n * later cycle does not retry the path (a retry lets Vite own the outcome). */\n type: \"module-load-failure\" | \"module-update-dropped\";\n /** Failed module path. Diagnostic for load failures; for dropped updates it\n * must be the exact accepted-module path Vite reported so the adapter can\n * match it against later update payloads. */\n path: string;\n message?: string;\n};\n\nexport type CanvasHostRecoveryFeed = {\n publish(event: CanvasHostRecoveryEvent): void;\n subscribe(listener: (event: CanvasHostRecoveryEvent) => void): () => void;\n};\n\nconst FEED_KEY = \"__tempoCanvasHostRecoveryFeed\";\n\nfunction createFeed(): CanvasHostRecoveryFeed {\n const listeners = new Set<(event: CanvasHostRecoveryEvent) => void>();\n return {\n publish(event) {\n for (const listener of [...listeners]) listener(event);\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\n/**\n * Returns the document's shared recovery feed, creating it when this is the\n * first party to ask. The generated adapter bootstraps an identically-shaped\n * feed, so whichever side evaluates first wins and the other reuses it.\n */\nexport function getCanvasHostRecoveryFeed(): CanvasHostRecoveryFeed {\n const globals = globalThis as typeof globalThis & {\n [FEED_KEY]?: CanvasHostRecoveryFeed;\n };\n return (globals[FEED_KEY] ??= createFeed());\n}\n","import { isTempoInteractFrameName } from \"./interact-frame.ts\";\nimport { installTempoInteractProjectionSource } from \"./interact-projection.ts\";\n\n/** Post-load source owner for integrated documents that Vite did not claim. */\nexport function installTempoInteractProjectionFallback(\n owner: \"electron\" | \"canvas-host\" = \"electron\",\n): (() => void) | null {\n if (\n typeof window === \"undefined\" ||\n window.parent === window ||\n !isTempoInteractFrameName(window.name)\n ) {\n return null;\n }\n if (window.__tempoInteractProjectionOwner) return null;\n window.__tempoInteractProjectionOwner = owner;\n const stopSource = installTempoInteractProjectionSource();\n return () => {\n stopSource();\n if (window.__tempoInteractProjectionOwner === owner) {\n delete window.__tempoInteractProjectionOwner;\n }\n };\n}\n","import {\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport {\n applyLegacyRenderIsolation,\n createLegacyHostHealth,\n} from \"./canvas-host-legacy-compat\";\nimport {\n captureStoryboardCombined,\n captureStoryboardHtml,\n captureStoryboardImage,\n captureStoryboardStaticHtml,\n watchStoryboardCombined,\n watchStoryboardHtml,\n} from \"./canvas-host-operations\";\nimport type { CanvasHostRenderRequest } from \"./canvas-host-protocol\";\nimport {\n readCanvasHostCommand,\n readOptionalNumber,\n readPinId,\n readRenderRequest,\n readWatchId,\n requireRenderTarget,\n resolveRenderTarget,\n} from \"./canvas-host-protocol\";\nimport {\n acquireRender,\n buildRenderSizeMap,\n buildRenderStatePayload,\n buildRenderStatusMap,\n type CanvasHostRenderEntry,\n evictCachedRenders,\n pinRenderSource,\n releaseRender,\n renderRequestMatchesEntry,\n renderRequestTargetsEntry,\n} from \"./canvas-host-render-state\";\nimport type {\n CanvasHostWatch,\n CanvasHostWatchResumeOptions,\n} from \"./canvas-host-runtime\";\nimport type { CanvasHostRuntimeError } from \"./runtime-context\";\nimport { forgetFreshMount, noteFreshMount } from \"./fresh-mounts\";\nimport {\n createCanvasHostProblemTracker,\n installCanvasHostRuntimeProblemTracking,\n} from \"./runtime-problems\";\n\ntype WatchLease = {\n renderId: string;\n bindingKey: string;\n establishment: WatchEstablishment;\n watch: CanvasHostWatch;\n};\n\ntype WatchEstablishment = {\n status: \"pending\" | \"established\" | \"failed\";\n};\n\ntype WatchRequest = {\n // watch-html is only sent by pre-0.0.20 Tempo clients (see the legacy\n // command surface below); watch-combined is the current contract.\n commandType: \"render-pool:watch-combined\" | \"render-pool:watch-html\";\n requestId: unknown;\n watchId: string;\n source?: MessageEventSource | null;\n targetOrigin?: string;\n request: CanvasHostRenderRequest;\n payload: Record<string, unknown>;\n paused: boolean;\n bindingKey: string;\n establishment: WatchEstablishment;\n};\n\ntype PendingRenderWaiter = {\n resolve(): void;\n reject(error: Error): void;\n};\n\ntype ProblemWatcher = {\n requestId: unknown;\n watchId?: string;\n source?: MessageEventSource | null;\n targetOrigin?: string;\n};\n\nconst DEFAULT_MAX_CACHED_RENDERS = 20;\n\n// Security boundary: CanvasHost runs inside Tempo's generated host page and is\n// driven only by the trusted Electron/frame-pool bridge or by same-page test\n// commands (`__render-pool:command`). Browser `message` replies use the\n// captured `event.origin`; Electron/file/custom-event commands fall back to\n// \"*\" because those bridges do not provide a stable browser-origin string.\n// Command payloads are still structurally validated before use, and replies\n// are sent only to the captured source.\nfunction postToMessageSource(\n source: MessageEventSource | null | undefined,\n response: Record<string, unknown>,\n targetOrigin?: string,\n): void {\n const origin = safePostMessageTargetOrigin(targetOrigin);\n if (source && \"postMessage\" in source && source !== window) {\n (source as Window).postMessage(response, origin);\n } else {\n window.postMessage(response, origin);\n }\n}\n\nfunction safePostMessageTargetOrigin(targetOrigin: string | undefined): string {\n if (targetOrigin && targetOrigin !== \"null\" && targetOrigin !== \"file://\") {\n return targetOrigin;\n }\n const currentOrigin = window.location.origin;\n return currentOrigin && currentOrigin !== \"null\" ? currentOrigin : \"*\";\n}\n\nfunction acknowledgeWatchEstablishment(request: WatchRequest): void {\n if (request.establishment.status !== \"pending\") return;\n request.establishment.status = \"established\";\n postToMessageSource(\n request.source,\n {\n type: \"render-pool:ack\",\n requestId: request.requestId,\n command: request.commandType,\n },\n request.targetOrigin,\n );\n}\n\nfunction rejectWatchEstablishment(request: WatchRequest, error: Error): void {\n if (request.establishment.status !== \"pending\") return;\n request.establishment.status = \"failed\";\n postWatchError(request, error);\n}\n\nfunction postWatchError(request: WatchRequest, error: Error): void {\n postToMessageSource(\n request.source,\n {\n type: \"render-pool:error\",\n requestId: request.requestId,\n watchId: request.watchId,\n command: request.commandType,\n error: error.message,\n },\n request.targetOrigin,\n );\n}\n\nfunction readWatchResumeOptions(\n payload: Record<string, unknown>,\n): CanvasHostWatchResumeOptions | undefined {\n const flush = payload.flush;\n const triggers = Array.isArray(payload.triggers)\n ? payload.triggers.filter(\n (trigger): trigger is \"viewport-capture\" =>\n trigger === \"viewport-capture\",\n )\n : [];\n const validFlush =\n flush === \"always\" || flush === \"if-dirty\" || flush === \"never\"\n ? flush\n : undefined;\n return validFlush === undefined && triggers.length === 0\n ? undefined\n : { flush: validFlush, triggers };\n}\n\nfunction setRuntimeWatchPaused(\n watch: CanvasHostWatch,\n paused: boolean,\n resumeOptions?: CanvasHostWatchResumeOptions,\n): void {\n if (watch.setPaused) {\n if (resumeOptions === undefined) {\n watch.setPaused(paused);\n } else {\n watch.setPaused(paused, resumeOptions);\n }\n } else if (paused) {\n watch.pause?.();\n } else {\n if (resumeOptions === undefined) {\n watch.resume?.();\n } else {\n watch.resume?.(resumeOptions);\n }\n }\n}\n\nexport function useCanvasHostPostMessage(\n registeredCanvasPaths: readonly string[] = [],\n /**\n * The render id this document's own URL pins (a direct-render capture\n * document, `?canvasPath=&storyboardId=`), or null. That storyboard's slot\n * geometry is owned by the URL, so no render request can change it — see\n * `waitForRender`.\n */\n urlPinnedRenderId: string | null = null,\n registerCanvas?: (canvasPath: string, moduleUrl: string) => Promise<void>,\n): {\n renderStatusById: ReadonlyMap<string, \"active\" | \"cached\">;\n renderSizeById: ReadonlyMap<\n string,\n {\n width?: number;\n height?: number;\n revision?: number;\n }\n >;\n markStoryboardRendered(storyboardId: string): void;\n markStoryboardUnmounted(storyboardId: string): void;\n reportStoryboardError(\n storyboardId: string,\n error: CanvasHostRuntimeError,\n ): void;\n clearStoryboardError(storyboardId: string): void;\n reportCanvasImportError(\n canvasPath: string,\n error: CanvasHostRuntimeError,\n ): void;\n clearCanvasImportError(canvasPath: string): void;\n registerCanvasProblemScope(canvasPath: string): () => void;\n} {\n const [renderEntriesById, setRenderEntriesById] = useState<\n ReadonlyMap<string, CanvasHostRenderEntry>\n >(() => new Map());\n const [watchRequestsById, setWatchRequestsById] = useState(\n () => new Map<string, WatchRequest>(),\n );\n const [renderCommitVersionById, setRenderCommitVersionById] = useState(\n () => new Map<string, number>(),\n );\n const renderEntriesRef = useRef(renderEntriesById);\n // The entries React last committed, which is what the slots show.\n // `renderEntriesRef` can run ahead of React: it takes an update when React\n // computes it, which for an idle host is as the update is queued, before\n // the render that commits it. So it can hold a state no slot ever showed.\n // See `waitForRender`.\n const committedRenderEntriesRef = useRef(renderEntriesById);\n useLayoutEffect(() => {\n committedRenderEntriesRef.current = renderEntriesById;\n }, [renderEntriesById]);\n const renderStatusRef = useRef<ReadonlyMap<string, \"active\" | \"cached\">>();\n const renderSizeRef = useRef<ReadonlyMap<string, CanvasHostRenderSize>>();\n const watchRequestsRef = useRef(watchRequestsById);\n const registeredCanvasPathsRef = useRef<readonly string[]>([]);\n registeredCanvasPathsRef.current = registeredCanvasPaths;\n const urlPinnedRenderIdRef = useRef<string | null>(null);\n urlPinnedRenderIdRef.current = urlPinnedRenderId;\n const registerCanvasRef = useRef(registerCanvas);\n registerCanvasRef.current = registerCanvas;\n const maxCachedRef = useRef(DEFAULT_MAX_CACHED_RENDERS);\n const legacyHealthRef = useRef(createLegacyHostHealth());\n const renderedRenderIdsRef = useRef(new Set<string>());\n const pendingRenderWaitersRef = useRef(\n new Map<string, PendingRenderWaiter[]>(),\n );\n const sourcePinsRef = useRef(\n new Map<\n string,\n {\n renderId: string;\n canvasPath?: string;\n ready: Promise<void>;\n cancel(error: Error): void;\n }\n >(),\n );\n const watchesRef = useRef(new Map<string, WatchLease>());\n const startingWatchesRef = useRef(\n new Map<\n string,\n { bindingKey: string; establishment: WatchRequest[\"establishment\"] }\n >(),\n );\n const problemWatchersRef = useRef(new Map<string, ProblemWatcher>());\n const problemTrackerRef = useRef(createCanvasHostProblemTracker());\n\n const updateWatchRequests = useCallback(\n (\n update: (\n requests: Map<string, WatchRequest>,\n ) => Map<string, WatchRequest>,\n ): void => {\n const current = watchRequestsRef.current;\n const next = update(current);\n if (next === current) return;\n watchRequestsRef.current = next;\n setWatchRequestsById(next);\n },\n [],\n );\n\n const buildProblemSnapshot = useCallback(\n () => problemTrackerRef.current.snapshot(),\n [],\n );\n\n const publishProblemSnapshot = useCallback(() => {\n const payload = buildProblemSnapshot();\n for (const watcher of problemWatchersRef.current.values()) {\n postToMessageSource(\n watcher.source,\n {\n type: \"render-pool:problem-snapshot\",\n requestId: watcher.requestId,\n watchId: watcher.watchId,\n payload,\n },\n watcher.targetOrigin,\n );\n }\n }, [buildProblemSnapshot]);\n\n const setEntries = useCallback(\n (\n update: (\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n ) => ReadonlyMap<string, CanvasHostRenderEntry>,\n ) => {\n setRenderEntriesById((entries) => {\n const next = update(entries);\n if (next === entries) return entries;\n renderEntriesRef.current = next;\n problemTrackerRef.current.syncRenderSourcePaths([...next.values()]);\n for (const renderId of [...renderedRenderIdsRef.current]) {\n if (!next.has(renderId)) {\n renderedRenderIdsRef.current.delete(renderId);\n legacyHealthRef.current.forgetRender(renderId);\n }\n }\n return next;\n });\n },\n [],\n );\n\n const waitForRender = useCallback(\n (request: CanvasHostRenderRequest): Promise<void> => {\n const committed = committedRenderEntriesRef.current.get(request.renderId);\n const rendered = renderedRenderIdsRef.current.has(request.renderId);\n // The request's entry normally decides the slot's geometry, so only a\n // matching entry the slot shows active counts as rendered; a new or\n // changed entry re-commits the storyboard and resolves the waiter\n // below. A storyboard the document's URL pins is different: the URL\n // owns its slot, a request can change nothing, and its committed\n // render already IS the requested render — waiting for a further\n // commit there would wait forever.\n //\n // \"Shows\" is the committed entry, never the queued one. A slot reports\n // a commit only on a change it renders, so a waiter registered against\n // a state React never committed waits for a report that never comes.\n // A watch lease released and taken again with a capture's lease\n // between them, three messages handled before React rendered, queued\n // a parked entry the slot never showed: the capture waited for the\n // slot to come back from a park it never made, and the command\n // client's serial queue held every resize behind it until the capture\n // timed out 10 s later (a Flutter board resized right after its\n // canvas was reopened kept its old size that long).\n const alreadyRendered =\n rendered &&\n (urlPinnedRenderIdRef.current === request.renderId ||\n (committed?.status === \"active\" &&\n renderRequestMatchesEntry(committed, request)));\n\n setEntries((entries) => acquireRender(entries, request));\n\n if (alreadyRendered) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve, reject) => {\n const pendingWaiters =\n pendingRenderWaitersRef.current.get(request.renderId) ?? [];\n pendingWaiters.push({ resolve, reject });\n pendingRenderWaitersRef.current.set(request.renderId, pendingWaiters);\n });\n },\n [setEntries],\n );\n\n const releaseRenderLease = useCallback(\n (renderId: string, cacheWhenIdle?: boolean) => {\n setEntries((entries) =>\n releaseRender(\n entries,\n renderId,\n maxCachedRef.current,\n Date.now(),\n cacheWhenIdle,\n ),\n );\n },\n [setEntries],\n );\n\n const stopRuntimeWatch = useCallback(\n async (watchId: string, establishment?: WatchEstablishment) => {\n const existingWatch = watchesRef.current.get(watchId);\n if (\n !existingWatch ||\n (establishment && existingWatch.establishment !== establishment)\n ) {\n return;\n }\n watchesRef.current.delete(watchId);\n await existingWatch.watch.stop();\n },\n [],\n );\n\n const removeWatchRequest = useCallback(\n async (watchId: string, reason?: Error): Promise<void> => {\n const existingRequest = watchRequestsRef.current.get(watchId);\n if (existingRequest) {\n rejectWatchEstablishment(\n existingRequest,\n reason ??\n new Error(\n `Canvas host watch ${watchId} was cancelled before establishment`,\n ),\n );\n }\n try {\n await stopRuntimeWatch(watchId, existingRequest?.establishment);\n } finally {\n if (existingRequest) {\n updateWatchRequests((requests) => {\n if (\n requests.get(watchId)?.establishment !==\n existingRequest.establishment\n ) {\n return requests;\n }\n const next = new Map(requests);\n next.delete(watchId);\n return next;\n });\n releaseRenderLease(existingRequest.request.renderId);\n }\n }\n },\n [releaseRenderLease, stopRuntimeWatch, updateWatchRequests],\n );\n\n const suspendEstablishedWatch = useCallback(\n (request: WatchRequest): void => {\n if (request.establishment.status !== \"established\") return;\n\n void stopRuntimeWatch(request.watchId, request.establishment).catch(\n () => {},\n );\n },\n [stopRuntimeWatch],\n );\n\n const runtimeIdRef = useRef<string | undefined>(undefined);\n const buildState = useCallback(\n () => ({\n runtimeId: runtimeIdRef.current,\n sourceCapturePins: true,\n ...(registerCanvasRef.current\n ? { incrementalCanvasRegistration: true }\n : {}),\n ...buildRenderStatePayload(\n renderEntriesRef.current,\n maxCachedRef.current,\n registeredCanvasPathsRef.current,\n ),\n }),\n [],\n );\n\n const markStoryboardRendered = useCallback((storyboardId: string) => {\n renderedRenderIdsRef.current.add(storyboardId);\n legacyHealthRef.current.recordRenderCommit(storyboardId);\n setRenderCommitVersionById((versions) => {\n const next = new Map(versions);\n next.set(storyboardId, (next.get(storyboardId) ?? 0) + 1);\n return next;\n });\n problemTrackerRef.current.clearRecoveredComponentProblemsAfterRender(\n storyboardId,\n );\n const pendingWaiters = pendingRenderWaitersRef.current.get(storyboardId);\n if (!pendingWaiters) return;\n pendingRenderWaitersRef.current.delete(storyboardId);\n for (const waiter of pendingWaiters) {\n waiter.resolve();\n }\n }, []);\n\n const markStoryboardUnmounted = useCallback(\n (storyboardId: string) => {\n queueMicrotask(() => {\n const remounted = [\n ...document.querySelectorAll(\"[data-render-id]\"),\n ].some(\n (element) => element.getAttribute(\"data-render-id\") === storyboardId,\n );\n if (remounted) return;\n renderedRenderIdsRef.current.delete(storyboardId);\n\n // Keep the consumer's logical request, but detach its DOM observer from\n // the removed slot. A later real React commit wakes the establishment\n // effect and binds the same request to the replacement DOM.\n for (const request of watchRequestsRef.current.values()) {\n if (request.request.renderId === storyboardId) {\n suspendEstablishedWatch(request);\n }\n }\n\n const pendingWaiters =\n pendingRenderWaitersRef.current.get(storyboardId);\n if (!pendingWaiters) return;\n pendingRenderWaitersRef.current.delete(storyboardId);\n const error = new Error(\n `Storyboard ${JSON.stringify(storyboardId)} unmounted before its requested render committed`,\n );\n for (const waiter of pendingWaiters) {\n waiter.reject(error);\n }\n });\n },\n [suspendEstablishedWatch],\n );\n\n const reportStoryboardError = useCallback(\n (storyboardId: string, error: CanvasHostRuntimeError) => {\n renderedRenderIdsRef.current.delete(storyboardId);\n problemTrackerRef.current.reportComponentProblem(\n storyboardId,\n \"render-error-boundary\",\n error.message,\n {\n stack: error.stack,\n componentStack: error.componentStack,\n },\n );\n const renderError = new Error(error.message);\n const pendingWaiters = pendingRenderWaitersRef.current.get(storyboardId);\n if (pendingWaiters) {\n pendingRenderWaitersRef.current.delete(storyboardId);\n for (const waiter of pendingWaiters) {\n waiter.reject(renderError);\n }\n }\n\n for (const request of watchRequestsRef.current.values()) {\n if (\n request.request.renderId !== storyboardId ||\n request.establishment.status === \"failed\"\n ) {\n continue;\n }\n if (request.establishment.status === \"pending\") {\n rejectWatchEstablishment(request, renderError);\n void removeWatchRequest(request.watchId, renderError);\n } else {\n postWatchError(request, renderError);\n // A render failure invalidates the observer's DOM root, not the\n // consumer's subscription. Park the observer and let the next\n // successful React commit re-establish this same logical watch.\n suspendEstablishedWatch(request);\n }\n }\n },\n [removeWatchRequest, suspendEstablishedWatch],\n );\n\n const clearStoryboardError = useCallback((storyboardId: string) => {\n problemTrackerRef.current.clearComponentProblem(storyboardId, [\n \"render-error-boundary\",\n ]);\n }, []);\n\n const reportCanvasImportError = useCallback(\n (canvasPath: string, error: CanvasHostRuntimeError) => {\n const normalizedPath = canvasPath.trim();\n if (!normalizedPath) return;\n problemTrackerRef.current.reportCanvasProblem(\n normalizedPath,\n \"runtime-bootstrap\",\n error.message,\n {\n stack: error.stack,\n componentStack: error.componentStack,\n filename: normalizedPath,\n },\n );\n // A failed canvas never registers a storyboard, so its render waiter\n // cannot resolve or receive a storyboard error boundary notification.\n for (const pin of sourcePinsRef.current.values()) {\n if (pin.canvasPath === normalizedPath)\n pin.cancel(new Error(error.message));\n }\n },\n [],\n );\n\n const clearCanvasImportError = useCallback((canvasPath: string) => {\n const normalizedPath = canvasPath.trim();\n if (!normalizedPath) return;\n problemTrackerRef.current.clearCanvasProblem(normalizedPath, [\n \"runtime-bootstrap\",\n ]);\n }, []);\n\n const registerCanvasProblemScope = useCallback(\n (canvasPath: string) =>\n problemTrackerRef.current.registerCanvasPath(canvasPath),\n [],\n );\n\n useEffect(\n () => () => {\n problemTrackerRef.current.dispose();\n },\n [],\n );\n\n // Subscribe before child passive effects can fail and race a source repair.\n useLayoutEffect(() => {\n if (typeof window === \"undefined\") return;\n const stopRuntimeProblemTracking = installCanvasHostRuntimeProblemTracking(\n problemTrackerRef.current,\n );\n return () => {\n stopRuntimeProblemTracking();\n };\n }, []);\n\n // `markStoryboardRendered` mutates a ref and advances this version state. The\n // version is intentionally a dependency: it re-runs watch establishment once\n // React commits the requested render slot.\n // biome-ignore lint/correctness/useExhaustiveDependencies: renderCommitVersionById is the ref-mutation signal described above.\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n\n const activeWatchIds = new Set(watchRequestsById.keys());\n\n for (const watchId of watchesRef.current.keys()) {\n if (!activeWatchIds.has(watchId)) {\n void stopRuntimeWatch(watchId);\n }\n }\n\n for (const request of watchRequestsById.values()) {\n if (request.establishment.status === \"failed\") continue;\n const renderEntry = renderEntriesById.get(request.request.renderId);\n const renderReady =\n renderEntry?.status === \"active\" &&\n renderedRenderIdsRef.current.has(request.request.renderId) &&\n renderRequestTargetsEntry(renderEntry, request.request);\n if (!renderReady) continue;\n\n const existing = watchesRef.current.get(request.watchId);\n if (\n existing?.bindingKey === request.bindingKey &&\n existing.establishment === request.establishment\n ) {\n const currentRequest = watchRequestsRef.current.get(request.watchId);\n if (currentRequest?.establishment !== request.establishment) continue;\n if (currentRequest.paused) setRuntimeWatchPaused(existing.watch, true);\n acknowledgeWatchEstablishment(currentRequest);\n continue;\n }\n\n // A viewport capture can register a logical watch while the shared host\n // is intentionally paused. Do not construct an observer that emits its\n // initial snapshot before pause can be applied; the resume transition\n // updates this request and wakes the effect.\n if (!existing && request.paused) continue;\n\n const starting = startingWatchesRef.current.get(request.watchId);\n if (\n starting?.bindingKey === request.bindingKey &&\n starting.establishment === request.establishment\n ) {\n continue;\n }\n const startToken = {\n bindingKey: request.bindingKey,\n establishment: request.establishment,\n };\n startingWatchesRef.current.set(request.watchId, startToken);\n\n void (async () => {\n if (existing) {\n await stopRuntimeWatch(request.watchId, existing.establishment);\n }\n\n const onUpdate = (capture: unknown) => {\n const currentRequest = watchRequestsRef.current.get(request.watchId);\n if (\n currentRequest?.establishment !== request.establishment ||\n currentRequest.establishment.status === \"failed\"\n ) {\n return;\n }\n legacyHealthRef.current.recordSourceAnnotatedCommit(\n request.request.renderId,\n );\n postToMessageSource(\n request.source,\n {\n type: \"render-pool:watch-update\",\n requestId: request.requestId,\n watchId: request.watchId,\n command: request.commandType,\n payload: { capture },\n },\n request.targetOrigin,\n );\n };\n const onError = (error: Error) => {\n const currentRequest = watchRequestsRef.current.get(request.watchId);\n if (currentRequest?.establishment !== request.establishment) return;\n if (currentRequest.establishment.status === \"pending\") {\n rejectWatchEstablishment(currentRequest, error);\n void removeWatchRequest(request.watchId, error);\n return;\n }\n postWatchError(request, error);\n };\n const common = {\n onUpdate,\n onError,\n debounceDelay: readOptionalNumber(request.payload, \"debounceDelay\"),\n maxWait: readOptionalNumber(request.payload, \"maxWait\"),\n timeout: readOptionalNumber(request.payload, \"timeout\"),\n };\n const watch =\n request.commandType === \"render-pool:watch-html\"\n ? await watchStoryboardHtml(request.request.renderId, common)\n : await watchStoryboardCombined(request.request.renderId, {\n ...common,\n fiberSelector:\n typeof request.payload.fiberSelector === \"string\"\n ? request.payload.fiberSelector\n : undefined,\n fiberTags: Array.isArray(request.payload.fiberTags)\n ? request.payload.fiberTags\n : undefined,\n knownSourceVersion:\n typeof request.payload.knownSourceVersion === \"object\" &&\n request.payload.knownSourceVersion !== null\n ? request.payload.knownSourceVersion\n : undefined,\n });\n\n const currentRequest = watchRequestsRef.current.get(request.watchId);\n if (\n currentRequest?.establishment !== request.establishment ||\n currentRequest.establishment.status === \"failed\"\n ) {\n await watch.stop();\n return;\n }\n\n watchesRef.current.set(request.watchId, {\n renderId: request.request.renderId,\n bindingKey: request.bindingKey,\n establishment: request.establishment,\n watch,\n });\n if (currentRequest.paused) {\n setRuntimeWatchPaused(watch, true);\n }\n acknowledgeWatchEstablishment(currentRequest);\n })()\n .catch((caught: unknown) => {\n const currentRequest = watchRequestsRef.current.get(request.watchId);\n if (currentRequest?.establishment !== request.establishment) {\n return;\n }\n const error =\n caught instanceof Error ? caught : new Error(String(caught));\n if (currentRequest.establishment.status === \"pending\") {\n rejectWatchEstablishment(currentRequest, error);\n } else {\n postWatchError(currentRequest, error);\n }\n void removeWatchRequest(request.watchId, error);\n })\n .finally(() => {\n if (startingWatchesRef.current.get(request.watchId) === startToken) {\n startingWatchesRef.current.delete(request.watchId);\n }\n });\n }\n }, [\n renderCommitVersionById,\n renderEntriesById,\n removeWatchRequest,\n stopRuntimeWatch,\n watchRequestsById,\n ]);\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n\n // State probes can reach this listener before its posted ready event.\n // Give both receipts the same identity, renewed on effect/HMR restart.\n runtimeIdRef.current = Array.from(\n crypto.getRandomValues(new Uint32Array(4)),\n ).join(\"-\");\n\n const waitForRenderLease = async (\n request: CanvasHostRenderRequest,\n ): Promise<void> => {\n try {\n await waitForRender(request);\n } catch (caught) {\n releaseRenderLease(request.renderId);\n throw caught;\n }\n };\n\n const withRenderLease = async <Result>(\n request: CanvasHostRenderRequest,\n run: () => Promise<Result>,\n ): Promise<Result> => {\n await waitForRenderLease(request);\n try {\n return await run();\n } finally {\n releaseRenderLease(request.renderId);\n }\n };\n\n const releaseSourcePin = (pinId: string): void => {\n const pin = sourcePinsRef.current.get(pinId);\n if (!pin) return;\n sourcePinsRef.current.delete(pinId);\n pin.cancel(new Error(`Canvas host source pin ${pinId} was cancelled`));\n forgetFreshMount(pin.renderId);\n releaseRenderLease(pin.renderId, false);\n };\n\n const acquireSourcePin = (\n pinId: string,\n request: CanvasHostRenderRequest,\n ) => {\n const existing = sourcePinsRef.current.get(pinId);\n if (existing) {\n if (existing.renderId !== request.renderId)\n throw new Error(\n `Canvas host source pin ${pinId} targets another render`,\n );\n return existing;\n }\n const canvasProblem = problemTrackerRef.current\n .snapshot()\n .canvasProblems.find(\n (entry) => entry.canvasPath === request.canvasPath,\n );\n if (canvasProblem) throw new Error(canvasProblem.problem.message);\n const committed = committedRenderEntriesRef.current.get(request.renderId);\n const alreadyRendered =\n renderedRenderIdsRef.current.has(request.renderId) &&\n (urlPinnedRenderIdRef.current === request.renderId ||\n committed?.status === \"active\");\n let resolve!: () => void;\n let reject!: (error: Error) => void;\n let settled = false;\n const ready = new Promise<void>((resolveReady, rejectReady) => {\n resolve = resolveReady;\n reject = rejectReady;\n });\n const removeWaiter = () => {\n const waiters = pendingRenderWaitersRef.current.get(request.renderId);\n if (!waiters) return;\n const remaining = waiters.filter((candidate) => candidate !== waiter);\n if (remaining.length)\n pendingRenderWaitersRef.current.set(request.renderId, remaining);\n else pendingRenderWaitersRef.current.delete(request.renderId);\n };\n const waiter: PendingRenderWaiter = {\n resolve() {\n if (settled) return;\n settled = true;\n removeWaiter();\n resolve();\n },\n reject(error) {\n if (settled) return;\n settled = true;\n removeWaiter();\n reject(error);\n },\n };\n const pin = {\n renderId: request.renderId,\n canvasPath: request.canvasPath,\n ready,\n cancel: waiter.reject,\n };\n sourcePinsRef.current.set(pinId, pin);\n // Pin before waiting: a watch can leave while the source is rendering.\n // This demand retains its inputs but never applies capture geometry.\n setEntries((entries) => pinRenderSource(entries, request));\n if (alreadyRendered) waiter.resolve();\n else {\n // This pin mounts the board; its first capture waits out the mount.\n noteFreshMount(request.renderId);\n const waiters =\n pendingRenderWaitersRef.current.get(request.renderId) ?? [];\n pendingRenderWaitersRef.current.set(request.renderId, [\n ...waiters,\n waiter,\n ]);\n }\n return pin;\n };\n\n const handleCommand = (\n message: unknown,\n source?: MessageEventSource | null,\n targetOrigin?: string,\n ) => {\n const command = readCanvasHostCommand(message);\n if (!command) return;\n const payload = command.payload;\n\n const post = (response: Record<string, unknown>) =>\n postToMessageSource(source, response, targetOrigin);\n const ack = () =>\n post({\n type: \"render-pool:ack\",\n requestId: command.requestId,\n command: command.type,\n });\n const error = (message: string) =>\n post({\n type: \"render-pool:error\",\n requestId: command.requestId,\n command: command.type,\n error: message,\n });\n const postAsyncError = (caught: unknown) => {\n error(caught instanceof Error ? caught.message : String(caught));\n };\n const postCaptureResult = (renderId: string) => (capture: unknown) => {\n // A successful capture proves the slot's DOM is live right now, which\n // may include source annotations that appeared only after the commit —\n // refresh the legacy health bookkeeping before replying.\n legacyHealthRef.current.recordSourceAnnotatedCommit(renderId);\n post({\n type: \"render-pool:capture-result\",\n requestId: command.requestId,\n command: command.type,\n payload: { capture },\n });\n };\n\n try {\n if (command.type === \"render-pool:pin-render\") {\n const pinId = readPinId(command.type, payload);\n const pin = acquireSourcePin(\n pinId,\n readRenderRequest(command.type, payload),\n );\n void pin.ready\n .then(() => {\n if (sourcePinsRef.current.get(pinId) !== pin)\n throw new Error(\n `Canvas host source pin ${pinId} was cancelled`,\n );\n ack();\n })\n .catch((caught: unknown) => {\n if (sourcePinsRef.current.get(pinId) === pin)\n releaseSourcePin(pinId);\n postAsyncError(caught);\n });\n return;\n }\n\n if (command.type === \"render-pool:unpin-render\") {\n releaseSourcePin(readPinId(command.type, payload));\n ack();\n return;\n }\n\n if (command.type === \"render-pool:capture-image\") {\n const captureOptions: Parameters<typeof captureStoryboardImage>[1] = {\n captureOverflow: payload.captureOverflow === true,\n childSelector:\n typeof payload.childSelector === \"string\"\n ? payload.childSelector\n : undefined,\n overlaySelector:\n typeof payload.overlaySelector === \"string\"\n ? payload.overlaySelector\n : undefined,\n format:\n payload.format === \"jpeg\" || payload.format === \"png\"\n ? payload.format\n : undefined,\n quality: readOptionalNumber(payload, \"quality\"),\n scale: readOptionalNumber(payload, \"scale\"),\n outputPath:\n typeof payload.outputPath === \"string\"\n ? payload.outputPath\n : undefined,\n forceRefresh: payload.forceRefresh === true,\n portalSelectors: Array.isArray(payload.portalSelectors)\n ? payload.portalSelectors.filter(\n (selector): selector is string =>\n typeof selector === \"string\",\n )\n : undefined,\n };\n // A canvas read takes the pixels a mounted board already holds, so\n // it is not a render request: it takes no lease and reads nothing\n // from the payload's size. A lease would write its request into the\n // live entry, and a read queued at a board's old size and run after\n // a resize handed the board its old size back. A board with no entry\n // has no painted canvas, which the read answers as a discard.\n if (payload.fromCanvas === true) {\n const { renderId } = requireRenderTarget(command.type, payload);\n void captureStoryboardImage(renderId, {\n ...captureOptions,\n fromCanvas: true,\n })\n .then(postCaptureResult(renderId))\n .catch(postAsyncError);\n return;\n }\n const request = readRenderRequest(command.type, payload);\n void withRenderLease(request, () =>\n captureStoryboardImage(request.renderId, captureOptions),\n )\n .then(postCaptureResult(request.renderId))\n .catch(postAsyncError);\n return;\n }\n\n if (command.type === \"render-pool:capture-html\") {\n const request = readRenderRequest(command.type, payload);\n void withRenderLease(request, () =>\n captureStoryboardHtml(request.renderId, {\n timeout: readOptionalNumber(payload, \"timeout\"),\n }),\n )\n .then(postCaptureResult(request.renderId))\n .catch(postAsyncError);\n return;\n }\n\n if (command.type === \"render-pool:capture-combined\") {\n const request = readRenderRequest(command.type, payload);\n void withRenderLease(request, () =>\n captureStoryboardCombined(request.renderId, {\n fiberSelector:\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined,\n fiberTags: Array.isArray(payload.fiberTags)\n ? payload.fiberTags\n : undefined,\n timeout: readOptionalNumber(payload, \"timeout\"),\n }),\n )\n .then(postCaptureResult(request.renderId))\n .catch(postAsyncError);\n return;\n }\n\n if (\n command.type === \"render-pool:watch-combined\" ||\n command.type === \"render-pool:watch-html\"\n ) {\n const request = readRenderRequest(command.type, payload);\n const watchId = readWatchId(command.type, payload);\n void removeWatchRequest(watchId)\n .then(() => {\n setEntries((entries) => acquireRender(entries, request));\n const establishment: WatchEstablishment = { status: \"pending\" };\n const watchRequest: WatchRequest = {\n commandType: command.type,\n requestId: command.requestId,\n watchId,\n source,\n targetOrigin,\n request,\n payload,\n paused: payload.paused === true,\n bindingKey: buildWatchBindingKey(command.type, payload),\n establishment,\n };\n updateWatchRequests((requests) => {\n const next = new Map(requests);\n next.set(watchId, watchRequest);\n return next;\n });\n // Registration is the command boundary. Rendering the requested\n // slot and taking its initial capture continue asynchronously;\n // failures on that path use the established watch's error event.\n acknowledgeWatchEstablishment(watchRequest);\n })\n .catch(postAsyncError);\n return;\n }\n\n if (command.type === \"render-pool:unwatch\") {\n const watchId = readWatchId(command.type, payload);\n void removeWatchRequest(watchId).then(ack).catch(postAsyncError);\n return;\n }\n\n if (command.type === \"render-pool:set-watch-paused\") {\n const watchId = readWatchId(command.type, payload);\n const paused = payload.paused === true;\n const watch = watchesRef.current.get(watchId)?.watch;\n if (watch) {\n setRuntimeWatchPaused(\n watch,\n paused,\n paused ? undefined : readWatchResumeOptions(payload),\n );\n }\n updateWatchRequests((requests) => {\n const current = requests.get(watchId);\n if (!current || current.paused === paused) return requests;\n const next = new Map(requests);\n next.set(watchId, { ...current, paused });\n return next;\n });\n ack();\n return;\n }\n\n if (command.type === \"render-pool:register-canvas\") {\n if (\n !registerCanvasRef.current ||\n typeof payload.canvasPath !== \"string\" ||\n !payload.canvasPath.trim() ||\n typeof payload.moduleUrl !== \"string\"\n )\n throw new Error(\"Invalid canvas registration command\");\n void registerCanvasRef\n .current(payload.canvasPath, payload.moduleUrl)\n .then(ack)\n .catch(postAsyncError);\n return;\n }\n\n if (command.type === \"render-pool:list\") {\n post({\n type: \"render-pool:state\",\n requestId: command.requestId,\n payload: buildState(),\n });\n return;\n }\n\n if (command.type === \"render-pool:watch-problems\") {\n const watchId =\n typeof payload.watchId === \"string\" && payload.watchId.trim()\n ? payload.watchId\n : String(command.requestId ?? \"default\");\n problemWatchersRef.current.set(watchId, {\n requestId: command.requestId,\n watchId,\n source,\n targetOrigin,\n });\n ack();\n post({\n type: \"render-pool:problem-snapshot\",\n requestId: command.requestId,\n watchId,\n payload: buildProblemSnapshot(),\n });\n return;\n }\n\n if (command.type === \"render-pool:unwatch-problems\") {\n const watchId =\n typeof payload.watchId === \"string\" && payload.watchId.trim()\n ? payload.watchId\n : String(command.requestId ?? \"default\");\n problemWatchersRef.current.delete(watchId);\n ack();\n return;\n }\n\n // ── Legacy command surface (pre-0.0.20 Tempo clients) ───────────────\n // A workspace's installed tempo-sdk tracks registry `latest`\n // independently of the user's desktop-app update cadence, so an old\n // client keeps driving this host with the previous command set —\n // potentially for weeks, until the force-upgrade floor ages it out\n // (see modules/component-render-pool/canvas-host-command-client.ts in\n // that client). Its storyboard pipeline renders THROUGH these\n // commands, so they must keep functioning, not fail fast. Removable in\n // a later major.\n\n if (command.type === \"render-pool:query-problems\") {\n // Same snapshot payload the retained watch-problems path emits, so\n // the old client's problem poll resolves with real data.\n post({\n type: \"render-pool:problem-snapshot\",\n requestId: command.requestId,\n payload: buildProblemSnapshot(),\n });\n return;\n }\n\n if (command.type === \"render-pool:render\") {\n const request = readRenderRequest(command.type, payload);\n void waitForRenderLease(request).then(ack).catch(postAsyncError);\n return;\n }\n\n if (command.type === \"render-pool:unrender\") {\n const target = requireRenderTarget(command.type, payload);\n releaseRenderLease(\n target.renderId,\n typeof payload.cacheWhenIdle === \"boolean\"\n ? payload.cacheWhenIdle\n : undefined,\n );\n ack();\n return;\n }\n\n if (command.type === \"render-pool:capture-static-html\") {\n const request = readRenderRequest(command.type, payload);\n void withRenderLease(request, () =>\n captureStoryboardStaticHtml(request.renderId, {\n timeout: readOptionalNumber(payload, \"timeout\"),\n }),\n )\n .then(postCaptureResult(request.renderId))\n .catch(postAsyncError);\n return;\n }\n\n if (command.type === \"render-pool:set-cache-limit\") {\n if (\n typeof payload.maxCached === \"number\" &&\n Number.isInteger(payload.maxCached)\n ) {\n maxCachedRef.current = Math.max(0, payload.maxCached);\n }\n setEntries((entries) =>\n evictCachedRenders(entries, maxCachedRef.current),\n );\n ack();\n return;\n }\n\n if (command.type === \"render-pool:isolate\") {\n applyLegacyRenderIsolation(\n resolveRenderTarget(payload)?.renderId ?? null,\n );\n ack();\n return;\n }\n\n if (command.type === \"render-pool:query-health\") {\n // The old client gives this probe a 500ms budget, resolves a dead\n // snapshot on timeout, and treats \"dead\" as a fatal host mount that\n // reload-loops the frame — the reply must stay synchronous, never\n // behind a render lease or async boundary.\n const renderId = resolveRenderTarget(payload)?.renderId ?? \"\";\n post({\n type: \"render-pool:health-snapshot\",\n requestId: command.requestId,\n snapshot: legacyHealthRef.current.buildSnapshot(renderId, {\n hasRenderEntries: renderEntriesRef.current.size > 0,\n claimErrorBoundaryTripped:\n problemTrackerRef.current.hasComponentProblem(renderId),\n }),\n });\n return;\n }\n\n // No fallback reply for anything unrecognized: the host's own\n // outbound messages loop back through this same window \"message\"\n // listener, so answering arbitrary types would echo forever.\n } catch (caught) {\n postAsyncError(caught);\n }\n };\n\n const onMessage = (event: MessageEvent) =>\n handleCommand(event.data, event.source, event.origin);\n const onBridgeCommand = (event: Event) =>\n handleCommand(event instanceof CustomEvent ? event.detail : undefined);\n\n window.addEventListener(\"message\", onMessage);\n window.addEventListener(\"__render-pool:command\", onBridgeCommand);\n const stopProblemPublisher = problemTrackerRef.current.watch(\n publishProblemSnapshot,\n );\n window.postMessage(\n { type: \"render-pool:ready\", runtimeId: runtimeIdRef.current },\n \"*\",\n );\n\n return () => {\n window.removeEventListener(\"message\", onMessage);\n window.removeEventListener(\"__render-pool:command\", onBridgeCommand);\n stopProblemPublisher();\n // An effect restart can preserve render state (e.g. React Refresh).\n // Release each demand as well as cancelling its readiness waiter.\n for (const pinId of sourcePinsRef.current.keys()) releaseSourcePin(pinId);\n for (const { watch } of watchesRef.current.values()) {\n void watch.stop();\n }\n watchesRef.current.clear();\n problemWatchersRef.current.clear();\n };\n }, [\n buildProblemSnapshot,\n buildState,\n publishProblemSnapshot,\n releaseRenderLease,\n removeWatchRequest,\n setEntries,\n updateWatchRequests,\n waitForRender,\n ]);\n\n return {\n renderStatusById: useMemo(\n () =>\n (renderStatusRef.current = buildRenderStatusMap(\n renderEntriesById,\n renderStatusRef.current,\n )),\n [renderEntriesById],\n ),\n renderSizeById: useMemo(\n () =>\n (renderSizeRef.current = buildRenderSizeMap(\n renderEntriesById,\n renderSizeRef.current,\n )),\n [renderEntriesById],\n ),\n markStoryboardRendered,\n markStoryboardUnmounted,\n reportStoryboardError,\n clearStoryboardError,\n reportCanvasImportError,\n clearCanvasImportError,\n registerCanvasProblemScope,\n };\n}\n\nfunction buildWatchBindingKey(\n commandType: string,\n payload: Record<string, unknown>,\n): string {\n try {\n return JSON.stringify({ commandType, payload });\n } catch {\n return `${commandType}:${Date.now()}`;\n }\n}\n","/**\n * Typed capture-discard channel.\n *\n * A `capture-selector` rejection has to survive a hop through the version-\n * skewed tempo-sdk boundary, where it travels as an Error MESSAGE STRING only\n * (`use-canvas-host-postmessage.ts` `postAsyncError` →\n * `canvas-host-command-client.ts` rejection): the Error subclass and its\n * fields do not cross that boundary, so the TOKEN embedded in the message is\n * the actual cross-boundary contract. Consumers recover the code by running\n * `parseCaptureDiscardCode` over the received message —\n * `tempo-modules/static-canvas-capture` imports the parser directly from this\n * module (across the package boundary), so the token stays a single source of\n * truth rather than a literal duplicated at each end. What the parser works\n * around is the lost Error class IDENTITY (an `instanceof` check can't survive\n * the hops), not any inability to share the token itself. tempo-sdk bundles\n * this file to spell `content_unavailable` from the page, so it must stay\n * dependency-free.\n */\n\n/** Discard codes. Every one means the capture could not be proven at this\n * instant. All but `content_unavailable` are transient and the caller's\n * retry ladder should re-run them; `content_unavailable` is the page saying\n * the storyboard has nothing to photograph for an unknown time (it holds\n * the unavailable marker, `PROJECTION_UNAVAILABLE_ATTRIBUTE`), so an\n * immediate retry sees the same answer and the caller waits for the\n * content to change instead. */\nexport type CaptureDiscardCode =\n | \"compositor_starved\"\n | \"capture_surface_budget_drift\"\n | \"degenerate_capture\"\n | \"isolation_violated\"\n | \"cdp_unresponsive\"\n | \"route_mismatch\"\n | \"content_changed\"\n | \"content_unavailable\";\n\n/** The literal the token is spelled as in a rejection message. Consumers on\n * the far side of the postMessage boundary match on this prefix. */\nexport function formatCaptureDiscardToken(code: CaptureDiscardCode): string {\n return `[frame-pool-capture:${code}]`;\n}\n\nconst TOKEN_PATTERN = /\\[frame-pool-capture:([a-z_]+)\\]/;\n\nconst KNOWN_CODES: ReadonlySet<string> = new Set<CaptureDiscardCode>([\n \"compositor_starved\",\n \"capture_surface_budget_drift\",\n \"degenerate_capture\",\n \"isolation_violated\",\n \"cdp_unresponsive\",\n \"route_mismatch\",\n \"content_changed\",\n \"content_unavailable\",\n]);\n\n/** Recover the discard code from a rejection message, or `null` if the message\n * carries no (recognized) capture-discard token. Same-process consumers use\n * this; cross-boundary consumers may match the token prefix textually. */\nexport function parseCaptureDiscardCode(\n message: string,\n): CaptureDiscardCode | null {\n const match = TOKEN_PATTERN.exec(message);\n if (!match) return null;\n const code = match[1];\n return code && KNOWN_CODES.has(code) ? (code as CaptureDiscardCode) : null;\n}\n\n/**\n * A capture that could not be PROVEN — the pixels are unavailable or untrusted,\n * as distinct from \"no capturable element\" (which stays a `null` return). The\n * message is prefixed with the token so it self-describes after the Error\n * identity is lost across the IPC/postMessage hops.\n */\nexport class CaptureDiscardedError extends Error {\n readonly code: CaptureDiscardCode;\n\n constructor(code: CaptureDiscardCode, detail?: string) {\n const token = formatCaptureDiscardToken(code);\n super(detail ? `${token} ${detail}` : token);\n this.name = \"CaptureDiscardedError\";\n this.code = code;\n }\n}\n","export type CanvasHostCaptureResult = {\n img: {\n src: string;\n width: number;\n height: number;\n paintInsets?: { top: number; right: number; bottom: number; left: number };\n /** The capture is fully transparent — the storyboard rendered nothing\n * visible. Reported by hosts that scan the decoded bitmap; absent means\n * the host did not answer, never that content was found. */\n contentEmpty?: boolean;\n };\n timing?: Record<string, number>;\n};\n\nexport type CanvasHostWatchResumeOptions = {\n flush?: \"always\" | \"if-dirty\" | \"never\";\n triggers?: readonly \"viewport-capture\"[];\n};\n\nexport type CanvasHostWatch = {\n stop(): void | Promise<void>;\n pause?(): void;\n resume?(options?: CanvasHostWatchResumeOptions): void;\n setPaused?(paused: boolean, options?: CanvasHostWatchResumeOptions): void;\n};\n\nexport type CanvasHostRuntime = {\n captureSelector(\n selector: string,\n options?: {\n captureOverflow?: boolean;\n overlaySelector?: string;\n format?: \"jpeg\" | \"png\";\n quality?: number;\n scale?: number;\n outputPath?: string;\n forceRefresh?: boolean;\n portalSelectors?: string[];\n },\n ): Promise<CanvasHostCaptureResult | null>;\n /** One canvas's backing store, read where it is: no resize of the host,\n * no compositor frame. Absent in desktop apps older than it. */\n captureCanvas?(\n selector: string,\n options?: {\n format?: \"jpeg\" | \"png\";\n quality?: number;\n outputPath?: string;\n },\n ): Promise<CanvasHostCaptureResult | null>;\n captureHtml?(options?: {\n selector?: string;\n timeout?: number;\n }): Promise<unknown | null>;\n // Only runtimes installed by pre-0.0.20 Tempo clients implement\n // captureStaticHtml/watchHtml; the current client never calls them. Kept for\n // the legacy command surface (see canvas-host-legacy-compat.ts).\n captureStaticHtml?(options?: {\n selector?: string;\n timeout?: number;\n }): Promise<unknown | null>;\n captureCombined?(options?: {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: unknown[];\n timeout?: number;\n }): Promise<unknown | null>;\n watchHtml?(options: {\n selector?: string;\n onUpdate(capture: unknown): void;\n onError?(error: Error): void;\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n }): Promise<CanvasHostWatch>;\n watchCombined?(options: {\n selector?: string;\n fiberSelector?: string;\n onUpdate(capture: unknown): void;\n onError?(error: Error): void;\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n fiberTags?: unknown[];\n // Sent by pre-0.0.20 clients so an old runtime can skip re-emitting a\n // capture the client already holds; new runtimes may ignore it.\n knownSourceVersion?: unknown;\n }): Promise<CanvasHostWatch>;\n};\n\ndeclare global {\n interface Window {\n __tempoCanvasHostRuntime?: CanvasHostRuntime;\n }\n}\n\nexport function getCanvasHostRuntime(): CanvasHostRuntime {\n const runtime = window.__tempoCanvasHostRuntime;\n if (!runtime) {\n throw new Error(\"window.__tempoCanvasHostRuntime is not installed.\");\n }\n return runtime;\n}\n\nexport function getOptionalCanvasHostRuntime(): CanvasHostRuntime | undefined {\n return typeof window === \"undefined\"\n ? undefined\n : window.__tempoCanvasHostRuntime;\n}\n","import {\n isProjectionUnavailableOnly,\n PROJECTION_PENDING_ATTRIBUTE,\n} from \"../../../modules/iframe-projection/combined/projection-pending\";\nimport { formatCaptureDiscardToken } from \"../../../modules/frame-pool/capture-discard\";\nimport {\n type CanvasHostCaptureResult,\n type CanvasHostRuntime,\n type CanvasHostWatch,\n getCanvasHostRuntime,\n} from \"./canvas-host-runtime\";\nimport { getStoryboardPortalSelectors } from \"./portal-tracking\";\n\nconst escapeRenderId = (renderId: string): string =>\n renderId.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n\nexport const buildRenderSelector = (renderId: string): string =>\n `[data-render-id=\"${escapeRenderId(renderId)}\"]`;\n\nexport const buildRenderContentSelector = (renderId: string): string =>\n `[data-render-content=\"${escapeRenderId(renderId)}\"]`;\n\nexport const buildRenderContentFiberSelector = (renderId: string): string =>\n [\n `${buildRenderContentSelector(renderId)} > :not([data-tempo-hide-fiber=\"true\"])`,\n `${buildRenderContentSelector(renderId)}:not(:has(> *))`,\n ].join(\", \");\n\ntype DomCaptureLike = {\n dom?: {\n selector?: string;\n attributes?: Record<string, unknown>;\n rootAttributes?: Record<string, unknown>;\n };\n};\n\nexport function stripRenderContentWrapperAttributes<T>(\n capture: T,\n renderId: string,\n): T {\n if (!capture || typeof capture !== \"object\") return capture;\n const dom = (capture as DomCaptureLike).dom;\n if (!dom) return capture;\n\n const shouldStripAttributes =\n dom.selector === \"\" && dom.attributes?.[\"data-render-content\"] === renderId;\n const shouldStripRootAttributes =\n dom.rootAttributes?.[\"data-render-content\"] === renderId;\n\n if (!shouldStripAttributes && !shouldStripRootAttributes) return capture;\n\n return {\n ...capture,\n dom: {\n ...dom,\n attributes: shouldStripAttributes ? undefined : dom.attributes,\n rootAttributes: shouldStripRootAttributes\n ? undefined\n : dom.rootAttributes,\n },\n };\n}\n\nexport function stripRenderContentWrapperFromCombinedCapture<T>(\n capture: T,\n renderId: string,\n): T {\n if (!capture || typeof capture !== \"object\" || !(\"html\" in capture)) {\n return capture;\n }\n const html = (capture as { html?: unknown }).html;\n if (!html) return capture;\n return {\n ...capture,\n html: stripRenderContentWrapperAttributes(html, renderId),\n };\n}\n\nconst nextAnimationFrame = (): Promise<void> =>\n new Promise((resolve) => {\n requestAnimationFrame(() => resolve());\n });\n\n/** Marks the canvas whose backing store is its storyboard's whole image (a\n * Flutter view's relay): a capture of such a board reads that canvas where\n * it is (`fromCanvas`). */\nexport const CAPTURE_CANVAS_ATTRIBUTE = \"data-tempo-capture-canvas\";\n\nconst contentUnavailable = (renderId: string, why: string): Error =>\n new Error(\n `${formatCaptureDiscardToken(\"content_unavailable\")} storyboard ${renderId} ${why}`,\n );\n\nexport async function captureStoryboardImage(\n renderId: string,\n options?: Parameters<CanvasHostRuntime[\"captureSelector\"]>[1] & {\n /** Capture a single descendant of the storyboard's render root instead of\n * the root — composed as `<renderRoot> <childSelector>`, so it can only\n * ever match inside this storyboard's slot. */\n childSelector?: string;\n /** Read the storyboard's capture canvas where it is instead of\n * photographing its element: no resize, no compositor frame, and no\n * render lease, so the read never changes what the board renders. */\n fromCanvas?: boolean;\n },\n): Promise<CanvasHostCaptureResult | null> {\n if (options?.fromCanvas) return captureStoryboardCanvas(renderId, options);\n const portalSelectors = [\n ...(options?.portalSelectors ?? []),\n ...getStoryboardPortalSelectors(renderId),\n ];\n\n const renderSelector = buildRenderSelector(renderId);\n const { childSelector, ...captureOptions } = options ?? {};\n const captureSelector = childSelector\n ? `${renderSelector} ${childSelector}`\n : renderSelector;\n\n // The renderer resizes the shared host before issuing this command. Let\n // resize observers, responsive React state, and their committed DOM reach a\n // paint boundary while host watches remain paused. The second frame covers\n // passive effects scheduled by the first paint; the catch-up watch capture\n // is tagged when the renderer resumes it after this command returns.\n await nextAnimationFrame();\n await nextAnimationFrame();\n\n // A storyboard showing only the unavailable marker (a Flutter board while\n // `flutter run` compiles) has nothing to photograph, and a photograph of\n // it would be a blank the canvas then shows as the board. The typed\n // discard keeps no image and tells the caller to wait for the content to\n // change; it never holds the capture lane. Same element and rule the\n // producer uses to report the root `unavailable`.\n const content = document.querySelector(buildRenderContentSelector(renderId));\n if (content && isProjectionUnavailableOnly(content)) {\n throw contentUnavailable(renderId, \"has no content to photograph yet\");\n }\n\n return await getCanvasHostRuntime().captureSelector(\n captureSelector,\n portalSelectors.length > 0\n ? { ...captureOptions, portalSelectors: [...new Set(portalSelectors)] }\n : captureOptions,\n );\n}\n\n/**\n * The image of a storyboard whose pixels one canvas already holds, read in\n * this document: the projection host keeps every mounted board painting,\n * so this needs no second document and never resizes the shared host. Only\n * painted pixels are an image of the board. While Flutter starts or its\n * engine boots the board shows a marker and no view; a failed board has no\n * canvas. Each answers the typed discard at once, keeping no image, and the\n * capture loop backs off and asks again.\n */\nasync function captureStoryboardCanvas(\n renderId: string,\n options: {\n format?: \"jpeg\" | \"png\";\n quality?: number;\n outputPath?: string;\n },\n): Promise<CanvasHostCaptureResult | null> {\n const contentSelector = buildRenderContentSelector(renderId);\n const content = document.querySelector(contentSelector);\n const canvasSelector = `${contentSelector} canvas[${CAPTURE_CANVAS_ATTRIBUTE}]`;\n const painted =\n content !== null &&\n content.querySelector(`canvas[${CAPTURE_CANVAS_ATTRIBUTE}]`) !== null &&\n content.querySelector(`[${PROJECTION_PENDING_ATTRIBUTE}]`) === null &&\n !isProjectionUnavailableOnly(content);\n if (!painted) throw contentUnavailable(renderId, \"has no painted canvas yet\");\n const runtime = getCanvasHostRuntime();\n if (!runtime.captureCanvas) {\n throw new Error(\n \"This Tempo app cannot read a storyboard's canvas; update Tempo to capture this board.\",\n );\n }\n return await runtime.captureCanvas(canvasSelector, {\n format: options.format,\n quality: options.quality,\n outputPath: options.outputPath,\n });\n}\n\nexport async function captureStoryboardHtml(\n renderId: string,\n options?: { timeout?: number },\n): Promise<unknown | null> {\n const capture = await getCanvasHostRuntime().captureHtml?.({\n selector: buildRenderContentSelector(renderId),\n timeout: options?.timeout,\n });\n return capture\n ? stripRenderContentWrapperAttributes(capture, renderId)\n : null;\n}\n\n// Pre-0.0.20 clients only; their installed runtime implements\n// captureStaticHtml. See canvas-host-legacy-compat.ts.\nexport function captureStoryboardStaticHtml(\n renderId: string,\n options?: { timeout?: number },\n): Promise<unknown | null> {\n return (\n getCanvasHostRuntime().captureStaticHtml?.({\n selector: buildRenderContentSelector(renderId),\n timeout: options?.timeout,\n }) ?? Promise.resolve(null)\n );\n}\n\nexport async function captureStoryboardCombined(\n renderId: string,\n options?: {\n fiberSelector?: string;\n fiberTags?: unknown[];\n timeout?: number;\n },\n): Promise<unknown | null> {\n const capture = await getCanvasHostRuntime().captureCombined?.({\n selector: buildRenderContentSelector(renderId),\n fiberSelector:\n options?.fiberSelector ?? buildRenderContentFiberSelector(renderId),\n fiberTags: options?.fiberTags,\n timeout: options?.timeout,\n });\n return capture\n ? stripRenderContentWrapperFromCombinedCapture(capture, renderId)\n : null;\n}\n\n// Pre-0.0.20 clients only; their installed runtime implements watchHtml. See\n// canvas-host-legacy-compat.ts.\nexport function watchStoryboardHtml(\n renderId: string,\n options: {\n onUpdate(capture: unknown): void;\n onError?(error: Error): void;\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n },\n): Promise<CanvasHostWatch> {\n const runtime = getCanvasHostRuntime();\n if (!runtime.watchHtml) {\n return Promise.reject(new Error(\"watchHtml is not available.\"));\n }\n return runtime.watchHtml({\n selector: buildRenderContentSelector(renderId),\n onUpdate(capture) {\n options.onUpdate(stripRenderContentWrapperAttributes(capture, renderId));\n },\n onError: options.onError,\n debounceDelay: options.debounceDelay,\n maxWait: options.maxWait,\n timeout: options.timeout,\n });\n}\n\nexport function watchStoryboardCombined(\n renderId: string,\n options: {\n onUpdate(capture: unknown): void;\n onError?(error: Error): void;\n fiberSelector?: string;\n fiberTags?: unknown[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n knownSourceVersion?: unknown;\n },\n): Promise<CanvasHostWatch> {\n const runtime = getCanvasHostRuntime();\n if (!runtime.watchCombined) {\n return Promise.reject(new Error(\"watchCombined is not available.\"));\n }\n return runtime.watchCombined({\n selector: buildRenderContentSelector(renderId),\n fiberSelector:\n options.fiberSelector ?? buildRenderContentFiberSelector(renderId),\n fiberTags: options.fiberTags,\n onUpdate(capture) {\n options.onUpdate(\n stripRenderContentWrapperFromCombinedCapture(capture, renderId),\n );\n },\n onError: options.onError,\n debounceDelay: options.debounceDelay,\n maxWait: options.maxWait,\n timeout: options.timeout,\n knownSourceVersion: options.knownSourceVersion,\n });\n}\n","import { buildRenderContentSelector } from \"./canvas-host-operations\";\n\n// Deprecated skew-window surface. A workspace's installed tempo-sdk tracks\n// registry `latest` independently of the user's desktop-app update cadence, so\n// a Tempo client older than this SDK keeps driving new hosts — potentially for\n// weeks — with the pre-0.0.20 render-pool command set\n// (modules/component-render-pool/canvas-host-command-client.ts in that\n// client). This module carries the state those commands need beyond the\n// current host paths: the commit-time bookkeeping behind\n// `render-pool:query-health` and the `render-pool:isolate` stylesheet.\n// Removable in a later major, once the desktop-app force-upgrade floor has\n// aged the old command set out.\n\nexport type LegacyHostHealth = {\n recordRenderCommit(renderId: string): void;\n recordSourceAnnotatedCommit(renderId: string): void;\n forgetRender(renderId: string): void;\n buildSnapshot(\n renderId: string,\n context: {\n hasRenderEntries: boolean;\n claimErrorBoundaryTripped: boolean;\n },\n ): Record<string, unknown>;\n};\n\n// The old client's error-clear watchdog reads these annotation attributes to\n// decide whether a render slot committed real Tempo-annotated content (vs. an\n// empty or fallback commit) after its last recorded failure.\nconst sourceAnnotationSelector =\n \"[data-tempo-source-file], [data-tempo-source-loc], [data-tempo-filepath], [data-tempo-html-filepath]\";\n\nfunction getObservedSourceFiles(slot: Element | null): string[] {\n if (!slot) return [];\n return [\n ...new Set(\n [...slot.querySelectorAll(sourceAnnotationSelector)]\n .flatMap((element) => [\n element.getAttribute(\"data-tempo-source-file\"),\n element.getAttribute(\"data-tempo-filepath\"),\n element.getAttribute(\"data-tempo-html-filepath\"),\n element.getAttribute(\"data-tempo-source-loc\"),\n ])\n .filter((file): file is string => Boolean(file)),\n ),\n ];\n}\n\nfunction latestTimestamp(values: ReadonlyMap<string, number>): number | null {\n let latest: number | null = null;\n for (const value of values.values()) {\n latest = latest === null ? value : Math.max(latest, value);\n }\n return latest;\n}\n\nfunction isReactConnected(): boolean {\n const hook = (\n window as unknown as {\n __REACT_DEVTOOLS_GLOBAL_HOOK__?: { renderers?: { size?: number } };\n }\n ).__REACT_DEVTOOLS_GLOBAL_HOOK__;\n return (hook?.renderers?.size ?? 0) > 0;\n}\n\nexport function createLegacyHostHealth(): LegacyHostHealth {\n const renderCommitTimes = new Map<string, number>();\n const sourceAnnotatedCommitTimes = new Map<string, number>();\n\n const recordSourceAnnotatedCommit = (\n renderId: string,\n observedAt = Date.now(),\n ): void => {\n const slot = document.querySelector(buildRenderContentSelector(renderId));\n if (getObservedSourceFiles(slot).length > 0) {\n sourceAnnotatedCommitTimes.set(renderId, observedAt);\n }\n };\n\n return {\n recordRenderCommit(renderId) {\n const committedAt = Date.now();\n renderCommitTimes.set(renderId, committedAt);\n recordSourceAnnotatedCommit(renderId, committedAt);\n },\n recordSourceAnnotatedCommit(renderId) {\n recordSourceAnnotatedCommit(renderId);\n },\n forgetRender(renderId) {\n renderCommitTimes.delete(renderId);\n sourceAnnotatedCommitTimes.delete(renderId);\n },\n buildSnapshot(renderId, context) {\n const slot = renderId\n ? document.querySelector(buildRenderContentSelector(renderId))\n : null;\n const observedSourceFiles = getObservedSourceFiles(slot);\n\n return {\n alive: true,\n reactConnected:\n isReactConnected() ||\n renderCommitTimes.size > 0 ||\n context.hasRenderEntries,\n documentReadyState: document.readyState,\n hasViteOverlayElement:\n document.querySelector(\"vite-error-overlay\") !== null,\n lastHostRenderCommitAt: latestTimestamp(renderCommitTimes),\n lastClaimRenderCommitAt: renderCommitTimes.get(renderId) ?? null,\n lastHostSourceAnnotatedCommitAt: latestTimestamp(\n sourceAnnotatedCommitTimes,\n ),\n lastClaimSourceAnnotatedCommitAt:\n sourceAnnotatedCommitTimes.get(renderId) ?? null,\n renderSlotExists: slot !== null,\n renderSlotHasSourceAnnotatedContent: observedSourceFiles.length > 0,\n renderSlotObservedSourceFiles: observedSourceFiles,\n claimErrorBoundaryTripped: context.claimErrorBoundaryTripped,\n observedAt: Date.now(),\n };\n },\n };\n}\n\n// `render-pool:isolate` hides every render slot except the target so the old\n// client can take clean per-storyboard screenshots. Passing null clears a\n// previous isolation.\nexport function applyLegacyRenderIsolation(renderId: string | null): void {\n document.querySelector(\"[data-render-isolation]\")?.remove();\n if (!renderId) return;\n\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-render-isolation\", \"\");\n const escapedId =\n typeof CSS !== \"undefined\" && typeof CSS.escape === \"function\"\n ? CSS.escape(renderId)\n : renderId;\n style.textContent =\n '[data-render-id]:not([data-render-id=\"' +\n escapedId +\n '\"]) { opacity: 0 !important; pointer-events: none !important; }';\n document.head.appendChild(style);\n}\n","import { getCanvasStoryboardRenderId } from \"./canvas\";\nimport {\n isV1CanvasClient,\n type V1RenderSizeCompat,\n v1RenderRequestSize,\n} from \"./v1-client-compat\";\n\nexport type CanvasHostCommand = {\n type: string;\n requestId?: unknown;\n payload: Record<string, unknown>;\n};\n\nexport type CanvasHostRenderTarget = {\n renderId: string;\n canvasPath?: string;\n storyboardId?: string;\n sourcePaths?: readonly string[];\n};\n\nexport type CanvasHostRenderRequest = CanvasHostRenderTarget &\n V1RenderSizeCompat & {\n userInitiated?: boolean;\n importPath: string;\n importName: string;\n props?: Record<string, unknown>;\n width?: number;\n height?: number;\n };\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function readCanvasHostCommand(\n message: unknown,\n): CanvasHostCommand | null {\n if (!isRecord(message) || typeof message.type !== \"string\") return null;\n return {\n type: message.type,\n requestId: message.requestId,\n payload: isRecord(message.payload) ? message.payload : {},\n };\n}\n\nconst readTrimmedString = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : undefined;\n};\n\nconst readStringArray = (value: unknown): string[] | undefined => {\n if (!Array.isArray(value)) return undefined;\n const values = value\n .map(readTrimmedString)\n .filter((entry): entry is string => entry !== undefined);\n return values.length > 0 ? [...new Set(values)] : undefined;\n};\n\nexport function resolveRenderTarget(\n payload: Record<string, unknown>,\n): CanvasHostRenderTarget | null {\n const explicitRenderId = readTrimmedString(payload.renderId);\n const canvasPath = readTrimmedString(payload.canvasPath);\n const storyboardId = readTrimmedString(payload.storyboardId);\n const sourcePaths = readStringArray(payload.sourcePaths);\n const renderId =\n explicitRenderId ||\n (canvasPath && storyboardId\n ? getCanvasStoryboardRenderId(canvasPath, storyboardId)\n : storyboardId);\n\n return renderId\n ? {\n renderId,\n ...(canvasPath ? { canvasPath } : {}),\n ...(storyboardId ? { storyboardId } : {}),\n ...(sourcePaths ? { sourcePaths } : {}),\n }\n : null;\n}\n\nexport function requireRenderTarget(\n commandType: string,\n payload: Record<string, unknown>,\n): CanvasHostRenderTarget {\n const target = resolveRenderTarget(payload);\n if (!target) {\n throw new Error(\n `${commandType} requires payload.renderId or payload.canvasPath + payload.storyboardId`,\n );\n }\n return target;\n}\n\nconst readPositiveFiniteNumber = (\n value: unknown,\n fieldName: string,\n): number => {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n throw new Error(`${fieldName} must be a positive finite number`);\n }\n return value;\n};\n\nexport function readOptionalNumber(\n payload: Record<string, unknown>,\n fieldName: string,\n): number | undefined {\n return typeof payload[fieldName] === \"number\"\n ? (payload[fieldName] as number)\n : undefined;\n}\n\nfunction readOptionalSize(payload: Record<string, unknown>): {\n width?: number;\n height?: number;\n} {\n const hasWidth = payload.width != null;\n const hasHeight = payload.height != null;\n if (!hasWidth && !hasHeight) return {};\n if (!hasWidth || !hasHeight) {\n throw new Error(\"width and height must be provided together\");\n }\n return {\n width: readPositiveFiniteNumber(payload.width, \"width\"),\n height: readPositiveFiniteNumber(payload.height, \"height\"),\n };\n}\n\nexport function readRenderRequest(\n commandType: string,\n payload: Record<string, unknown>,\n): CanvasHostRenderRequest {\n const target = requireRenderTarget(commandType, payload);\n const importPath = readTrimmedString(payload.importPath);\n const importName = readTrimmedString(payload.importName);\n const props = isRecord(payload.props) ? payload.props : undefined;\n\n return {\n ...target,\n importPath: importPath ?? target.canvasPath ?? target.renderId,\n importName: importName ?? target.storyboardId ?? target.renderId,\n ...(props ? { props } : {}),\n ...(payload.userInitiated === true ? { userInitiated: true } : {}),\n ...readOptionalSize(payload),\n ...(isV1CanvasClient() ? v1RenderRequestSize(payload) : {}),\n };\n}\n\nexport function readWatchId(\n commandType: string,\n payload: Record<string, unknown>,\n): string {\n const watchId = readTrimmedString(payload.watchId);\n if (!watchId) {\n throw new Error(`${commandType} requires payload.watchId`);\n }\n return watchId;\n}\n\nexport function readPinId(\n commandType: string,\n payload: Record<string, unknown>,\n): string {\n const pinId = readTrimmedString(payload.pinId);\n if (!pinId) throw new Error(`${commandType} requires payload.pinId`);\n return pinId;\n}\n","import type { CanvasHostRenderRequest } from \"./canvas-host-protocol\";\nimport { isV1CanvasClient, type V1RenderSizeCompat } from \"./v1-client-compat\";\n\nexport type CanvasHostRenderEntry = CanvasHostRenderRequest & {\n /** A cold capture activates the declared storyboard without owning its size. */\n sourceOnly?: true;\n status: \"active\" | \"cached\";\n activeCount: number;\n revision: number;\n lastInactiveAt?: number;\n lastUsedAt?: number;\n};\n\nexport type CanvasHostRenderSize = V1RenderSizeCompat & {\n width?: number;\n height?: number;\n revision?: number;\n};\n\nexport type CanvasHostRuntimeStatePayload = {\n /** Canvas modules present in this exact host document. This is a runtime\n * receipt, not a copy of the main-process registry: consumers use it to\n * prove a rewritten host wrapper has actually reached the document before\n * attaching storyboard claims. */\n canvasPaths: string[];\n renders: Array<{\n renderId: string;\n importPath: string;\n importName: string;\n props?: Record<string, unknown>;\n width?: number;\n height?: number;\n sourcePaths?: readonly string[];\n status: \"active\" | \"cached\";\n }>;\n maxCached: number;\n};\n\nconst propsMatch = (\n a: Record<string, unknown> | undefined,\n b: Record<string, unknown> | undefined,\n): boolean => JSON.stringify(a ?? {}) === JSON.stringify(b ?? {});\n\nexport function renderRequestMatchesEntry(\n entry: CanvasHostRenderEntry | undefined,\n request: CanvasHostRenderRequest,\n): boolean {\n return (\n entry?.sourceOnly !== true &&\n entry?.importPath === request.importPath &&\n entry.importName === request.importName &&\n entry.width === request.width &&\n entry.height === request.height &&\n (!isV1CanvasClient() || entry.intrinsicSize === request.intrinsicSize) &&\n propsMatch(entry.props, request.props)\n );\n}\n\nexport function renderRequestTargetsEntry(\n entry: CanvasHostRenderEntry | undefined,\n request: CanvasHostRenderRequest,\n): boolean {\n return (\n entry?.importPath === request.importPath &&\n entry.importName === request.importName &&\n propsMatch(entry.props, request.props)\n );\n}\n\nexport function acquireRender(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n request: CanvasHostRenderRequest,\n): Map<string, CanvasHostRenderEntry> {\n const next = new Map(entries);\n const current = next.get(request.renderId);\n const changed = !renderRequestMatchesEntry(current, request);\n next.set(request.renderId, {\n ...request,\n lastUsedAt: request.userInitiated ? Date.now() : current?.lastUsedAt,\n status: \"active\",\n activeCount: (current?.activeCount ?? 0) + 1,\n revision: changed ? (current?.revision ?? 0) + 1 : (current?.revision ?? 1),\n });\n return next;\n}\n\n/** Keep a capture's source alive without assigning capture inputs to it. */\nexport function pinRenderSource(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n request: CanvasHostRenderRequest,\n): Map<string, CanvasHostRenderEntry> {\n const next = new Map(entries);\n const current = next.get(request.renderId);\n if (current) {\n next.set(request.renderId, {\n ...current,\n status: \"active\",\n activeCount: current.activeCount + 1,\n });\n } else {\n const {\n width: _width,\n height: _height,\n intrinsicSize: _intrinsicSize,\n userInitiated: _userInitiated,\n ...source\n } = request;\n next.set(request.renderId, {\n ...source,\n sourceOnly: true,\n status: \"active\",\n activeCount: 1,\n revision: 1,\n });\n }\n return next;\n}\n\nexport function releaseRender(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n renderId: string,\n maxCached: number,\n now = Date.now(),\n cacheWhenIdle?: boolean,\n): ReadonlyMap<string, CanvasHostRenderEntry> {\n const previous = entries.get(renderId);\n if (!previous) return entries;\n const current =\n cacheWhenIdle === true ? { ...previous, lastUsedAt: now } : previous;\n\n const next = new Map(entries);\n const activeCount = Math.max(0, current.activeCount - 1);\n if (activeCount > 0) {\n next.set(renderId, { ...current, activeCount, status: \"active\" });\n return next;\n }\n\n // Background screenshot work need not keep application effects running.\n // Previously used instances remain cached; omission preserves old clients.\n if (cacheWhenIdle === false && current.lastUsedAt === undefined) {\n next.delete(renderId);\n return next;\n }\n next.set(renderId, {\n ...current,\n activeCount: 0,\n status: \"cached\",\n lastInactiveAt: now,\n });\n return evictCachedRenders(next, maxCached);\n}\n\nexport function evictCachedRenders(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n maxCached: number,\n): ReadonlyMap<string, CanvasHostRenderEntry> {\n const cached = [...entries.values()]\n .filter((entry) => entry.status === \"cached\")\n .sort(\n (a, b) =>\n (a.lastUsedAt ?? 0) - (b.lastUsedAt ?? 0) ||\n (a.lastInactiveAt ?? 0) - (b.lastInactiveAt ?? 0),\n );\n const evicted = cached.slice(0, Math.max(0, cached.length - maxCached));\n if (evicted.length === 0) return entries;\n const next = new Map(entries);\n for (const entry of evicted) next.delete(entry.renderId);\n return next;\n}\n\nexport function buildRenderStatePayload(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n maxCached: number,\n canvasPaths: readonly string[] = [],\n): CanvasHostRuntimeStatePayload {\n return {\n canvasPaths: [...canvasPaths],\n renders: [...entries.values()].map(\n ({\n activeCount: _activeCount,\n lastInactiveAt: _lastInactiveAt,\n lastUsedAt: _lastUsedAt,\n userInitiated: _userInitiated,\n revision: _revision,\n sourceOnly: _sourceOnly,\n ...entry\n }) => entry,\n ),\n maxCached,\n };\n}\n\n/** The maps the host renders from keep their identity while their content\n * is unchanged: a lease count moving on an active entry (a capture borrowing\n * a watched render) changes neither, and must not re-render every storyboard\n * through the runtime context. */\nfunction sameMap<T>(\n previous: ReadonlyMap<string, T> | undefined,\n next: ReadonlyMap<string, T>,\n same: (a: T, b: T) => boolean,\n): boolean {\n if (!previous || previous.size !== next.size) return false;\n for (const [id, value] of next) {\n const before = previous.get(id);\n if (before === undefined || !same(before, value)) return false;\n }\n return true;\n}\n\nexport function buildRenderStatusMap(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n previous?: ReadonlyMap<string, \"active\" | \"cached\">,\n): ReadonlyMap<string, \"active\" | \"cached\"> {\n const next = new Map([...entries].map(([id, entry]) => [id, entry.status]));\n return previous && sameMap(previous, next, (a, b) => a === b)\n ? previous\n : next;\n}\n\nexport function buildRenderSizeMap(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n previous?: ReadonlyMap<string, CanvasHostRenderSize>,\n): ReadonlyMap<string, CanvasHostRenderSize> {\n const v1Client = isV1CanvasClient();\n const next = new Map(\n [...entries]\n .filter(([, entry]) => !entry.sourceOnly)\n .map(([id, entry]) => [\n id,\n {\n width: entry.width,\n height: entry.height,\n revision: entry.revision,\n ...(v1Client ? { intrinsicSize: entry.intrinsicSize } : {}),\n },\n ]),\n );\n const sameSize = (a: CanvasHostRenderSize, b: CanvasHostRenderSize) =>\n a.width === b.width &&\n a.height === b.height &&\n a.revision === b.revision &&\n (!v1Client || a.intrinsicSize === b.intrinsicSize);\n return previous && sameMap(previous, next, sameSize) ? previous : next;\n}\n","/**\n * Boards the host mounted for a capture's source pin, by render id, kept on\n * the page's global so the canvas capture preload can read it from the page\n * world. The first capture of such a board waits for a longer quiet window\n * (`runtime/host-capture/source-capture.ts`): a component's mount-time\n * effects and timers run in the few hundred ms after its first commit,\n * which a board already rendered has long passed. No imports, so the\n * preload can take the name without the SDK's canvas modules.\n */\nexport const FRESH_MOUNTS_GLOBAL = \"__tempoCanvasFreshMounts\";\n\nfunction freshMounts(): Set<string> {\n const scope = globalThis as unknown as Record<\n string,\n Set<string> | undefined\n >;\n return (scope[FRESH_MOUNTS_GLOBAL] ??= new Set());\n}\n\nexport function noteFreshMount(renderId: string): void {\n freshMounts().add(renderId);\n}\n\nexport function forgetFreshMount(renderId: string): void {\n freshMounts().delete(renderId);\n}\n","type DiagnosticSourceMatchOptions = {\n /** Explicit root advertised by the rendered Vite document. */\n projectRoot?: string | null;\n /** A declared extensionless JS/TS import may match its resolved filename. */\n allowExtensionlessJsTs?: boolean;\n};\n\n/** Removes diagnostic transport syntax without inferring a project root. */\nfunction normalizeSourceIdentity(value: string): string {\n let normalized = value.trim().replace(/\\\\/g, \"/\");\n const suffixIndex = normalized.search(/[?#]/);\n if (suffixIndex !== -1) normalized = normalized.slice(0, suffixIndex);\n try {\n normalized = decodeURIComponent(normalized);\n } catch {\n // A malformed diagnostic path is still usable as an opaque identity.\n }\n normalized = normalized.replace(/^file:\\/\\//, \"\").replace(/^\\/@fs\\//, \"/\");\n return normalized.replace(/^\\.\\//, \"\").replace(/\\/{2,}/g, \"/\");\n}\n\nfunction distinctSourceIdentities(paths: readonly string[]): string[] {\n return [\n ...new Set(\n paths.map(normalizeSourceIdentity).filter((path) => path.length),\n ),\n ];\n}\n\nfunction normalizeDiagnosticText(value: string): string {\n const normalized = value.replace(/\\\\/g, \"/\");\n try {\n return decodeURIComponent(normalized)\n .replace(/\\bhttps?:\\/\\/[^/\\s)]+/g, \"\")\n .replace(/\\/@fs\\//g, \"/\");\n } catch {\n return normalized\n .replace(/\\bhttps?:\\/\\/[^/\\s)]+/g, \"\")\n .replace(/\\/@fs\\//g, \"/\");\n }\n}\n\nfunction isPathCharacter(value: string): boolean {\n return /[A-Za-z0-9._@+-]/.test(value);\n}\n\nfunction textMentionsPathSuffix(text: string, suffix: string): boolean {\n let fromIndex = 0;\n while (fromIndex < text.length) {\n const index = text.indexOf(suffix, fromIndex);\n if (index < 0) return false;\n const before = index === 0 ? \"\" : text[index - 1];\n const after = text[index + suffix.length] ?? \"\";\n if (\n (before === \"\" || before === \"/\" || !isPathCharacter(before)) &&\n (after === \"\" || !isPathCharacter(after))\n ) {\n return true;\n }\n fromIndex = index + 1;\n }\n return false;\n}\n\nfunction textMentionsExactPath(text: string, path: string): boolean {\n let fromIndex = 0;\n while (fromIndex < text.length) {\n const index = text.indexOf(path, fromIndex);\n if (index < 0) return false;\n const before = index === 0 ? \"\" : text[index - 1];\n const after = text[index + path.length] ?? \"\";\n if (\n (before === \"\" || (before !== \"/\" && !isPathCharacter(before))) &&\n (after === \"\" || (after !== \"/\" && !isPathCharacter(after)))\n ) {\n return true;\n }\n fromIndex = index + 1;\n }\n return false;\n}\n\n// macOS mounts /var and /tmp as symlinks into /private, so tooling that\n// realpaths (Babel, Vite transforms) reports `/private/var/...` for a\n// document whose advertised root is `/var/...` (and vice versa). Both spell\n// the SAME tree, so each rooted alias must exist in both spellings — without\n// this, a diagnostic for one canvas fails rooted attribution entirely and\n// gets misreported host-wide across every sibling canvas.\nfunction projectRootSpellings(projectRoot: string): string[] {\n const spellings = [projectRoot];\n if (/^\\/(?:var|tmp)\\//.test(projectRoot)) {\n spellings.push(`/private${projectRoot}`);\n } else if (/^\\/private\\/(?:var|tmp)\\//.test(projectRoot)) {\n spellings.push(projectRoot.slice(\"/private\".length));\n }\n return spellings;\n}\n\nfunction rootedDiagnosticAliases(\n identityValue: string,\n projectRootValue: string,\n): string[] {\n const identity = normalizeSourceIdentity(identityValue);\n const projectRoot = normalizeSourceIdentity(projectRootValue).replace(\n /\\/+$/,\n \"\",\n );\n if (!identity || !projectRoot) return [];\n\n const roots = projectRootSpellings(projectRoot);\n const rootPrefix = roots.find((root) => identity.startsWith(`${root}/`));\n const relative = rootPrefix\n ? identity.slice(rootPrefix.length + 1)\n : identity.startsWith(\"/\")\n ? identity.slice(1)\n : identity;\n return [\n ...new Set([\n relative,\n `/${relative}`,\n ...roots.map((root) => `${root}/${relative}`),\n ]),\n ];\n}\n\nfunction matchingDiagnosticSegments(text: string, identity: string): number {\n const segments = identity.split(\"/\").filter(Boolean);\n for (let count = segments.length; count >= 2; count -= 1) {\n if (textMentionsPathSuffix(text, segments.slice(-count).join(\"/\"))) {\n return count;\n }\n }\n return 0;\n}\n\n/**\n * Resolves browser/Vite diagnostic text against known problem owners.\n *\n * This is intentionally the only suffix-based source correlation in the SDK:\n * it runs after the candidate owner set is known and returns nothing unless one\n * normalized source identity wins globally. It must not be used for HMR\n * ownership, causality, retry, or recovery decisions.\n */\nexport function resolveUniqueDiagnosticSourceMatches(\n textValue: string,\n candidates: readonly string[],\n options: DiagnosticSourceMatchOptions = {},\n): string[] {\n const text = normalizeDiagnosticText(textValue);\n if (!text) return [];\n\n const projectRoot = options.projectRoot?.trim();\n if (projectRoot) {\n const exactMatches = candidates.filter((candidate) => {\n const aliases = rootedDiagnosticAliases(candidate, projectRoot);\n if (aliases.some((alias) => textMentionsExactPath(text, alias))) {\n return true;\n }\n if (\n !options.allowExtensionlessJsTs ||\n /\\.(?:[cm]?[jt]sx?)$/i.test(normalizeSourceIdentity(candidate))\n ) {\n return false;\n }\n return aliases.some((alias) =>\n [\".js\", \".jsx\", \".ts\", \".tsx\", \".mjs\", \".mts\", \".cjs\", \".cts\"].some(\n (extension) => textMentionsExactPath(text, `${alias}${extension}`),\n ),\n );\n });\n return distinctSourceIdentities(exactMatches).length === 1\n ? exactMatches\n : [];\n }\n\n const evaluated = candidates.map((candidate) => {\n const identity = normalizeSourceIdentity(candidate);\n return {\n candidate,\n identity,\n identitySegments: identity.split(\"/\").filter(Boolean).length,\n matchSegments: matchingDiagnosticSegments(text, identity),\n };\n });\n const pathMatches = evaluated.filter(\n ({ matchSegments }) => matchSegments > 0,\n );\n if (pathMatches.length > 0) {\n const strongest = Math.max(\n ...pathMatches.map(({ matchSegments }) => matchSegments),\n );\n const strongestMatches = pathMatches.filter(\n ({ matchSegments }) => matchSegments === strongest,\n );\n const fullMatches = strongestMatches.filter(\n ({ identitySegments, matchSegments }) =>\n identitySegments === matchSegments,\n );\n const unambiguousMatches =\n fullMatches.length > 0 ? fullMatches : strongestMatches;\n if (\n distinctSourceIdentities(\n unambiguousMatches.map(({ identity }) => identity),\n ).length === 1\n ) {\n return unambiguousMatches.map(({ candidate }) => candidate);\n }\n return [];\n }\n\n const basenameMatches = evaluated.filter(({ identity }) => {\n const basename = identity.split(\"/\").pop() ?? \"\";\n return basename.length > 0 && textMentionsPathSuffix(text, basename);\n });\n return distinctSourceIdentities(\n basenameMatches.map(({ identity }) => identity),\n ).length === 1\n ? basenameMatches.map(({ candidate }) => candidate)\n : [];\n}\n","import {\n type TempoViteErrorFeed,\n type TempoViteServerError,\n VITE_ERROR_FEED_KEY,\n} from \"../vite-error-transport\";\nimport { AdmissionBudgetError } from \"./admission-budget\";\nimport { getCanvasHostRecoveryFeed } from \"./host-recovery-feed\";\nimport { resolveUniqueDiagnosticSourceMatches } from \"./source-identity\";\n\nexport type CanvasHostProblemSourceKind =\n | \"page-error\"\n | \"unhandled-rejection\"\n | \"resource-load\"\n | \"vite-overlay\"\n | \"vite-hmr-error\"\n | \"console-vite-error\"\n | \"vite-ws-disconnect\"\n | \"did-fail-load\"\n | \"render-process-gone\"\n | \"render-process-oom\"\n | \"bridge-disconnect\"\n | \"capture-error\"\n | \"watch-error\"\n | \"timeout\"\n | \"runtime-bootstrap\"\n | \"render-error-boundary\"\n | \"worker-error\";\n\nexport type CanvasHostRuntimeProblem = {\n sourceKind: CanvasHostProblemSourceKind;\n message: string;\n stack?: string;\n componentStack?: string;\n filename?: string;\n line?: number;\n column?: number;\n frameUrl?: string;\n frameId?: number;\n timestamp: number;\n};\n\nexport type CanvasHostProblemSnapshot = {\n hostProblem?: CanvasHostRuntimeProblem;\n componentProblems: Array<{\n renderId: string;\n problem: CanvasHostRuntimeProblem;\n }>;\n // Failures scoped to a whole canvas rather than a single storyboard. A canvas\n // whose module fails to load never registers any storyboard, so it has no\n // renderId to key a component problem on; but reporting host-wide would\n // false-flag the sibling canvases sharing this host. Keying by canvas path\n // lets the renderer surface the error on exactly that canvas's storyboards.\n canvasProblems: Array<{\n canvasPath: string;\n problem: CanvasHostRuntimeProblem;\n }>;\n};\n\nexport class CanvasHostProblemTracker {\n private hostProblem: CanvasHostRuntimeProblem | undefined;\n private hostProblemWasNearRender = false;\n private componentProblems = new Map<string, CanvasHostRuntimeProblem>();\n private canvasProblems = new Map<string, CanvasHostRuntimeProblem>();\n private registeredCanvasPaths = new Map<string, number>();\n private registeredRenderSourcePaths = new Map<string, readonly string[]>();\n private watchers = new Set<() => void>();\n private hostProblemClearedWatchers = new Set<\n (problem: CanvasHostRuntimeProblem) => void\n >();\n private publishedViteProjectionSignature: string | undefined;\n\n snapshot(): CanvasHostProblemSnapshot {\n const componentProblems = new Map(this.componentProblems);\n const canvasProblems = new Map(this.canvasProblems);\n const projectViteProblem = (problem: CanvasHostRuntimeProblem): boolean => {\n const canvasPaths = this.matchingCanvasPaths(problem);\n if (canvasPaths.length > 0) {\n for (const canvasPath of canvasPaths) {\n canvasProblems.set(canvasPath, problem);\n }\n return true;\n }\n\n const renderIds = this.matchingRenderIds(problem);\n if (renderIds.length === 0) return false;\n for (const renderId of renderIds) {\n componentProblems.set(\n renderId,\n this.problemForMatchedRender(problem, renderId),\n );\n }\n return true;\n };\n\n const currentViteOverlay = readCurrentViteOverlay();\n let hostProblem =\n this.hostProblem?.sourceKind === \"vite-overlay\"\n ? undefined\n : this.hostProblem;\n if (\n hostProblem &&\n isViteProblemSourceKind(hostProblem.sourceKind) &&\n projectViteProblem(hostProblem)\n ) {\n hostProblem = undefined;\n }\n if (\n hostProblem &&\n (this.hostProblemWasNearRender ||\n isNearRenderProblemSourceKind(hostProblem.sourceKind)) &&\n projectViteProblem(hostProblem)\n ) {\n hostProblem = undefined;\n }\n if (currentViteOverlay && !projectViteProblem(currentViteOverlay)) {\n hostProblem = currentViteOverlay;\n }\n\n return {\n hostProblem,\n componentProblems: [...componentProblems].map(([renderId, problem]) => ({\n renderId,\n problem,\n })),\n canvasProblems: [...canvasProblems].map(([canvasPath, problem]) => ({\n canvasPath,\n problem,\n })),\n };\n }\n\n watch(callback: () => void): () => void {\n this.watchers.add(callback);\n return () => {\n this.watchers.delete(callback);\n };\n }\n\n watchHostProblemCleared(\n callback: (problem: CanvasHostRuntimeProblem) => void,\n ): () => void {\n this.hostProblemClearedWatchers.add(callback);\n return () => {\n this.hostProblemClearedWatchers.delete(callback);\n };\n }\n\n reportHostProblem(\n sourceKind: CanvasHostProblemSourceKind,\n error: unknown,\n details: Partial<CanvasHostRuntimeProblem> = {},\n ): void {\n this.hostProblem = createProblem(sourceKind, error, details);\n this.hostProblemWasNearRender = false;\n this.publish();\n }\n\n reportProblemNearRender(\n sourceKind: CanvasHostProblemSourceKind,\n error: unknown,\n details: Partial<CanvasHostRuntimeProblem> = {},\n ): void {\n const problem = createProblem(sourceKind, error, details);\n const renderIds = this.matchingRenderIds(problem);\n if (renderIds.length > 0) {\n for (const renderId of renderIds) {\n this.componentProblems.set(\n renderId,\n this.problemForMatchedRender(problem, renderId),\n );\n }\n } else {\n this.hostProblem = problem;\n this.hostProblemWasNearRender = true;\n }\n this.publish();\n }\n\n // A whole-canvas failure (its module failed to import, so none of its\n // storyboards ever registered). Keyed by canvas path, not renderId — the\n // renderer scopes it to that canvas's storyboards.\n reportCanvasProblem(\n canvasPath: string,\n sourceKind: CanvasHostProblemSourceKind,\n error: unknown,\n details: Partial<CanvasHostRuntimeProblem> = {},\n ): void {\n this.canvasProblems.set(\n canvasPath,\n createProblem(sourceKind, error, details),\n );\n this.publish();\n }\n\n clearCanvasProblem(\n canvasPath: string,\n sourceKinds?: readonly CanvasHostProblemSourceKind[],\n ): void {\n const problem = this.canvasProblems.get(canvasPath);\n if (!problem) return;\n if (sourceKinds && !sourceKinds.includes(problem.sourceKind)) return;\n this.canvasProblems.delete(canvasPath);\n this.publish();\n }\n\n registerCanvasPath(canvasPath: string): () => void {\n const normalizedPath = normalizeCanvasPath(canvasPath);\n if (!normalizedPath) return () => {};\n this.registeredCanvasPaths.set(\n normalizedPath,\n (this.registeredCanvasPaths.get(normalizedPath) ?? 0) + 1,\n );\n this.publishIfViteProjectionChanged();\n return () => {\n const count = this.registeredCanvasPaths.get(normalizedPath) ?? 0;\n if (count <= 1) {\n this.registeredCanvasPaths.delete(normalizedPath);\n this.clearCanvasProblem(normalizedPath, [\"vite-overlay\"]);\n } else {\n this.registeredCanvasPaths.set(normalizedPath, count - 1);\n }\n this.publishIfViteProjectionChanged();\n };\n }\n\n matchingCanvasPaths(problem: CanvasHostRuntimeProblem): string[] {\n const candidates = [...this.registeredCanvasPaths.keys()];\n const filenameMatches = resolveUniqueDiagnosticSourceMatches(\n problem.filename ?? \"\",\n candidates,\n { projectRoot: readTempoProjectRoot() },\n );\n if (filenameMatches.length > 0) return filenameMatches;\n const text = [problem.message, problem.stack, problem.filename]\n .filter(Boolean)\n .join(\"\\n\");\n return resolveUniqueDiagnosticSourceMatches(text, candidates, {\n projectRoot: readTempoProjectRoot(),\n });\n }\n\n clearHostProblem(sourceKinds?: readonly CanvasHostProblemSourceKind[]): void {\n if (!this.hostProblem) return;\n if (sourceKinds && !sourceKinds.includes(this.hostProblem.sourceKind))\n return;\n const clearedProblem = this.hostProblem;\n this.hostProblem = undefined;\n this.hostProblemWasNearRender = false;\n this.publish();\n this.publishHostProblemCleared(clearedProblem);\n }\n\n reportComponentProblem(\n renderId: string,\n sourceKind: CanvasHostProblemSourceKind,\n error: unknown,\n details: Partial<CanvasHostRuntimeProblem> = {},\n ): void {\n this.componentProblems.set(\n renderId,\n createProblem(sourceKind, error, details),\n );\n this.publish();\n }\n\n clearComponentProblem(\n renderId: string,\n sourceKinds?: readonly CanvasHostProblemSourceKind[],\n ): void {\n const problem = this.componentProblems.get(renderId);\n if (!problem) return;\n if (sourceKinds && !sourceKinds.includes(problem.sourceKind)) return;\n this.componentProblems.delete(renderId);\n this.publish();\n }\n\n hasComponentProblem(renderId: string): boolean {\n return this.componentProblems.has(renderId);\n }\n\n syncRenderSourcePaths(\n entries: readonly { renderId: string; sourcePaths?: readonly string[] }[],\n ): void {\n const next = new Map(\n entries.flatMap((entry) =>\n entry.sourcePaths?.length\n ? [[entry.renderId, entry.sourcePaths] as const]\n : [],\n ),\n );\n const changed =\n JSON.stringify([...this.registeredRenderSourcePaths]) !==\n JSON.stringify([...next]);\n if (!changed) return;\n this.registeredRenderSourcePaths = next;\n if (\n this.hostProblem &&\n (this.hostProblemWasNearRender ||\n isNearRenderProblemSourceKind(this.hostProblem.sourceKind)) &&\n this.matchingRenderIds(this.hostProblem).length > 0\n ) {\n this.publish();\n } else {\n this.publishIfViteProjectionChanged();\n }\n }\n\n matchingRenderIds(problem: CanvasHostRuntimeProblem): string[] {\n return findRenderIdsForProblem(\n problem,\n [...this.registeredRenderSourcePaths].flatMap(([renderId, sourcePaths]) =>\n sourcePaths.map((sourceFile) => ({ renderId, sourceFile })),\n ),\n );\n }\n\n private problemForMatchedRender(\n problem: CanvasHostRuntimeProblem,\n renderId: string,\n ): CanvasHostRuntimeProblem {\n if (\n problem.sourceKind !== \"unhandled-rejection\" ||\n !this.matchingDeclaredRenderIds(problem).includes(renderId)\n ) {\n return problem;\n }\n return { ...problem, sourceKind: \"render-error-boundary\" };\n }\n\n private matchingDeclaredRenderIds(\n problem: CanvasHostRuntimeProblem,\n ): string[] {\n return findRenderIdsForProblem(\n problem,\n [...this.registeredRenderSourcePaths].flatMap(([renderId, sourcePaths]) =>\n sourcePaths.map((sourceFile) => ({ renderId, sourceFile })),\n ),\n false,\n );\n }\n\n clearRecoveredComponentProblemsAfterRender(renderId: string): void {\n let changed = false;\n const problem = this.componentProblems.get(renderId);\n if (problem && problem.sourceKind !== \"render-error-boundary\") {\n this.componentProblems.delete(renderId);\n changed = true;\n }\n if (this.clearRecoveredHostProblemAfterRender(renderId)) changed = true;\n if (changed) {\n this.publish();\n } else {\n this.publishIfViteProjectionChanged();\n }\n }\n\n reconcileViteOverlayProjection(): void {\n this.publishIfViteProjectionChanged();\n }\n\n dispose(): void {\n this.watchers.clear();\n this.hostProblemClearedWatchers.clear();\n this.registeredCanvasPaths.clear();\n this.registeredRenderSourcePaths.clear();\n }\n\n private publish(): void {\n this.publishedViteProjectionSignature = this.viteProjectionSignature();\n for (const watcher of this.watchers) {\n watcher();\n }\n }\n\n private publishIfViteProjectionChanged(): void {\n const signature = this.viteProjectionSignature();\n if (this.publishedViteProjectionSignature === undefined) {\n this.publishedViteProjectionSignature = signature;\n return;\n }\n if (signature === this.publishedViteProjectionSignature) return;\n this.publish();\n }\n\n private viteProjectionSignature(): string {\n const snapshot = this.snapshot();\n const identify = (problem: CanvasHostRuntimeProblem): string =>\n [problem.sourceKind, problem.filename, problem.message].join(\"\\0\");\n return JSON.stringify({\n host:\n snapshot.hostProblem &&\n isProjectedViteProblemSourceKind(snapshot.hostProblem.sourceKind)\n ? identify(snapshot.hostProblem)\n : null,\n components: snapshot.componentProblems.flatMap(({ renderId, problem }) =>\n isProjectedViteProblemSourceKind(problem.sourceKind)\n ? [[renderId, identify(problem)]]\n : [],\n ),\n canvases: snapshot.canvasProblems.flatMap(({ canvasPath, problem }) =>\n isProjectedViteProblemSourceKind(problem.sourceKind)\n ? [[canvasPath, identify(problem)]]\n : [],\n ),\n });\n }\n\n private publishHostProblemCleared(problem: CanvasHostRuntimeProblem): void {\n for (const watcher of this.hostProblemClearedWatchers) {\n watcher(problem);\n }\n }\n\n private clearRecoveredHostProblemAfterRender(renderId: string): boolean {\n if (\n !this.hostProblem ||\n !renderRecoveredHostProblemSourceKinds.includes(\n this.hostProblem.sourceKind,\n )\n ) {\n return false;\n }\n const matchingRenderIds = this.matchingRenderIds(this.hostProblem);\n if (matchingRenderIds.length > 0 && !matchingRenderIds.includes(renderId))\n return false;\n const clearedProblem = this.hostProblem;\n this.hostProblem = undefined;\n this.hostProblemWasNearRender = false;\n this.publishHostProblemCleared(clearedProblem);\n return true;\n }\n}\n\nexport function createCanvasHostProblemTracker(): CanvasHostProblemTracker {\n return new CanvasHostProblemTracker();\n}\n\nexport function installCanvasHostRuntimeProblemTracking(\n tracker: CanvasHostProblemTracker,\n): () => void {\n if (typeof window === \"undefined\") return () => {};\n\n // The Electron preload owns errors before CanvasHost can install this\n // standing tracker. Take that bounded buffer first: the preload removes its\n // listeners synchronously, and the live listeners below are installed in\n // the same task, so browser events cannot fall into a gap or hit both owners.\n const startupProblems = takeFrameStartupProblems();\n const cleanupHostCapture = installHostProblemCapture(tracker);\n const cleanupViteCapture = installViteProblemCapture(tracker);\n const cleanupViteErrorStream = installViteErrorStream(tracker);\n for (const problem of startupProblems) {\n tracker.reportProblemNearRender(\n problem.kind === \"error\" ? \"page-error\" : \"unhandled-rejection\",\n problem.message,\n {\n timestamp: problem.timestamp,\n stack: problem.stack,\n filename: problem.filename,\n line: problem.line,\n column: problem.column,\n },\n );\n }\n\n return () => {\n cleanupHostCapture();\n cleanupViteCapture();\n cleanupViteErrorStream();\n };\n}\n\nfunction installViteErrorStream(tracker: CanvasHostProblemTracker): () => void {\n const receive = (problem: TempoViteServerError | null): void => {\n if (problem === null) {\n tracker.clearHostProblem([\"vite-hmr-error\"]);\n return;\n }\n if (typeof problem?.message !== \"string\") return;\n tracker.reportHostProblem(\"vite-hmr-error\", problem.message, {\n stack: problem.stack,\n filename: problem.file ?? problem.loc?.file,\n });\n };\n\n const feed = (\n globalThis as typeof globalThis & {\n [VITE_ERROR_FEED_KEY]?: TempoViteErrorFeed;\n }\n )[VITE_ERROR_FEED_KEY];\n if (feed) return feed.subscribe(receive);\n\n // Compatibility with hosts generated by older plugins or with HMR off.\n if (typeof EventSource === \"undefined\") return () => {};\n const source = new EventSource(\"/__tempo/errors\");\n source.onmessage = (event) => {\n let problem: TempoViteServerError | null;\n try {\n problem = JSON.parse(event.data) as TempoViteServerError | null;\n } catch {\n return;\n }\n receive(problem);\n };\n\n return () => {\n source.close();\n };\n}\n\ntype FrameStartupProblem = {\n kind: \"error\" | \"unhandledrejection\";\n timestamp: number;\n message: string;\n stack?: string;\n filename?: string;\n line?: number;\n column?: number;\n};\n\nfunction takeFrameStartupProblems(): FrameStartupProblem[] {\n const take = (\n window as Window & {\n framePool?: { takeStartupErrors?: () => unknown };\n }\n ).framePool?.takeStartupErrors;\n if (typeof take !== \"function\") return [];\n\n let value: unknown;\n try {\n value = take();\n } catch {\n return [];\n }\n if (!Array.isArray(value)) return [];\n\n return value.flatMap((candidate): FrameStartupProblem[] => {\n if (\n !candidate ||\n typeof candidate !== \"object\" ||\n ((candidate as { kind?: unknown }).kind !== \"error\" &&\n (candidate as { kind?: unknown }).kind !== \"unhandledrejection\") ||\n typeof (candidate as { message?: unknown }).message !== \"string\" ||\n typeof (candidate as { timestamp?: unknown }).timestamp !== \"number\"\n ) {\n return [];\n }\n const record = candidate as Record<string, unknown>;\n return [\n {\n kind: record.kind as FrameStartupProblem[\"kind\"],\n timestamp: record.timestamp as number,\n message: record.message as string,\n ...(typeof record.stack === \"string\" && { stack: record.stack }),\n ...(typeof record.filename === \"string\" && {\n filename: record.filename,\n }),\n ...(typeof record.line === \"number\" && { line: record.line }),\n ...(typeof record.column === \"number\" && { column: record.column }),\n },\n ];\n });\n}\n\nconst renderRecoveredHostProblemSourceKinds: readonly CanvasHostProblemSourceKind[] =\n [\"page-error\", \"unhandled-rejection\", \"console-vite-error\", \"vite-hmr-error\"];\n\n/** Probe schedule for a fetch-shaped failed reload: the same mid-write race\n * that failed Vite's own module fetch can fail an immediate probe, so the\n * transform is re-asked a short ladder apart before concluding the code is\n * genuinely broken. A healthy dev server answers each probe in\n * milliseconds; a genuinely broken file just fails all three. */\nconst FAILED_RELOAD_PROBE_DELAYS_MS = [50, 400, 1600];\n\n/** Ask the dev server whether `path`'s CURRENT content transforms cleanly,\n * with the same URL shape Vite's own update fetch uses (root-relative path\n * resolved against this document's origin, cache-busted). Only a served\n * JavaScript module counts: Vite answers a path it cannot load (a deleted\n * file) through its SPA fallback with `index.html` and a 200 whenever the\n * request accepts HTML, so the probe asks for JavaScript alone and treats\n * anything else, a 404 included, as a module that did not transform. */\nasync function moduleTransformSucceeds(path: string): Promise<boolean> {\n const [pathname, query = \"\"] = path.split(\"?\");\n const url = `${pathname}?${query ? `${query}&` : \"\"}t=${Date.now()}`;\n const response = await fetch(url, {\n cache: \"no-store\",\n headers: { Accept: \"application/javascript\" },\n });\n return (\n response.ok &&\n /javascript/i.test(response.headers.get(\"content-type\") ?? \"\")\n );\n}\n\n/** Probe a compile-error problem's file. Overlay/error-stream filenames are\n * absolute filesystem paths (optionally `:line:col`-suffixed), served by\n * Vite at `/@fs<path>`; failed-reload paths are already root-relative\n * URLs, so both spellings are tried. A file that cannot be located at\n * either spelling counts as still broken — publishing must rest on\n * POSITIVE proof of staleness, never on a probe that merely missed. */\nasync function compileErrorFileStillBroken(file: string): Promise<boolean> {\n const cleaned = file.replace(/:\\d+(?::\\d+)?$/, \"\");\n const candidates = cleaned.startsWith(\"/@\")\n ? [cleaned]\n : [`/@fs${cleaned}`, cleaned];\n for (const candidate of candidates) {\n try {\n if (await moduleTransformSucceeds(candidate)) return false;\n } catch {\n return true;\n }\n }\n return true;\n}\n\nfunction isViteProblemSourceKind(\n sourceKind: CanvasHostProblemSourceKind,\n): boolean {\n return sourceKind === \"vite-hmr-error\" || sourceKind === \"console-vite-error\";\n}\n\nfunction isNearRenderProblemSourceKind(\n sourceKind: CanvasHostProblemSourceKind,\n): boolean {\n return (\n sourceKind === \"page-error\" ||\n sourceKind === \"unhandled-rejection\" ||\n sourceKind === \"console-vite-error\"\n );\n}\n\nfunction isProjectedViteProblemSourceKind(\n sourceKind: CanvasHostProblemSourceKind,\n): boolean {\n return sourceKind === \"vite-overlay\" || isViteProblemSourceKind(sourceKind);\n}\n\nfunction createProblem(\n sourceKind: CanvasHostProblemSourceKind,\n error: unknown,\n details: Partial<CanvasHostRuntimeProblem> = {},\n): CanvasHostRuntimeProblem {\n return {\n sourceKind,\n ...describeError(error),\n frameUrl: typeof window === \"undefined\" ? undefined : window.location.href,\n timestamp: Date.now(),\n ...details,\n };\n}\n\n/**\n * The message and stack a problem shows for a thrown value. An error that\n * wraps another names it too: React reports a render it recovered from as\n * \"There was an error during concurrent rendering but React was able to\n * recover...\" with the real failure only on `cause`, and a problem that\n * showed the wrapper alone said nothing a reader could act on.\n */\nfunction describeError(error: unknown): { message: string; stack?: string } {\n if (!(error instanceof Error)) return { message: String(error) };\n const cause = error.cause;\n if (cause === undefined || cause === null) {\n return { message: error.message, stack: error.stack };\n }\n const inner = describeError(cause);\n return {\n message: `${error.message} Cause: ${inner.message}`,\n stack: inner.stack ?? error.stack,\n };\n}\n\nfunction findRenderIdsForProblem(\n problem: CanvasHostRuntimeProblem,\n registered: readonly { renderId: string; sourceFile: string }[] = [],\n includeDom = true,\n): string[] {\n const observed: Array<{ renderId: string; sourceFile: string }> = [\n ...registered,\n ];\n if (includeDom && typeof document !== \"undefined\") {\n for (const slot of document.querySelectorAll(\"[data-render-id]\")) {\n const renderId = slot.getAttribute(\"data-render-id\");\n if (!renderId) continue;\n for (const sourceFile of getObservedSourceFiles(slot)) {\n observed.push({ renderId, sourceFile });\n }\n }\n }\n if (observed.length === 0) return [];\n\n const exactFilenameMatches = new Set(\n resolveUniqueDiagnosticSourceMatches(\n problem.filename ?? \"\",\n observed.map(({ sourceFile }) => sourceFile),\n {\n projectRoot: readTempoProjectRoot(),\n allowExtensionlessJsTs: true,\n },\n ),\n );\n if (exactFilenameMatches.size > 0) {\n return uniqueRenderIds(\n observed.filter(({ sourceFile }) => exactFilenameMatches.has(sourceFile)),\n );\n }\n\n const filenameMatches = matchObservedRenderIds(\n problem.filename ?? \"\",\n observed,\n );\n if (filenameMatches.length > 0) return filenameMatches;\n\n const haystack = [problem.message, problem.stack, problem.componentStack]\n .filter(Boolean)\n .join(\"\\n\");\n return matchObservedRenderIds(haystack, observed);\n}\n\nconst sourceAnnotationSelector =\n \"[data-tempo-source-file], [data-tempo-source-loc], [data-tempo-filepath], [data-tempo-html-filepath]\";\n\nfunction getObservedSourceFiles(slot: Element): string[] {\n const sourceFiles = new Set<string>();\n for (const element of slot.querySelectorAll(sourceAnnotationSelector)) {\n for (const attribute of [\n \"data-tempo-source-file\",\n \"data-tempo-filepath\",\n \"data-tempo-html-filepath\",\n ]) {\n const value = element.getAttribute(attribute);\n if (value) sourceFiles.add(value);\n }\n const sourceLoc = element.getAttribute(\"data-tempo-source-loc\");\n const sourceFile = sourceLoc?.split(\":\")[0];\n if (sourceFile) sourceFiles.add(sourceFile);\n }\n return [...sourceFiles];\n}\n\nfunction matchObservedRenderIds(\n text: string,\n observed: readonly { renderId: string; sourceFile: string }[],\n): string[] {\n const matches = new Set(\n resolveUniqueDiagnosticSourceMatches(\n text,\n observed.map(({ sourceFile }) => sourceFile),\n {\n projectRoot: readTempoProjectRoot(),\n allowExtensionlessJsTs: true,\n },\n ),\n );\n return uniqueRenderIds(\n observed.filter(({ sourceFile }) => matches.has(sourceFile)),\n );\n}\n\nfunction readTempoProjectRoot(): string | null {\n if (typeof document === \"undefined\") return null;\n return (\n document\n .querySelector<HTMLMetaElement>('meta[name=\"tempo-source-identity-root\"]')\n ?.content.trim() ||\n document\n .querySelector<HTMLMetaElement>('meta[name=\"tempo-project-root\"]')\n ?.content.trim() ||\n null\n );\n}\n\nfunction uniqueRenderIds(matches: readonly { renderId: string }[]): string[] {\n return [...new Set(matches.map(({ renderId }) => renderId))];\n}\n\nfunction normalizeCanvasPath(value: string): string {\n return value.trim();\n}\n\n/**\n * React reports a render it threw away and redid synchronously through\n * `reportError`, with the throw on `cause`. An admission budget throw that\n * arrives that way was not a recursion: the budget resets only when a\n * `Storyboard` component itself renders, so a wide update that re-renders\n * thousands of descendants across a heavy canvas while the storyboards bail\n * out shares one budget and exceeds it; the synchronous retry renders the\n * whole root, resets per storyboard, and finishes. A real recursion trips the\n * retry too and reaches the storyboard's error boundary instead of here.\n */\nfunction isRecoveredAdmissionBudgetError(error: unknown): boolean {\n return error instanceof Error && error.cause instanceof AdmissionBudgetError;\n}\n\nfunction installHostProblemCapture(\n tracker: CanvasHostProblemTracker,\n): () => void {\n const onError = (event: ErrorEvent): void => {\n if (event.target instanceof Element) return;\n if (isRecoveredAdmissionBudgetError(event.error)) return;\n tracker.reportProblemNearRender(\n \"page-error\",\n event.error ?? event.message,\n {\n filename: event.filename || undefined,\n line: typeof event.lineno === \"number\" ? event.lineno : undefined,\n column: typeof event.colno === \"number\" ? event.colno : undefined,\n },\n );\n };\n const onUnhandledRejection = (event: PromiseRejectionEvent): void => {\n tracker.reportProblemNearRender(\"unhandled-rejection\", event.reason);\n };\n\n const resourceTags = new Set([\n \"IMG\",\n \"SCRIPT\",\n \"LINK\",\n \"AUDIO\",\n \"VIDEO\",\n \"SOURCE\",\n ]);\n const onResourceError = (event: Event): void => {\n const target = event.target;\n if (!(target instanceof Element) || !resourceTags.has(target.tagName)) {\n return;\n }\n const url = target.getAttribute(\"src\") || target.getAttribute(\"href\") || \"\";\n const message = `Failed to load ${target.tagName.toLowerCase()}${url ? `: ${url}` : \"\"}`;\n const renderId = target\n .closest(\"[data-render-id]\")\n ?.getAttribute(\"data-render-id\");\n if (renderId) {\n tracker.reportComponentProblem(renderId, \"resource-load\", message);\n } else {\n tracker.reportHostProblem(\"resource-load\", message, {\n filename: url || undefined,\n });\n }\n };\n\n const onFontLoadingError = (event: Event): void => {\n const faces =\n (event as Event & { fontfaces?: ReadonlyArray<{ family?: string }> })\n .fontfaces ?? [];\n const families = faces\n .map((face) => face.family)\n .filter(Boolean)\n .join(\", \");\n tracker.reportHostProblem(\n \"resource-load\",\n `Failed to load font${families ? `: ${families}` : \"\"}`,\n );\n };\n const fontFaceSet =\n typeof document.fonts?.addEventListener === \"function\"\n ? document.fonts\n : undefined;\n\n window.addEventListener(\"error\", onError);\n window.addEventListener(\"unhandledrejection\", onUnhandledRejection);\n window.addEventListener(\"error\", onResourceError, { capture: true });\n document.addEventListener(\"error\", onResourceError, { capture: true });\n fontFaceSet?.addEventListener(\"loadingerror\", onFontLoadingError);\n\n return () => {\n window.removeEventListener(\"error\", onError);\n window.removeEventListener(\"unhandledrejection\", onUnhandledRejection);\n window.removeEventListener(\"error\", onResourceError, { capture: true });\n document.removeEventListener(\"error\", onResourceError, { capture: true });\n fontFaceSet?.removeEventListener(\"loadingerror\", onFontLoadingError);\n };\n}\n\nfunction installViteProblemCapture(\n tracker: CanvasHostProblemTracker,\n): () => void {\n const reconcileViteOverlay = (): void => {\n tracker.reconcileViteOverlayProjection();\n };\n\n const observer = new MutationObserver(reconcileViteOverlay);\n if (document.body) {\n observer.observe(document.body, { childList: true });\n reconcileViteOverlay();\n void Promise.resolve().then(reconcileViteOverlay);\n }\n\n const evalFailedModules = new Map<string, CanvasHostRuntimeProblem>();\n const latestEvaluationFailure = (): CanvasHostRuntimeProblem | undefined => {\n let latest: CanvasHostRuntimeProblem | undefined;\n for (const problem of evalFailedModules.values()) {\n if (!latest || problem.timestamp >= latest.timestamp) latest = problem;\n }\n return latest;\n };\n const reconcileEvaluationHostProblem = (): void => {\n const latest = latestEvaluationFailure();\n if (latest) {\n tracker.reportHostProblem(\"vite-hmr-error\", latest.message, latest);\n } else {\n tracker.clearHostProblem([\"vite-hmr-error\"]);\n }\n };\n\n const failedReloadPattern = /^Failed to reload (.+?)\\. This could be due to/;\n let lastViteConsoleErrorDetail: {\n message: string;\n stack?: string;\n filename?: string;\n } | null = null;\n\n const stopClearedWatch = tracker.watchHostProblemCleared((problem) => {\n if (problem.sourceKind !== \"vite-hmr-error\") return;\n const removed = problem.filename\n ? evalFailedModules.delete(problem.filename)\n : false;\n if (!removed) return;\n queueMicrotask(reconcileEvaluationHostProblem);\n });\n\n const originalConsoleError = console.error;\n const patchedConsoleError = (...args: unknown[]): void => {\n originalConsoleError(...args);\n const error = readViteConsoleError(args[0], args[1]);\n if (!error) return;\n\n const failedReload = failedReloadPattern.exec(error.message);\n if (failedReload) {\n const path = failedReload[1] ?? error.message;\n const detail = lastViteConsoleErrorDetail;\n lastViteConsoleErrorDetail = null;\n if (detail && !/failed to fetch/i.test(detail.message)) {\n // Module-evaluation failure: the throw cleared the module's Fast\n // Refresh accepts, so Vite can never converge this document in\n // place. Flag the broken module and arm the recovery latch.\n const problem = createProblem(\"vite-hmr-error\", detail.message, {\n stack: detail.stack,\n filename: path,\n });\n evalFailedModules.set(path, problem);\n reconcileEvaluationHostProblem();\n getCanvasHostRecoveryFeed().publish({\n type: \"module-load-failure\",\n path,\n message: detail.message,\n });\n return;\n }\n // Fetch-shaped failure: the module request 404/500ed mid-update, Vite\n // dropped the update outright (accept callbacks ran with `undefined`),\n // logged no detail error, and will never retry. Which repair applies\n // depends on WHY the fetch failed, known only server-side — so ask\n // the server by re-requesting the failed module AND every file a\n // live compile-error problem names:\n // - The failed path itself failing to transform proves the code is\n // genuinely broken: Vite's in-place degradation is correct, and\n // a reload would cold-import the broken module and kill every\n // canvas in the document. A path that no longer exists (a deleted\n // file's last update) is moot, as a prune would be: its dropped\n // update can never matter, and nothing would ever resolve it.\n // - The failed path transforming is NOT yet proof of a lost good\n // state: Vite's failed-reload names the ACCEPTING BOUNDARY,\n // which can be healthy while its DEPENDENCY is the broken file\n // (a canvas page importing a syntax-broken component). Only when\n // every compile-error-named file ALSO transforms are the shown\n // errors STALE — nothing will ever retry the dropped update, so\n // publish it for the recovery adapter's reload. A named file\n // that still fails marks the error LIVE: fixing it updates its\n // importers, so Vite converges natively without a reload.\n // Deciding from the problem tracker's snapshot alone deadlocks the\n // heal path: a STALE overlay problem left by the broken write would\n // suppress the heal update's own recovery forever (CI-proven — the\n // server answered 200 while the \"compile error\" stayed shown).\n void (async () => {\n for (const delayMs of FAILED_RELOAD_PROBE_DELAYS_MS) {\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n try {\n if (!(await moduleTransformSucceeds(path))) continue;\n const snapshot = tracker.snapshot();\n const compileErrorFiles = new Set<string>();\n for (const problem of [\n snapshot.hostProblem,\n ...snapshot.componentProblems.map((entry) => entry.problem),\n ...snapshot.canvasProblems.map((entry) => entry.problem),\n ]) {\n if (!problem) continue;\n if (!isProjectedViteProblemSourceKind(problem.sourceKind)) {\n continue;\n }\n if (problem.filename) compileErrorFiles.add(problem.filename);\n }\n for (const file of compileErrorFiles) {\n if (await compileErrorFileStillBroken(file)) return;\n }\n getCanvasHostRecoveryFeed().publish({\n type: \"module-update-dropped\",\n path,\n message: error.message,\n });\n return;\n } catch {\n // Network-level failure — the dev server is unreachable, so a\n // reload cannot help either; leave the document alone.\n return;\n }\n }\n })();\n return;\n }\n\n lastViteConsoleErrorDetail = error;\n queueMicrotask(() => {\n if (lastViteConsoleErrorDetail !== error) return;\n lastViteConsoleErrorDetail = null;\n tracker.reportProblemNearRender(\"console-vite-error\", error.message, {\n stack: error.stack,\n filename: error.filename,\n });\n });\n };\n console.error = patchedConsoleError;\n\n return () => {\n observer.disconnect();\n stopClearedWatch();\n if (console.error === patchedConsoleError) {\n console.error = originalConsoleError;\n }\n };\n}\n\nfunction readCurrentViteOverlay(): CanvasHostRuntimeProblem | undefined {\n if (typeof document === \"undefined\") return undefined;\n const overlay = document.querySelector(\"vite-error-overlay\");\n if (!overlay) return undefined;\n const { message, stack, filename } = readViteOverlayContent(overlay);\n return createProblem(\"vite-overlay\", message, { stack, filename });\n}\n\nfunction readViteOverlayContent(overlay: Element): {\n message: string;\n stack?: string;\n filename?: string;\n} {\n const root = overlay.shadowRoot ?? overlay;\n const text = (selector: string): string | undefined => {\n const value = root.querySelector(selector)?.textContent?.trim();\n return value ? value : undefined;\n };\n const message =\n text(\".message-body\") ??\n text(\".message\") ??\n overlay.textContent?.trim() ??\n \"Unknown Vite error\";\n const stack = [text(\".stack\"), text(\".plugin\"), text(\".frame\")]\n .filter(Boolean)\n .join(\"\\n\");\n return {\n message,\n stack: stack || undefined,\n filename: text(\".file\"),\n };\n}\n\nfunction readViteError(\n value: unknown,\n): { message: string; stack?: string; filename?: string } | undefined {\n if (value instanceof Error) {\n return {\n message: value.message,\n stack: value.stack,\n filename:\n typeof (value as Error & { id?: unknown }).id === \"string\"\n ? (value as Error & { id: string }).id\n : undefined,\n };\n }\n if (typeof value === \"string\") return { message: value };\n if (typeof value !== \"object\" || value === null) return undefined;\n\n const record = value as Record<string, unknown>;\n const nested =\n typeof record.err === \"object\" && record.err !== null\n ? (record.err as Record<string, unknown>)\n : record;\n const message =\n typeof nested.message === \"string\"\n ? nested.message\n : typeof record.message === \"string\"\n ? record.message\n : undefined;\n if (!message) return undefined;\n\n return {\n message,\n stack:\n typeof nested.stack === \"string\"\n ? nested.stack\n : typeof record.stack === \"string\"\n ? record.stack\n : undefined,\n filename:\n typeof nested.filename === \"string\"\n ? nested.filename\n : typeof nested.file === \"string\"\n ? nested.file\n : typeof nested.id === \"string\"\n ? nested.id\n : typeof record.id === \"string\"\n ? record.id\n : undefined,\n };\n}\n\nfunction readViteConsoleError(\n first: unknown,\n second: unknown,\n): { message: string; stack?: string; filename?: string } | undefined {\n if (first === \"[vite]\") return readViteError(second);\n if (typeof first !== \"string\" || !first.startsWith(\"[vite]\")) {\n return undefined;\n }\n\n const detail = readViteError(second);\n const message = first.replace(/^\\[vite\\]\\s*/, \"\") || detail?.message;\n return message\n ? {\n message,\n stack: detail?.stack,\n filename: detail?.filename,\n }\n : undefined;\n}\n","/**\n * The widget snapshots behind Flutter storyboard selection.\n *\n * A Flutter view has no DOM per widget, so the Dart bridge the dev server\n * generates (`tempo_layers.dart`) walks the user's widgets after each frame\n * and pushes one JSON snapshot per view through\n * `window.__tempoFlutter.onLayers(json)`. This store keeps the latest\n * snapshot per view, converts each widget's 1-based line and column into\n * the character offset the canvas's layer model uses\n * (`data-tempo-position`), and tells the projection by writing the view\n * root's `data-tempo-flutter-rev` attribute: that attribute change is an\n * ordinary DOM mutation, so the producer rebuilds the root's subtree from\n * `window.__tempoFlutter.layers.get(viewId)` on its next flush. No other\n * channel exists between the bridge and the canvas.\n *\n * Offsets need each file's line table, which the dev server's gate serves\n * per file (`GET /__tempo/flutter/__tempo_flutter_source?file=`). A node\n * whose table is not in hand carries `position: null` and no location\n * rather than a wrong one; when the table lands the snapshot is converted\n * again and the rev bumped again. Staleness is the whole difficulty: an\n * edit moves every line after it, so after a hot reload (the bridge's\n * `reloads` counter) every table is dropped and only snapshots from the\n * current reload epoch convert; a request outrun by a reload is discarded\n * when it lands; an engine restart drops everything.\n *\n * A reload must not take a view's addresses away. Publishing the new\n * epoch's snapshot before its tables land showed the canvas every widget\n * with no source for the 50-550 ms the fetches take, twice per edit\n * (Cmd+L, View Code and the inspector lost their file and line, and every\n * widget layer was republished twice). So a snapshot from a newer epoch\n * than the view's published one is held until every file it references\n * has a settled table (ready, absent, or failed: a failed fetch publishes\n * that file's nodes with no address, and its retry converts them later),\n * then published once, one rev; meanwhile the published snapshot stays.\n * A view's first snapshot is published at once: it has nothing to keep.\n */\n\n/** The view id, written on the view root when the view is added. */\nexport const FLUTTER_VIEW_ATTRIBUTE = \"data-tempo-flutter-view\";\n/** The store's revision for the view, bumped on every stored conversion. */\nexport const FLUTTER_REV_ATTRIBUTE = \"data-tempo-flutter-rev\";\n/** The gate's line-table route, as the page reaches it through the canvas\n * host's proxy (which strips the `/__tempo/flutter` prefix). */\nexport const FLUTTER_SOURCE_URL = \"/__tempo/flutter/__tempo_flutter_source\";\n/** Waits between retries of a failed table fetch (the gate down, a network\n * error): the timer owns retries, so an idle app that frames nothing still\n * gets its addresses once the gate answers. */\nconst TABLE_RETRY_DELAYS_MS = [2_000, 4_000, 8_000, 16_000, 30_000];\n\n/** One widget as the bridge emits it. */\nexport type FlutterBridgeNode = {\n /** `identityHashCode(element)`: stable across rebuilds and hot reloads. */\n id: string;\n /** The nearest local ancestor, null for the view's top widget. */\n parent: string | null;\n /** The widget's runtime type name. */\n name: string;\n /** Project-relative path, as React layers carry in `data-tempo-filepath`. */\n file: string;\n line: number;\n column: number;\n /** CSS px relative to the view's host element. */\n x: number;\n y: number;\n width: number;\n height: number;\n painted: boolean;\n};\n\nexport type FlutterBridgeSnapshot = {\n viewId: number;\n rev: number;\n /** Hot reloads so far; a change means every line table is stale. */\n reloads: number;\n /** Pre-order; siblings in paint order. */\n nodes: FlutterBridgeNode[];\n};\n\nexport type FlutterConvertedNode = FlutterBridgeNode & {\n /** UTF-16 code unit offset of the constructor call, null without a table. */\n position: number | null;\n /** The line table's `modifiedTs`, carried as `data-tempo-modifiedts`. */\n modifiedTs: number | null;\n};\n\nexport type FlutterConvertedSnapshot = {\n viewId: number;\n /** This store's revision for the view: grows on every stored snapshot and\n * on every reconversion, so the root attribute always changes. */\n rev: number;\n nodes: FlutterConvertedNode[];\n};\n\n/** What the gate answers for one file. */\ntype LineTable = { modifiedTs: number | null; lineStarts: number[] };\n\n/** `token` names the request that owns a pending or failed entry, so an\n * older request's answer, or an older timer, can be told apart on landing. */\ntype TableEntry =\n | { kind: \"ready\"; table: LineTable }\n | { kind: \"pending\"; token: number }\n /** Outside the app directory, or deleted: never has a table. */\n | { kind: \"missing\" }\n | { kind: \"failed\"; token: number; attempts: number; timer: number };\n\ntype StoredView = {\n bridge: FlutterBridgeSnapshot;\n converted: FlutterConvertedSnapshot;\n};\n\nexport type FlutterLayerStore = {\n /** The bridge's entry: a JSON string (or an already parsed object). It\n * never throws; a malformed push is dropped. */\n onLayers(json: unknown): void;\n /** The latest converted snapshot for a view the runtime knows. */\n get(viewId: number): FlutterConvertedSnapshot | undefined;\n /** A view was added under `viewRoot`: stamps the view id on it. */\n viewAdded(viewId: number, viewRoot: Element): void;\n /** The view is gone: its snapshot and the root's stamps go with it. */\n viewRemoved(viewId: number): void;\n /** The engine restarted: every view, table and reload epoch is gone. */\n reset(): void;\n};\n\nexport function createFlutterLayerStore(\n win: Window,\n options: {\n sourceUrl?: string;\n /** Called after each snapshot the store publishes for a view (its first,\n * and every one after it), once the view root carries its new rev. The\n * runtime holds a board's pending marker until its view's first. */\n onPublished?(viewId: number): void;\n } = {},\n): FlutterLayerStore {\n const sourceUrl = options.sourceUrl ?? FLUTTER_SOURCE_URL;\n const roots = new Map<number, Element>();\n const views = new Map<number, StoredView>();\n const revisions = new Map<number, number>();\n const tables = new Map<string, TableEntry>();\n // Per view, a snapshot from a newer epoch than its published one, waiting\n // for its files' tables (see the header). A newer push replaces it.\n const held = new Map<number, FlutterBridgeSnapshot>();\n // The reload epoch the tables describe. Engine-wide, never per view: a\n // view added after a reload has no earlier snapshot to compare against,\n // and a reload reported by one view has moved the lines of every file.\n let lastReloads: number | null = null;\n let nextToken = 1;\n let warnedMalformed = false;\n\n function warnMalformed(reason: string) {\n if (warnedMalformed) return;\n warnedMalformed = true;\n console.warn(`[tempo] Flutter layer snapshot dropped: ${reason}`);\n }\n\n function filesOf(snapshot: FlutterBridgeSnapshot): Set<string> {\n return new Set(snapshot.nodes.map((node) => node.file));\n }\n\n function referenced(file: string): boolean {\n for (const view of views.values()) {\n if (filesOf(view.bridge).has(file)) return true;\n }\n for (const snapshot of held.values()) {\n if (filesOf(snapshot).has(file)) return true;\n }\n return false;\n }\n\n // In hand, known absent, or failed (its retry timer owns it from here):\n // nothing more is coming for this epoch that a held snapshot should await.\n function settled(file: string): boolean {\n const kind = tables.get(file)?.kind;\n return kind === \"ready\" || kind === \"missing\" || kind === \"failed\";\n }\n\n function publishSettledHeld() {\n for (const [viewId, snapshot] of held) {\n // A reload since it was held moved its lines again; the view's push\n // for the new epoch takes its place.\n if (snapshot.reloads !== lastReloads) {\n held.delete(viewId);\n continue;\n }\n if (![...filesOf(snapshot)].every(settled)) continue;\n held.delete(viewId);\n store(viewId, snapshot);\n }\n }\n\n function convert(snapshot: FlutterBridgeSnapshot): FlutterConvertedNode[] {\n // A snapshot from an earlier epoch carries line numbers of the file\n // before the reload; against the current tables they would be wrong,\n // not merely old. Its view pushes again right after the reload (the\n // bridge compares `reloads` too), so null is the honest answer for the\n // moment in between.\n const currentEpoch = snapshot.reloads === lastReloads;\n return snapshot.nodes.map((node) => {\n const entry = tables.get(node.file);\n if (!currentEpoch || entry?.kind !== \"ready\") {\n return { ...node, position: null, modifiedTs: null };\n }\n const lineStart = entry.table.lineStarts[node.line - 1];\n // A line past the table's end is a stale snapshot against a shorter\n // file; it has no address until the next snapshot or table.\n if (lineStart === undefined) {\n return { ...node, position: null, modifiedTs: null };\n }\n return {\n ...node,\n position: lineStart + (node.column - 1),\n modifiedTs: entry.table.modifiedTs,\n };\n });\n }\n\n function store(viewId: number, bridge: FlutterBridgeSnapshot) {\n const root = roots.get(viewId);\n if (!root) return;\n const rev = (revisions.get(viewId) ?? 0) + 1;\n revisions.set(viewId, rev);\n views.set(viewId, {\n bridge,\n converted: { viewId, rev, nodes: convert(bridge) },\n });\n root.setAttribute(FLUTTER_REV_ATTRIBUTE, String(rev));\n options.onPublished?.(viewId);\n }\n\n // A new table converts the published snapshots of its epoch. One from an\n // older epoch keeps its conversion until its view's held snapshot\n // replaces it: against the new table its lines would be wrong.\n function reconvertViewsReferencing(file: string) {\n for (const [viewId, view] of views) {\n const currentEpoch = view.bridge.reloads === lastReloads;\n if (currentEpoch && filesOf(view.bridge).has(file))\n store(viewId, view.bridge);\n }\n }\n\n function dropTables() {\n for (const entry of tables.values()) {\n if (entry.kind === \"failed\") win.clearTimeout(entry.timer);\n }\n tables.clear();\n }\n\n function scheduleRetry(file: string, attempts: number) {\n const token = nextToken++;\n const delay =\n TABLE_RETRY_DELAYS_MS[\n Math.min(attempts - 1, TABLE_RETRY_DELAYS_MS.length - 1)\n ] ?? 30_000;\n const timer = win.setTimeout(() => {\n const current = tables.get(file);\n if (current?.kind !== \"failed\" || current.token !== token) return;\n // Nothing shows the file any more: let it go rather than poll for it.\n if (!referenced(file)) {\n tables.delete(file);\n return;\n }\n void fetchTable(file, attempts);\n }, delay);\n tables.set(file, { kind: \"failed\", token, attempts, timer });\n }\n\n async function fetchTable(file: string, previousAttempts = 0) {\n const token = nextToken++;\n tables.set(file, { kind: \"pending\", token });\n let entry:\n | { kind: \"ready\"; table: LineTable }\n | { kind: \"missing\" }\n | null = null;\n try {\n const response = await win.fetch(\n `${sourceUrl}?file=${encodeURIComponent(file)}`,\n { cache: \"no-store\" },\n );\n if (response.status === 404) entry = { kind: \"missing\" };\n else if (response.ok) {\n const table = readLineTable(await response.json());\n if (table) entry = { kind: \"ready\", table };\n }\n } catch {\n // A network failure is retried below like any other.\n }\n // A reload dropped this request's entry, or a newer request owns it:\n // this answer describes a file that is no longer the one in hand.\n const current = tables.get(file);\n if (current?.kind !== \"pending\" || current.token !== token) return;\n if (entry === null) {\n scheduleRetry(file, previousAttempts + 1);\n } else {\n tables.set(file, entry);\n if (entry.kind === \"ready\") reconvertViewsReferencing(file);\n }\n // After the reconversion, which only touches published snapshots of this\n // epoch, so a held snapshot published here is published once.\n publishSettledHeld();\n }\n\n function ensureTables(snapshot: FlutterBridgeSnapshot) {\n for (const file of filesOf(snapshot)) {\n // A failed entry's timer owns its retries; everything else is either\n // in hand, on its way, or known to be absent.\n if (!tables.has(file)) void fetchTable(file);\n }\n }\n\n // Runs inside the engine's frame callback through Dart's JS interop, so it\n // must never throw back into it.\n function onLayers(json: unknown) {\n try {\n const snapshot = readSnapshot(json);\n if (!snapshot) {\n warnMalformed(\"not a {viewId, rev, reloads, nodes[]} snapshot\");\n return;\n }\n // The sentinel's view, or one a restart already dropped, has no root.\n // Its push says nothing about this engine's epoch either: a deferred\n // walk of the pre-restart Dart instance can land just after a hot\n // restart with a counter of its own.\n if (!roots.has(snapshot.viewId)) return;\n // A reload moved the lines of every file, whichever view reports it\n // first: drop every table. Published snapshots keep their conversion\n // until their views push in the new epoch (the bridge compares\n // `reloads` too, so every view pushes after a reload).\n if (lastReloads !== null && snapshot.reloads !== lastReloads) {\n dropTables();\n }\n lastReloads = snapshot.reloads;\n ensureTables(snapshot);\n const published = views.get(snapshot.viewId);\n const newerEpoch =\n published !== undefined && published.bridge.reloads !== lastReloads;\n if (newerEpoch && ![...filesOf(snapshot)].every(settled)) {\n held.set(snapshot.viewId, snapshot);\n return;\n }\n held.delete(snapshot.viewId);\n store(snapshot.viewId, snapshot);\n } catch (error) {\n warnMalformed(error instanceof Error ? error.message : String(error));\n }\n }\n\n function viewRemoved(viewId: number) {\n const root = roots.get(viewId);\n roots.delete(viewId);\n views.delete(viewId);\n held.delete(viewId);\n revisions.delete(viewId);\n root?.removeAttribute(FLUTTER_VIEW_ATTRIBUTE);\n root?.removeAttribute(FLUTTER_REV_ATTRIBUTE);\n }\n\n return {\n onLayers,\n get: (viewId) => views.get(viewId)?.converted,\n viewAdded(viewId, viewRoot) {\n roots.set(viewId, viewRoot);\n viewRoot.setAttribute(FLUTTER_VIEW_ATTRIBUTE, String(viewId));\n },\n viewRemoved,\n reset() {\n // The new engine's shell starts its reload counter over and reuses\n // view ids; nothing from the old engine may answer for it.\n for (const viewId of [...roots.keys()]) viewRemoved(viewId);\n dropTables();\n lastReloads = null;\n },\n };\n}\n\nfunction readSnapshot(json: unknown): FlutterBridgeSnapshot | null {\n const value: unknown = typeof json === \"string\" ? JSON.parse(json) : json;\n if (typeof value !== \"object\" || value === null) return null;\n const { viewId, rev, reloads, nodes } = value as Record<string, unknown>;\n if (\n !Number.isInteger(viewId) ||\n typeof rev !== \"number\" ||\n typeof reloads !== \"number\" ||\n !Array.isArray(nodes)\n ) {\n return null;\n }\n if (!nodes.every(isBridgeNode)) return null;\n return {\n viewId: viewId as number,\n rev,\n reloads,\n nodes: nodes as FlutterBridgeNode[],\n };\n}\n\nfunction isBridgeNode(value: unknown): value is FlutterBridgeNode {\n if (typeof value !== \"object\" || value === null) return false;\n const node = value as Record<string, unknown>;\n const numbers = [\n node.line,\n node.column,\n node.x,\n node.y,\n node.width,\n node.height,\n ];\n return (\n typeof node.id === \"string\" &&\n (node.parent === null || typeof node.parent === \"string\") &&\n typeof node.name === \"string\" &&\n typeof node.file === \"string\" &&\n typeof node.painted === \"boolean\" &&\n numbers.every((n) => typeof n === \"number\" && Number.isFinite(n))\n );\n}\n\nfunction readLineTable(value: unknown): LineTable | null {\n if (typeof value !== \"object\" || value === null) return null;\n const { modifiedTs, lineStarts } = value as Record<string, unknown>;\n const validStarts =\n Array.isArray(lineStarts) &&\n lineStarts.every((n) => typeof n === \"number\" && Number.isFinite(n));\n if (!validStarts) return null;\n return {\n modifiedTs: typeof modifiedTs === \"number\" ? modifiedTs : null,\n lineStarts: lineStarts as number[],\n };\n}\n","import type { FlutterApp } from \"./flutter-runtime\";\n\n/**\n * Workaround switch for flutter/flutter#185034 (Flutter 3.41 to 3.47; fix PR\n * flutter/flutter#194401): every view's canvas bitmap takes the pixel size of\n * the most recently added view, so a larger view added earlier renders\n * clipped. The engine re-derives that size only when a view is added. While\n * the switch is on, the runtime keeps a hidden sentinel view, sized to the\n * largest mounted storyboard, as the most recently added view. Turn it off\n * (and delete this module) once the canvas host's Flutter SDK floor includes\n * the fix.\n */\nexport const FLUTTER_MULTI_VIEW_SIZING_WORKAROUND = true;\n\n/**\n * The sentinel's preview key. The generated Dart shell renders\n * `SizedBox.shrink()` for it, so the sentinel never paints.\n */\nexport const FLUTTER_SIZING_SENTINEL_PREVIEW = \"__tempo_sentinel__\";\n\n/** Marks the sentinel's host element. */\nexport const FLUTTER_SIZING_SENTINEL_ATTRIBUTE =\n \"data-tempo-flutter-sizing-sentinel\";\n\n/** One mounted storyboard view, as the sizing strategy sees it. */\nexport type FlutterSizedView = {\n hostElement: HTMLElement;\n /** The storyboard's size in CSS px, the size its Dart shell lays out at. */\n width: number;\n height: number;\n};\n\nexport type FlutterSizingState = {\n /** The engine's app, or null once no engine is ready. */\n app: FlutterApp | null;\n views: readonly FlutterSizedView[];\n};\n\n/**\n * The workaround as the runtime drives it: the runtime reports each change\n * to its view set and each engine restart, and the strategy reads the current\n * set itself when it acts.\n *\n * The mechanism is the sentinel, chosen by experiment on 3.47.7 over the\n * \"arena\" (every real host sized to the uniform max). Real hosts keep their\n * own sizes because the bug affects only the canvas bitmap; the storyboard\n * content clips to its size and the relay crops to it.\n */\nexport type FlutterViewSizing = {\n /** A storyboard view was added or removed. */\n viewsChanged(): void;\n /** The engine restarted: the sentinel died with the old app. */\n engineRestarted(): void;\n};\n\ntype SentinelView = { app: FlutterApp; viewId: number; host: HTMLElement };\n\nexport function createFlutterViewSizing(\n win: Window,\n readState: () => FlutterSizingState,\n): FlutterViewSizing {\n let sentinel: SentinelView | null = null;\n let refreshQueued = false;\n\n /** Drops the sentinel's host element; the caller decides about its view. */\n function forgetSentinel(): SentinelView | null {\n const current = sentinel;\n sentinel = null;\n current?.host.remove();\n return current;\n }\n\n /** Remove, then add a fresh sentinel: only an add re-derives canvas sizes,\n * and a removal lets them shrink. */\n function refresh() {\n refreshQueued = false;\n const removed = forgetSentinel();\n if (removed) {\n try {\n removed.app.removeView(removed.viewId);\n } catch {\n // A dead engine already dropped its views.\n }\n }\n const { app, views } = readState();\n if (!app || views.length === 0) return;\n const width = Math.max(...views.map((view) => view.width));\n const height = Math.max(...views.map((view) => view.height));\n const host = win.document.createElement(\"div\");\n host.setAttribute(FLUTTER_SIZING_SENTINEL_ATTRIBUTE, \"\");\n host.setAttribute(\"aria-hidden\", \"true\");\n host.setAttribute(\"data-tempo-hide-fiber\", \"true\");\n // Off-screen, never display:none: a host that measures 0x0 sizes nothing.\n Object.assign(host.style, {\n position: \"absolute\",\n left: \"-10000px\",\n top: \"0px\",\n width: `${width}px`,\n height: `${height}px`,\n pointerEvents: \"none\",\n });\n win.document.body.append(host);\n try {\n const viewId = app.addView({\n hostElement: host,\n initialData: {\n preview: FLUTTER_SIZING_SENTINEL_PREVIEW,\n width,\n height,\n },\n });\n sentinel = { app, viewId, host };\n } catch {\n host.remove();\n }\n }\n\n return {\n viewsChanged() {\n // In the same task as the add or removal, before the engine renders\n // its next frame: until the sentinel is the newest view again, every\n // taller or wider view renders clipped to the view just added. A\n // 100 ms debounce, re-armed by each add, kept that window open for\n // seconds while a cold canvas mounted its boards one at a time, and\n // every taller board showed a strip along its top. A microtask still\n // coalesces the adds of one commit into one refresh.\n if (refreshQueued) return;\n refreshQueued = true;\n queueMicrotask(refresh);\n },\n engineRestarted() {\n // Never remove it through the new app: its view ids restart, so the old\n // sentinel's id may name a new storyboard view. The re-added\n // storyboards schedule the next refresh.\n forgetSentinel();\n },\n };\n}\n","import type { FlutterPreviewProblem } from \"./flutter-preview\";\nimport { emitRenderErrorRecoveryBeat } from \"./render-error-recovery\";\nimport {\n createFlutterLayerStore,\n type FlutterLayerStore,\n} from \"./flutter-layers\";\nimport {\n createFlutterViewSizing,\n FLUTTER_MULTI_VIEW_SIZING_WORKAROUND,\n type FlutterViewSizing,\n} from \"./flutter-view-sizing\";\n\n/**\n * The document's one Flutter engine, shared by every `FlutterStoryboard`.\n *\n * Flutter Web runs one engine per document and renders any number of views\n * from it (multi-view embedding), so a storyboard is an `app.addView` into its\n * own host element, never a page of its own. This module boots that engine\n * once, hands its app to the storyboards that are mounted, keeps the\n * viewId bookkeeping, and copies each painted view into its storyboard's\n * light-DOM relay canvas, which is what the canvas projection streams.\n *\n * The engine is booted by the Flutter dev server's `flutter_bootstrap.js`,\n * served through the canvas host under `/__tempo/flutter/`. The bootstrap\n * never adds views; it publishes the app (the hand-off contract):\n *\n * window.__tempoFlutterApp = { app, generation }\n * window.dispatchEvent(new CustomEvent(\"tempo-flutter-app\",\n * { detail: window.__tempoFlutterApp }))\n *\n * A hot restart re-runs the bootstrap's entrypoint callback with a new app\n * and a higher generation. The old app's views are gone, so the bookkeeping\n * is dropped and every mounted storyboard adds its view again.\n *\n * Frames are observed here, not reported by Dart: the engine's frame\n * callbacks run before it hands a view its pixels, which it does with\n * `ImageBitmapRenderingContext.transferFromImageBitmap` on the view's canvas\n * after an awaited `createImageBitmap` (about 200 ms after a view's first\n * frame). This module wraps that method once per document and copies the\n * view into its relay right after the pixels land.\n *\n * A bootstrap that fails may dispatch `tempo-flutter-error` with\n * `detail: { message }` to fail fast; without it the runtime fails when the\n * hand-off misses its deadline.\n */\n\n/** The app `engine.runApp()` returns in multi-view mode. */\nexport type FlutterApp = {\n addView(options: { hostElement: HTMLElement; initialData?: unknown }): number;\n removeView(viewId: number): unknown;\n};\n\n/** What the bootstrap publishes on `window.__tempoFlutterApp`. */\nexport type FlutterAppHandoff = { app: FlutterApp; generation: number };\n\nexport const FLUTTER_BOOTSTRAP_URL = \"/__tempo/flutter/flutter_bootstrap.js\";\nexport const FLUTTER_APP_EVENT = \"tempo-flutter-app\";\nexport const FLUTTER_ERROR_EVENT = \"tempo-flutter-error\";\nconst BOOTSTRAP_SCRIPT_ATTRIBUTE = \"data-tempo-flutter-bootstrap\";\n\n/** Waits between unanswered bootstrap probes: 1 s, 2 s, 4 s, then 8 s. */\nconst PROBE_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000];\n/** Bounds one probe, so a server that accepts but never answers is retried. */\nconst PROBE_TIMEOUT_MS = 10_000;\n/** How often a dev server that says Flutter is starting is asked again, and\n * how often the gate's status is read while the engine boots. */\nconst STARTING_PROBE_INTERVAL_MS = 2_000;\n/** The gate's own status (`{ status, spawn, error, message }`), served beside\n * the bootstrap through the same proxy and never forwarded to Flutter. */\nconst GATE_STATUS_NAME = \"__tempo_flutter_status\";\n/** A bootstrap script whose body never finishes fires neither load nor error;\n * after this long the probes resume while it keeps loading. */\nconst SCRIPT_LOAD_BUDGET_MS = 30_000;\n/** How long an added view may go without a transfer before it is taken as a\n * scene that paints nothing. A view's first frame takes about 200 ms. */\nconst EMPTY_SCENE_GRACE_MS = 1_500;\n/** How long a painted view waits for its first widget snapshot before its\n * content counts as ready without one. The bridge walks at most 50 ms after\n * a frame (and the walk takes milliseconds), so a snapshot that has not come\n * by then is not coming: a generated host older than `tempo_layers.dart`, a\n * bridge that is off, or a walk that throws for this view. */\nexport const FLUTTER_LAYERS_GRACE_MS = 1_000;\n\n/**\n * The device pixel ratio every Flutter view renders at, whatever the host\n * document's own (an offscreen canvas host runs at 1). Why 2: boards stay\n * sharp when the canvas is zoomed in and their screenshots are sharper, at\n * four times the pixels per board in the engine's surface, the relay, the\n * pixel lane and the capture. The runtime hands it to the generated\n * main.dart on `window.__tempoFlutter.devicePixelRatio`, which applies it\n * with `ui_web.debugOverrideDevicePixelRatio` before any view exists. Fixed\n * for now; a ratio that follows the canvas zoom is a known limitation of the\n * rendering spec.\n */\nexport const FLUTTER_DEVICE_PIXEL_RATIO = 2;\n\n/** A typed Flutter runtime failure. The message names the code and the fix. */\nexport class FlutterRuntimeError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(`[${code}] ${message}`);\n this.name = \"FlutterRuntimeError\";\n this.code = code;\n }\n}\n\nexport type FlutterRuntimeState =\n /** The dev server has no engine to boot: Flutter is compiling (the gate\n * answers 503 `flutter_starting`), the gate does not answer, or the\n * bootstrap script failed to load or is still loading past its budget\n * (the gate answered, but the script's body stalls). That lasts seconds warm and minutes\n * cold, so boards show nothing of their own and hold no pending marker:\n * the capture lane is serial per host and waits on that marker for up to\n * its 30 s step budget, and the canvas times pending content out. A board\n * renders the unavailable marker instead (flutter.tsx), ordinary content\n * that says it has nothing to show or photograph. The progress is the dev\n * server's to report, in the canvas's loading bar. */\n | { kind: \"starting\" }\n /** Waiting seconds for a known answer: the first probe (the initial state)\n * or, after the bootstrap answered 200, the engine's boot. Boards render\n * the pending marker. The initial state is this one, not `starting`,\n * because a new document cannot yet tell whether Flutter is serving; a\n * capture lane document is often new while Flutter has long been ready,\n * and a capture taken before the first answer photographed nothing. The\n * round trip is milliseconds, bounded by the probe's timeout. Rendered\n * directly, never through Suspense: a component that suspends on an\n * update keeps its previous DOM hidden beside the fallback, which would\n * leave the unavailable marker in the document beside the pending one. */\n | { kind: \"loading\" }\n | { kind: \"ready\"; app: FlutterApp; generation: number }\n | { kind: \"failed\"; error: FlutterRuntimeError };\n\nexport type FlutterViewInit = {\n /** The element the view's layers hang from: it contains the engine's host\n * and the relay, and carries the view id and rev stamps the projection\n * reads (flutter-layers.ts). Never the engine's host itself, which the\n * engine empties on addView. */\n viewRoot: HTMLElement;\n /** The element the engine renders the view into. */\n hostElement: HTMLElement;\n /** The light-DOM canvas each painted frame is copied into. */\n relay: HTMLCanvasElement;\n preview: string;\n /** The storyboard's size in CSS px. */\n width: number;\n height: number;\n /** Called once, when the view's content is in the document: its first\n * frame has reached the relay (or its scene was settled as painting\n * nothing) and the layer store has published its first widget snapshot,\n * or `FLUTTER_LAYERS_GRACE_MS` after that first frame when no snapshot\n * comes. The board holds its pending marker until then, so the\n * projection's first full of the board carries its widgets. */\n onContentReady(): void;\n};\n\n/** An added view. Only the runtime that returned it can remove it. */\nexport type FlutterMountedView = { readonly viewId: number };\n\nexport type FlutterRuntime = {\n getState(): FlutterRuntimeState;\n getPreviewProblems(): readonly FlutterPreviewProblem[] | null;\n /** Notified when the engine becomes ready, restarts, or fails. */\n subscribe(listener: () => void): () => void;\n /** Adds a view to the ready engine. Throws when the engine is not ready. */\n addView(view: FlutterViewInit): FlutterMountedView;\n /** Removes a view; a view a restart already dropped is ignored. */\n removeView(view: FlutterMountedView): void;\n};\n\nexport type FlutterRuntimeOptions = {\n bootstrapUrl?: string;\n /** How long an unanswered dev server is retried before the runtime fails. */\n reachBudgetMs?: number;\n /** How long a loaded bootstrap may take to hand the app over. */\n bootBudgetMs?: number;\n /** How long the bootstrap script may load before the probes resume. */\n scriptBudgetMs?: number;\n};\n\ntype ViewEntry = {\n viewId: number;\n app: FlutterApp;\n init: FlutterViewInit;\n painted: boolean;\n /** The layer store has published a widget snapshot for this view. */\n layersPublished: boolean;\n /** `init.onContentReady` has been called. */\n contentReady: boolean;\n context: CanvasRenderingContext2D | null;\n emptySceneTimer: number;\n /** Runs from the first frame while no snapshot has come. */\n layersGraceTimer: number | null;\n};\n\n/** What the gate says about Flutter while a page's engine boots. */\ntype GateDiagnostics = {\n resolutionRevision?: number;\n previewProblems?: FlutterPreviewProblem[];\n};\ntype GateStatus = (\n | { status: \"starting\" | \"ready\" | \"reloading\" }\n | { status: \"failed\"; error: FlutterRuntimeError }\n) &\n GateDiagnostics;\n\ntype ProbeOutcome =\n | { kind: \"ok\" }\n /** The dev server is starting Flutter (first spawn, or a relaunch). */\n | { kind: \"starting\" }\n /** Nothing answered: Flutter is still compiling, or its port is dead. */\n | { kind: \"unanswered\" }\n /** The dev server named its failure (a missing SDK, a failed `flutter\n * run`); it may still recover, e.g. after the user fixes the app. */\n | { kind: \"reported\"; error: FlutterRuntimeError }\n /** This host serves no Flutter at all; only a new host page changes that. */\n | { kind: \"unconfigured\"; error: FlutterRuntimeError };\n\nlet documentRuntime: FlutterRuntime | null = null;\n\n/** The document's runtime, created (and its engine boot started) on first use. */\nexport function getFlutterRuntime(): FlutterRuntime {\n documentRuntime ??= createFlutterRuntime(window);\n return documentRuntime;\n}\n\n/** A module import that failed to load, with its URL (Chromium, Firefox). */\nconst MODULE_IMPORT_FAILURE =\n /(?:Failed to fetch dynamically imported module|error loading dynamically imported module): (\\S+)/i;\n/** A fetch or module load that failed without naming its URL. */\nconst FETCH_FAILURE =\n /Failed to fetch|NetworkError when attempting to fetch|Importing a module script failed/i;\n\n/**\n * The flutter_boot_failed message for what the bootstrap caught. A failed\n * load (the engine's renderer, CanvasKit, or a module it imports) is a\n * network or asset failure, and says so with its URL. Only another error\n * points at Dart: a compile error surfaces through the dev server's log.\n */\nfunction bootFailure(caught: string): string {\n const url = MODULE_IMPORT_FAILURE.exec(caught)?.[1];\n if (url) {\n return `The Flutter engine failed to start: it could not load ${url}. That is a network or asset failure, not a Dart compile error: check that this machine can reach that URL, then reload the canvas.`;\n }\n if (FETCH_FAILURE.test(caught)) {\n return `The Flutter engine failed to start: ${caught}. That is a network or asset failure, not a Dart compile error: check that the canvas dev server is running and reachable, then reload the canvas.`;\n }\n return `The Flutter engine failed to start: ${caught}. Check the canvas dev server log for Dart compile errors.`;\n}\n\nexport function createFlutterRuntime(\n win: Window,\n options: FlutterRuntimeOptions = {},\n): FlutterRuntime {\n const bootstrapUrl = options.bootstrapUrl ?? FLUTTER_BOOTSTRAP_URL;\n const reachBudgetMs = options.reachBudgetMs ?? 60_000;\n const bootBudgetMs = options.bootBudgetMs ?? 60_000;\n const scriptBudgetMs = options.scriptBudgetMs ?? SCRIPT_LOAD_BUDGET_MS;\n const listeners = new Set<() => void>();\n const views = new Map<number, ViewEntry>();\n // The bootstrap script this runtime added, until it fails to load. The\n // browser cannot cancel a script it has started fetching: a removed element\n // still runs when its response arrives (verified in Chromium). A script\n // that outlives its deadline is therefore waited on again, never replaced,\n // because a replacement could start a second engine.\n let bootstrapScript: Promise<boolean> | null = null;\n let bootstrapScriptAddedAt = 0;\n let bootstrapScriptLoaded = false;\n // Whether the script in flight is still within its budget: the engine then\n // boots in seconds, which is what the pending marker promises.\n const scriptLoadingInBudget = () =>\n bootstrapScript !== null &&\n !bootstrapScriptLoaded &&\n Date.now() - bootstrapScriptAddedAt < scriptBudgetMs;\n const gateStatusUrl = bootstrapUrl.replace(/[^/]*$/, GATE_STATUS_NAME);\n // Loading until the first probe answers (see FlutterRuntimeState).\n let state: FlutterRuntimeState = { kind: \"loading\" };\n let previewProblems: readonly FlutterPreviewProblem[] | null = null;\n let resolutionRevision: number | undefined;\n let latestGate: GateStatus | null = null;\n async function pollGate() {\n const gate = await readGateStatus(win, gateStatusUrl);\n if (gate) {\n latestGate = gate;\n if (gate.status === \"failed\") fail(gate.error);\n if (\n Array.isArray(gate.previewProblems) &&\n (gate.resolutionRevision !== resolutionRevision ||\n previewProblems === null)\n ) {\n resolutionRevision = gate.resolutionRevision;\n previewProblems = gate.previewProblems ?? [];\n for (const listener of [...listeners]) listener();\n emitRenderErrorRecoveryBeat();\n }\n }\n win.setTimeout(() => {\n void pollGate();\n }, STARTING_PROBE_INTERVAL_MS);\n }\n void pollGate();\n const sizing: FlutterViewSizing | null = FLUTTER_MULTI_VIEW_SIZING_WORKAROUND\n ? createFlutterViewSizing(win, () => ({\n app: state.kind === \"ready\" ? state.app : null,\n views: [...views.values()].map((entry) => entry.init),\n }))\n : null;\n // The widget snapshots the Dart bridge pushes, kept per view for the\n // projection to read (see flutter-layers.ts).\n const layers: FlutterLayerStore = createFlutterLayerStore(win, {\n onPublished: noteLayersPublished,\n });\n\n function setState(next: FlutterRuntimeState) {\n state = next;\n for (const listener of [...listeners]) listener();\n }\n\n function fail(error: FlutterRuntimeError) {\n // Background probing repeats the same failure every few seconds; only a\n // changed failure is news to the storyboards.\n if (state.kind === \"failed\" && state.error.message === error.message) {\n return;\n }\n setState({ kind: \"failed\", error });\n }\n\n function adoptHandoff(handoff: unknown) {\n if (!isFlutterAppHandoff(handoff)) return;\n const unchanged =\n state.kind === \"ready\" &&\n state.app === handoff.app &&\n state.generation === handoff.generation;\n if (unchanged) return;\n // A new app means the old engine and every view it held are gone. The\n // storyboards re-add theirs when they see the new state; an id in the\n // new app may repeat an old one, so no old entry may survive to match it.\n views.clear();\n layers.reset();\n sizing?.engineRestarted();\n installFrameHook();\n setState({\n kind: \"ready\",\n app: handoff.app,\n generation: handoff.generation,\n });\n }\n\n // `window.__tempoFlutter` is the SDK's object; augment rather than replace\n // it, since every hook (frames, layers) hangs off the same object.\n // `onFrame` and `onLayers` are the runtime the hooks report to: re-pointing\n // them at each hand-off lets a hook installed by an earlier runtime in this\n // document keep working.\n function installFrameHook() {\n const globals = win as unknown as { __tempoFlutter?: unknown };\n if (\n typeof globals.__tempoFlutter !== \"object\" ||\n globals.__tempoFlutter === null\n ) {\n globals.__tempoFlutter = {};\n }\n const hooks = globals.__tempoFlutter as {\n onFrame?: unknown;\n onLayers?: unknown;\n layers?: unknown;\n wantLayers?: unknown;\n devicePixelRatio?: unknown;\n };\n // Read by the generated main.dart before its first view: set before the\n // bootstrap script is added.\n hooks.devicePixelRatio = FLUTTER_DEVICE_PIXEL_RATIO;\n hooks.onFrame = handleFrame;\n hooks.onLayers = layers.onLayers;\n hooks.layers = { get: layers.get };\n // The bridge walks widgets only while this is true, and only on frames,\n // so it is set before the first addView. Every document wants the walk:\n // after the first Play the interact iframe becomes the projection\n // source and keeps that role after Stop, so it needs layers too.\n hooks.wantLayers = true;\n installViewPaintHook(win);\n }\n\n // Runs inside the engine's render path right after a view's pixels landed,\n // so the copy reads this frame. It must never throw into the engine.\n function handleFrame(viewIds?: unknown) {\n try {\n const ids =\n viewIds === undefined || viewIds === null\n ? [...views.keys()]\n : Array.from(viewIds as ArrayLike<unknown>, Number);\n for (const id of ids) {\n const entry = views.get(id);\n if (entry) copyFrame(entry);\n }\n } catch {\n // A malformed report must not break the engine's render loop.\n }\n }\n\n function copyFrame(entry: ViewEntry) {\n let copied = false;\n try {\n copied = copyViewToRelay(entry);\n } catch {\n // One view's unreadable canvas must not hold back the others.\n }\n if (copied) markPainted(entry);\n }\n\n function markPainted(entry: ViewEntry) {\n if (entry.painted) return;\n entry.painted = true;\n win.clearTimeout(entry.emptySceneTimer);\n settleContent(entry);\n }\n\n function noteLayersPublished(viewId: number) {\n const entry = views.get(viewId);\n if (!entry || entry.layersPublished) return;\n entry.layersPublished = true;\n settleContent(entry);\n }\n\n // A view's content is in the document once its pixels are on the relay\n // and its widgets are in the layer store. The board's pending marker comes\n // off then, and the producer's full of the root, which the marker held,\n // reads both. Pixels alone were not enough: the bridge walks at most every\n // 50 ms across all views, so a view whose first frame landed inside\n // another view's window went out as a widgetless host, and a board the\n // canvas rests after its first baseline kept no widgets in Layers.\n // Usually the snapshot comes first (the walk runs in the frame callback,\n // before the engine hands the view its pixels), so this adds nothing; a\n // deferred walk adds at most its 50 ms window. A snapshot that never\n // comes is bounded by FLUTTER_LAYERS_GRACE_MS from the first frame.\n function settleContent(entry: ViewEntry) {\n if (!entry.painted || entry.contentReady) return;\n if (entry.layersPublished) {\n reportContentReady(entry);\n return;\n }\n if (entry.layersGraceTimer !== null) return;\n entry.layersGraceTimer = win.setTimeout(() => {\n entry.layersGraceTimer = null;\n if (views.get(entry.viewId) === entry) reportContentReady(entry);\n }, FLUTTER_LAYERS_GRACE_MS);\n }\n\n function reportContentReady(entry: ViewEntry) {\n if (entry.contentReady) return;\n entry.contentReady = true;\n if (entry.layersGraceTimer !== null) {\n win.clearTimeout(entry.layersGraceTimer);\n entry.layersGraceTimer = null;\n }\n entry.init.onContentReady();\n }\n\n // A preview whose scene paints nothing never transfers a bitmap. Without\n // this its pending marker would hold every capture until the capture lane\n // spends its settle budget, so an attached view that stays silent counts\n // as painted empty: the relay is left blank, and the marker goes once its\n // widgets are published, as for any painted view. The bridge walks it\n // like any other: an empty widget tree is a snapshot with no nodes.\n function settleEmptyScene(entry: ViewEntry) {\n if (views.get(entry.viewId) !== entry || entry.painted) return;\n if (!entry.init.hostElement.querySelector(\"flutter-view\")) return;\n // The empty scene is this view's first frame: the relay takes its size\n // in the same task it goes blank, as a painted frame does.\n const relay = entry.init.relay;\n const size = sizeRelay(\n relay,\n entry.init.width,\n entry.init.height,\n FLUTTER_DEVICE_PIXEL_RATIO,\n );\n entry.context ??= relay.getContext(\"2d\");\n entry.context?.clearRect(0, 0, size.width, size.height);\n markPainted(entry);\n }\n\n // Nothing known to finish in seconds is booting: the boards have nothing to\n // show. Reached from the initial state's first answer, from a failure the\n // dev server is recovering from (a relaunch; the error boundaries retry into\n // it), on every probe that reports Flutter still starting or the gate\n // unanswered, and when the bootstrap script outlives its budget.\n function becomeStarting() {\n if (state.kind === \"ready\" || state.kind === \"starting\") return;\n // A bootstrap still loading within its budget will hand the app over in\n // seconds; one that failed to load, or is long overdue, is not that.\n if (state.kind === \"loading\" && scriptLoadingInBudget()) return;\n setState({ kind: \"starting\" });\n }\n\n // The bootstrap answered: the engine boots now, and the boards hold the\n // pending marker until it paints. An answer also ends a failure the dev\n // server has recovered from.\n function becomeLoading() {\n if (state.kind !== \"starting\" && state.kind !== \"failed\") return;\n setState({ kind: \"loading\" });\n }\n\n // Adds the bootstrap script once and waits for it within what remains of\n // its budget. Past the budget the boards go back to starting while the\n // probes continue: a script whose body stalls (a held connection) may still\n // finish, and must never be replaced (see bootstrapScript).\n async function loadBootstrap(): Promise<\"loaded\" | \"failed\" | \"loading\"> {\n if (bootstrapScript === null) {\n bootstrapScript = injectBootstrapScript(win, bootstrapUrl);\n bootstrapScriptAddedAt = Date.now();\n }\n const remainingMs = bootstrapScriptAddedAt + scriptBudgetMs - Date.now();\n if (remainingMs > 0) becomeLoading();\n const loaded = await settledWithin(\n win,\n bootstrapScript,\n Math.max(0, remainingMs),\n );\n if (loaded === true) {\n bootstrapScriptLoaded = true;\n becomeLoading();\n return \"loaded\";\n }\n // A script that failed to load never ran, so a later answer may add a\n // fresh one, and nothing is booting meanwhile.\n if (loaded === false) {\n bootstrapScript = null;\n becomeStarting();\n return \"failed\";\n }\n // The gate answered, so this is never the unreachable budget's failure;\n // a script that has not loaded within its budget and the boot's together\n // gets a failure that names it.\n const stalledBudgetMs = scriptBudgetMs + bootBudgetMs;\n if (Date.now() - bootstrapScriptAddedAt >= stalledBudgetMs) {\n fail(\n new FlutterRuntimeError(\n \"flutter_bootstrap_stalled\",\n `The Flutter dev server answered ${bootstrapUrl}, but the script did not finish loading within ${Math.round(stalledBudgetMs / 1000)} s. Reload the canvas; if it persists, check the canvas dev server log.`,\n ),\n );\n } else becomeStarting();\n return \"loading\";\n }\n\n // A function, not an inline check: the state changes across the awaits\n // below (a published app can arrive at any time).\n const engineReady = () => state.kind === \"ready\";\n\n async function bootEngine() {\n // What the dev server last answered, and since when: the backoff and the\n // unanswered budget both run from the moment the answer changed, so a\n // named failure followed by a relaunch never inherits a spent budget.\n let answer: string | null = null;\n let since = Date.now();\n let attempt = 0;\n while (!engineReady()) {\n const probe = await probeBootstrap(win, bootstrapUrl);\n if (engineReady()) return;\n if (probe.kind === \"unconfigured\") {\n fail(probe.error);\n return;\n }\n if (probe.kind === \"ok\") {\n const loaded = await loadBootstrap();\n if (engineReady()) return;\n if (loaded === \"loaded\") {\n await awaitHandoff();\n return;\n }\n // A script that failed to load, or one still loading past its\n // budget: the probes below keep asking, so a dev server that changes\n // its answer (a relaunch, a named failure) is heard.\n }\n const observed =\n probe.kind === \"reported\" ? `reported:${probe.error.code}` : probe.kind;\n if (observed !== answer) {\n answer = observed;\n since = Date.now();\n attempt = 0;\n }\n // Starting Flutter takes as long as its first compile; the boards wait\n // however long that is, with no budget.\n if (probe.kind === \"starting\") {\n becomeStarting();\n await new Promise((resolve) =>\n win.setTimeout(resolve, STARTING_PROBE_INTERVAL_MS),\n );\n continue;\n }\n // An unanswered gate is starting too (becomeStarting leaves a loading\n // state alone only while a script loads within its budget); a named\n // failure the boards already show is not replaced by it.\n if (probe.kind === \"unanswered\" && state.kind !== \"failed\")\n becomeStarting();\n // A named failure fails the storyboards at once. Either way the probing\n // continues, capped at 8 s, so a dev server that recovers or comes up\n // later still boots the engine (the storyboards' error boundaries retry\n // on their own timers).\n if (probe.kind === \"reported\") fail(probe.error);\n const delay =\n PROBE_RETRY_DELAYS_MS[\n Math.min(attempt, PROBE_RETRY_DELAYS_MS.length - 1)\n ] ?? 8_000;\n attempt += 1;\n // Unanswered: nothing reached the dev server's gate (a 502 from the\n // canvas host, a dead port). The storyboards fail once the next wait\n // would cross the budget. Only an unanswered probe spends it: a gate\n // that answered 200 is reachable however slowly its script loads.\n const budgetSpent = Date.now() - since + delay > reachBudgetMs;\n if (probe.kind === \"unanswered\" && budgetSpent) {\n fail(\n new FlutterRuntimeError(\n \"flutter_unreachable\",\n `The Flutter dev server did not answer ${bootstrapUrl} within ${Math.round(reachBudgetMs / 1000)} s. Tempo starts Flutter when a canvas preview resolves; check the canvas dev server log (install Flutter or set TEMPO_FLUTTER_BIN if it reports flutter_sdk_missing).`,\n ),\n );\n }\n await new Promise((resolve) => win.setTimeout(resolve, delay));\n }\n }\n\n // The engine boots between the bootstrap's load and its hand-off, and the\n // boot budget measures only that: time while the dev server serves Flutter.\n // The gate is read meanwhile, because the dev server can reload or relaunch\n // Flutter under a booting page: a save held through a compile is flushed as\n // a hot reload the moment Flutter is ready, exactly when pages start\n // booting. Any state but ready stops the clock, and the next ready starts\n // the phase over, also after the budget ran out once: a board fails only\n // after a full budget of uninterrupted ready. A relaunch also returns the\n // boards to starting, since their engine dies with its process; the host\n // page reloads once the new process is ready (spec §8.4). The bootstrap\n // loads once per document (a second load would start a second engine), so\n // waiting is all this can do, and a hand-off after the deadline still\n // recovers.\n async function awaitHandoff() {\n let deadline: number | null = null;\n let clockStopped = false;\n const startClock = () => {\n deadline = win.setTimeout(() => {\n deadline = null;\n if (engineReady()) return;\n fail(\n new FlutterRuntimeError(\n \"flutter_boot_timeout\",\n `${bootstrapUrl} loaded but the Flutter engine did not start within ${Math.round(bootBudgetMs / 1000)} s of Flutter serving it. Check the canvas dev server log and the browser console for Dart compile errors.`,\n ),\n );\n }, bootBudgetMs);\n };\n const stopClock = () => {\n if (deadline !== null) win.clearTimeout(deadline);\n deadline = null;\n clockStopped = true;\n };\n startClock();\n while (!engineReady()) {\n await new Promise((resolve) =>\n win.setTimeout(resolve, STARTING_PROBE_INTERVAL_MS),\n );\n if (engineReady()) break;\n const gate = latestGate;\n if (engineReady()) break;\n // An unreadable status leaves the clock as it is.\n if (gate === null) continue;\n if (gate.status === \"ready\") {\n if (!clockStopped) continue;\n clockStopped = false;\n becomeLoading();\n startClock();\n continue;\n }\n stopClock();\n if (gate.status === \"starting\") becomeStarting();\n if (gate.status === \"failed\") fail(gate.error);\n // Reloading: the boards keep their pending marker; it takes seconds.\n }\n stopClock();\n }\n\n installFrameHook();\n win.addEventListener(FLUTTER_APP_EVENT, (event) => {\n adoptHandoff((event as CustomEvent<unknown>).detail);\n });\n win.addEventListener(FLUTTER_ERROR_EVENT, (event) => {\n const detail = (event as CustomEvent<{ message?: unknown } | undefined>)\n .detail;\n const message =\n typeof detail?.message === \"string\" ? detail.message : \"unknown error\";\n fail(new FlutterRuntimeError(\"flutter_boot_failed\", bootFailure(message)));\n });\n const published = (win as unknown as { __tempoFlutterApp?: unknown })\n .__tempoFlutterApp;\n if (isFlutterAppHandoff(published)) adoptHandoff(published);\n else void bootEngine();\n\n return {\n getState: () => state,\n getPreviewProblems: () => previewProblems,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n addView(init) {\n if (state.kind !== \"ready\") {\n throw state.kind === \"failed\"\n ? state.error\n : new Error(\"The Flutter engine is not ready yet.\");\n }\n const { app } = state;\n // A restart leaves the dead engine's flutter-view behind in the host.\n init.hostElement.replaceChildren();\n const viewId = app.addView({\n hostElement: init.hostElement,\n initialData: {\n preview: init.preview,\n width: init.width,\n height: init.height,\n },\n });\n const entry: ViewEntry = {\n viewId,\n app,\n init,\n painted: false,\n layersPublished: false,\n contentReady: false,\n context: null,\n emptySceneTimer: 0,\n layersGraceTimer: null,\n };\n entry.emptySceneTimer = win.setTimeout(\n () => settleEmptyScene(entry),\n EMPTY_SCENE_GRACE_MS,\n );\n views.set(viewId, entry);\n // Stamped before the engine's first frame, so the bridge's first\n // snapshot for this view finds its root.\n layers.viewAdded(viewId, init.viewRoot);\n // The relay is not sized here. A new size is a new view, and assigning\n // a canvas dimension clears it: the canvas lane streamed that cleared\n // relay for the 50 to 100 ms before the new view's first frame, a blank\n // board after every resize. It keeps the replaced view's pixels instead,\n // at their own size and scale, until copyViewToRelay sizes its backing\n // and CSS box and draws the new frame in one task.\n sizing?.viewsChanged();\n return entry;\n },\n removeView(view) {\n const entry = view as ViewEntry;\n if (views.get(entry.viewId) !== entry) return;\n views.delete(entry.viewId);\n layers.viewRemoved(entry.viewId);\n win.clearTimeout(entry.emptySceneTimer);\n if (entry.layersGraceTimer !== null) {\n win.clearTimeout(entry.layersGraceTimer);\n }\n try {\n entry.app.removeView(entry.viewId);\n } catch {\n // A failed engine may refuse; its views are gone either way.\n }\n sizing?.viewsChanged();\n },\n };\n}\n\nfunction isFlutterAppHandoff(value: unknown): value is FlutterAppHandoff {\n if (typeof value !== \"object\" || value === null) return false;\n const { app, generation } = value as { app?: unknown; generation?: unknown };\n return (\n typeof generation === \"number\" &&\n typeof app === \"object\" &&\n app !== null &&\n typeof (app as { addView?: unknown }).addView === \"function\" &&\n typeof (app as { removeView?: unknown }).removeView === \"function\"\n );\n}\n\n/**\n * Asks for the bootstrap before loading it as a script: a script's error event\n * carries no status or body, and a canvas host without the Flutter proxy\n * answers with its own index.html, which a script tag would run and then wait\n * on forever.\n */\nasync function probeBootstrap(win: Window, url: string): Promise<ProbeOutcome> {\n const controller = new AbortController();\n const timeout = win.setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);\n try {\n const response = await win.fetch(url, {\n cache: \"no-store\",\n signal: controller.signal,\n });\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (response.ok && contentType.includes(\"text/html\")) {\n return {\n kind: \"unconfigured\",\n error: new FlutterRuntimeError(\n \"flutter_not_configured\",\n `This canvas host has no Flutter dev server: ${url} returned the host page. Tempo enables Flutter when a canvas declares a FlutterStoryboard; a newly added board triggers one host reload.`,\n ),\n };\n }\n if (response.ok) return { kind: \"ok\" };\n const body = await response.json().catch(() => null);\n const code =\n typeof body?.error === \"string\" && body.error.trim()\n ? body.error.trim()\n : null;\n // The dev server answers on Flutter's port itself while Flutter is not\n // serving: 503 `flutter_starting` while it starts, else 503 with\n // `flutter_sdk_missing | flutter_app_invalid | flutter_run_failed`, a\n // failure worth showing at once rather than after the unanswered budget.\n if (code === \"flutter_starting\") return { kind: \"starting\" };\n if (code && code !== \"flutter_unreachable\") {\n const message =\n typeof body?.message === \"string\" && body.message.trim()\n ? body.message.trim()\n : `The Flutter dev server reported ${code} for ${url}.`;\n return {\n kind: \"reported\",\n error: new FlutterRuntimeError(code, message),\n };\n }\n return { kind: \"unanswered\" };\n } catch {\n return { kind: \"unanswered\" };\n } finally {\n win.clearTimeout(timeout);\n }\n}\n\n/** The gate's status, or null when nothing readable answered (an old dev\n * server, a dead port, a host page without the Flutter proxy). */\nasync function readGateStatus(\n win: Window,\n url: string,\n): Promise<GateStatus | null> {\n const controller = new AbortController();\n const timeout = win.setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);\n try {\n const response = await win.fetch(url, {\n cache: \"no-store\",\n signal: controller.signal,\n });\n if (!response.ok) return null;\n const body = await response.json().catch(() => null);\n const status = body?.status;\n if (status === \"failed\") {\n const code =\n typeof body.error === \"string\" && body.error\n ? body.error\n : \"flutter_run_failed\";\n const message =\n typeof body.message === \"string\" && body.message.trim()\n ? body.message.trim()\n : `The Flutter dev server reported ${code}.`;\n return {\n status,\n error: new FlutterRuntimeError(code, message),\n resolutionRevision: body.resolutionRevision,\n previewProblems: body.previewProblems,\n };\n }\n const known =\n status === \"starting\" || status === \"ready\" || status === \"reloading\";\n return known\n ? {\n status,\n resolutionRevision: body.resolutionRevision,\n previewProblems: body.previewProblems,\n }\n : null;\n } catch {\n return null;\n } finally {\n win.clearTimeout(timeout);\n }\n}\n\n/**\n * Resolves true once the bootstrap script ran, false when it failed to load.\n * A failed script never ran, so its element is removed and a later attempt\n * may add another. A response whose body stops arriving settles neither way.\n */\nfunction injectBootstrapScript(win: Window, url: string): Promise<boolean> {\n const document = win.document;\n // A bootstrap that already ran here (its flutter.js defines `_flutter`)\n // must not run again: a second run starts a second engine.\n const ran = (win as unknown as { _flutter?: unknown })._flutter !== undefined;\n if (ran || document.querySelector(`script[${BOOTSTRAP_SCRIPT_ATTRIBUTE}]`)) {\n return Promise.resolve(true);\n }\n return new Promise((resolve) => {\n const script = document.createElement(\"script\");\n script.src = url;\n script.setAttribute(BOOTSTRAP_SCRIPT_ATTRIBUTE, \"\");\n script.addEventListener(\"load\", () => resolve(true), { once: true });\n script.addEventListener(\n \"error\",\n () => {\n script.remove();\n resolve(false);\n },\n { once: true },\n );\n document.head.append(script);\n });\n}\n\n/** The promise's value when it settles within `budgetMs`, else \"pending\". */\nfunction settledWithin<T>(\n win: Window,\n promise: Promise<T>,\n budgetMs: number,\n): Promise<T | \"pending\"> {\n return new Promise((resolve) => {\n const deadline = win.setTimeout(() => resolve(\"pending\"), budgetMs);\n void promise.then((value) => {\n win.clearTimeout(deadline);\n resolve(value);\n });\n });\n}\n\n/**\n * The link the pixel lane's draw tracker\n * (`modules/iframe-projection/canvas-frames/draw-tracker.ts`) keeps on every\n * wrapper it chains: the function that wrapper replaced. Following the same\n * protocol lets the tracker and this hook install and dispose in any order\n * without dropping each other.\n */\nconst WRAPPED_FUNCTION_LINK = Symbol.for(\n \"iframe-projection.canvas-frames.draw-tracker.inner\",\n);\n/** Marks a document whose bitmaprenderer prototype already carries the hook,\n * however many runtimes (module copies, re-evaluations) the document sees. */\nconst VIEW_PAINT_HOOK = Symbol.for(\"tempo-sdk.flutter.view-paint-hook\");\n\ntype TransferFromImageBitmap = (\n this: ImageBitmapRenderingContext,\n bitmap: ImageBitmap | null,\n) => void;\ntype LinkedTransfer = TransferFromImageBitmap & {\n [WRAPPED_FUNCTION_LINK]?: TransferFromImageBitmap;\n};\n\n/**\n * Wraps `ImageBitmapRenderingContext.prototype.transferFromImageBitmap`, the\n * call that hands a Flutter view its pixels, once per document. After the\n * call it reports the painted view to `window.__tempoFlutter.onFrame`. It\n * calls through whatever it replaced, so a draw tracker below it still sees\n * every transfer.\n */\nfunction installViewPaintHook(win: Window): void {\n const prototype = (\n win as unknown as {\n ImageBitmapRenderingContext?: { prototype: Record<PropertyKey, unknown> };\n }\n ).ImageBitmapRenderingContext?.prototype;\n if (!prototype || prototype[VIEW_PAINT_HOOK]) return;\n const descriptor = Object.getOwnPropertyDescriptor(\n prototype,\n \"transferFromImageBitmap\",\n );\n const replaced = descriptor?.value as TransferFromImageBitmap | undefined;\n if (typeof replaced !== \"function\") return;\n const hook: LinkedTransfer = function (this, bitmap) {\n const result = Reflect.apply(\n hook[WRAPPED_FUNCTION_LINK] ?? replaced,\n this,\n [bitmap],\n );\n reportViewPaint(win, this);\n return result;\n };\n hook[WRAPPED_FUNCTION_LINK] = replaced;\n Object.defineProperty(prototype, \"transferFromImageBitmap\", {\n ...descriptor,\n value: hook,\n });\n Object.defineProperty(prototype, VIEW_PAINT_HOOK, { value: true });\n}\n\n/**\n * Finds the Flutter view a painted canvas belongs to. The engine paints each\n * view into a canvas inside `flt-glass-pane`'s open shadow root, below the\n * view's `flutter-view`, whose `flt-view-id` attribute is the id `addView`\n * returned. Any other bitmaprenderer canvas in the document is ignored.\n */\nfunction reportViewPaint(\n win: Window,\n context: ImageBitmapRenderingContext,\n): void {\n try {\n const canvas = context.canvas as Partial<HTMLCanvasElement>;\n if (typeof canvas.getRootNode !== \"function\") return;\n const pane = (canvas.getRootNode() as Partial<ShadowRoot>).host;\n if (pane?.localName !== \"flt-glass-pane\") return;\n const viewId = pane.closest(\"flutter-view\")?.getAttribute(\"flt-view-id\");\n if (viewId === null || viewId === undefined) return;\n const hooks = (\n win as unknown as {\n __tempoFlutter?: { onFrame?: (viewIds: number[]) => void };\n }\n ).__tempoFlutter;\n hooks?.onFrame?.([Number(viewId)]);\n } catch {\n // Never throw into the engine's render path.\n }\n}\n\n/**\n * The pixel ratio the engine painted `canvas` at: it styles each render\n * canvas at its bitmap size over its ratio (render_canvas.dart). Read rather\n * than assumed: a generated main.dart older than FLUTTER_DEVICE_PIXEL_RATIO\n * renders at the browser's ratio, and a relay at another ratio would crop or\n * stretch the view. Null for a canvas with no CSS width.\n */\nfunction renderedPixelRatio(canvas: HTMLCanvasElement): number | null {\n const cssWidth = Number.parseFloat(canvas.style.width);\n return cssWidth > 0 ? canvas.width / cssWidth : null;\n}\n\n/**\n * Guard against flutter/flutter#185034: true when the engine painted this\n * view into a bitmap smaller than the view's physical size (its CSS size\n * times the ratio the engine rendered at). The bug gives every view's bitmap\n * the size of the most recently added view, so a taller board renders\n * clipped to a shorter one added after it until the sizing sentinel is the\n * newest view again. Copied, such a frame showed a strip along the board's\n * top and the rest blank. The caller skips it: the relay keeps its last good\n * pixels, and the frame the sentinel's add triggers (the Dart shell rebuilds\n * every view on a view change) is whole. A larger bitmap is the sentinel at\n * work and is cropped as usual. Judged only against a ratio the canvas\n * states (its CSS width): an assumed ratio would make a 1x canvas look\n * clipped and drop every frame. One pixel of slack, because the engine\n * rounds a fractional physical size its own way. Delete with\n * flutter-view-sizing.ts once the Flutter floor includes the upstream fix.\n */\nfunction isClippedByMultiViewSizingBug(\n entry: ViewEntry,\n sources: readonly HTMLCanvasElement[],\n): boolean {\n const ratio = renderedPixelRatio(sources[0]!);\n if (ratio === null) return false;\n const viewWidth = Math.round(entry.init.width * ratio);\n const viewHeight = Math.round(entry.init.height * ratio);\n return sources.some(\n (source) => source.width < viewWidth - 1 || source.height < viewHeight - 1,\n );\n}\n\n/** The relay's backing store holds the view's physical pixels. */\nfunction sizeRelay(\n relay: HTMLCanvasElement,\n width: number,\n height: number,\n devicePixelRatio: number,\n): { width: number; height: number } {\n const backingWidth = Math.max(1, Math.round(width * devicePixelRatio));\n const backingHeight = Math.max(1, Math.round(height * devicePixelRatio));\n // Assigning a canvas dimension clears it, even to the same value.\n if (relay.width !== backingWidth) relay.width = backingWidth;\n if (relay.height !== backingHeight) relay.height = backingHeight;\n // The CSS box changes with the backing, never before it: a box that\n // follows the board's new size while the backing still holds the old\n // frame shows that frame stretched. The projection mirrors both in one\n // DOM batch with the frame drawn in this same task.\n const cssWidth = `${width}px`;\n const cssHeight = `${height}px`;\n if (relay.style.width !== cssWidth) relay.style.width = cssWidth;\n if (relay.style.height !== cssHeight) relay.style.height = cssHeight;\n return { width: backingWidth, height: backingHeight };\n}\n\n/**\n * Copies the view's painted pixels into its relay. The engine paints each\n * view into canvases inside `flt-glass-pane`'s open shadow root, which the\n * projection never enters; the relay is the light-DOM canvas it streams.\n * A scene with platform views splits into several full-size canvases stacked\n * in DOM order, so every one is drawn, in that order. The source rectangle is\n * cropped to the storyboard because the engine's canvases can be larger than\n * the view (see flutter-view-sizing.ts). The relay takes the ratio the engine\n * actually painted at, so its pixels match the engine's 1:1.\n *\n * The relay's size, its cleared backing and the new pixels all change in\n * this one task, so nothing reads it between a resize and its frame. A frame\n * clipped by the multi-view sizing bug is never copied (see\n * isClippedByMultiViewSizingBug).\n */\nfunction copyViewToRelay(entry: ViewEntry): boolean {\n const sources = [\n ...(entry.init.hostElement\n .querySelector(\"flt-glass-pane\")\n ?.shadowRoot?.querySelectorAll(\"canvas\") ?? []),\n ].filter((canvas) => canvas.width > 0 && canvas.height > 0);\n if (sources.length === 0) return false;\n if (isClippedByMultiViewSizingBug(entry, sources)) return false;\n const relay = entry.init.relay;\n const size = sizeRelay(\n relay,\n entry.init.width,\n entry.init.height,\n renderedPixelRatio(sources[0]!) ?? FLUTTER_DEVICE_PIXEL_RATIO,\n );\n entry.context ??= relay.getContext(\"2d\");\n const context = entry.context;\n if (!context) return false;\n context.clearRect(0, 0, size.width, size.height);\n for (const source of sources) {\n context.drawImage(\n source,\n 0,\n 0,\n size.width,\n size.height,\n 0,\n 0,\n size.width,\n size.height,\n );\n }\n return true;\n}\n","import {\n parseFlutterPreview,\n FLUTTER_PREVIEW_KEY_ATTRIBUTE,\n} from \"./flutter-preview\";\nimport { FlutterRuntimeError } from \"./flutter-runtime\";\nimport { useLayoutEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport { PROJECTION_PENDING_ATTRIBUTE } from \"../../../modules/iframe-projection/combined/projection-pending\";\nimport { PROJECTION_SCOPE_ROLE } from \"../../../modules/iframe-projection/fiber/projection-scope\";\n\nimport { CAPTURE_CANVAS_ATTRIBUTE } from \"./canvas-host-operations\";\nimport {\n CanvasPendingMarker,\n CanvasUnavailableMarker,\n} from \"./canvas-pending-marker\";\nimport {\n type FlutterApp,\n type FlutterRuntime,\n type FlutterRuntimeState,\n getFlutterRuntime,\n} from \"./flutter-runtime\";\nimport { useStoryboardSize } from \"./runtime-context\";\nimport {\n type StoryboardLayout,\n StoryboardSlot,\n type StoryboardVrtConfig,\n} from \"./storyboard\";\n\n/**\n * A storyboard that renders a Flutter widget from the project's own Flutter\n * packages. `preview` names a public top-level `@Preview` function by a file\n * path relative to the declaring canvas and its name, e.g.\n * `\"../../../../mobile/lib/cards.dart#productCard\"`. The widget is a view of the document's one\n * Flutter engine, laid out at the storyboard's size.\n */\nexport function FlutterStoryboard({\n id,\n name,\n preview,\n layout,\n vrt,\n [FLUTTER_PREVIEW_KEY_ATTRIBUTE]: previewKey,\n}: {\n id: string;\n preview: string;\n layout: StoryboardLayout & { width: number; height: number };\n name?: string;\n /** Opt this storyboard into visual regression testing (static mark). */\n vrt?: boolean | StoryboardVrtConfig;\n // The compiler's source stamps are accepted and dropped: the content is\n // Flutter's, so no authored element can carry them.\n} & Record<`data-tempo-${string}`, unknown>) {\n return (\n <StoryboardSlot\n data-tempo-hide-fiber=\"true\"\n id={id}\n name={name}\n layout={layout}\n kind=\"component\"\n vrt={!!vrt}\n preview={preview}\n previewKey={typeof previewKey === \"string\" ? previewKey : undefined}\n // Parked boards stay laid out: the engine sizes the view from its\n // host's box, so the view keeps painting at its size (the relay a\n // capture reads stays current) and parking changes nothing in it.\n keepLayoutWhenParked\n >\n <FlutterViewMount\n id={id}\n preview={preview}\n previewKey={previewKey}\n layout={layout}\n />\n </StoryboardSlot>\n );\n}\n\n/** The size the slot renders at: the host runtime's size for this board (an\n * accepted resize, a direct-render width and height) when it has one, else\n * the declared layout, exactly as `StoryboardSlot` sizes itself. */\nfunction useFlutterViewSize(\n id: string,\n layout: { width: number; height: number },\n): { width: number; height: number } {\n const renderSize = useStoryboardSize(id);\n return {\n width:\n typeof renderSize?.width === \"number\" ? renderSize.width : layout.width,\n height:\n typeof renderSize?.height === \"number\"\n ? renderSize.height\n : layout.height,\n };\n}\n\nconst subscribeNowhere = () => () => {};\nconst noDocument = () => null;\n\n/** The runtime's state, thrown into the error boundary when the engine\n * failed; null when rendering without a document (server rendering). The\n * component renders each other state itself rather than suspending: a\n * component that suspends on an update keeps its previous DOM hidden\n * beside the fallback, which would leave the unavailable marker in the\n * document next to the pending one. */\nfunction useFlutterEngine(\n runtime: FlutterRuntime | null,\n): FlutterRuntimeState | null {\n const state: FlutterRuntimeState | null = useSyncExternalStore(\n runtime ? runtime.subscribe : subscribeNowhere,\n runtime ? runtime.getState : noDocument,\n noDocument,\n );\n if (!state) return null;\n return state;\n}\n\nfunction FlutterViewMount({\n id,\n preview: authoredPreview,\n previewKey,\n layout,\n}: {\n id: string;\n preview: string;\n previewKey: unknown;\n layout: { width: number; height: number };\n}) {\n // A new size is a new view: the Dart shell lays out from the view's\n // initialData, so the board re-adds it (which also refreshes the sizing\n // sentinel when the largest board grew).\n const { width, height } = useFlutterViewSize(id, layout);\n const runtime = typeof window === \"undefined\" ? null : getFlutterRuntime();\n const snapshot = useSyncExternalStore(\n runtime ? runtime.subscribe : subscribeNowhere,\n runtime\n ? () => runtime.getPreviewProblems() ?? runtime.getState()\n : noDocument,\n noDocument,\n );\n const problems = Array.isArray(snapshot) ? snapshot : null;\n const preview = typeof previewKey === \"string\" ? previewKey : \"\";\n const engineState = useFlutterEngine(runtime);\n const engine = engineState?.kind === \"ready\" ? engineState : null;\n const viewRootRef = useRef<HTMLDivElement | null>(null);\n const hostRef = useRef<HTMLDivElement | null>(null);\n const relayRef = useRef<HTMLCanvasElement | null>(null);\n const [mountError, setMountError] = useState<unknown>(null);\n // Every add is a new view whose content has yet to reach the document; the\n // key names the add so a replaced view's readiness cannot clear its marker.\n const viewKey = engine\n ? `${engine.generation}\\n${preview}\\n${width}x${height}`\n : null;\n const [readyViewKey, setReadyViewKey] = useState<string | null>(null);\n const contentReady = viewKey !== null && readyViewKey === viewKey;\n // Whether any view of this mount has been content-ready: the board's\n // first full waits for it (see the view root below).\n const [everContentReady, setEverContentReady] = useState(false);\n const app = engine?.app;\n\n useLayoutEffect(() => {\n const viewRoot = viewRootRef.current;\n const hostElement = hostRef.current;\n const relay = relayRef.current;\n if (!runtime || !app || !viewRoot || !hostElement || !relay) return;\n let view: ReturnType<FlutterRuntime[\"addView\"]>;\n try {\n view = runtime.addView({\n viewRoot,\n hostElement,\n relay,\n preview,\n width,\n height,\n onContentReady: () => {\n setReadyViewKey(viewKey);\n setEverContentReady(true);\n },\n });\n } catch (error) {\n setMountError(error);\n return;\n }\n return () => runtime.removeView(view);\n }, [runtime, app, viewKey, preview, width, height]);\n\n const parsed = parseFlutterPreview(authoredPreview);\n if (\"error\" in parsed)\n throw new FlutterRuntimeError(\"flutter_preview_invalid\", parsed.error);\n if (typeof previewKey !== \"string\")\n throw new FlutterRuntimeError(\n \"flutter_preview_unresolved\",\n \"This Flutter board's preview was not resolved by Tempo's canvas compiler; it renders only inside a Tempo canvas host.\",\n );\n const problem = problems?.find((problem) => problem.key === previewKey);\n if (problem) throw new FlutterRuntimeError(problem.code, problem.message);\n if (engineState?.kind === \"failed\") throw engineState.error;\n if (mountError) throw mountError;\n // Seconds: the first probe's answer, or the engine booting. The marker\n // holds captures and settle waits until the view's content is ready.\n if (engineState?.kind === \"loading\") return <CanvasPendingMarker />;\n // No engine to boot yet (the dev server compiling Flutter, or not\n // answering): minutes cold. The board paints nothing of its own, and the\n // progress is the dev server's, in the canvas's loading bar. A pending\n // marker here would hold the host's serial capture lane for its 30 s step\n // budget per capture (a sibling board's Cmd+L queued behind it) and trip\n // the canvas's pending timeouts, so the board commits the unavailable\n // marker: the canvas shows its loading presentation, owes no screenshot,\n // and any capture of the board is a typed discard.\n if (engineState?.kind === \"starting\") return <CanvasUnavailableMarker />;\n return (\n <>\n {/* The view root is the one layer of this board the projection emits:\n the runtime stamps it with the view id and rev (flutter-layers.ts)\n and the projection hands its subtree to the widget snapshot. It\n takes no data-tempo-hide-fiber prop, which would drop the node from\n the React lane; the projection marks it transparent on the wire.\n Both the engine's host and the relay sit inside it, so every point\n over the board resolves up the mirror's DOM to this layer. */}\n {/* Until this mount's first view is content-ready the root is pending\n too, so every child of the board is: the producer then reports the\n board suspended and serves its first full only once the widgets are\n in the layer store. Beside a visible root the marker alone holds\n captures, not that full, which carried a widgetless host whenever\n the first frame beat the bridge's walk; the canvas rests a board\n after its first baseline, so those widgets never arrived. Later\n views of the mount (a resize, a hot restart) keep their root\n unmarked: the receiver has its baseline, and their snapshots\n arrive as patches, with no suspended episode in a resize. */}\n <div\n ref={viewRootRef}\n data-tempo-flutter-root=\"\"\n {...(everContentReady ? {} : { [PROJECTION_PENDING_ATTRIBUTE]: \"\" })}\n style={{ position: \"relative\", width, height, overflow: \"hidden\" }}\n >\n {/* The engine's own element: addView empties it and appends its\n flutter-view, so nothing of ours may live inside. */}\n <div\n ref={hostRef}\n data-tempo-flutter-host=\"\"\n style={{ position: \"absolute\", inset: 0 }}\n />\n {/* Hidden from layers: the only rows inside a Flutter board are the\n user's widgets. The relay stays a real, visible element so the\n mirror shows its pixels, and a later sibling of the engine's host\n so it paints above the engine's view. */}\n {/* It also holds the board's whole image, so a capture reads it here\n (CAPTURE_CANVAS_ATTRIBUTE) instead of photographing the board. */}\n <FlutterRelay canvasRef={relayRef} width={width} height={height} />\n </div>\n {/* Holds captures and settle waits until this view's content is in\n the document: Flutter has painted it and the bridge has published\n its widgets (FlutterViewInit.onContentReady). The slot reports its\n commit before the engine's first frame. */}\n {contentReady ? null : <CanvasPendingMarker />}\n </>\n );\n}\n\n/**\n * The relay canvas. Its CSS box starts at the size of the board it is\n * created in, and from then on the runtime sizes the box together with the\n * backing, in the task that draws the frame of that size (`sizeRelay`):\n * React never changes it. Re-sized by React, the box followed a resize at\n * once while the backing still held the old frame, which showed stretched\n * until the new view's first frame. Created without a box, the relay's\n * mirror had none either until the patch that carried the first copy's,\n * which on a board opened cold lands up to a second after its first frame.\n */\nfunction FlutterRelay({\n canvasRef,\n width,\n height,\n}: {\n canvasRef: { current: HTMLCanvasElement | null };\n width: number;\n height: number;\n}) {\n const [createdBox] = useState(() => ({ width, height }));\n return (\n <canvas\n ref={canvasRef}\n data-tempo-flutter-relay=\"\"\n {...{ [CAPTURE_CANVAS_ATTRIBUTE]: \"\" }}\n data-tempo-hide-fiber=\"true\"\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n width: createdBox.width,\n height: createdBox.height,\n pointerEvents: \"none\",\n }}\n />\n );\n}\n\n// SDK plumbing between the public FlutterStoryboard and its content, never an\n// authored layer.\nObject.assign(FlutterViewMount, { [PROJECTION_SCOPE_ROLE]: \"transparent\" });\nObject.assign(FlutterRelay, { [PROJECTION_SCOPE_ROLE]: \"transparent\" });\n","/**\n * The CanvasHost protocol capability this SDK build implements.\n *\n * The authoritative compatibility gate is devserver-side: tempo-devserver\n * resolves the installed tempo-sdk package version BEFORE generating a host\n * document and refuses generation with a typed, actionable error when the\n * installed SDK predates the generated contract. That check cannot be an\n * in-host import assertion, because an SDK old enough to matter does not\n * export this constant — the named import itself would throw before any\n * assertion ran.\n *\n * This constant exists as defense-in-depth for FUTURE protocol bumps, once\n * every supported SDK version is known to export it.\n */\nexport const canvasHostCapability = {\n protocolVersion: 1,\n supportsModules: true,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EAEE,aAAAA;AAAA,EACA,eAAAC;AAAA,EACA,mBAAAC;AAAA,EACA,UAAAC;AAAA,EACA,YAAAC;AAAA,EACA,WAAAC;AAAA,EACA;AAAA,OACK;;;ACTP;AAAA,EACE;AAAA,EAGA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AC4BP,IAAM,WAAW;AAEjB,SAAS,aAAqC;AAC5C,QAAM,YAAY,oBAAI,IAA8C;AACpE,SAAO;AAAA,IACL,QAAQ,OAAO;AACb,iBAAW,YAAY,CAAC,GAAG,SAAS,EAAG,UAAS,KAAK;AAAA,IACvD;AAAA,IACA,UAAU,UAAU;AAClB,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM,UAAU,OAAO,QAAQ;AAAA,IACxC;AAAA,EACF;AACF;AAOO,SAAS,4BAAoD;AAClE,QAAM,UAAU;AAGhB,SAAQ,0CAAsB,WAAW;AAC3C;;;AD2DqB,cA8Hb,YA9Ha;AA5FrB,IAAM,4BAAN,cAAwC,UAGtC;AAAA,EAHF;AAAA;AAIE,iBAAQ,EAAE,UAAU,MAAM;AAAA;AAAA,EAE1B,OAAO,2BAA2B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,QACL,2BAAwB;AAAA,QACvB,GAAI,mBAAmB,CAAC,IAAI,EAAE,CAAC,4BAA4B,GAAG,GAAG;AAAA,QAClE,OAAO,EAAE,UAAU,YAAY,OAAO,QAAQ,UAAU,SAAS;AAAA,QAIjE;AAAA,0BAAAD;AAAA,YAAC;AAAA;AAAA,cACC,KAAK;AAAA,cACL,2BAAwB;AAAA,cACxB,OAAO,EAAE,UAAU,YAAY,OAAO,EAAE;AAAA;AAAA,UAC1C;AAAA,UAOA,gBAAAA,KAAC,gBAAa,WAAW,UAAU,OAAc,QAAgB;AAAA;AAAA;AAAA,IACnE;AAAA,IAKC,eAAe,OAAO,gBAAAA,KAAC,uBAAoB;AAAA,KAC9C;AAEJ;AAYA,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,QAAM,CAAC,UAAU,IAAII,UAAS,OAAO,EAAE,OAAO,OAAO,EAAE;AACvD,SACE,gBAAAJ;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL,4BAAyB;AAAA,MACxB,GAAG,EAAE,CAAC,wBAAwB,GAAG,GAAG;AAAA,MACrC,yBAAsB;AAAA,MACtB,OAAO;AAAA,QACL,UAAU;AAAA,QACV,MAAM;AAAA,QACN,KAAK;AAAA,QACL,OAAO,WAAW;AAAA,QAClB,QAAQ,WAAW;AAAA,QACnB,eAAe;AAAA,MACjB;AAAA;AAAA,EACF;AAEJ;AAIA,OAAO,OAAO,kBAAkB,EAAE,CAAC,qBAAqB,GAAG,cAAc,CAAC;AAC1E,OAAO,OAAO,cAAc,EAAE,CAAC,qBAAqB,GAAG,cAAc,CAAC;;;AC5R/D,IAAM,uBAAuB;AAAA,EAClC,iBAAiB;AAAA,EACjB,iBAAiB;AACnB;","names":["useEffect","useCallback","useLayoutEffect","useRef","useState","useMemo","replacement","Component","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","getObservedSourceFiles","sourceAnnotationSelector","useState","useRef","useLayoutEffect","useCallback","useEffect","currentRequest","message","useMemo","jsx","jsxs","useState","useRef","useMemo","useCallback","useLayoutEffect","useEffect","document","useLayoutEffect","useRef","useState","useSyncExternalStore","jsx","jsxs","useSyncExternalStore","useRef","useState","useLayoutEffect","problem"]}
|