tempo-sdk 0.0.19 → 0.0.22

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../canvas/canvas.tsx","../../canvas/ids.ts","../../canvas/canvas-host.tsx","../../canvas/runtime-context.ts","../../canvas/use-canvas-host-postmessage.ts","../../canvas/canvas-host-runtime.ts","../../canvas/portal-tracking.ts","../../canvas/canvas-host-operations.ts","../../canvas/canvas-host-protocol.ts","../../canvas/canvas-host-render-state.ts","../../canvas/runtime-problems.ts","../../canvas/storyboard.tsx"],"sourcesContent":["import {\n Children,\n cloneElement,\n createContext,\n isValidElement,\n useContext,\n useMemo,\n type ReactNode,\n} from \"react\";\n\nimport { normalizeId } from \"./ids\";\n\ntype CanvasIdentity = {\n path: string;\n};\n\nconst CanvasIdentityContext = createContext<CanvasIdentity | null>(null);\n\nexport function getCanvasStoryboardRenderId(\n canvasPath: string,\n storyboardId: string,\n): string {\n return `canvas:${encodeURIComponent(\n normalizeId(canvasPath, \"Canvas path\"),\n )}#storyboard:${encodeURIComponent(\n normalizeId(storyboardId, \"Storyboard id\"),\n )}`;\n}\n\nexport function useCanvasIdentity(): CanvasIdentity | null {\n return useContext(CanvasIdentityContext);\n}\n\nexport function useCanvasStoryboardRenderId(storyboardId: string): string {\n const canvas = useCanvasIdentity();\n const normalizedId = normalizeId(storyboardId, \"Storyboard id\");\n return canvas\n ? getCanvasStoryboardRenderId(canvas.path, normalizedId)\n : normalizedId;\n}\n\nexport function Canvas({\n children,\n name,\n path,\n backgroundColor,\n defaultViewport,\n}: {\n children?: ReactNode;\n name: string;\n path?: string;\n backgroundColor?: string;\n defaultViewport?: { x: number; y: number; zoom: number };\n}) {\n const contextIdentity = useCanvasIdentity();\n const canvasName = normalizeId(name, \"Canvas name\");\n const canvasPath =\n path === undefined\n ? contextIdentity?.path\n : normalizeId(path, \"Canvas path\");\n\n if (!canvasPath) {\n throw new Error(\n '<Canvas> must be rendered inside <CanvasContext path=\"...\"> or receive a path prop.',\n );\n }\n\n const identity = useMemo(() => ({ path: canvasPath }), [canvasPath]);\n\n // Key each storyboard child by its declared id so React reconciles slots\n // by STORYBOARD IDENTITY rather than child position. Canvas files declare\n // storyboards as static JSX siblings (no keys), and positional\n // reconciliation reuses one storyboard's slot DOM node for another when\n // an edit inserts or removes a sibling above it — but slot DOM identity\n // is load-bearing: capture watchers, portal tracking, and the pool's\n // render-content wrappers all anchor to the slot node, and a reused node\n // silently starts feeding one storyboard's pipeline with another's\n // render.\n const keyedChildren = useMemo(\n () =>\n Children.map(children, (child) => {\n if (!isValidElement(child)) return child;\n if (child.key != null) return child;\n const id = (child.props as { id?: unknown }).id;\n if (typeof id !== \"string\" || id.length === 0) return child;\n return cloneElement(child, { key: `storyboard:${id}` });\n }),\n [children],\n );\n\n return (\n <CanvasIdentityContext.Provider value={identity}>\n <div\n data-tempo-canvas={canvasName}\n data-tempo-canvas-path={canvasPath}\n data-tempo-canvas-background={backgroundColor}\n data-tempo-canvas-viewport={\n defaultViewport ? JSON.stringify(defaultViewport) : undefined\n }\n >\n {keyedChildren}\n </div>\n </CanvasIdentityContext.Provider>\n );\n}\n\nexport function CanvasContext({\n children,\n path,\n}: {\n children?: ReactNode;\n path: string;\n}) {\n const canvasPath = normalizeId(path, \"Canvas path\");\n const identity = useMemo(() => ({ path: canvasPath }), [canvasPath]);\n return (\n <CanvasIdentityContext.Provider value={identity}>\n {children}\n </CanvasIdentityContext.Provider>\n );\n}\n","export function normalizeId(value: string | undefined, label: string): string {\n const normalized = value?.trim();\n if (!normalized) {\n throw new Error(`${label} is required.`);\n }\n return normalized;\n}\n","import {\n useMemo,\n type ReactNode,\n} from \"react\";\n\nimport { getCanvasStoryboardRenderId } from \"./canvas\";\nimport { normalizeId } from \"./ids\";\nimport { CanvasHostContext } from \"./runtime-context\";\nimport type { CanvasHostRuntimeSize } from \"./runtime-context\";\nimport { useCanvasHostPostMessage } from \"./use-canvas-host-postmessage\";\n\ntype DirectUrlRender = {\n renderId: string;\n size?: CanvasHostRuntimeSize;\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(params: URLSearchParams): CanvasHostRuntimeSize | undefined {\n const width = params.get(\"width\")?.trim();\n const height = params.get(\"height\")?.trim();\n if (!width && !height) return undefined;\n if (!width || !height) {\n throw new Error(\"Direct URL width and height must be provided together\");\n }\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 renderId: getCanvasStoryboardRenderId(canvasPath, storyboardId),\n size: readDirectUrlSize(params),\n };\n}\n\nexport function CanvasHost({\n children,\n activeStoryboardIds,\n isStoryboardActive,\n}: {\n children?: ReactNode;\n activeStoryboardIds?: ReadonlySet<string> | readonly string[];\n isStoryboardActive?: (storyboardId: string) => boolean;\n}) {\n const {\n renderStatusById,\n renderSizeById,\n markStoryboardRendered,\n reportStoryboardError,\n clearStoryboardError,\n } = useCanvasHostPostMessage();\n const directUrlSearch =\n typeof window === \"undefined\" ? \"\" : window.location.search;\n const directUrlRender = useMemo(readDirectUrlRender, [directUrlSearch]);\n const propActiveIds = useMemo(\n () => new Set(activeStoryboardIds ?? []),\n [activeStoryboardIds],\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 markStoryboardRendered,\n reportStoryboardError,\n clearStoryboardError,\n }),\n [\n clearStoryboardError,\n directUrlRender,\n isStoryboardActive,\n markStoryboardRendered,\n propActiveIds,\n reportStoryboardError,\n renderSizeById,\n renderStatusById,\n ],\n );\n\n return (\n <CanvasHostContext.Provider value={runtime}>\n {children}\n </CanvasHostContext.Provider>\n );\n}\n","import { createContext, useCallback, useContext } from \"react\";\n\nimport { useCanvasStoryboardRenderId } from \"./canvas\";\n\nexport type CanvasHostRuntimeError = {\n message: string;\n stack?: string;\n componentStack?: string;\n};\n\nexport type CanvasHostRuntimeSize = {\n width?: number | string;\n height?: number | string;\n intrinsicSize?: boolean;\n revision?: number;\n};\n\nexport type CanvasHostRuntimePlacement = {\n left: number;\n top: number;\n};\n\nexport type CanvasHostRuntime = {\n getStoryboardStatus(storyboardId: string): \"active\" | \"cached\" | \"unmounted\";\n getStoryboardSize(storyboardId: string): CanvasHostRuntimeSize | undefined;\n getStoryboardPlacement(\n storyboardId: string,\n ): CanvasHostRuntimePlacement | undefined;\n markStoryboardRendered(storyboardId: string): void;\n reportStoryboardError(storyboardId: string, error: CanvasHostRuntimeError): void;\n clearStoryboardError(storyboardId: string): void;\n};\n\nexport const CanvasHostContext = createContext<CanvasHostRuntime | null>(null);\n\nfunction useRequiredCanvasHost(): CanvasHostRuntime {\n const host = useContext(CanvasHostContext);\n if (!host) {\n throw new Error(\n \"Tempo canvas components must be rendered inside <CanvasHost>.\",\n );\n }\n return host;\n}\n\nexport function useActiveState(storyboardId: string): boolean {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardStatus(renderId) !== \"unmounted\";\n}\n\nexport function useStoryboardStatus(\n storyboardId: string,\n): \"active\" | \"cached\" | \"unmounted\" {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardStatus(renderId);\n}\n\nexport function useStoryboardRendered(storyboardId: string): () => void {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return useCallback(() => {\n host.markStoryboardRendered(renderId);\n }, [host, renderId]);\n}\n\nexport function useStoryboardErrorReporter(storyboardId: string): {\n reportError(error: CanvasHostRuntimeError): void;\n clearError(): void;\n} {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n const reportError = useCallback(\n (error: CanvasHostRuntimeError) => {\n host.reportStoryboardError(renderId, error);\n },\n [host, renderId],\n );\n const clearError = useCallback(() => {\n host.clearStoryboardError(renderId);\n }, [host, renderId]);\n return { reportError, clearError };\n}\n\nexport function useStoryboardSize(\n storyboardId: string,\n): CanvasHostRuntimeSize | undefined {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardSize(renderId);\n}\n\nexport function useStoryboardPlacement(\n storyboardId: string,\n): CanvasHostRuntimePlacement | undefined {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardPlacement(renderId);\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport {\n buildRenderContentSelector,\n captureStoryboardCombined,\n captureStoryboardHtml,\n captureStoryboardImage,\n captureStoryboardStaticHtml,\n watchStoryboardCombined,\n watchStoryboardHtml,\n} from \"./canvas-host-operations\";\nimport type { CanvasHostWatch } from \"./canvas-host-runtime\";\nimport type { CanvasHostRuntimeError } from \"./runtime-context\";\nimport {\n readCanvasHostCommand,\n readOptionalNumber,\n readRenderRequest,\n readWatchId,\n requireRenderTarget,\n resolveRenderTarget,\n} from \"./canvas-host-protocol\";\nimport type { CanvasHostRenderRequest } from \"./canvas-host-protocol\";\nimport {\n acquireRender,\n buildRenderSizeMap,\n buildRenderStatePayload,\n buildRenderStatusMap,\n evictCachedRenders,\n releaseRender,\n renderRequestMatchesEntry,\n type CanvasHostRenderEntry,\n} from \"./canvas-host-render-state\";\nimport {\n createCanvasHostProblemTracker,\n installCanvasHostRuntimeProblemTracking,\n} from \"./runtime-problems\";\n\ntype WatchLease = {\n renderId: string;\n bindingKey: string;\n watch: CanvasHostWatch;\n};\n\ntype WatchRequest = {\n commandType: \"render-pool:watch-html\" | \"render-pool:watch-combined\";\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};\n\ntype PendingRenderAck = {\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\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\nexport function useCanvasHostPostMessage(): {\n renderStatusById: ReadonlyMap<string, \"active\" | \"cached\">;\n renderSizeById: ReadonlyMap<\n string,\n { width?: number; height?: number; intrinsicSize?: boolean; revision?: number }\n >;\n markStoryboardRendered(storyboardId: string): void;\n reportStoryboardError(storyboardId: string, error: CanvasHostRuntimeError): void;\n clearStoryboardError(storyboardId: string): void;\n} {\n const [renderEntriesById, setRenderEntriesById] = useState(\n () => new Map<string, CanvasHostRenderEntry>(),\n );\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 watchRequestsRef = useRef(watchRequestsById);\n const maxCachedRef = useRef(20);\n const renderedRenderIdsRef = useRef(new Set<string>());\n const pendingRenderAcksRef = useRef(new Map<string, PendingRenderAck[]>());\n const watchesRef = useRef(new Map<string, WatchLease>());\n const problemWatchersRef = useRef(new Map<string, ProblemWatcher>());\n const problemTrackerRef = useRef(createCanvasHostProblemTracker());\n const renderCommitTimesRef = useRef(new Map<string, number>());\n const sourceAnnotatedCommitTimesRef = useRef(new Map<string, number>());\n\n const buildProblemSnapshot = useCallback(\n () => problemTrackerRef.current.snapshot(),\n [],\n );\n\n const recordSourceAnnotatedCommit = useCallback(\n (renderId: string, observedAt = Date.now()) => {\n if (renderSlotHasSourceAnnotations(renderId)) {\n sourceAnnotatedCommitTimesRef.current.set(renderId, observedAt);\n }\n },\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 ) => Map<string, CanvasHostRenderEntry>,\n ) => {\n setRenderEntriesById((entries) => {\n const next = update(entries);\n renderEntriesRef.current = next;\n for (const renderId of [...renderedRenderIdsRef.current]) {\n if (!next.has(renderId)) {\n renderedRenderIdsRef.current.delete(renderId);\n renderCommitTimesRef.current.delete(renderId);\n sourceAnnotatedCommitTimesRef.current.delete(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 alreadyRendered =\n current?.status === \"active\" &&\n renderedRenderIdsRef.current.has(request.renderId) &&\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 pendingAcks =\n pendingRenderAcksRef.current.get(request.renderId) ?? [];\n pendingAcks.push({ resolve, reject });\n pendingRenderAcksRef.current.set(request.renderId, pendingAcks);\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(async (watchId: string) => {\n const existingWatch = watchesRef.current.get(watchId);\n if (!existingWatch) return;\n watchesRef.current.delete(watchId);\n await existingWatch.watch.stop();\n }, []);\n\n const removeWatchRequest = useCallback(\n async (watchId: string): Promise<void> => {\n const existingRequest = watchRequestsRef.current.get(watchId);\n try {\n await stopRuntimeWatch(watchId);\n } finally {\n if (!existingRequest) return;\n setWatchRequestsById((requests) => {\n const next = new Map(requests);\n next.delete(watchId);\n watchRequestsRef.current = next;\n return next;\n });\n releaseRenderLease(existingRequest.request.renderId);\n }\n },\n [releaseRenderLease, stopRuntimeWatch],\n );\n\n const buildState = useCallback(\n () => buildRenderStatePayload(renderEntriesRef.current, maxCachedRef.current),\n [],\n );\n\n const buildHealthSnapshot = useCallback((renderId: string) => {\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 renderCommitTimesRef.current.size > 0 ||\n renderEntriesRef.current.size > 0,\n documentReadyState: document.readyState,\n hasViteOverlayElement:\n document.querySelector(\"vite-error-overlay\") !== null,\n lastHostRenderCommitAt: latestTimestamp(renderCommitTimesRef.current),\n lastClaimRenderCommitAt: renderCommitTimesRef.current.get(renderId) ?? null,\n lastHostSourceAnnotatedCommitAt: latestTimestamp(\n sourceAnnotatedCommitTimesRef.current,\n ),\n lastClaimSourceAnnotatedCommitAt:\n sourceAnnotatedCommitTimesRef.current.get(renderId) ?? null,\n renderSlotExists: slot !== null,\n renderSlotHasSourceAnnotatedContent: observedSourceFiles.length > 0,\n renderSlotObservedSourceFiles: observedSourceFiles,\n claimErrorBoundaryTripped:\n problemTrackerRef.current.hasComponentProblem(renderId),\n observedAt: Date.now(),\n };\n }, []);\n\n const markStoryboardRendered = useCallback(\n (storyboardId: string) => {\n const committedAt = Date.now();\n renderedRenderIdsRef.current.add(storyboardId);\n renderCommitTimesRef.current.set(storyboardId, committedAt);\n recordSourceAnnotatedCommit(storyboardId, committedAt);\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 pendingAcks = pendingRenderAcksRef.current.get(storyboardId);\n if (!pendingAcks) return;\n pendingRenderAcksRef.current.delete(storyboardId);\n for (const ack of pendingAcks) {\n ack.resolve();\n }\n },\n [recordSourceAnnotatedCommit],\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 pendingAcks = pendingRenderAcksRef.current.get(storyboardId);\n if (pendingAcks) {\n pendingRenderAcksRef.current.delete(storyboardId);\n const renderError = new Error(error.message);\n for (const ack of pendingAcks) {\n ack.reject(renderError);\n }\n }\n },\n [],\n );\n\n const clearStoryboardError = useCallback(\n (storyboardId: string) => {\n problemTrackerRef.current.clearComponentProblem(storyboardId, [\n \"render-error-boundary\",\n ]);\n },\n [],\n );\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n\n let cancelled = false;\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 const renderEntry = renderEntriesById.get(request.request.renderId);\n const renderReady =\n renderEntry?.status === \"active\" &&\n renderedRenderIdsRef.current.has(request.request.renderId) &&\n renderRequestMatchesEntry(renderEntry, request.request);\n if (!renderReady) continue;\n\n const existing = watchesRef.current.get(request.watchId);\n if (existing?.bindingKey === request.bindingKey) continue;\n\n void (async () => {\n if (existing) {\n await stopRuntimeWatch(request.watchId);\n }\n if (cancelled) return;\n\n const onUpdate = (capture: unknown) => {\n recordSourceAnnotatedCommit(request.request.renderId);\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 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 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 if (cancelled || !watchRequestsRef.current.has(request.watchId)) {\n await watch.stop();\n return;\n }\n\n watchesRef.current.set(request.watchId, {\n renderId: request.request.renderId,\n bindingKey: request.bindingKey,\n watch,\n });\n if (request.paused) {\n if (watch.setPaused) watch.setPaused(true);\n else watch.pause?.();\n }\n })().catch((caught: unknown) => {\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: caught instanceof Error ? caught.message : String(caught),\n },\n request.targetOrigin,\n );\n });\n }\n\n return () => {\n cancelled = true;\n };\n }, [\n recordSourceAnnotatedCommit,\n renderCommitVersionById,\n renderEntriesById,\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 = (capture: unknown) =>\n post({\n type: \"render-pool:capture-result\",\n requestId: command.requestId,\n command: command.type,\n payload: { capture },\n });\n\n try {\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:capture-image\") {\n const request = readRenderRequest(command.type, payload);\n void withRenderLease(request, () =>\n captureStoryboardImage(request.renderId, {\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((capture) => {\n recordSourceAnnotatedCommit(request.renderId);\n postCaptureResult(capture);\n })\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((capture) => {\n recordSourceAnnotatedCommit(request.renderId);\n postCaptureResult(capture);\n })\n .catch(postAsyncError);\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((capture) => {\n recordSourceAnnotatedCommit(request.renderId);\n postCaptureResult(capture);\n })\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((capture) => {\n recordSourceAnnotatedCommit(request.renderId);\n postCaptureResult(capture);\n })\n .catch(postAsyncError);\n return;\n }\n\n if (\n command.type === \"render-pool:watch-html\" ||\n command.type === \"render-pool:watch-combined\"\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 setWatchRequestsById((requests) => {\n const next = new Map(requests);\n next.set(watchId, {\n commandType: command.type,\n requestId: command.requestId,\n watchId,\n source,\n targetOrigin,\n request,\n payload,\n paused: false,\n bindingKey: buildWatchBindingKey(command.type, payload),\n });\n watchRequestsRef.current = next;\n return next;\n });\n ack();\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 watch?.setPaused?.(paused);\n if (!watch?.setPaused) {\n if (paused) watch?.pause?.();\n else watch?.resume?.();\n }\n setWatchRequestsById((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 watchRequestsRef.current = next;\n return next;\n });\n ack();\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: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:set-cache-limit\") {\n const maxCached =\n typeof payload.maxCached === \"number\" &&\n Number.isInteger(payload.maxCached)\n ? Math.max(0, payload.maxCached)\n : maxCachedRef.current;\n maxCachedRef.current = maxCached;\n setEntries((entries) => evictCachedRenders(entries, maxCached));\n ack();\n return;\n }\n\n if (command.type === \"render-pool:isolate\") {\n const target = resolveRenderTarget(payload);\n document.querySelector(\"[data-render-isolation]\")?.remove();\n\n if (target?.renderId) {\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(target.renderId)\n : target.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 ack();\n return;\n }\n\n if (command.type === \"render-pool:query-health\") {\n const target = resolveRenderTarget(payload);\n post({\n type: \"render-pool:health-snapshot\",\n requestId: command.requestId,\n snapshot: buildHealthSnapshot(target?.renderId ?? \"\"),\n });\n return;\n }\n\n if (command.type === \"render-pool:query-problems\") {\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: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 }\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 const stopRuntimeProblemTracking = installCanvasHostRuntimeProblemTracking(\n problemTrackerRef.current,\n );\n window.postMessage({ type: \"render-pool:ready\" }, \"*\");\n\n return () => {\n window.removeEventListener(\"message\", onMessage);\n window.removeEventListener(\"__render-pool:command\", onBridgeCommand);\n stopRuntimeProblemTracking();\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 buildHealthSnapshot,\n buildProblemSnapshot,\n buildState,\n publishProblemSnapshot,\n recordSourceAnnotatedCommit,\n releaseRenderLease,\n removeWatchRequest,\n setEntries,\n waitForRender,\n ]);\n\n return {\n renderStatusById: useMemo(\n () => buildRenderStatusMap(renderEntriesById),\n [renderEntriesById],\n ),\n renderSizeById: useMemo(\n () => buildRenderSizeMap(renderEntriesById),\n [renderEntriesById],\n ),\n markStoryboardRendered,\n reportStoryboardError,\n clearStoryboardError,\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\nfunction buildWatchBindingKey(commandType: string, payload: Record<string, unknown>): string {\n try {\n return JSON.stringify({ commandType, payload });\n } catch {\n return `${commandType}:${Date.now()}`;\n }\n}\n\nconst sourceAnnotationSelector =\n \"[data-tempo-source-file], [data-tempo-source-loc], [data-tempo-filepath], [data-tempo-html-filepath]\";\n\nfunction renderSlotHasSourceAnnotations(renderId: string): boolean {\n const slot =\n typeof document === \"undefined\"\n ? null\n : document.querySelector(buildRenderContentSelector(renderId));\n return getObservedSourceFiles(slot).length > 0;\n}\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","export type CanvasHostCaptureResult = {\n img: { src: string; width: number; height: number };\n timing?: Record<string, number>;\n};\n\nexport type CanvasHostWatch = {\n stop(): void | Promise<void>;\n pause?(): void;\n resume?(): void;\n setPaused?(paused: boolean): 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 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 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","type FiberLike = {\n return: FiberLike | null;\n stateNode: unknown;\n};\n\ntype PortalWatcher = {\n element: Element;\n onPortalFound(portalRoot: Element): void;\n onPortalRemoved(portalRoot: Element): void;\n};\n\ntype PortalInlineStyleValue = {\n value: string;\n priority: string;\n};\n\ntype PortalInlineStyle = {\n visibility: PortalInlineStyleValue;\n pointerEvents: PortalInlineStyleValue;\n contentVisibility: PortalInlineStyleValue;\n transition: PortalInlineStyleValue;\n animation: PortalInlineStyleValue;\n};\n\ntype PortalManagedProperty = {\n // The PortalInlineStyle field that holds this property's saved baseline.\n key: keyof PortalInlineStyle;\n // The CSS property name as written in inline styles.\n cssName: string;\n // The value forced (with !important) while the portal is hidden.\n hiddenValue: string;\n};\n\n// Single source of truth for the inline-style properties this module overrides\n// to hide cached/inactive portals, so the hide path and the restore path can't\n// drift out of sync.\nconst PORTAL_MANAGED_PROPERTIES: readonly PortalManagedProperty[] = [\n { key: \"visibility\", cssName: \"visibility\", hiddenValue: \"hidden\" },\n { key: \"pointerEvents\", cssName: \"pointer-events\", hiddenValue: \"none\" },\n {\n key: \"contentVisibility\",\n cssName: \"content-visibility\",\n hiddenValue: \"hidden\",\n },\n { key: \"transition\", cssName: \"transition\", hiddenValue: \"none\" },\n { key: \"animation\", cssName: \"animation\", hiddenValue: \"none\" },\n];\n\nconst portalElementsByRenderId = new Map<string, Set<Element>>();\nconst portalOwnerRenderIdsByElement = new Map<Element, Set<string>>();\nconst portalInlineStyleByElement = new Map<Element, PortalInlineStyle>();\nconst renderStatusById = new Map<string, \"active\" | \"cached\">();\nconst projectionPortalIdAttribute = \"data-projection-portal-id\";\nlet nextSdkPortalId = 1;\n\nfunction escapeAttributeValue(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\nfunction ensureProjectionPortalId(portalRoot: Element): string {\n const existingId = portalRoot.getAttribute(projectionPortalIdAttribute);\n if (existingId) return existingId;\n\n const id = `tempo-sdk-portal-${nextSdkPortalId++}`;\n portalRoot.setAttribute(projectionPortalIdAttribute, id);\n return id;\n}\n\nfunction buildProjectionPortalSelector(portalRoot: Element): string {\n return `[${projectionPortalIdAttribute}=\"${escapeAttributeValue(\n ensureProjectionPortalId(portalRoot),\n )}\"]`;\n}\n\nfunction findFiberKey(element: Element): string | null {\n return (\n Object.keys(element).find(\n (key) =>\n key.startsWith(\"__reactFiber$\") ||\n key.startsWith(\"__reactInternalInstance$\"),\n ) ?? null\n );\n}\n\nfunction findContainerKey(element: Element): string | null {\n return Object.keys(element).find((key) => key.startsWith(\"__reactContainer$\")) ?? null;\n}\n\nfunction getFiberFromElement(element: Element): FiberLike | null {\n const fiberKey = findFiberKey(element);\n if (fiberKey) {\n return (\n (element as unknown as Record<string, FiberLike | undefined>)[fiberKey] ??\n null\n );\n }\n\n const containerKey = findContainerKey(element);\n if (containerKey) {\n return (\n (element as unknown as Record<string, FiberLike | undefined>)[\n containerKey\n ] ?? null\n );\n }\n\n return null;\n}\n\nclass PortalTracker {\n private readonly watchers = new Set<PortalWatcher>();\n private readonly ownerWatchersByPortalRoot = new Map<\n Element,\n Set<PortalWatcher>\n >();\n private observer: MutationObserver | null = null;\n\n register(watcher: PortalWatcher): () => void {\n this.watchers.add(watcher);\n\n if (this.watchers.size === 1) {\n this.startObserving();\n }\n\n if (typeof document !== \"undefined\" && document.body) {\n this.checkExistingElements();\n queueMicrotask(() => this.checkExistingElements());\n }\n\n return () => this.unregister(watcher);\n }\n\n private checkExistingElements(): void {\n if (typeof document === \"undefined\" || !document.body) return;\n for (const child of Array.from(document.body.children)) {\n this.checkElement(child);\n }\n }\n\n private unregister(watcher: PortalWatcher): void {\n this.watchers.delete(watcher);\n\n for (const [portalRoot, owners] of this.ownerWatchersByPortalRoot) {\n owners.delete(watcher);\n if (owners.size === 0) {\n this.ownerWatchersByPortalRoot.delete(portalRoot);\n }\n }\n\n if (this.watchers.size === 0) {\n this.stopObserving();\n }\n }\n\n private startObserving(): void {\n if (\n this.observer ||\n typeof document === \"undefined\" ||\n !document.body ||\n typeof MutationObserver === \"undefined\"\n ) {\n return;\n }\n\n this.observer = new MutationObserver(this.handleMutations);\n this.observer.observe(document.body, { childList: true });\n }\n\n private stopObserving(): void {\n this.observer?.disconnect();\n this.observer = null;\n }\n\n private handleMutations = (mutations: MutationRecord[]): void => {\n for (const mutation of mutations) {\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n queueMicrotask(() => this.checkElement(node));\n }\n }\n\n for (const node of mutation.removedNodes) {\n if (!(node instanceof Element)) continue;\n const owners = this.ownerWatchersByPortalRoot.get(node);\n if (!owners) continue;\n for (const owner of owners) {\n owner.onPortalRemoved(node);\n }\n this.ownerWatchersByPortalRoot.delete(node);\n }\n }\n };\n\n private checkElement(element: Element): void {\n const ancestorDomNodes = this.getDomAncestorsViaFiber(element);\n if (ancestorDomNodes.length === 0) return;\n\n let owners = this.ownerWatchersByPortalRoot.get(element);\n for (const watcher of this.watchers) {\n const belongsToWatcher = ancestorDomNodes.some(\n (node) => watcher.element.contains(node) || watcher.element === node,\n );\n if (!belongsToWatcher) continue;\n\n if (!owners) {\n owners = new Set<PortalWatcher>();\n this.ownerWatchersByPortalRoot.set(element, owners);\n }\n if (owners.has(watcher)) continue;\n\n owners.add(watcher);\n watcher.onPortalFound(element);\n }\n }\n\n private getDomAncestorsViaFiber(element: Element): Element[] {\n const fiber = getFiberFromElement(element);\n if (!fiber) return [];\n\n const domNodes: Element[] = [];\n let current: FiberLike | null = fiber.return;\n while (current) {\n if (current.stateNode instanceof Element) {\n domNodes.push(current.stateNode);\n }\n current = current.return;\n }\n return domNodes;\n }\n}\n\nlet portalTracker: PortalTracker | null = null;\n\nfunction getPortalTracker(): PortalTracker {\n if (!portalTracker) {\n portalTracker = new PortalTracker();\n }\n return portalTracker;\n}\n\nfunction getStylablePortalElement(\n portalRoot: Element,\n): HTMLElement | SVGElement | null {\n if (portalRoot instanceof HTMLElement || portalRoot instanceof SVGElement) {\n return portalRoot;\n }\n return null;\n}\n\nfunction ensurePortalInlineStyle(portalRoot: Element): PortalInlineStyle {\n const existing = portalInlineStyleByElement.get(portalRoot);\n if (existing) return existing;\n\n const stylableElement = getStylablePortalElement(portalRoot);\n const baseline = {\n visibility: readInlineStyleValue(stylableElement, \"visibility\"),\n pointerEvents: readInlineStyleValue(stylableElement, \"pointer-events\"),\n contentVisibility: readInlineStyleValue(\n stylableElement,\n \"content-visibility\",\n ),\n transition: readInlineStyleValue(stylableElement, \"transition\"),\n animation: readInlineStyleValue(stylableElement, \"animation\"),\n };\n portalInlineStyleByElement.set(portalRoot, baseline);\n return baseline;\n}\n\nfunction readInlineStyleValue(\n element: HTMLElement | SVGElement | null,\n propertyName: string,\n): PortalInlineStyleValue {\n return {\n value: element?.style.getPropertyValue(propertyName) ?? \"\",\n priority: element?.style.getPropertyPriority(propertyName) ?? \"\",\n };\n}\n\nfunction restoreInlineStyleValue(\n style: CSSStyleDeclaration,\n propertyName: string,\n baseline: PortalInlineStyleValue,\n): void {\n if (baseline.value) {\n style.setProperty(propertyName, baseline.value, baseline.priority);\n return;\n }\n style.removeProperty(propertyName);\n}\n\nfunction restorePortalInlineStyle(portalRoot: Element): void {\n const stylableElement = getStylablePortalElement(portalRoot);\n const baseline = portalInlineStyleByElement.get(portalRoot);\n if (!stylableElement || !baseline) return;\n\n for (const property of PORTAL_MANAGED_PROPERTIES) {\n restoreInlineStyleValue(\n stylableElement.style,\n property.cssName,\n baseline[property.key],\n );\n }\n}\n\nfunction syncPortalVisibility(portalRoot: Element): void {\n const owners = portalOwnerRenderIdsByElement.get(portalRoot);\n if (!owners || owners.size === 0) {\n restorePortalInlineStyle(portalRoot);\n portalInlineStyleByElement.delete(portalRoot);\n return;\n }\n\n const stylableElement = getStylablePortalElement(portalRoot);\n if (!stylableElement) return;\n\n const shouldBeVisible = [...owners].some(\n (renderId) => renderStatusById.get(renderId) === \"active\",\n );\n\n if (shouldBeVisible) {\n restorePortalInlineStyle(portalRoot);\n portalInlineStyleByElement.delete(portalRoot);\n return;\n }\n\n ensurePortalInlineStyle(portalRoot);\n for (const property of PORTAL_MANAGED_PROPERTIES) {\n stylableElement.style.setProperty(\n property.cssName,\n property.hiddenValue,\n \"important\",\n );\n }\n}\n\nfunction trackPortal(renderId: string, portalRoot: Element): void {\n ensureProjectionPortalId(portalRoot);\n\n const portals = portalElementsByRenderId.get(renderId) ?? new Set<Element>();\n portals.add(portalRoot);\n portalElementsByRenderId.set(renderId, portals);\n\n const owners = portalOwnerRenderIdsByElement.get(portalRoot) ?? new Set<string>();\n owners.add(renderId);\n portalOwnerRenderIdsByElement.set(portalRoot, owners);\n syncPortalVisibility(portalRoot);\n}\n\nfunction untrackPortal(renderId: string, portalRoot: Element): void {\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) return;\n\n portals.delete(portalRoot);\n if (portals.size === 0) {\n portalElementsByRenderId.delete(renderId);\n }\n\n const owners = portalOwnerRenderIdsByElement.get(portalRoot);\n if (owners) {\n owners.delete(renderId);\n if (owners.size === 0) {\n portalOwnerRenderIdsByElement.delete(portalRoot);\n }\n }\n syncPortalVisibility(portalRoot);\n}\n\nexport function releaseStoryboardPortals(renderId: string): void {\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) {\n renderStatusById.delete(renderId);\n return;\n }\n\n for (const portalRoot of [...portals]) {\n untrackPortal(renderId, portalRoot);\n }\n renderStatusById.delete(renderId);\n}\n\nexport function getStoryboardPortalSelectors(renderId: string): string[] {\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) return [];\n return [...portals]\n .filter((portalRoot) => portalRoot.isConnected)\n .map(buildProjectionPortalSelector);\n}\n\nexport function syncStoryboardPortals(\n renderId: string,\n status: \"active\" | \"cached\",\n): void {\n renderStatusById.set(renderId, status);\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) return;\n for (const portalRoot of portals) {\n syncPortalVisibility(portalRoot);\n }\n}\n\nexport function trackStoryboardPortals(\n renderId: string,\n element: Element,\n status: \"active\" | \"cached\",\n): () => void {\n syncStoryboardPortals(renderId, status);\n const unregister = getPortalTracker().register({\n element,\n onPortalFound(portalRoot) {\n trackPortal(renderId, portalRoot);\n },\n onPortalRemoved(portalRoot) {\n untrackPortal(renderId, portalRoot);\n },\n });\n\n return () => {\n unregister();\n releaseStoryboardPortals(renderId);\n };\n}\n","import {\n getCanvasHostRuntime,\n type CanvasHostCaptureResult,\n type CanvasHostRuntime,\n type CanvasHostWatch,\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 `${buildRenderContentSelector(renderId)} > :not([data-tempo-hide-fiber=\"true\"])`;\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\nexport function captureStoryboardImage(\n renderId: string,\n options?: Parameters<CanvasHostRuntime[\"captureSelector\"]>[1],\n): Promise<CanvasHostCaptureResult | null> {\n const portalSelectors = [\n ...(options?.portalSelectors ?? []),\n ...getStoryboardPortalSelectors(renderId),\n ];\n\n return getCanvasHostRuntime().captureSelector(\n buildRenderSelector(renderId),\n portalSelectors.length > 0\n ? { ...options, portalSelectors: [...new Set(portalSelectors)] }\n : options,\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\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: options?.fiberSelector ?? buildRenderContentFiberSelector(renderId),\n fiberTags: options?.fiberTags,\n timeout: options?.timeout,\n });\n return capture\n ? stripRenderContentWrapperFromCombinedCapture(capture, renderId)\n : null;\n}\n\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 { getCanvasStoryboardRenderId } from \"./canvas\";\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};\n\nexport type CanvasHostRenderRequest = CanvasHostRenderTarget & {\n importPath: string;\n importName: string;\n props?: Record<string, unknown>;\n width?: number;\n height?: number;\n intrinsicSize?: boolean;\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(message: unknown): 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\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 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 }\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(\n payload: Record<string, unknown>,\n): { width?: number; height?: number } {\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 intrinsicSize: payload.intrinsicSize === true ? true : undefined,\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\";\n\nexport type CanvasHostRenderEntry = CanvasHostRenderRequest & {\n status: \"active\" | \"cached\";\n activeCount: number;\n revision: number;\n lastInactiveAt?: number;\n};\n\nexport type CanvasHostRenderSize = {\n width?: number;\n height?: number;\n intrinsicSize?: boolean;\n revision?: number;\n};\n\nexport type CanvasHostRuntimeStatePayload = {\n renders: Array<{\n renderId: string;\n importPath: string;\n importName: string;\n props?: Record<string, unknown>;\n width?: number;\n height?: number;\n intrinsicSize?: boolean;\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 entry.intrinsicSize === request.intrinsicSize &&\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): Map<string, CanvasHostRenderEntry> {\n const current = entries.get(renderId);\n if (!current) return new Map(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): Map<string, CanvasHostRenderEntry> {\n const next = new Map(entries);\n const cached = [...next.values()]\n .filter((entry) => entry.status === \"cached\")\n .sort((a, b) => (a.lastInactiveAt ?? 0) - (b.lastInactiveAt ?? 0));\n for (const entry of cached.slice(0, Math.max(0, cached.length - maxCached))) {\n next.delete(entry.renderId);\n }\n return next;\n}\n\nexport function buildRenderStatePayload(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n maxCached: number,\n): CanvasHostRuntimeStatePayload {\n return {\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\nexport function buildRenderStatusMap(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n): ReadonlyMap<string, \"active\" | \"cached\"> {\n return new Map([...entries].map(([id, entry]) => [id, entry.status]));\n}\n\nexport function buildRenderSizeMap(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n): ReadonlyMap<string, CanvasHostRenderSize> {\n return new Map(\n [...entries].map(([id, entry]) => [\n id,\n {\n width: entry.width,\n height: entry.height,\n intrinsicSize: entry.intrinsicSize,\n revision: entry.revision,\n },\n ]),\n );\n}\n","export 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 type CanvasHostCurrentFrameProblemSnapshot = {\n currentHostFailure?: CanvasHostRuntimeProblem;\n currentRenderFailures: Array<{\n renderId: string | null;\n failure: CanvasHostRuntimeProblem;\n }>;\n // See CanvasHostProblemSnapshot.canvasProblems — the pull-probe mirror of the\n // canvas-scoped failure lane.\n currentCanvasFailures: Array<{\n canvasPath: string;\n failure: CanvasHostRuntimeProblem;\n }>;\n observedAt: number;\n};\n\nexport class CanvasHostProblemTracker {\n private hostProblem: CanvasHostRuntimeProblem | undefined;\n private hostProblemHmrGeneration = 0;\n private componentProblems = new Map<string, CanvasHostRuntimeProblem>();\n private componentProblemHmrGenerations = new Map<string, number>();\n private canvasProblems = new Map<string, CanvasHostRuntimeProblem>();\n private watchers = new Set<() => void>();\n private hostProblemClearedWatchers = new Set<\n (problem: CanvasHostRuntimeProblem) => void\n >();\n private hmrGeneration = 0;\n\n snapshot(): CanvasHostProblemSnapshot {\n const currentViteOverlay = readCurrentViteOverlay();\n const hostProblem =\n currentViteOverlay ??\n (this.hostProblem?.sourceKind === \"vite-overlay\"\n ? undefined\n : this.hostProblem);\n return {\n hostProblem,\n componentProblems: [...this.componentProblems].map(\n ([renderId, problem]) => ({ renderId, problem }),\n ),\n canvasProblems: [...this.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.hostProblemHmrGeneration = this.hmrGeneration;\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 renderId = findRenderIdForProblem(problem);\n if (renderId) {\n this.componentProblems.set(renderId, problem);\n this.componentProblemHmrGenerations.set(renderId, this.hmrGeneration);\n } else {\n this.hostProblem = problem;\n this.hostProblemHmrGeneration = this.hmrGeneration;\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(canvasPath: string): void {\n if (!this.canvasProblems.delete(canvasPath)) return;\n this.publish();\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.hostProblemHmrGeneration = 0;\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.componentProblemHmrGenerations.set(renderId, this.hmrGeneration);\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.componentProblemHmrGenerations.delete(renderId);\n this.publish();\n }\n\n hasComponentProblem(renderId: string): boolean {\n return this.componentProblems.has(renderId);\n }\n\n clearRecoveredComponentProblemsAfterRender(renderId: string): void {\n let changed = false;\n const problem = this.componentProblems.get(renderId);\n if (\n problem &&\n problem.sourceKind !== \"render-error-boundary\" &&\n this.hmrGeneration >\n (this.componentProblemHmrGenerations.get(renderId) ??\n this.hmrGeneration)\n ) {\n this.componentProblems.delete(renderId);\n this.componentProblemHmrGenerations.delete(renderId);\n changed = true;\n }\n if (this.clearRecoveredHostProblemAfterRender(renderId)) changed = true;\n if (changed) this.publish();\n }\n\n noteHmrUpdateStarted(): void {\n this.hmrGeneration += 1;\n }\n\n dispose(): void {\n this.watchers.clear();\n this.hostProblemClearedWatchers.clear();\n }\n\n inspectCurrentProblems(options: { renderId?: string | null } = {}) {\n const renderIdFilter = options.renderId ?? undefined;\n const currentRenderFailures: CanvasHostCurrentFrameProblemSnapshot[\"currentRenderFailures\"] =\n [];\n for (const [renderId, failure] of this.componentProblems) {\n if (renderIdFilter != null && renderId !== renderIdFilter) continue;\n currentRenderFailures.push({ renderId, failure });\n }\n\n const currentHostFailure = readCurrentViteOverlay() ?? this.hostProblem;\n return {\n ...(currentHostFailure ? { currentHostFailure } : {}),\n currentRenderFailures,\n currentCanvasFailures: [...this.canvasProblems].map(\n ([canvasPath, failure]) => ({ canvasPath, failure }),\n ),\n observedAt: Date.now(),\n };\n }\n\n private publish(): void {\n for (const watcher of this.watchers) {\n watcher();\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 if (this.hmrGeneration <= this.hostProblemHmrGeneration) return false;\n if (\n this.hostProblem.sourceKind === \"vite-hmr-error\" &&\n findRenderIdForProblem(this.hostProblem) !== renderId\n ) {\n return false;\n }\n const clearedProblem = this.hostProblem;\n this.hostProblem = undefined;\n this.hostProblemHmrGeneration = 0;\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 const cleanupHostCapture = installHostProblemCapture(tracker);\n const cleanupCanvasImportCapture = installCanvasImportProblemCapture(tracker);\n const cleanupViteCapture = installViteProblemCapture(tracker);\n const cleanupInspector = installCurrentProblemInspector(tracker);\n\n return () => {\n cleanupHostCapture();\n cleanupCanvasImportCapture();\n cleanupViteCapture();\n cleanupInspector();\n tracker.dispose();\n };\n}\n\n// The generated .tempo/tempo-host.tsx wraps each demand-registered canvas in a\n// CanvasImportBoundary that, on a module-load failure, renders null (isolating\n// the broken canvas) AND dispatches a `tempo:canvas-import-error` window\n// CustomEvent tagged with the canvas path. That boundary has no import surface\n// beyond React, so the event is its only way to reach this tracker. Convert it\n// into a canvas-scoped problem so the renderer can surface it on that canvas's\n// storyboards instead of leaving them spinning. Keep the event name in sync\n// with buildTempoHostWrapper in tempo-devserver.ts.\ntype CanvasImportErrorDetail = {\n canvasPath?: unknown;\n message?: unknown;\n stack?: unknown;\n};\n\nfunction installCanvasImportProblemCapture(\n tracker: CanvasHostProblemTracker,\n): () => void {\n const onCanvasImportError = (event: Event): void => {\n const detail = (event as CustomEvent<CanvasImportErrorDetail>).detail;\n if (typeof detail !== \"object\" || detail === null) return;\n const canvasPath =\n typeof detail.canvasPath === \"string\" ? detail.canvasPath : \"\";\n if (!canvasPath) return;\n const message =\n typeof detail.message === \"string\" && detail.message\n ? detail.message\n : \"Canvas module failed to load\";\n tracker.reportCanvasProblem(canvasPath, \"runtime-bootstrap\", message, {\n stack: typeof detail.stack === \"string\" ? detail.stack : undefined,\n filename: canvasPath,\n });\n };\n window.addEventListener(\"tempo:canvas-import-error\", onCanvasImportError);\n return () => {\n window.removeEventListener(\n \"tempo:canvas-import-error\",\n onCanvasImportError,\n );\n };\n}\n\nconst renderRecoveredHostProblemSourceKinds: readonly CanvasHostProblemSourceKind[] =\n [\"page-error\", \"unhandled-rejection\", \"console-vite-error\", \"vite-hmr-error\"];\n\nfunction createProblem(\n sourceKind: CanvasHostProblemSourceKind,\n error: unknown,\n details: Partial<CanvasHostRuntimeProblem> = {},\n): CanvasHostRuntimeProblem {\n return {\n sourceKind,\n message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n frameUrl: typeof window === \"undefined\" ? undefined : window.location.href,\n timestamp: Date.now(),\n ...details,\n };\n}\n\nfunction findRenderIdForProblem(\n problem: CanvasHostRuntimeProblem,\n): string | undefined {\n if (typeof document === \"undefined\") return undefined;\n const haystack = [\n problem.message,\n problem.stack,\n problem.componentStack,\n problem.filename,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n if (!haystack) return undefined;\n\n for (const slot of document.querySelectorAll(\"[data-render-id]\")) {\n const renderId = slot.getAttribute(\"data-render-id\");\n if (!renderId) continue;\n const sourceFiles = getObservedSourceFiles(slot);\n if (\n sourceFiles.some((sourceFile) =>\n problemTextMentionsSource(haystack, sourceFile),\n )\n ) {\n return renderId;\n }\n }\n return undefined;\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 problemTextMentionsSource(text: string, sourceFile: string): boolean {\n const normalizedSource = sourceFile.replace(/\\\\/g, \"/\");\n const basename = normalizedSource.split(\"/\").pop() ?? normalizedSource;\n return (\n text.includes(normalizedSource) ||\n (basename !== \"\" && text.includes(basename))\n );\n}\n\nfunction installHostProblemCapture(\n tracker: CanvasHostProblemTracker,\n): () => void {\n const onError = (event: ErrorEvent): void => {\n if (event.target instanceof Element) 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 =\n \"Failed to load \" +\n target.tagName.toLowerCase() +\n (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 const problem = readCurrentViteOverlay();\n if (problem) {\n tracker.reportHostProblem(\"vite-overlay\", problem.message, {\n stack: problem.stack,\n filename: problem.filename,\n });\n } else {\n tracker.clearHostProblem([\"vite-overlay\"]);\n }\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 viteHmrFailedModules = new Map<string, CanvasHostRuntimeProblem>();\n const latestViteHmrFailure = (): CanvasHostRuntimeProblem | undefined => {\n let latest: CanvasHostRuntimeProblem | undefined;\n for (const problem of viteHmrFailedModules.values()) {\n if (!latest || problem.timestamp >= latest.timestamp) latest = problem;\n }\n return latest;\n };\n const deleteViteHmrFailureForPath = (path: string): boolean => {\n let removed = false;\n for (const key of [...viteHmrFailedModules.keys()]) {\n if (key !== pathlessViteErrorKey && modulePathsMatch(key, path)) {\n viteHmrFailedModules.delete(key);\n removed = true;\n }\n }\n return removed;\n };\n const reconcileViteHmrHostProblem = (): void => {\n const latest = latestViteHmrFailure();\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 const pathlessViteErrorKey = \"__tempo:pathless-vite-error\";\n let viteHmrCycleActive = false;\n let cycleFailedPaths = new Map<string, CanvasHostRuntimeProblem>();\n let lastCycleViteErrorDetail:\n | { message: string; stack?: string; filename?: string }\n | undefined;\n\n // Monotonic HMR cycle counter plus the cycle in which each (normalized)\n // path last reloaded cleanly. Lets the async failed-reload verifier below\n // detect that its failure was already superseded by a clean update and\n // must not be resurrected.\n let hmrCycleSeq = 0;\n const cleanUpdateCycleByPath = new Map<string, number>();\n\n const onViteBeforeUpdate = (): void => {\n viteHmrCycleActive = true;\n hmrCycleSeq += 1;\n cycleFailedPaths = new Map();\n lastCycleViteErrorDetail = undefined;\n tracker.noteHmrUpdateStarted();\n };\n\n const onViteAfterUpdate = (payload: unknown): void => {\n const updatedPaths = readUpdatePaths(payload);\n let shouldReconcile = false;\n\n // An undo/fix of a broken edit must clear the stale failure: a path that\n // updates in a cycle without a captured failure has provably reloaded\n // cleanly, so any previously-recorded failure for that module is stale.\n // Nothing else in this tracker ever revisits a recorded path — before\n // this delete, a \"Failed to reload X\" popup outlived the fix forever.\n // Matching is normalized (cache-busting ?t= queries, absolute /@fs ids\n // vs root-relative URLs) because the failure key and the update payload\n // spell the same module differently.\n const failedThisCycle = [...cycleFailedPaths.keys()];\n for (const updatedPath of updatedPaths) {\n if (\n failedThisCycle.some((failed) => modulePathsMatch(failed, updatedPath))\n ) {\n continue;\n }\n cleanUpdateCycleByPath.set(normalizeModulePath(updatedPath), hmrCycleSeq);\n for (const key of [...viteHmrFailedModules.keys()]) {\n if (key === pathlessViteErrorKey) continue;\n if (modulePathsMatch(key, updatedPath)) {\n viteHmrFailedModules.delete(key);\n shouldReconcile = true;\n }\n }\n }\n if (\n updatedPaths.length > 0 &&\n !cycleFailedPaths.has(pathlessViteErrorKey)\n ) {\n if (viteHmrFailedModules.delete(pathlessViteErrorKey)) {\n shouldReconcile = true;\n }\n }\n for (const [path, problem] of cycleFailedPaths) {\n viteHmrFailedModules.set(path, problem);\n shouldReconcile = true;\n void verifyModuleStillExists(path).then((exists) => {\n if (exists) return;\n if (deleteViteHmrFailureForPath(path)) {\n reconcileViteHmrHostProblem();\n }\n });\n }\n viteHmrCycleActive = false;\n cycleFailedPaths = new Map();\n if (shouldReconcile) reconcileViteHmrHostProblem();\n };\n\n const onViteError = (payload: unknown): void => {\n const error = readViteError(payload);\n if (!error) return;\n\n lastCycleViteErrorDetail = error;\n const path = error.filename ?? pathlessViteErrorKey;\n const problem = createProblem(\"vite-hmr-error\", error.message, {\n stack: error.stack,\n filename: error.filename,\n });\n if (viteHmrCycleActive) {\n cycleFailedPaths.set(path, problem);\n } else {\n viteHmrFailedModules.set(path, problem);\n }\n reconcileViteHmrHostProblem();\n };\n\n let hotEventsCancelled = false;\n let subscribedHot: ViteHot | undefined;\n const subscribeHotEvents = (hot: ViteHot): void => {\n subscribedHot = hot;\n hot.on?.(\"vite:beforeUpdate\", onViteBeforeUpdate);\n hot.on?.(\"vite:afterUpdate\", onViteAfterUpdate);\n hot.on?.(\"vite:error\", onViteError);\n };\n const hot = readViteHot();\n if (hot?.on) {\n subscribeHotEvents(hot);\n } else {\n void import(\n /* @vite-ignore */\n /* webpackIgnore: true */\n /* turbopackIgnore: true */\n \"/@vite/client\"\n )\n .then((client: unknown) => {\n const createHotContext = (\n client as {\n createHotContext?: (ownerPath: string) => ViteHot | undefined;\n }\n ).createHotContext;\n const context = createHotContext?.(\"/__tempo-canvas-host__\");\n if (!context || hotEventsCancelled) return;\n subscribeHotEvents(context);\n })\n .catch(() => {});\n }\n\n const stopClearedWatch = tracker.watchHostProblemCleared((problem) => {\n if (problem.sourceKind !== \"vite-hmr-error\") return;\n // Entries can be keyed by the reloaded path while the problem carries a\n // different filename (e.g. the vite:error detail's id) — match by module\n // rather than exact key so a render-proven recovery can't strand an\n // entry that reconcile would immediately re-report.\n const filename = problem.filename;\n let removed = false;\n if (filename == null) {\n removed = viteHmrFailedModules.delete(pathlessViteErrorKey);\n } else {\n removed = deleteViteHmrFailureForPath(filename);\n }\n if (!removed) return;\n void Promise.resolve().then(reconcileViteHmrHostProblem);\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];\n const detail = lastCycleViteErrorDetail;\n const problem = createProblem(\n \"vite-hmr-error\",\n detail?.message ?? \"Failed to reload \" + path,\n {\n stack: detail?.stack ?? error.stack,\n filename: detail?.filename ?? path,\n },\n );\n if (detail) {\n cycleFailedPaths.set(path, problem);\n viteHmrFailedModules.set(path, problem);\n reconcileViteHmrHostProblem();\n } else {\n const observedCycleSeq = hmrCycleSeq;\n void verifyModuleStillExists(path).then((exists) => {\n // The verify fetch can outlive the failing cycle; if the module\n // already reloaded cleanly in a LATER cycle, this failure is\n // stale and must not be resurrected.\n const cleanSeq = cleanUpdateCycleByPath.get(\n normalizeModulePath(path),\n );\n if (cleanSeq !== undefined && cleanSeq > observedCycleSeq) return;\n if (exists) viteHmrFailedModules.set(path, problem);\n else viteHmrFailedModules.delete(path);\n reconcileViteHmrHostProblem();\n });\n }\n return;\n }\n\n if (viteHmrCycleActive) {\n lastCycleViteErrorDetail = error;\n return;\n }\n\n tracker.reportProblemNearRender(\"console-vite-error\", error.message, {\n stack: error.stack,\n filename: error.filename,\n });\n };\n console.error = patchedConsoleError;\n\n return () => {\n observer.disconnect();\n stopClearedWatch();\n hotEventsCancelled = true;\n subscribedHot?.off?.(\"vite:beforeUpdate\", onViteBeforeUpdate);\n subscribedHot?.off?.(\"vite:afterUpdate\", onViteAfterUpdate);\n subscribedHot?.off?.(\"vite:error\", onViteError);\n if (console.error === patchedConsoleError) {\n console.error = originalConsoleError;\n }\n };\n}\n\nfunction installCurrentProblemInspector(\n tracker: CanvasHostProblemTracker,\n): () => void {\n const maybeWindow = window as unknown as {\n __tempoErrorTrackingInspectCurrentProblems?: (options?: {\n renderId?: string | null;\n }) => CanvasHostCurrentFrameProblemSnapshot | null;\n };\n const previous = maybeWindow.__tempoErrorTrackingInspectCurrentProblems;\n const inspect = (options: { renderId?: string | null } = {}) =>\n mergeCurrentProblemSnapshots(\n tracker.inspectCurrentProblems(options),\n previous?.(options) ?? null,\n );\n maybeWindow.__tempoErrorTrackingInspectCurrentProblems = inspect;\n return () => {\n if (maybeWindow.__tempoErrorTrackingInspectCurrentProblems === inspect) {\n maybeWindow.__tempoErrorTrackingInspectCurrentProblems = previous;\n }\n };\n}\n\ntype ViteHot = {\n on?: (name: string, callback: (payload: unknown) => void) => void;\n off?: (name: string, callback: (payload: unknown) => void) => void;\n};\n\nfunction readViteHot(): ViteHot | undefined {\n const explicitHot = (\n window as unknown as { __tempoCanvasHostViteHot?: ViteHot }\n ).__tempoCanvasHostViteHot;\n if (explicitHot) return explicitHot;\n try {\n // eslint-disable-next-line no-eval\n return eval(\"import.meta && import.meta.hot\") as ViteHot | undefined;\n } catch {\n return undefined;\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\nfunction readUpdatePaths(payload: unknown): string[] {\n const updates =\n typeof payload === \"object\" &&\n payload !== null &&\n Array.isArray((payload as { updates?: unknown }).updates)\n ? (payload as { updates: Array<Record<string, unknown>> }).updates\n : [];\n const paths = new Set<string>();\n const collectPath = (value: unknown): void => {\n if (typeof value === \"string\") paths.add(value);\n };\n for (const update of updates) {\n collectPath(update.path);\n collectPath(update.acceptedPath);\n collectPath(update.id);\n }\n return [...paths];\n}\n\n/** Strip the cache-busting query (`?t=...`) and hash so hot-update URLs and\n * plain module ids compare as the same module. */\nfunction normalizeModulePath(value: string): string {\n const cutIndex = value.search(/[?#]/);\n return cutIndex === -1 ? value : value.slice(0, cutIndex);\n}\n\n/**\n * Whether two module identifiers refer to the same module. The failure key\n * and Vite's update payload spell the same module differently — cache-busting\n * `?t=` queries, absolute filesystem ids (vite:error `err.id`) vs the\n * root-relative URLs the client updates with — so equality alone misses.\n * The suffix match requires a leading \"/\" on the shorter side so it can only\n * bind at a path-segment boundary.\n */\nfunction modulePathsMatch(a: string, b: string): boolean {\n const left = normalizeModulePath(a);\n const right = normalizeModulePath(b);\n if (!left || !right) return false;\n if (left === right) return true;\n const [longer, shorter] =\n left.length >= right.length ? [left, right] : [right, left];\n return shorter.startsWith(\"/\") && longer.endsWith(shorter);\n}\n\nasync function verifyModuleStillExists(path: string): Promise<boolean> {\n if (typeof fetch !== \"function\") return true;\n try {\n const response = await fetch(path, { cache: \"no-store\" });\n if (\"ok\" in response && response.ok === false) return false;\n const contentType = response.headers.get(\"content-type\") || \"\";\n return !contentType.includes(\"text/html\");\n } catch {\n return true;\n }\n}\n\nfunction mergeCurrentProblemSnapshots(\n primary: CanvasHostCurrentFrameProblemSnapshot,\n fallback: CanvasHostCurrentFrameProblemSnapshot | null,\n): CanvasHostCurrentFrameProblemSnapshot {\n if (!fallback) return primary;\n const currentRenderFailures = [...primary.currentRenderFailures];\n const seen = new Set(\n currentRenderFailures.map(\n (entry) =>\n `${entry.renderId ?? \"\"}:${entry.failure.sourceKind}:${entry.failure.message}`,\n ),\n );\n for (const entry of fallback.currentRenderFailures) {\n const key = `${entry.renderId ?? \"\"}:${entry.failure.sourceKind}:${entry.failure.message}`;\n if (seen.has(key)) continue;\n seen.add(key);\n currentRenderFailures.push(entry);\n }\n const currentCanvasFailures = [...(primary.currentCanvasFailures ?? [])];\n const seenCanvas = new Set(\n currentCanvasFailures.map(\n (entry) =>\n `${entry.canvasPath}:${entry.failure.sourceKind}:${entry.failure.message}`,\n ),\n );\n for (const entry of fallback.currentCanvasFailures ?? []) {\n const key = `${entry.canvasPath}:${entry.failure.sourceKind}:${entry.failure.message}`;\n if (seenCanvas.has(key)) continue;\n seenCanvas.add(key);\n currentCanvasFailures.push(entry);\n }\n return {\n currentHostFailure:\n primary.currentHostFailure ?? fallback.currentHostFailure,\n currentRenderFailures,\n currentCanvasFailures,\n observedAt: Math.max(primary.observedAt, fallback.observedAt),\n };\n}\n","import {\n Component,\n Suspense,\n useEffect,\n useRef,\n type ComponentType,\n type ErrorInfo,\n type ReactNode,\n} from \"react\";\n\nimport type { TempoStoryboard } from \"../page\";\nimport { useCanvasIdentity, useCanvasStoryboardRenderId } from \"./canvas\";\nimport {\n syncStoryboardPortals,\n trackStoryboardPortals,\n} from \"./portal-tracking\";\nimport {\n useStoryboardErrorReporter,\n useStoryboardPlacement,\n useStoryboardRendered,\n useStoryboardSize,\n useStoryboardStatus,\n} from \"./runtime-context\";\n\nexport interface StoryboardLayout {\n x: number;\n y: number;\n width: number;\n height: number;\n zIndex?: number;\n intrinsicSizing?: \"root-element\";\n}\n\nexport function Storyboard<Props extends object = object>({\n id,\n name,\n component,\n layout,\n props,\n}: {\n id: string;\n component: ComponentType<Props>;\n layout: StoryboardLayout;\n name?: string;\n props?: Props;\n}) {\n const Component = component as ComponentType<Props>;\n\n return (\n <StoryboardSlot id={id} name={name} layout={layout} kind=\"component\">\n <Component {...(props ?? ({} as Props))} />\n </StoryboardSlot>\n );\n}\n\nexport function LegacyStoryboardV1({\n id,\n storyboard,\n}: {\n id: string;\n storyboard: TempoStoryboard;\n}) {\n return (\n <StoryboardSlot\n id={id}\n name={storyboard.name}\n layout={storyboard.layout}\n kind=\"component\"\n >\n <LegacyStoryboardV1Render render={storyboard.render} />\n </StoryboardSlot>\n );\n}\n\nfunction LegacyStoryboardV1Render({\n render,\n}: {\n render: TempoStoryboard[\"render\"];\n}) {\n return <>{render()}</>;\n}\n\nexport function RouteStoryboard({\n id,\n name,\n route,\n layout,\n}: {\n id: string;\n route: string;\n layout: StoryboardLayout;\n name?: string;\n}) {\n return (\n <StoryboardSlot\n id={id}\n name={name}\n layout={layout}\n kind=\"route\"\n route={route}\n />\n );\n}\n\nexport function HtmlStoryboard({\n id,\n name,\n filepath,\n src,\n layout,\n}: {\n id: string;\n layout: StoryboardLayout;\n filepath?: string;\n src?: string;\n name?: string;\n}) {\n return (\n <StoryboardSlot\n id={id}\n name={name}\n layout={layout}\n kind=\"html\"\n filepath={filepath}\n src={src}\n />\n );\n}\n\nexport function StoryboardSlot({\n children,\n id,\n kind,\n layout,\n name,\n route,\n filepath,\n src,\n}: {\n children?: ReactNode;\n id: string;\n kind: \"component\" | \"route\" | \"html\";\n layout: StoryboardLayout;\n name?: string;\n route?: string;\n filepath?: string;\n src?: string;\n}) {\n const renderId = useCanvasStoryboardRenderId(id);\n const canvas = useCanvasIdentity();\n const status = useStoryboardStatus(id);\n const renderSize = useStoryboardSize(id);\n const placement = useStoryboardPlacement(id);\n const markRendered = useStoryboardRendered(id);\n const { reportError, clearError } = useStoryboardErrorReporter(id);\n const renderWidth = renderSize?.width;\n const renderHeight = renderSize?.height;\n const intrinsicSize =\n renderSize?.intrinsicSize ??\n (kind === \"component\" && layout.intrinsicSizing === \"root-element\");\n const resetKey = `${renderId}:${renderSize?.revision ?? 0}`;\n const contentRef = useRef<HTMLDivElement | null>(null);\n\n useEffect(() => {\n if (!contentRef.current || status === \"unmounted\") return;\n return trackStoryboardPortals(renderId, contentRef.current, status);\n }, [renderId, status]);\n\n useEffect(() => {\n if (status === \"unmounted\") return;\n syncStoryboardPortals(renderId, status);\n }, [renderId, status]);\n\n if (status === \"unmounted\") return null;\n\n return (\n <div\n data-render-id={renderId}\n data-render-status={status}\n data-tempo-storyboard-render-id={renderId}\n data-tempo-storyboard-id={id}\n data-tempo-canvas-path={canvas?.path}\n data-tempo-storyboard-name={name}\n data-tempo-storyboard-kind={kind}\n data-tempo-storyboard-route={route}\n data-tempo-storyboard-filepath={filepath}\n data-tempo-storyboard-src={src}\n style={{\n position: \"absolute\",\n left: placement?.left ?? layout.x,\n top: placement?.top ?? layout.y,\n width: intrinsicSize ? \"max-content\" : (renderWidth ?? layout.width),\n height: intrinsicSize ? \"max-content\" : (renderHeight ?? layout.height),\n minWidth: intrinsicSize ? renderWidth : undefined,\n minHeight: intrinsicSize ? renderHeight : undefined,\n zIndex: layout.zIndex,\n visibility: status === \"active\" ? \"visible\" : \"hidden\",\n pointerEvents: status === \"active\" ? \"auto\" : \"none\",\n }}\n >\n <div\n data-render-content={renderId}\n ref={contentRef}\n style={{ width: \"100%\", height: \"100%\" }}\n >\n <StoryboardErrorBoundary\n onError={reportError}\n onRecover={clearError}\n resetKey={resetKey}\n >\n <Suspense fallback={null}>\n {children}\n <StoryboardReadySentinel\n active={status === \"active\"}\n clearError={clearError}\n markRendered={markRendered}\n />\n </Suspense>\n </StoryboardErrorBoundary>\n </div>\n </div>\n );\n}\n\ntype StoryboardErrorBoundaryProps = {\n children?: ReactNode;\n onError(error: {\n message: string;\n stack?: string;\n componentStack?: string;\n }): void;\n onRecover(): void;\n resetKey: string;\n};\n\ntype StoryboardErrorBoundaryState = {\n error: Error | null;\n componentStack?: string;\n resetKey: string;\n};\n\nconst renderErrorRetryDelayMs = 1_000;\n\nclass StoryboardErrorBoundary extends Component<\n StoryboardErrorBoundaryProps,\n StoryboardErrorBoundaryState\n> {\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n\n state: StoryboardErrorBoundaryState = {\n error: null,\n componentStack: undefined,\n resetKey: this.props.resetKey,\n };\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n static getDerivedStateFromProps(\n props: StoryboardErrorBoundaryProps,\n state: StoryboardErrorBoundaryState,\n ) {\n if (props.resetKey !== state.resetKey) {\n return { error: null, componentStack: undefined, resetKey: props.resetKey };\n }\n return null;\n }\n\n componentDidCatch(error: Error, info: ErrorInfo) {\n this.setState({ componentStack: info.componentStack ?? undefined });\n this.props.onError({\n message: error.message,\n stack: error.stack,\n componentStack: info.componentStack ?? undefined,\n });\n this.scheduleRetry();\n }\n\n componentDidUpdate(\n _prevProps: Readonly<StoryboardErrorBoundaryProps>,\n prevState: Readonly<StoryboardErrorBoundaryState>,\n ) {\n if (this.state.error) {\n if (!this.retryTimer) this.scheduleRetry();\n return;\n }\n this.clearRetryTimer();\n if (prevState.error && !this.state.error) {\n this.props.onRecover();\n }\n }\n\n componentWillUnmount() {\n this.clearRetryTimer();\n }\n\n private scheduleRetry() {\n this.clearRetryTimer();\n this.retryTimer = setTimeout(() => {\n this.retryTimer = null;\n this.setState((state) =>\n state.error\n ? { error: null, componentStack: undefined, resetKey: state.resetKey }\n : null,\n );\n }, renderErrorRetryDelayMs);\n }\n\n private clearRetryTimer() {\n if (!this.retryTimer) return;\n clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n\n render() {\n if (this.state.error) {\n return (\n <div\n data-render-error=\"true\"\n data-render-error-message={this.state.error.message}\n style={{ width: \"100%\", height: \"100%\" }}\n />\n );\n }\n return this.props.children;\n }\n}\n\nfunction StoryboardReadySentinel({\n active,\n clearError,\n markRendered,\n}: {\n active: boolean;\n clearError(): void;\n markRendered(): void;\n}) {\n useEffect(() => {\n if (!active) return;\n let paintFrame = 0;\n const commitFrame = requestAnimationFrame(() => {\n paintFrame = requestAnimationFrame(() => {\n clearError();\n markRendered();\n });\n });\n return () => {\n cancelAnimationFrame(commitFrame);\n cancelAnimationFrame(paintFrame);\n };\n }, [active, clearError, markRendered]);\n\n return null;\n}\n"],"mappings":";A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AW,MAAM;AACjC,WAAK,aAAa;AAClB,WAAK;AAAA,QAAS,CAAC,UACb,MAAM,QACF,EAAE,OAAO,MAAM,gBAAgB,QAAW,UAAU,MAAM,SAAS,IACnE;AAAA,MACN;AAAA,IACF,GAAG,uBAAuB;AAAA,EAC5B;AAAA,EAEQ,kBAAkB;AACxB,QAAI,CAAC,KAAK,WAAY;AACtB,iBAAa,KAAK,UAAU;AAC5B,SAAK,aAAa;AAAA,EACpB;AAAA,EAEA,SAAS;AACP,QAAI,KAAK,MAAM,OAAO;AACpB,aACE,gBAAAA;AAAA,QAAC;AAAA;AAAA,UACC,qBAAkB;AAAA,UAClB,6BAA2B,KAAK,MAAM,MAAM;AAAA,UAC5C,OAAO,EAAE,OAAO,QAAQ,QAAQ,OAAO;AAAA;AAAA,MACzC;AAAA,IAEJ;AACA,WAAO,KAAK,MAAM;AAAA,EACpB;AACF;AAEA,SAAS,wBAAwB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,EAAAG,WAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AACb,QAAI,aAAa;AACjB,UAAM,cAAc,sBAAsB,MAAM;AAC9C,mBAAa,sBAAsB,MAAM;AACvC,mBAAW;AACX,qBAAa;AAAA,MACf,CAAC;AAAA,IACH,CAAC;AACD,WAAO,MAAM;AACX,2BAAqB,WAAW;AAChC,2BAAqB,UAAU;AAAA,IACjC;AAAA,EACF,GAAG,CAAC,QAAQ,YAAY,YAAY,CAAC;AAErC,SAAO;AACT;","names":["useMemo","createContext","useContext","createContext","useContext","useCallback","useMemo","hot","useCallback","getObservedSourceFiles","message","useMemo","sourceAnnotationSelector","jsx","renderStatusById","useMemo","useEffect","useRef","jsx","Component","useRef","useEffect"]}
1
+ {"version":3,"sources":["../../canvas/canvas.tsx","../../canvas/ids.ts","../../canvas/canvas-host.tsx","../../canvas/canvas-import-boundary.tsx","../../canvas/canvas-pending-marker.tsx","../../canvas/host-recovery-feed.ts","../../canvas/runtime-context.ts","../../canvas/use-canvas-host-postmessage.ts","../../canvas/canvas-host-runtime.ts","../../canvas/portal-tracking.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","../../canvas/storyboard.tsx","../../canvas/admission-budget.ts","../../canvas/render-error-recovery.ts"],"sourcesContent":["import {\n Children,\n cloneElement,\n createContext,\n isValidElement,\n useContext,\n useMemo,\n type HTMLAttributes,\n type ReactNode,\n} from \"react\";\n\nimport { normalizeId } from \"./ids\";\n\ntype CanvasIdentity = {\n path: string;\n};\n\nconst CanvasIdentityContext = createContext<CanvasIdentity | null>(null);\n\nexport function getCanvasStoryboardRenderId(\n canvasPath: string,\n storyboardId: string,\n): string {\n return `canvas:${encodeURIComponent(\n normalizeId(canvasPath, \"Canvas path\"),\n )}#storyboard:${encodeURIComponent(\n normalizeId(storyboardId, \"Storyboard id\"),\n )}`;\n}\n\nexport function useCanvasIdentity(): CanvasIdentity | null {\n return useContext(CanvasIdentityContext);\n}\n\nexport function useCanvasStoryboardRenderId(storyboardId: string): string {\n const canvas = useCanvasIdentity();\n const normalizedId = normalizeId(storyboardId, \"Storyboard id\");\n return canvas\n ? getCanvasStoryboardRenderId(canvas.path, normalizedId)\n : normalizedId;\n}\n\nexport function Canvas({\n children,\n name,\n path,\n backgroundColor,\n defaultViewport,\n ...sourceAnnotations\n}: {\n children?: ReactNode;\n name: string;\n path?: string;\n backgroundColor?: string;\n defaultViewport?: { x: number; y: number; zoom: number };\n} & Record<`data-tempo-${string}`, unknown>) {\n const contextIdentity = useCanvasIdentity();\n const canvasName = normalizeId(name, \"Canvas name\");\n const canvasPath =\n path === undefined\n ? contextIdentity?.path\n : normalizeId(path, \"Canvas path\");\n\n if (!canvasPath) {\n throw new Error(\n '<Canvas> must be rendered inside <CanvasContext path=\"...\"> or receive a path prop.',\n );\n }\n\n const identity = useMemo(() => ({ path: canvasPath }), [canvasPath]);\n\n // Key each storyboard child by its declared id so React reconciles slots\n // by STORYBOARD IDENTITY rather than child position. Canvas files declare\n // storyboards as static JSX siblings (no keys), and positional\n // reconciliation reuses one storyboard's slot DOM node for another when\n // an edit inserts or removes a sibling above it — but slot DOM identity\n // is load-bearing: capture watchers, portal tracking, and the pool's\n // render-content wrappers all anchor to the slot node, and a reused node\n // silently starts feeding one storyboard's pipeline with another's\n // render.\n const keyedChildren = useMemo(\n () =>\n Children.map(children, (child) => {\n if (!isValidElement(child)) return child;\n if (child.key != null) return child;\n const id = (child.props as { id?: unknown }).id;\n if (typeof id !== \"string\" || id.length === 0) return child;\n return cloneElement(child, { key: `storyboard:${id}` });\n }),\n [children],\n );\n\n return (\n <CanvasIdentityContext.Provider value={identity}>\n <div\n {...(sourceAnnotations as HTMLAttributes<HTMLDivElement>)}\n data-tempo-canvas={canvasName}\n data-tempo-canvas-path={canvasPath}\n data-tempo-canvas-background={backgroundColor}\n data-tempo-canvas-viewport={\n defaultViewport ? JSON.stringify(defaultViewport) : undefined\n }\n >\n {keyedChildren}\n </div>\n </CanvasIdentityContext.Provider>\n );\n}\n\nexport function CanvasContext({\n children,\n path,\n}: {\n children?: ReactNode;\n path: string;\n}) {\n const canvasPath = normalizeId(path, \"Canvas path\");\n const identity = useMemo(() => ({ path: canvasPath }), [canvasPath]);\n return (\n <CanvasIdentityContext.Provider value={identity}>\n {children}\n </CanvasIdentityContext.Provider>\n );\n}\n","export function normalizeId(value: string | undefined, label: string): string {\n const normalized = value?.trim();\n if (!normalized) {\n throw new Error(`${label} is required.`);\n }\n return normalized;\n}\n","import { type ReactNode, useEffect, useMemo } from \"react\";\n\nimport { getCanvasStoryboardRenderId } from \"./canvas\";\nimport {\n CanvasImportBoundary,\n type CanvasModule,\n} from \"./canvas-import-boundary\";\nimport { normalizeId } from \"./ids\";\nimport type { CanvasHostRuntimeSize } from \"./runtime-context\";\nimport { CanvasHostContext } from \"./runtime-context\";\nimport { useCanvasHostPostMessage } from \"./use-canvas-host-postmessage\";\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 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 const width = params.get(\"width\")?.trim();\n const height = params.get(\"height\")?.trim();\n if (!width && !height) return undefined;\n if (!width || !height) {\n throw new Error(\"Direct URL width and height must be provided together\");\n }\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 renderId: getCanvasStoryboardRenderId(canvasPath, storyboardId),\n size: readDirectUrlSize(params),\n };\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 {\n renderStatusById,\n renderSizeById,\n markStoryboardRendered,\n markStoryboardUnmounted,\n reportStoryboardError,\n clearStoryboardError,\n reportCanvasImportError,\n clearCanvasImportError,\n registerCanvasProblemScope,\n } = useCanvasHostPostMessage(registeredCanvasPaths);\n useEffect(() => {\n if (typeof document === \"undefined\") return;\n return protectCanvasHostDocumentTitle(document);\n }, []);\n\n const directUrlSearch =\n typeof window === \"undefined\" ? \"\" : window.location.search;\n const directUrlRender = useMemo(() => {\n void directUrlSearch;\n return readDirectUrlRender();\n }, [directUrlSearch]);\n const propActiveIds = useMemo(\n () => new Set(activeStoryboardIds ?? []),\n [activeStoryboardIds],\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 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 return (\n <CanvasHostContext.Provider value={runtime}>\n {children}\n {canvasModules?.map(({ canvasPath, load }) => (\n <CanvasImportBoundary\n key={canvasPath}\n canvasPath={canvasPath}\n load={load}\n />\n ))}\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 {\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 loadRef = useRef(load);\n const previousLoadRef = useRef(load);\n loadRef.current = load;\n const [retryRevision, setRetryRevision] = useState(0);\n const lazyIdentity = `${canvasPath}:${retryRevision}`;\n const LazyCanvas = useMemo(() => {\n void lazyIdentity;\n return lazy(() =>\n Promise.resolve()\n .then(() => loadRef.current())\n .catch((error: unknown) => {\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 repairs those without any 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 reportCanvasImportError(canvasPath, error);\n },\n [canvasPath, reportCanvasImportError],\n );\n const markCommitted = useCallback(() => {\n failedRef.current = false;\n clearCanvasImportError(canvasPath);\n }, [canvasPath, clearCanvasImportError]);\n\n useEffect(() => {\n const loadChanged = previousLoadRef.current !== load;\n previousLoadRef.current = load;\n if (loadChanged && failedRef.current) {\n setRetryRevision((revision) => revision + 1);\n }\n }, [load]);\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 />\n <CanvasCommitSignal onCommit={markCommitted} />\n </CanvasContext>\n </Suspense>\n </CanvasImportErrorBoundary>\n );\n}\n","import { PROJECTION_PENDING_ATTRIBUTE } from \"../../../modules/iframe-projection/combined/projection-pending\";\n\n/**\n * The fallback every Tempo-owned Suspense boundary renders while it waits.\n *\n * A suspended subtree reaches the DOM as an empty one, which is\n * indistinguishable from a subtree that genuinely emptied. This marker makes\n * the difference observable to the projection producer, which treats a root\n * whose children are all markers as pending and holds the mirror's last-good\n * content instead of publishing the blank.\n *\n * Only Tempo's own boundaries render it. A user's Suspense inside their\n * storyboard keeps mirroring faithfully: their fallback — even `null` —\n * renders inside the root with no marker beside it, so their loading state\n * stays a real state the mirror shows.\n *\n * It carries no layout of its own: the host document must look the same with a\n * subtree pending as it does with that subtree absent.\n */\nexport function CanvasPendingMarker() {\n return (\n <div\n {...{ [PROJECTION_PENDING_ATTRIBUTE]: \"\" }}\n style={{ display: \"none\" }}\n aria-hidden=\"true\"\n />\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 { createContext, useCallback, useContext } from \"react\";\n\nimport { useCanvasStoryboardRenderId } from \"./canvas\";\n\nexport type CanvasHostRuntimeError = {\n message: string;\n stack?: string;\n componentStack?: string;\n};\n\nexport type CanvasHostRuntimeSize = {\n width?: number | string;\n height?: number | string;\n intrinsicSize?: boolean;\n revision?: number;\n};\n\nexport type CanvasHostRuntimePlacement = {\n left: number;\n top: number;\n};\n\nexport type CanvasHostRuntime = {\n getStoryboardStatus(storyboardId: string): \"active\" | \"cached\" | \"unmounted\";\n getStoryboardSize(storyboardId: string): CanvasHostRuntimeSize | undefined;\n getStoryboardPlacement(\n storyboardId: string,\n ): CanvasHostRuntimePlacement | undefined;\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 /**\n * Declares a canvas path as a problem-attribution candidate while its\n * boundary is mounted. Host-level Vite diagnostics that uniquely name a\n * registered canvas's source are scoped to that canvas instead of being\n * shown host-wide on every sibling. Returns the unregister disposer.\n */\n registerCanvasProblemScope(canvasPath: string): () => void;\n};\n\nexport const CanvasHostContext = createContext<CanvasHostRuntime | null>(null);\n\nexport function useRequiredCanvasHost(): CanvasHostRuntime {\n const host = useContext(CanvasHostContext);\n if (!host) {\n throw new Error(\n \"Tempo canvas components must be rendered inside <CanvasHost>.\",\n );\n }\n return host;\n}\n\nexport function useActiveState(storyboardId: string): boolean {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardStatus(renderId) !== \"unmounted\";\n}\n\nexport function useStoryboardStatus(\n storyboardId: string,\n): \"active\" | \"cached\" | \"unmounted\" {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardStatus(renderId);\n}\n\nexport function useStoryboardRendered(storyboardId: string): () => void {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return useCallback(() => {\n host.markStoryboardRendered(renderId);\n }, [host, renderId]);\n}\n\nexport function useStoryboardUnmounted(storyboardId: string): () => void {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const { markStoryboardUnmounted } = useRequiredCanvasHost();\n return useCallback(() => {\n markStoryboardUnmounted(renderId);\n }, [markStoryboardUnmounted, renderId]);\n}\n\nexport function useStoryboardErrorReporter(storyboardId: string): {\n reportError(error: CanvasHostRuntimeError): void;\n clearError(): void;\n} {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n const reportError = useCallback(\n (error: CanvasHostRuntimeError) => {\n host.reportStoryboardError(renderId, error);\n },\n [host, renderId],\n );\n const clearError = useCallback(() => {\n host.clearStoryboardError(renderId);\n }, [host, renderId]);\n return { reportError, clearError };\n}\n\nexport function useStoryboardSize(\n storyboardId: string,\n): CanvasHostRuntimeSize | undefined {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardSize(renderId);\n}\n\nexport function useStoryboardPlacement(\n storyboardId: string,\n): CanvasHostRuntimePlacement | undefined {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardPlacement(renderId);\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 renderStatusById: ReadonlyMap<string, \"active\" | \"cached\">;\n renderSizeById: ReadonlyMap<\n string,\n {\n width?: number;\n height?: number;\n intrinsicSize?: boolean;\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 () => new Map<string, CanvasHostRenderEntry>(),\n );\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 watchRequestsRef = useRef(watchRequestsById);\n const registeredCanvasPathsRef = useRef<readonly string[]>([]);\n registeredCanvasPathsRef.current = registeredCanvasPaths;\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 ) => Map<string, CanvasHostRenderEntry>,\n ) => {\n setRenderEntriesById((entries) => {\n const next = update(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 alreadyRendered =\n current?.status === \"active\" &&\n renderedRenderIdsRef.current.has(request.renderId) &&\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 () => buildRenderStatusMap(renderEntriesById),\n [renderEntriesById],\n ),\n renderSizeById: useMemo(\n () => buildRenderSizeMap(renderEntriesById),\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: { src: string; width: number; height: number };\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","type FiberLike = {\n return: FiberLike | null;\n stateNode: unknown;\n};\n\ntype PortalWatcher = {\n element: Element;\n onPortalFound(portalRoot: Element): void;\n onPortalRemoved(portalRoot: Element): void;\n};\n\ntype PortalInlineStyleValue = {\n value: string;\n priority: string;\n};\n\ntype PortalInlineStyle = {\n visibility: PortalInlineStyleValue;\n pointerEvents: PortalInlineStyleValue;\n contentVisibility: PortalInlineStyleValue;\n transition: PortalInlineStyleValue;\n animation: PortalInlineStyleValue;\n};\n\ntype PortalManagedProperty = {\n // The PortalInlineStyle field that holds this property's saved baseline.\n key: keyof PortalInlineStyle;\n // The CSS property name as written in inline styles.\n cssName: string;\n // The value forced (with !important) while the portal is hidden.\n hiddenValue: string;\n};\n\n// Single source of truth for the inline-style properties this module overrides\n// to hide cached/inactive portals, so the hide path and the restore path can't\n// drift out of sync.\nconst PORTAL_MANAGED_PROPERTIES: readonly PortalManagedProperty[] = [\n { key: \"visibility\", cssName: \"visibility\", hiddenValue: \"hidden\" },\n { key: \"pointerEvents\", cssName: \"pointer-events\", hiddenValue: \"none\" },\n {\n key: \"contentVisibility\",\n cssName: \"content-visibility\",\n hiddenValue: \"hidden\",\n },\n { key: \"transition\", cssName: \"transition\", hiddenValue: \"none\" },\n { key: \"animation\", cssName: \"animation\", hiddenValue: \"none\" },\n];\n\nconst portalElementsByRenderId = new Map<string, Set<Element>>();\nconst portalOwnerRenderIdsByElement = new Map<Element, Set<string>>();\nconst portalInlineStyleByElement = new Map<Element, PortalInlineStyle>();\nconst renderStatusById = new Map<string, \"active\" | \"cached\">();\nconst projectionPortalIdAttribute = \"data-projection-portal-id\";\nlet nextSdkPortalId = 1;\n\nfunction escapeAttributeValue(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\nfunction ensureProjectionPortalId(portalRoot: Element): string {\n const existingId = portalRoot.getAttribute(projectionPortalIdAttribute);\n if (existingId) return existingId;\n\n const id = `tempo-sdk-portal-${nextSdkPortalId++}`;\n portalRoot.setAttribute(projectionPortalIdAttribute, id);\n return id;\n}\n\nfunction buildProjectionPortalSelector(portalRoot: Element): string {\n return `[${projectionPortalIdAttribute}=\"${escapeAttributeValue(\n ensureProjectionPortalId(portalRoot),\n )}\"]`;\n}\n\nfunction findFiberKey(element: Element): string | null {\n return (\n Object.keys(element).find(\n (key) =>\n key.startsWith(\"__reactFiber$\") ||\n key.startsWith(\"__reactInternalInstance$\"),\n ) ?? null\n );\n}\n\nfunction findContainerKey(element: Element): string | null {\n return Object.keys(element).find((key) => key.startsWith(\"__reactContainer$\")) ?? null;\n}\n\nfunction getFiberFromElement(element: Element): FiberLike | null {\n const fiberKey = findFiberKey(element);\n if (fiberKey) {\n return (\n (element as unknown as Record<string, FiberLike | undefined>)[fiberKey] ??\n null\n );\n }\n\n const containerKey = findContainerKey(element);\n if (containerKey) {\n return (\n (element as unknown as Record<string, FiberLike | undefined>)[\n containerKey\n ] ?? null\n );\n }\n\n return null;\n}\n\nclass PortalTracker {\n private readonly watchers = new Set<PortalWatcher>();\n private readonly ownerWatchersByPortalRoot = new Map<\n Element,\n Set<PortalWatcher>\n >();\n private observer: MutationObserver | null = null;\n\n register(watcher: PortalWatcher): () => void {\n this.watchers.add(watcher);\n\n if (this.watchers.size === 1) {\n this.startObserving();\n }\n\n if (typeof document !== \"undefined\" && document.body) {\n this.checkExistingElements();\n queueMicrotask(() => this.checkExistingElements());\n }\n\n return () => this.unregister(watcher);\n }\n\n private checkExistingElements(): void {\n if (typeof document === \"undefined\" || !document.body) return;\n for (const child of Array.from(document.body.children)) {\n this.checkElement(child);\n }\n }\n\n private unregister(watcher: PortalWatcher): void {\n this.watchers.delete(watcher);\n\n for (const [portalRoot, owners] of this.ownerWatchersByPortalRoot) {\n owners.delete(watcher);\n if (owners.size === 0) {\n this.ownerWatchersByPortalRoot.delete(portalRoot);\n }\n }\n\n if (this.watchers.size === 0) {\n this.stopObserving();\n }\n }\n\n private startObserving(): void {\n if (\n this.observer ||\n typeof document === \"undefined\" ||\n !document.body ||\n typeof MutationObserver === \"undefined\"\n ) {\n return;\n }\n\n this.observer = new MutationObserver(this.handleMutations);\n this.observer.observe(document.body, { childList: true });\n }\n\n private stopObserving(): void {\n this.observer?.disconnect();\n this.observer = null;\n }\n\n private handleMutations = (mutations: MutationRecord[]): void => {\n for (const mutation of mutations) {\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n queueMicrotask(() => this.checkElement(node));\n }\n }\n\n for (const node of mutation.removedNodes) {\n if (!(node instanceof Element)) continue;\n const owners = this.ownerWatchersByPortalRoot.get(node);\n if (!owners) continue;\n for (const owner of owners) {\n owner.onPortalRemoved(node);\n }\n this.ownerWatchersByPortalRoot.delete(node);\n }\n }\n };\n\n private checkElement(element: Element): void {\n const ancestorDomNodes = this.getDomAncestorsViaFiber(element);\n if (ancestorDomNodes.length === 0) return;\n\n let owners = this.ownerWatchersByPortalRoot.get(element);\n for (const watcher of this.watchers) {\n const belongsToWatcher = ancestorDomNodes.some(\n (node) => watcher.element.contains(node) || watcher.element === node,\n );\n if (!belongsToWatcher) continue;\n\n if (!owners) {\n owners = new Set<PortalWatcher>();\n this.ownerWatchersByPortalRoot.set(element, owners);\n }\n if (owners.has(watcher)) continue;\n\n owners.add(watcher);\n watcher.onPortalFound(element);\n }\n }\n\n private getDomAncestorsViaFiber(element: Element): Element[] {\n const fiber = getFiberFromElement(element);\n if (!fiber) return [];\n\n const domNodes: Element[] = [];\n let current: FiberLike | null = fiber.return;\n while (current) {\n if (current.stateNode instanceof Element) {\n domNodes.push(current.stateNode);\n }\n current = current.return;\n }\n return domNodes;\n }\n}\n\nlet portalTracker: PortalTracker | null = null;\n\nfunction getPortalTracker(): PortalTracker {\n if (!portalTracker) {\n portalTracker = new PortalTracker();\n }\n return portalTracker;\n}\n\nfunction getStylablePortalElement(\n portalRoot: Element,\n): HTMLElement | SVGElement | null {\n if (portalRoot instanceof HTMLElement || portalRoot instanceof SVGElement) {\n return portalRoot;\n }\n return null;\n}\n\nfunction ensurePortalInlineStyle(portalRoot: Element): PortalInlineStyle {\n const existing = portalInlineStyleByElement.get(portalRoot);\n if (existing) return existing;\n\n const stylableElement = getStylablePortalElement(portalRoot);\n const baseline = {\n visibility: readInlineStyleValue(stylableElement, \"visibility\"),\n pointerEvents: readInlineStyleValue(stylableElement, \"pointer-events\"),\n contentVisibility: readInlineStyleValue(\n stylableElement,\n \"content-visibility\",\n ),\n transition: readInlineStyleValue(stylableElement, \"transition\"),\n animation: readInlineStyleValue(stylableElement, \"animation\"),\n };\n portalInlineStyleByElement.set(portalRoot, baseline);\n return baseline;\n}\n\nfunction readInlineStyleValue(\n element: HTMLElement | SVGElement | null,\n propertyName: string,\n): PortalInlineStyleValue {\n return {\n value: element?.style.getPropertyValue(propertyName) ?? \"\",\n priority: element?.style.getPropertyPriority(propertyName) ?? \"\",\n };\n}\n\nfunction restoreInlineStyleValue(\n style: CSSStyleDeclaration,\n propertyName: string,\n baseline: PortalInlineStyleValue,\n): void {\n if (baseline.value) {\n style.setProperty(propertyName, baseline.value, baseline.priority);\n return;\n }\n style.removeProperty(propertyName);\n}\n\nfunction restorePortalInlineStyle(portalRoot: Element): void {\n const stylableElement = getStylablePortalElement(portalRoot);\n const baseline = portalInlineStyleByElement.get(portalRoot);\n if (!stylableElement || !baseline) return;\n\n for (const property of PORTAL_MANAGED_PROPERTIES) {\n restoreInlineStyleValue(\n stylableElement.style,\n property.cssName,\n baseline[property.key],\n );\n }\n}\n\nfunction syncPortalVisibility(portalRoot: Element): void {\n const owners = portalOwnerRenderIdsByElement.get(portalRoot);\n if (!owners || owners.size === 0) {\n restorePortalInlineStyle(portalRoot);\n portalInlineStyleByElement.delete(portalRoot);\n return;\n }\n\n const stylableElement = getStylablePortalElement(portalRoot);\n if (!stylableElement) return;\n\n const shouldBeVisible = [...owners].some(\n (renderId) => renderStatusById.get(renderId) === \"active\",\n );\n\n if (shouldBeVisible) {\n restorePortalInlineStyle(portalRoot);\n portalInlineStyleByElement.delete(portalRoot);\n return;\n }\n\n ensurePortalInlineStyle(portalRoot);\n for (const property of PORTAL_MANAGED_PROPERTIES) {\n stylableElement.style.setProperty(\n property.cssName,\n property.hiddenValue,\n \"important\",\n );\n }\n}\n\nfunction trackPortal(renderId: string, portalRoot: Element): void {\n ensureProjectionPortalId(portalRoot);\n\n const portals = portalElementsByRenderId.get(renderId) ?? new Set<Element>();\n portals.add(portalRoot);\n portalElementsByRenderId.set(renderId, portals);\n\n const owners = portalOwnerRenderIdsByElement.get(portalRoot) ?? new Set<string>();\n owners.add(renderId);\n portalOwnerRenderIdsByElement.set(portalRoot, owners);\n syncPortalVisibility(portalRoot);\n}\n\nfunction untrackPortal(renderId: string, portalRoot: Element): void {\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) return;\n\n portals.delete(portalRoot);\n if (portals.size === 0) {\n portalElementsByRenderId.delete(renderId);\n }\n\n const owners = portalOwnerRenderIdsByElement.get(portalRoot);\n if (owners) {\n owners.delete(renderId);\n if (owners.size === 0) {\n portalOwnerRenderIdsByElement.delete(portalRoot);\n }\n }\n syncPortalVisibility(portalRoot);\n}\n\nexport function releaseStoryboardPortals(renderId: string): void {\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) {\n renderStatusById.delete(renderId);\n return;\n }\n\n for (const portalRoot of [...portals]) {\n untrackPortal(renderId, portalRoot);\n }\n renderStatusById.delete(renderId);\n}\n\nexport function getStoryboardPortalSelectors(renderId: string): string[] {\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) return [];\n return [...portals]\n .filter((portalRoot) => portalRoot.isConnected)\n .map(buildProjectionPortalSelector);\n}\n\nexport function syncStoryboardPortals(\n renderId: string,\n status: \"active\" | \"cached\",\n): void {\n renderStatusById.set(renderId, status);\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) return;\n for (const portalRoot of portals) {\n syncPortalVisibility(portalRoot);\n }\n}\n\nexport function trackStoryboardPortals(\n renderId: string,\n element: Element,\n status: \"active\" | \"cached\",\n): () => void {\n syncStoryboardPortals(renderId, status);\n const unregister = getPortalTracker().register({\n element,\n onPortalFound(portalRoot) {\n trackPortal(renderId, portalRoot);\n },\n onPortalRemoved(portalRoot) {\n untrackPortal(renderId, portalRoot);\n },\n });\n\n return () => {\n unregister();\n releaseStoryboardPortals(renderId);\n };\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\";\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 importPath: string;\n importName: string;\n props?: Record<string, unknown>;\n width?: number;\n height?: number;\n intrinsicSize?: boolean;\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(message: unknown): 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(\n payload: Record<string, unknown>,\n): { width?: number; height?: number } {\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 intrinsicSize: payload.intrinsicSize === true ? true : undefined,\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\";\n\nexport type CanvasHostRenderEntry = CanvasHostRenderRequest & {\n status: \"active\" | \"cached\";\n activeCount: number;\n revision: number;\n lastInactiveAt?: number;\n};\n\nexport type CanvasHostRenderSize = {\n width?: number;\n height?: number;\n intrinsicSize?: boolean;\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 intrinsicSize?: boolean;\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 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): Map<string, CanvasHostRenderEntry> {\n const current = entries.get(renderId);\n if (!current) return new Map(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): Map<string, CanvasHostRenderEntry> {\n const next = new Map(entries);\n const cached = [...next.values()]\n .filter((entry) => entry.status === \"cached\")\n .sort((a, b) => (a.lastInactiveAt ?? 0) - (b.lastInactiveAt ?? 0));\n for (const entry of cached.slice(0, Math.max(0, cached.length - maxCached))) {\n next.delete(entry.renderId);\n }\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\nexport function buildRenderStatusMap(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n): ReadonlyMap<string, \"active\" | \"cached\"> {\n return new Map([...entries].map(([id, entry]) => [id, entry.status]));\n}\n\nexport function buildRenderSizeMap(\n entries: ReadonlyMap<string, CanvasHostRenderEntry>,\n): ReadonlyMap<string, CanvasHostRenderSize> {\n return new Map(\n [...entries].map(([id, entry]) => [\n id,\n {\n width: entry.width,\n height: entry.height,\n intrinsicSize: entry.intrinsicSize,\n revision: entry.revision,\n },\n ]),\n );\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 { 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\ntype TempoViteServerError = {\n message: string;\n stack?: string;\n file?: string;\n loc?: { file?: string };\n};\n\nfunction installViteErrorStream(tracker: CanvasHostProblemTracker): () => void {\n if (typeof EventSource === \"undefined\") return () => {};\n\n // Vite can reject an initial dynamic import before its HMR websocket has\n // connected. The Tempo Vite plugin records errors server-side before the\n // broadcast and replays its current state here, closing that startup gap\n // without polling or delaying canvas imports.\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 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 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). */\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, { cache: \"no-store\" });\n return response.ok;\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 message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n frameUrl: typeof window === \"undefined\" ? undefined : window.location.href,\n timestamp: Date.now(),\n ...details,\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\nfunction installHostProblemCapture(\n tracker: CanvasHostProblemTracker,\n): () => void {\n const onError = (event: ErrorEvent): void => {\n if (event.target instanceof Element) 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.\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","import {\n Children,\n Component,\n type ComponentType,\n cloneElement,\n type ErrorInfo,\n isValidElement,\n type ReactNode,\n Suspense,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport type { TempoStoryboard } from \"../page\";\nimport { beginAdmissionWindow } from \"./admission-budget\";\nimport { useCanvasIdentity, useCanvasStoryboardRenderId } from \"./canvas\";\nimport { CanvasPendingMarker } from \"./canvas-pending-marker\";\nimport {\n syncStoryboardPortals,\n trackStoryboardPortals,\n} from \"./portal-tracking\";\nimport { useRenderErrorRecovery } from \"./render-error-recovery\";\nimport {\n useStoryboardErrorReporter,\n useStoryboardPlacement,\n useStoryboardRendered,\n useStoryboardSize,\n useStoryboardStatus,\n useStoryboardUnmounted,\n} from \"./runtime-context\";\n\nexport interface StoryboardLayout {\n x: number;\n y: number;\n width: number;\n height: number;\n zIndex?: number;\n intrinsicSizing?: \"root-element\";\n}\n\nexport function Storyboard<Props extends object = object>({\n id,\n name,\n component,\n layout,\n props,\n}: {\n id: string;\n component: ComponentType<Props>;\n layout: StoryboardLayout;\n name?: string;\n props?: Props;\n}) {\n const Component = component as ComponentType<Props>;\n\n return (\n <StoryboardSlot id={id} name={name} layout={layout} kind=\"component\">\n <Component {...(props ?? ({} as Props))} />\n </StoryboardSlot>\n );\n}\n\nexport function LegacyStoryboardV1({\n id,\n storyboard,\n}: {\n id: string;\n storyboard: TempoStoryboard;\n}) {\n return (\n <StoryboardSlot\n id={id}\n name={storyboard.name}\n layout={storyboard.layout}\n kind=\"component\"\n >\n <LegacyStoryboardV1Render render={storyboard.render} />\n </StoryboardSlot>\n );\n}\n\nfunction LegacyStoryboardV1Render({\n render,\n}: {\n render: TempoStoryboard[\"render\"];\n}) {\n return <>{render()}</>;\n}\n\nexport function RouteStoryboard({\n id,\n name,\n route,\n layout,\n}: {\n id: string;\n route: string;\n layout: StoryboardLayout;\n name?: string;\n}) {\n return (\n <StoryboardSlot\n id={id}\n name={name}\n layout={layout}\n kind=\"route\"\n route={route}\n />\n );\n}\n\n/** @deprecated Legacy HTML storyboards are render-only. */\nexport function HtmlStoryboard({\n id,\n name,\n filepath,\n src,\n layout,\n}: {\n id: string;\n layout: StoryboardLayout;\n filepath?: string;\n src?: string;\n name?: string;\n}) {\n return (\n <StoryboardSlot\n id={id}\n name={name}\n layout={layout}\n kind=\"html\"\n filepath={filepath}\n src={src}\n />\n );\n}\n\nexport function StoryboardSlot({\n children,\n id,\n kind,\n layout,\n name,\n route,\n filepath,\n src,\n}: {\n children?: ReactNode;\n id: string;\n kind: \"component\" | \"route\" | \"html\";\n layout: StoryboardLayout;\n name?: string;\n route?: string;\n filepath?: string;\n src?: string;\n}) {\n const renderId = useCanvasStoryboardRenderId(id);\n const canvas = useCanvasIdentity();\n const status = useStoryboardStatus(id);\n const renderSize = useStoryboardSize(id);\n const placement = useStoryboardPlacement(id);\n const markRendered = useStoryboardRendered(id);\n const markUnmounted = useStoryboardUnmounted(id);\n const { reportError, clearError } = useStoryboardErrorReporter(id);\n const renderWidth = renderSize?.width;\n const renderHeight = renderSize?.height;\n const renderRevision = renderSize?.revision ?? 0;\n const intrinsicSize =\n renderSize?.intrinsicSize ??\n (kind === \"component\" && layout.intrinsicSizing === \"root-element\");\n const resetKey = `${renderId}:${renderRevision}`;\n const contentRef = useRef<HTMLDivElement | null>(null);\n // Phase 1 commits this slot's own elements with no user code under them, so\n // the projection root can register off a DOM node that exists whatever the\n // storyboard's component does; phase 2 admits the user tree one task later,\n // by which point the registration command has been answered. Keying the\n // admission by render id gives every projection identity its own phase 1.\n // Server rendering has no live document to register against and no event\n // loop to keep responsive, so there the whole tree is admitted at once.\n const [admittedRenderId, setAdmittedRenderId] = useState<string | null>(\n typeof document === \"undefined\" ? renderId : null,\n );\n const admitted = admittedRenderId === renderId;\n const errorBoundaryRef = useRef<StoryboardErrorBoundary | null>(null);\n const lastReportedCommitRef = useRef<string | null>(null);\n const previousChildrenRef = useRef(children);\n const [recoveryRevision, setRecoveryRevision] = useState(0);\n const commitKey = `${resetKey}:${recoveryRevision}`;\n // Bumping the recovery revision after a successful boundary reset remounts\n // the commit signal, so a recovery is re-reported (clearError) instead of\n // being swallowed by the commit-key dedupe.\n const retryRenderNow = useCallback(() => {\n if (!errorBoundaryRef.current?.retry()) return false;\n setRecoveryRevision((revision) => revision + 1);\n return true;\n }, []);\n const { noteRenderError, noteRecovered } =\n useRenderErrorRecovery(retryRenderNow);\n const handleRenderError = useCallback(\n (error: { message: string; stack?: string; componentStack?: string }) => {\n noteRenderError();\n reportError(error);\n },\n [noteRenderError, reportError],\n );\n // React finishes the remaining layout effects after capturing a sibling\n // layout-effect error, so the commit signal is provisional. Report success\n // in the next task, after the boundary has had a chance to record the error.\n const pendingRenderedReportRef = useRef<ReturnType<typeof setTimeout> | null>(\n null,\n );\n const handleRendered = useCallback(\n (reportedCommitKey: string) => {\n if (pendingRenderedReportRef.current !== null) {\n clearTimeout(pendingRenderedReportRef.current);\n }\n pendingRenderedReportRef.current = setTimeout(() => {\n pendingRenderedReportRef.current = null;\n if (errorBoundaryRef.current?.hasError()) return;\n noteRecovered();\n if (lastReportedCommitRef.current === reportedCommitKey) return;\n lastReportedCommitRef.current = reportedCommitKey;\n clearError();\n markRendered();\n }, 0);\n },\n [clearError, markRendered, noteRecovered],\n );\n useEffect(\n () => () => {\n if (pendingRenderedReportRef.current !== null) {\n clearTimeout(pendingRenderedReportRef.current);\n pendingRenderedReportRef.current = null;\n }\n },\n [],\n );\n const renderChildren = useMemo(() => {\n if (isValidElement(children)) return cloneElement(children);\n return Children.map(children, (child) =>\n isValidElement(child) ? cloneElement(child) : child,\n );\n }, [children]);\n\n useEffect(() => markUnmounted, [markUnmounted]);\n\n // A passive effect, deliberately: React flushes these in a scheduler task of\n // their own, so the microtask checkpoint between phase 1's commit and this\n // admission is where the frame's registration observer gets to run.\n useEffect(() => {\n setAdmittedRenderId(renderId);\n }, [renderId]);\n\n useEffect(() => {\n const childrenChanged = previousChildrenRef.current !== children;\n previousChildrenRef.current = children;\n if (childrenChanged) retryRenderNow();\n }, [children, retryRenderNow]);\n\n useEffect(() => {\n if (!contentRef.current || status === \"unmounted\") return;\n return trackStoryboardPortals(renderId, contentRef.current, status);\n }, [renderId, status]);\n\n useEffect(() => {\n if (status === \"unmounted\") return;\n syncStoryboardPortals(renderId, status);\n }, [renderId, status]);\n\n if (status === \"unmounted\") return null;\n\n return (\n <div\n data-render-id={renderId}\n data-render-status={status}\n data-tempo-storyboard-render-id={renderId}\n data-tempo-storyboard-id={id}\n data-tempo-canvas-path={canvas?.path}\n data-tempo-storyboard-name={name}\n data-tempo-storyboard-kind={kind}\n data-tempo-storyboard-route={route}\n data-tempo-storyboard-filepath={filepath}\n data-tempo-storyboard-src={src}\n style={{\n position: \"absolute\",\n left: placement?.left ?? layout.x,\n top: placement?.top ?? layout.y,\n width: intrinsicSize ? \"max-content\" : (renderWidth ?? layout.width),\n height: intrinsicSize ? \"max-content\" : (renderHeight ?? layout.height),\n minWidth: intrinsicSize ? renderWidth : undefined,\n minHeight: intrinsicSize ? renderHeight : undefined,\n zIndex: layout.zIndex,\n visibility: status === \"active\" ? \"visible\" : \"hidden\",\n pointerEvents: status === \"active\" ? \"auto\" : \"none\",\n }}\n >\n <div\n data-render-content={renderId}\n // Phase 2's marker: the producer registers off the shell but waits for\n // this before opening its watch, so no baseline is ever taken from the\n // deliberately-empty phase 1.\n data-render-admitted={admitted ? \"true\" : undefined}\n data-tempo-render-mode={kind === \"html\" ? \"static-dom\" : undefined}\n data-tempo-hide-fiber=\"true\"\n ref={contentRef}\n style={{ width: \"100%\", height: \"100%\" }}\n >\n <StoryboardErrorBoundary\n ref={errorBoundaryRef}\n onError={handleRenderError}\n resetKey={resetKey}\n >\n {admitted ? (\n <Suspense fallback={<CanvasPendingMarker />}>\n <StoryboardAdmission>{renderChildren}</StoryboardAdmission>\n <StoryboardCommitSignal\n key={commitKey}\n commitKey={commitKey}\n onCommit={handleRendered}\n />\n </Suspense>\n ) : null}\n </StoryboardErrorBoundary>\n </div>\n </div>\n );\n}\n\n/** Opens the admission budget for the user tree React is about to render\n * under it. Rendering this component is what arms the counter, so it must sit\n * directly above the user tree and below the error boundary that catches the\n * budget's throw. */\nfunction StoryboardAdmission({ children }: { children?: ReactNode }) {\n beginAdmissionWindow();\n return children;\n}\n\nfunction StoryboardCommitSignal({\n commitKey,\n onCommit,\n}: {\n commitKey: string;\n onCommit(commitKey: string): void;\n}) {\n const onCommitRef = useRef(onCommit);\n onCommitRef.current = onCommit;\n useLayoutEffect(() => onCommitRef.current(commitKey), [commitKey]);\n return null;\n}\n\ntype StoryboardErrorBoundaryProps = {\n children?: ReactNode;\n onError(error: {\n message: string;\n stack?: string;\n componentStack?: string;\n }): void;\n resetKey: string;\n};\n\ntype StoryboardErrorBoundaryState = {\n error: Error | null;\n componentStack?: string;\n resetKey: string;\n};\n\n/** React emits one component-stack frame per fiber, so a storyboard that\n * recursed until it hit the admission budget produces a megabyte of stack in\n * which every frame after the first few is the same repeated line. The whole\n * string is reported onto the storyboard's problem lane and read back by the\n * Tempo renderer, so it is cut where it stops being evidence. */\nconst maxReportedComponentStackFrames = 40;\n\nfunction boundComponentStack(\n componentStack: string | null | undefined,\n): string | undefined {\n if (!componentStack) return undefined;\n const frames = componentStack.split(\"\\n\");\n if (frames.length <= maxReportedComponentStackFrames) return componentStack;\n const dropped = frames.length - maxReportedComponentStackFrames;\n return [\n ...frames.slice(0, maxReportedComponentStackFrames),\n ` ... ${dropped} more frames`,\n ].join(\"\\n\");\n}\n\nclass StoryboardErrorBoundary extends Component<\n StoryboardErrorBoundaryProps,\n StoryboardErrorBoundaryState\n> {\n state: StoryboardErrorBoundaryState = {\n error: null,\n componentStack: undefined,\n resetKey: this.props.resetKey,\n };\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n static getDerivedStateFromProps(\n props: StoryboardErrorBoundaryProps,\n state: StoryboardErrorBoundaryState,\n ) {\n if (props.resetKey !== state.resetKey) {\n return {\n error: null,\n componentStack: undefined,\n resetKey: props.resetKey,\n };\n }\n return null;\n }\n\n componentDidCatch(error: Error, info: ErrorInfo) {\n const componentStack = boundComponentStack(info.componentStack);\n this.setState({ componentStack });\n this.props.onError({\n message: error.message,\n stack: error.stack,\n componentStack,\n });\n }\n\n hasError(): boolean {\n return this.state.error !== null;\n }\n\n retry(): boolean {\n if (!this.state.error) return false;\n this.setState((state) =>\n state.error\n ? { error: null, componentStack: undefined, resetKey: state.resetKey }\n : null,\n );\n return true;\n }\n\n render() {\n if (this.state.error) {\n return (\n <div\n data-render-error=\"true\"\n data-render-error-message={this.state.error.message}\n style={{ width: \"100%\", height: \"100%\" }}\n />\n );\n }\n return this.props.children;\n }\n}\n","import * as React from \"react\";\n\n/**\n * A bound on how much render work can happen in one uninterrupted burst.\n *\n * A user can write `const Loop = () => <Loop/>` — or split the same cycle\n * across two modules that import each other — into any storyboard file. React\n * then allocates fibers until the renderer dies at V8's 4 GB heap limit. No\n * timer, watchdog, or IPC message can intervene, because the render loop is\n * synchronous and never yields the thread: nothing else in the document runs\n * again, ever. The bound therefore has to be enforced from inside the render\n * itself.\n *\n * React transitions its hooks dispatcher on entry to and exit from every\n * function component (`renderWithHooks` / `finishRenderingHooks` both assign\n * `ReactSharedInternals.H`), so an accessor on that one property counts render\n * work across arbitrary user code with nothing injected into user modules.\n * Past the budget the accessor throws, which is an ordinary render-phase\n * throw: React unwinds to the nearest storyboard error boundary, every sibling\n * in the same pass still renders and commits, and an infinite recursion\n * becomes one storyboard showing a problem instead of a dead canvas.\n *\n * The counter re-arms on the first microtask after any step, which is what\n * makes the bound *per burst* rather than per render pass. A synchronous React\n * pass never reaches a microtask checkpoint, so a runaway drains one budget and\n * throws, while ordinary work is handed a full budget again the moment the\n * thread returns to the event loop. Bounding bursts rather than passes is what\n * catches the common case: a user edits an already-mounted storyboard into a\n * recursive one, and Fast Refresh re-renders that component's own fiber without\n * ever re-rendering the storyboard slot above it.\n */\n\n/**\n * Dispatcher transitions one burst may spend. React transitions twice per\n * function component, so this is roughly 50k component instantiations: orders\n * of magnitude above any real storyboard (a large one costs a few thousand)\n * and orders of magnitude below the fiber count that exhausts the heap.\n */\nexport const admissionRenderStepBudget = 100_000;\n\n/** Thrown from inside the render that exceeded {@link admissionRenderStepBudget}. */\nexport class AdmissionBudgetError extends Error {\n constructor() {\n super(\n \"This storyboard renders itself recursively: it kept creating \" +\n \"components without ever finishing a render. Check for a component \" +\n \"that returns itself, or two components that render each other.\",\n );\n this.name = \"AdmissionBudgetError\";\n }\n}\n\n/**\n * Where React keeps the current hooks dispatcher: `H` on React 19's client\n * internals, `ReactCurrentDispatcher.current` on React 18. Both are assigned\n * on every function component render, which is the only property of them this\n * module depends on.\n */\nfunction findDispatcherSlot(): {\n holder: Record<string, unknown>;\n key: string;\n} | null {\n const react = React as unknown as Record<string, Record<string, unknown>>;\n const modern =\n react.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;\n if (modern && \"H\" in modern) return { holder: modern, key: \"H\" };\n const legacy = react.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n ?.ReactCurrentDispatcher as Record<string, unknown> | undefined;\n if (legacy && \"current\" in legacy) return { holder: legacy, key: \"current\" };\n return null;\n}\n\nlet stepsRemaining = admissionRenderStepBudget;\nlet rearmScheduled = false;\nlet counterState: \"uninstalled\" | \"installed\" | \"unavailable\" = \"uninstalled\";\n\nfunction scheduleRearm(): void {\n if (rearmScheduled) return;\n rearmScheduled = true;\n queueMicrotask(() => {\n rearmScheduled = false;\n stepsRemaining = admissionRenderStepBudget;\n });\n}\n\nfunction installCounter(): boolean {\n if (counterState !== \"uninstalled\") return counterState === \"installed\";\n const slot = findDispatcherSlot();\n if (!slot) {\n // A React whose dispatcher lives somewhere else still renders storyboards\n // correctly; it just runs without this bound. Failing open is deliberate:\n // an internals rename must never stop storyboards from rendering, and the\n // projection stall watchdog remains the outcome-based net underneath.\n counterState = \"unavailable\";\n return false;\n }\n const { holder, key } = slot;\n let dispatcher = holder[key];\n Object.defineProperty(holder, key, {\n configurable: true,\n get: () => dispatcher,\n set: (value: unknown) => {\n dispatcher = value;\n scheduleRearm();\n stepsRemaining -= 1;\n if (stepsRemaining > 0) return;\n // Re-arming as it throws lets React's unwinding assignments through, and\n // hands React's one automatic retry of the failed root a fresh budget so\n // the retry trips the same way and the boundary finally sees the error.\n stepsRemaining = admissionRenderStepBudget;\n throw new AdmissionBudgetError();\n },\n });\n counterState = \"installed\";\n return true;\n}\n\n/**\n * Charges the storyboard about to render its own budget, so one pass covering\n * many storyboards cannot accumulate their work into a single overrun. Called\n * during render, immediately above the user tree.\n */\nexport function beginAdmissionWindow(): void {\n if (!installCounter()) return;\n stepsRemaining = admissionRenderStepBudget;\n}\n","import { useCallback, useEffect, useRef } from \"react\";\n\n/**\n * Self-contained recovery for storyboard render errors.\n *\n * A render error unmounts the throwing subtree, so React Fast Refresh alone\n * cannot repair it: refresh only re-renders mounted fibers, and the fixed\n * component has none. The design shell repairs this by advancing the render\n * revision (which resets the boundary), but a host page without the shell —\n * a direct `/tempo-host?canvasPath=...` document — has no revision driver at\n * all. Recovery must therefore be armed from inside the SDK:\n *\n * - a retry timer with exponential backoff, armed while a boundary is\n * errored — the universal mechanism, needing no signal from anyone; and\n * - an immediate retry on a Vite HMR beat, when one is observable — new\n * code just arrived, so waiting out the backoff would be pure latency.\n *\n * The beat is best-effort by design: this module usually reaches the browser\n * prebundled by the host app's Vite (optimizeDeps), where `import.meta.hot`\n * is undefined and no beat ever fires. Only source-served setups (a linked\n * SDK, `optimizeDeps.exclude`) get the fast path. That asymmetry is why the\n * backoff cap stays low: without a beat, the cap IS the worst-case\n * fix-to-recovery latency.\n */\n\n/** First retry after a fresh error; also the rung the ladder resets to. */\nexport const renderErrorRetryBaseDelayMs = 1_000;\n/**\n * Backoff cap. Doubling stops here (1s → 2s → 4s → 8s) so a persistently\n * broken storyboard costs at most one re-render per 8s — negligible even for\n * expensive trees — while a fix still becomes visible within 8s when no HMR\n * beat is observable.\n */\nexport const renderErrorRetryMaxDelayMs = 8_000;\n\ntype ViteHotLike = {\n on?: (event: string, callback: (payload?: unknown) => void) => void;\n};\n\nconst beatListeners = new Set<() => void>();\n\n/**\n * Announces \"new code may have arrived\" to every errored boundary. Exported\n * so tests can drive beats directly; production beats come only from the\n * `vite:afterUpdate` wiring below.\n */\nexport function emitRenderErrorRecoveryBeat(): void {\n for (const listener of [...beatListeners]) listener();\n}\n\n// `vite:*` events are client-wide: one listener hears every update batch in\n// the document regardless of which module changed. Registered at module\n// scope because the beat is a document-lifetime fact, not a per-storyboard\n// one; when this module re-evaluates under HMR, Vite recreates the hot\n// context for the path and drops the stale listener with it. Reading `.hot`\n// through a cast keeps the literal `import.meta.hot` in the built output,\n// which is what makes Vite inject a hot context when serving this file as\n// source. This observes updates only — cycle counting and reload decisions\n// stay in the devserver-generated recovery adapter.\nconst hot = (import.meta as { hot?: ViteHotLike }).hot;\nhot?.on?.(\"vite:afterUpdate\", emitRenderErrorRecoveryBeat);\n\n/**\n * Owns the retry schedule for one storyboard's error boundary. The caller\n * reports the boundary's state transitions (`noteRenderError` from every\n * catch, `noteRecovered` from every healthy commit) and supplies `retryNow`,\n * which resets the boundary and returns whether it was actually errored.\n *\n * The normal still-broken loop is: timer fires → retry → children throw →\n * catch calls `noteRenderError` → next rung is armed. A retry that sticks\n * leads to a commit, whose `noteRecovered` clears the pending state and\n * resets the ladder.\n */\nexport function useRenderErrorRecovery(retryNow: () => boolean): {\n noteRenderError(): void;\n noteRecovered(): void;\n} {\n const retryNowRef = useRef(retryNow);\n retryNowRef.current = retryNow;\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const nextDelayRef = useRef(renderErrorRetryBaseDelayMs);\n const erroredRef = useRef(false);\n\n const clearTimer = useCallback(() => {\n if (timerRef.current === null) return;\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }, []);\n\n const noteRenderError = useCallback(() => {\n erroredRef.current = true;\n // A pending timer already covers this error (e.g. a children-change\n // retry failed while the scheduled one was still counting down).\n if (timerRef.current !== null) return;\n const delay = nextDelayRef.current;\n nextDelayRef.current = Math.min(delay * 2, renderErrorRetryMaxDelayMs);\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n retryNowRef.current();\n }, delay);\n }, []);\n\n const noteRecovered = useCallback(() => {\n erroredRef.current = false;\n nextDelayRef.current = renderErrorRetryBaseDelayMs;\n clearTimer();\n }, [clearTimer]);\n\n useEffect(() => {\n const onBeat = () => {\n // Fresh code deserves a fresh ladder: whether the immediate retry\n // below succeeds or re-catches, the next scheduled attempt starts\n // from the base delay again.\n nextDelayRef.current = renderErrorRetryBaseDelayMs;\n if (!erroredRef.current) return;\n clearTimer();\n retryNowRef.current();\n };\n beatListeners.add(onBeat);\n return () => {\n beatListeners.delete(onBeat);\n clearTimer();\n };\n }, [clearTimer]);\n\n return { noteRenderError, noteRecovered };\n}\n"],"mappings":";;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACTA,SAAS,YAAY,OAA2B,OAAuB;AAC5E,QAAM,aAAa,OAAO,KAAK;AAC/B,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,MAAM,GAAG,KAAK,eAAe;AAAA,EACzC;AACA,SAAO;AACT;;;ADwFM;AA7EN,IAAM,wBAAwB,cAAqC,IAAI;AAEhE,SAAS,4BACd,YACA,cACQ;AACR,SAAO,UAAU;AAAA,IACf,YAAY,YAAY,aAAa;AAAA,EACvC,CAAC,eAAe;AAAA,IACd,YAAY,cAAc,eAAe;AAAA,EAC3C,CAAC;AACH;AAEO,SAAS,oBAA2C;AACzD,SAAO,WAAW,qBAAqB;AACzC;AAEO,SAAS,4BAA4B,cAA8B;AACxE,QAAM,SAAS,kBAAkB;AACjC,QAAM,eAAe,YAAY,cAAc,eAAe;AAC9D,SAAO,SACH,4BAA4B,OAAO,MAAM,YAAY,IACrD;AACN;AAEO,SAAS,OAAO;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAM6C;AAC3C,QAAM,kBAAkB,kBAAkB;AAC1C,QAAM,aAAa,YAAY,MAAM,aAAa;AAClD,QAAM,aACJ,SAAS,SACL,i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AA,EAC9B;AAAA,EAEA,QAAiB;AACf,QAAI,CAAC,KAAK,MAAM,MAAO,QAAO;AAC9B,SAAK;AAAA,MAAS,CAAC,UACb,MAAM,QACF,EAAE,OAAO,MAAM,gBAAgB,QAAW,UAAU,MAAM,SAAS,IACnE;AAAA,IACN;AACA,WAAO;AAAA,EACT;AAAA,EAEA,SAAS;AACP,QAAI,KAAK,MAAM,OAAO;AACpB,aACE,gBAAAF;AAAA,QAAC;AAAA;AAAA,UACC,qBAAkB;AAAA,UAClB,6BAA2B,KAAK,MAAM,MAAM;AAAA,UAC5C,OAAO,EAAE,OAAO,QAAQ,QAAQ,OAAO;AAAA;AAAA,MACzC;AAAA,IAEJ;AACA,WAAO,KAAK,MAAM;AAAA,EACpB;AACF;","names":["useEffect","useMemo","useCallback","useMemo","jsx","createContext","useContext","createContext","useContext","jsx","useMemo","useCallback","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","getObservedSourceFiles","sourceAnnotationSelector","useState","useRef","useCallback","useEffect","useLayoutEffect","currentRequest","message","useMemo","jsx","jsxs","useMemo","renderStatusById","useEffect","Children","Component","cloneElement","isValidElement","Suspense","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","useCallback","useEffect","useRef","jsx","jsxs","Component","useRef","useState","useCallback","useEffect","useMemo","isValidElement","cloneElement","Children","Suspense","useLayoutEffect"]}