tempo-sdk 0.0.57 → 0.0.60
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/dist/canvas/editor.js +1 -1
- package/dist/canvas/index.d.ts +4 -2
- package/dist/canvas/index.js +100 -20
- package/dist/canvas/index.js.map +1 -1
- package/dist/canvas/interact-projection.js +1 -1
- package/dist/canvas/parser.js +1 -1
- package/dist/canvas/svelte.d.ts +1 -1
- package/dist/canvas/svelte.js +1 -1
- package/dist/{chunk-U3SLJNRS.js → chunk-7DT5DDSH.js} +1 -1
- package/dist/chunk-7DT5DDSH.js.map +1 -0
- package/dist/{chunk-QXL6GL2P.js → chunk-FQSZRVSL.js} +3 -3
- package/dist/{chunk-QXL6GL2P.js.map → chunk-FQSZRVSL.js.map} +1 -1
- package/dist/{chunk-U64AHDHZ.js → chunk-MXKZZOLM.js} +14 -4
- package/dist/chunk-MXKZZOLM.js.map +1 -0
- package/dist/{chunk-EMYYTS6D.js → chunk-OTVBSF7U.js} +3 -3
- package/dist/{chunk-EMYYTS6D.js.map → chunk-OTVBSF7U.js.map} +1 -1
- package/dist/{chunk-RHHVVWAC.js → chunk-VMTQDG4U.js} +3 -3
- package/dist/{chunk-RHHVVWAC.js.map → chunk-VMTQDG4U.js.map} +1 -1
- package/dist/expo/plugin.cjs +2 -2
- package/dist/expo/plugin.cjs.map +1 -1
- package/dist/expo/plugin.js +1 -1
- package/dist/expo-babel-plugin.cjs +2 -2
- package/dist/expo-babel-plugin.cjs.map +1 -1
- package/dist/expo-babel-plugin.js +1 -1
- package/dist/index.js +211 -40
- package/dist/index.js.map +1 -1
- package/dist/nextjs/plugin.cjs +2 -2
- package/dist/nextjs/plugin.cjs.map +1 -1
- package/dist/nextjs/plugin.js +1 -1
- package/dist/nextjs-loader.cjs +4 -4
- package/dist/nextjs-loader.cjs.map +1 -1
- package/dist/nextjs.cjs +2 -2
- package/dist/nextjs.cjs.map +1 -1
- package/dist/nextjs.js +1 -1
- package/dist/{storyboard-BtQuVGpl.d.ts → storyboard-DjOF61B_.d.ts} +2 -0
- package/package.json +2 -2
- package/dist/chunk-U3SLJNRS.js.map +0 -1
- package/dist/chunk-U64AHDHZ.js.map +0 -1
package/dist/canvas/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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","../../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/source-identity.ts","../../canvas/runtime-problems.ts","../../canvas/host-capability.ts"],"sourcesContent":["import {\n type ReactNode,\n useEffect,\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\";\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\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()) 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 activeStoryboardIds,\n isStoryboardActive,\n}: {\n children?: ReactNode;\n canvasModules?: readonly CanvasHostModule[];\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 registeredCanvasPaths = useMemo(\n () =>\n [\n ...new Set(\n canvasModules?.map(({ canvasPath }) => canvasPath.trim()) ?? [],\n ),\n ].filter(Boolean),\n [canvasModules],\n );\n const directUrlSearch = useSyncExternalStore(\n subscribeDirectUrlSearch,\n readDirectUrlSearch,\n () => \"\",\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 );\n useEffect(() => {\n if (typeof document === \"undefined\") return;\n return protectCanvasHostDocumentTitle(document);\n }, []);\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 ? canvasModules?.filter(\n ({ canvasPath }) =>\n canvasPath.trim() === directUrlRender.canvasPath,\n )\n : canvasModules,\n [canvasModules, 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)) return;\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 return (\n <CanvasImportErrorBoundary key={retryRevision} reportError={reportError}>\n <Suspense fallback={<CanvasPendingMarker />}>\n <CanvasContext path={canvasPath}>\n <LazyCanvas replacement={replacement} />\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 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 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 {\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): {\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 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 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 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 current = renderEntriesRef.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, already-committed entry 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 const alreadyRendered =\n rendered &&\n (urlPinnedRenderIdRef.current === request.renderId ||\n (current?.status === \"active\" &&\n renderRequestMatchesEntry(current, 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) => {\n setEntries((entries) =>\n releaseRender(entries, renderId, maxCachedRef.current),\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 buildState = useCallback(\n () =>\n buildRenderStatePayload(\n renderEntriesRef.current,\n maxCachedRef.current,\n registeredCanvasPathsRef.current,\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 },\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 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 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:capture-image\") {\n const request = readRenderRequest(command.type, payload);\n void withRenderLease(request, () =>\n captureStoryboardImage(request.renderId, {\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 )\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: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(target.renderId);\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({ type: \"render-pool:ready\" }, \"*\");\n\n return () => {\n window.removeEventListener(\"message\", onMessage);\n window.removeEventListener(\"__render-pool:command\", onBridgeCommand);\n stopProblemPublisher();\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","export type CanvasHostCaptureResult = {\n img: {\n src: string;\n width: number;\n height: 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 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 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 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\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 },\n): Promise<CanvasHostCaptureResult | null> {\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 return await getCanvasHostRuntime().captureSelector(\n captureSelector,\n portalSelectors.length > 0\n ? { ...captureOptions, portalSelectors: [...new Set(portalSelectors)] }\n : captureOptions,\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 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 ...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","import type { CanvasHostRenderRequest } from \"./canvas-host-protocol\";\nimport { isV1CanvasClient, type V1RenderSizeCompat } from \"./v1-client-compat\";\n\nexport type CanvasHostRenderEntry = CanvasHostRenderRequest & {\n status: \"active\" | \"cached\";\n activeCount: number;\n revision: number;\n lastInactiveAt?: 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?.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 status: \"active\",\n activeCount: (current?.activeCount ?? 0) + 1,\n revision: changed ? (current?.revision ?? 0) + 1 : (current?.revision ?? 1),\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): ReadonlyMap<string, CanvasHostRenderEntry> {\n const current = entries.get(renderId);\n if (!current) return entries;\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 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((a, b) => (a.lastInactiveAt ?? 0) - (b.lastInactiveAt ?? 0));\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 revision: _revision,\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].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","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 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,WAAAC;AAAA,EACA;AAAA,OACK;;;ACLP;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,QAA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;AAC3C,cAAM,eAAe,YAAY,cAAc,eAAe;AAC9D,eAAO,iBAAiB,aAAa,eACjC,EAAE,MAAM,GAAG,KAAK,EAAE,IAClB;AAAA,MACN;AAAA,MACA,yBAAyB,cAAsB;AAC7C,YAAI,iBAAiB,aAAa,aAAc;AAChD,cAAM,gBAAgB;AAGtB,sBAAc,iCAAiC;AAAA,MACjD;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAKA,QAAM,mBAAmBA;AAAA,IACvB,MACE,sBAAsB,IAAI,CAAC,EAAE,YAAY,KAAK,MAC5C,gBAAAF;AAAA,MAAC;AAAA;AAAA,QAEC;AAAA,QACA;AAAA;AAAA,MAFK;AAAA,IAGP,CACD;AAAA,IACH,CAAC,oBAAoB;AAAA,EACvB;AAEA,SACE,gBAAAC,MAAC,kBAAkB,UAAlB,EAA2B,OAAO,SAChC;AAAA;AAAA,IACA;AAAA,KACH;AAEJ;;;AYnRO,IAAM,uBAAuB;AAAA,EAClC,iBAAiB;AAAA,EACjB,iBAAiB;AACnB;","names":["useEffect","useMemo","replacement","Component","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","getObservedSourceFiles","sourceAnnotationSelector","useState","useRef","useCallback","useEffect","useLayoutEffect","currentRequest","message","useMemo","jsx","jsxs","useMemo","useEffect"]}
|
|
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","../../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/source-identity.ts","../../canvas/runtime-problems.ts","../../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\";\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\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 if (\n url.origin !== window.location.origin ||\n !url.pathname.startsWith(\"/@fs/\")\n ) {\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 { canvasPath, load: () => import(/* @vite-ignore */ url.href) },\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\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)) return;\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 return (\n <CanvasImportErrorBoundary key={retryRevision} reportError={reportError}>\n <Suspense fallback={<CanvasPendingMarker />}>\n <CanvasContext path={canvasPath}>\n <LazyCanvas replacement={replacement} />\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 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 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 {\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 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 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 current = renderEntriesRef.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, already-committed entry 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 const alreadyRendered =\n rendered &&\n (urlPinnedRenderIdRef.current === request.renderId ||\n (current?.status === \"active\" &&\n renderRequestMatchesEntry(current, 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) => {\n setEntries((entries) =>\n releaseRender(entries, renderId, maxCachedRef.current),\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 buildState = useCallback(\n () => ({\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 },\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 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 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:capture-image\") {\n const request = readRenderRequest(command.type, payload);\n void withRenderLease(request, () =>\n captureStoryboardImage(request.renderId, {\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 )\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(target.renderId);\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({ type: \"render-pool:ready\" }, \"*\");\n\n return () => {\n window.removeEventListener(\"message\", onMessage);\n window.removeEventListener(\"__render-pool:command\", onBridgeCommand);\n stopProblemPublisher();\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","export type CanvasHostCaptureResult = {\n img: {\n src: string;\n width: number;\n height: 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 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 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 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\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 },\n): Promise<CanvasHostCaptureResult | null> {\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 return await getCanvasHostRuntime().captureSelector(\n captureSelector,\n portalSelectors.length > 0\n ? { ...captureOptions, portalSelectors: [...new Set(portalSelectors)] }\n : captureOptions,\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 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 ...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","import type { CanvasHostRenderRequest } from \"./canvas-host-protocol\";\nimport { isV1CanvasClient, type V1RenderSizeCompat } from \"./v1-client-compat\";\n\nexport type CanvasHostRenderEntry = CanvasHostRenderRequest & {\n status: \"active\" | \"cached\";\n activeCount: number;\n revision: number;\n lastInactiveAt?: 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?.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 status: \"active\",\n activeCount: (current?.activeCount ?? 0) + 1,\n revision: changed ? (current?.revision ?? 0) + 1 : (current?.revision ?? 1),\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): ReadonlyMap<string, CanvasHostRenderEntry> {\n const current = entries.get(renderId);\n if (!current) return entries;\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 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((a, b) => (a.lastInactiveAt ?? 0) - (b.lastInactiveAt ?? 0));\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 revision: _revision,\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].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","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 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;A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BAAO,gBAAgB;AAAA,QACzB;AACA,eAAO,eAAe,IAAI,YAAY;AAAA,MACxC;AAAA,MACA,uBAAuB,cAAsB;AAC3C,cAAM,eAAe,YAAY,cAAc,eAAe;AAC9D,eAAO,iBAAiB,aAAa,eACjC,EAAE,MAAM,GAAG,KAAK,EAAE,IAClB;AAAA,MACN;AAAA,MACA,yBAAyB,cAAsB;AAC7C,YAAI,iBAAiB,aAAa,aAAc;AAChD,cAAM,gBAAgB;AAGtB,sBAAc,iCAAiC;AAAA,MACjD;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAKA,QAAM,mBAAmBA;AAAA,IACvB,MACE,sBAAsB,IAAI,CAAC,EAAE,YAAY,KAAK,MAC5C,gBAAAJ;AAAA,MAAC;AAAA;AAAA,QAEC;AAAA,QACA;AAAA;AAAA,MAFK;AAAA,IAGP,CACD;AAAA,IACH,CAAC,oBAAoB;AAAA,EACvB;AAEA,SACE,gBAAAC,MAAC,kBAAkB,UAAlB,EAA2B,OAAO,SAChC;AAAA;AAAA,IACA;AAAA,KACH;AAEJ;;;AYjWO,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","useCallback","useEffect","useLayoutEffect","currentRequest","message","useMemo","jsx","jsxs","useState","useRef","useMemo","useCallback","useLayoutEffect","useEffect"]}
|