tempo-sdk 0.0.81 → 0.0.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/astro.js +3 -3
- package/dist/canvas/astro.js +2 -2
- package/dist/canvas/index.js +3 -3
- package/dist/canvas/interact-projection.js +2 -2
- package/dist/canvas/svelte.js +2 -2
- package/dist/canvas/vue.js +2 -2
- package/dist/{chunk-4XKABOQR.js → chunk-2OFKPSKO.js} +4 -3
- package/dist/{chunk-4XKABOQR.js.map → chunk-2OFKPSKO.js.map} +1 -1
- package/dist/{chunk-XFPFWTWX.js → chunk-2ZQMVAFM.js} +4 -1
- package/dist/{chunk-XFPFWTWX.js.map → chunk-2ZQMVAFM.js.map} +1 -1
- package/dist/{chunk-UBTL6JUF.js → chunk-DMT5MRMS.js} +4 -1
- package/dist/chunk-DMT5MRMS.js.map +1 -0
- package/dist/{chunk-VUCDEJ4Q.js → chunk-DNERBE7A.js} +68 -23
- package/dist/chunk-DNERBE7A.js.map +1 -0
- package/dist/{chunk-D6LZ7Z3W.js → chunk-G3W3FVUJ.js} +2 -2
- package/dist/{chunk-D6LZ7Z3W.js.map → chunk-G3W3FVUJ.js.map} +1 -1
- package/dist/{chunk-WNQ7HYZN.js → chunk-KPWCY6PY.js} +93 -55
- package/dist/chunk-KPWCY6PY.js.map +1 -0
- package/dist/{chunk-AFA3RUX4.js → chunk-O74WU2S7.js} +2 -2
- package/dist/{chunk-AFA3RUX4.js.map → chunk-O74WU2S7.js.map} +1 -1
- package/dist/{chunk-6SCRM7WZ.js → chunk-PPIIUCX5.js} +2 -2
- package/dist/{chunk-PRVU3F6M.js → chunk-WP74QZYX.js} +2 -2
- package/dist/{chunk-PRVU3F6M.js.map → chunk-WP74QZYX.js.map} +1 -1
- package/dist/expo/plugin.cjs +3 -0
- package/dist/expo/plugin.cjs.map +1 -1
- package/dist/expo/plugin.js +1 -1
- package/dist/expo-babel-plugin.cjs +3 -0
- package/dist/expo-babel-plugin.cjs.map +1 -1
- package/dist/expo-babel-plugin.js +1 -1
- package/dist/index.js +3 -3
- package/dist/nextjs/plugin.cjs +1 -1
- package/dist/nextjs/plugin.cjs.map +1 -1
- package/dist/nextjs/plugin.js +1 -1
- package/dist/nextjs-loader.cjs +4 -1
- package/dist/nextjs-loader.cjs.map +1 -1
- package/dist/nextjs.cjs +1 -1
- package/dist/nextjs.cjs.map +1 -1
- package/dist/nextjs.js +1 -1
- package/dist/nuxt/runtime/identity.js +1 -1
- package/dist/nuxt.js +5 -1
- package/dist/nuxt.js.map +1 -1
- package/dist/svelte.js +1 -1
- package/dist/vue.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-UBTL6JUF.js.map +0 -1
- package/dist/chunk-VUCDEJ4Q.js.map +0 -1
- package/dist/chunk-WNQ7HYZN.js.map +0 -1
- /package/dist/{chunk-6SCRM7WZ.js.map → chunk-PPIIUCX5.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../local-prebuilt-aliases.ts","../canvas-dependency-scan.ts","../compile-error-stream.ts","../hot-update-net.ts","../missed-change-sweep.ts","../rapid-hot-update-replay.ts","../canvas-host-registration-barrier.ts","../canvas-host-registration-contract.ts","../canvas-host-registration-work.ts","../index.ts","../jsx-module-annotation.ts","../assets/controls-transform.ts","../canvas-component-reference.ts","../default-export-identity.ts","../pruned-module-deletion.ts","../flutter-proxy.ts","../hmr-generation-fence.ts","../react-refresh-boundary.ts","../vite-client-pending-updates.ts","../tailwind-scan-net.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\n/** A development client explicitly installs its prebuilt SDK into the host.\n * Monorepo canvases can otherwise alias these entries to a different checkout,\n * silently bypassing that installed build (and every SDK fix being tested).\n * Ordinary published clients keep the project's own resolution choices. */\nexport function localPrebuiltAliases(root: string | undefined) {\n if (process.env.TEMPO_MONOREPO_SDK_SOURCE !== \"local-prebuilt\") return [];\n const sdk = resolve(root ?? process.cwd(), \"node_modules/tempo-sdk\");\n if (!existsSync(join(sdk, \".tempo-prebuilt-source.json\"))) return [];\n return [\"canvas\", \"assets\"].flatMap((entry) => {\n const replacement = join(sdk, \"dist\", entry, \"index.js\");\n return existsSync(replacement)\n ? [{ find: new RegExp(`^tempo-sdk/${entry}$`), replacement }]\n : [];\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { join, relative, resolve } from \"node:path\";\nimport type { UserConfig } from \"vite\";\n\n/** The launcher supplies these only to the canvas server, never the user's\n * app server. Adapt legacy generated globs in memory without rewriting an\n * editable config or discarding custom optimizer entries/exclusions. */\nexport function applyManagedCanvasDependencyScan(\n config: UserConfig,\n env: NodeJS.ProcessEnv = process.env,\n): void {\n const host = env.TEMPO_CANVAS_HOST_ROOT;\n const canvases = env.TEMPO_CANVAS_SOURCE_ROOT;\n if (\n !host ||\n !canvases ||\n resolve(config.root ?? process.cwd()) !== resolve(host)\n )\n return;\n const legacyGlob = [\n relative(host, canvases).replace(/\\\\/g, \"/\"),\n \"**/index.canvas.tsx\",\n ]\n .filter(Boolean)\n .join(\"/\");\n const entries = config.optimizeDeps?.entries;\n const retained = (\n entries === undefined\n ? []\n : typeof entries === \"string\"\n ? [entries]\n : entries\n ).filter(\n (entry) => entry.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\") !== legacyGlob,\n );\n config.optimizeDeps ??= {};\n config.optimizeDeps.entries = [...new Set([\"index.html\", ...retained])];\n // The generated host and projection scripts are injected after the HTML\n // scan. Bundle their shared runtime with React before either is requested;\n // a late SDK optimization can otherwise load a second React chunk while\n // the first renderer is already mounted (especially with React 18).\n for (const client of [\n \"tempo-sdk/canvas\",\n \"tempo-sdk/canvas/interact-projection\",\n ]) {\n if (\n config.optimizeDeps.exclude?.some(\n (id) => client === id || client.startsWith(`${id}/`),\n )\n )\n continue;\n config.optimizeDeps.include = [\n ...new Set([...(config.optimizeDeps.include ?? []), client]),\n ];\n }\n}\n\n/** The canvas host's folder in a project, which Tempo always names `tempo/`. */\nconst TEMPO_HOST_DIR = \"tempo\";\n\n/**\n * Keep the app's own dependency scan out of Tempo's canvas host. With no\n * `optimizeDeps.entries` and no build input, Vite crawls every `**\\/*.html`\n * under the app root, and an app at the project root holds the host in\n * `tempo/`: its `tempo/index.html` imports the React canvas host and\n * `tempo-sdk/canvas`. A Vue or Svelte app then fails the scan on `react` (the\n * trial agent added `optimizeDeps.entries` by hand), and every app prebundles\n * the host's dependencies, or fails on them before `tempo/` is installed.\n *\n * The replacement is Vite's own default crawl (its `__tests__`/`coverage`\n * ignores become `!` patterns, because Vite drops them once entries are\n * explicit) minus the host. Entries or an input the app sets are its own and\n * stay untouched; so does an app whose root holds no Tempo host (the host\n * itself, or a subfolder app whose host sits above its root).\n */\nexport function excludeTempoHostFromAppDependencyScan(\n config: UserConfig,\n): void {\n if (config.optimizeDeps?.entries !== undefined) return;\n if (config.build?.rollupOptions?.input !== undefined) return;\n const root = resolve(config.root ?? process.cwd());\n const hostConfig = join(root, TEMPO_HOST_DIR, \"tempo.config.json\");\n if (!existsSync(hostConfig)) return;\n config.optimizeDeps ??= {};\n config.optimizeDeps.entries = [\n \"**/*.html\",\n \"!**/__tests__/**\",\n \"!**/coverage/**\",\n `!${TEMPO_HOST_DIR}/**`,\n ];\n}\n","// The compile-error stream of a Tempo host on a Vite dev server: Vite's\n// compile errors, kept per module, cleared by the HMR update that repairs the\n// module (or by a validated re-transform when no update can), and delivered\n// to the canvas host page, whose problem tracker turns them into board\n// problems (`canvas/runtime-problems.ts`). The page subscribes on Vite's own\n// HMR socket through the client module in vite-error-transport.ts; the\n// `/__tempo/errors` SSE route remains for pages without that client.\n//\n// `tempoVitePlugin()` drives the stream from its own HMR tap; a host without\n// that plugin (the Nuxt sidecar) installs `compileErrorStreamPlugin()`.\n\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { parseSync } from \"oxc-parser\";\nimport type { Plugin, ViteDevServer } from \"vite\";\n\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport type { CanvasHostWrapperTransformer } from \"./canvas-host-registration-barrier.ts\";\nimport {\n fsPathFromModuleId,\n HOT_UPDATE_NET_SWEEP_INTERVAL_MS,\n} from \"./hot-update-net.ts\";\nimport {\n VITE_ERROR_CLIENT_ID,\n VITE_ERROR_CLIENT_PATH,\n VITE_ERROR_CLIENT_SOURCE,\n VITE_ERROR_STATE_EVENT,\n VITE_ERROR_SUBSCRIBE_EVENT,\n} from \"./vite-error-transport.ts\";\n\ntype HmrSendTarget = {\n send: (...args: unknown[]) => unknown;\n};\n\n/** The poll's starting cadence: the missed-change sweep's, which drives it\n * on the Vite host. */\nconst MISSED_CHANGE_SWEEP_INTERVAL_MS = HOT_UPDATE_NET_SWEEP_INTERVAL_MS;\n\n/** Error payload captured from Vite's HMR error events or console interception. */\nexport type TempoViteError = {\n type: \"compile\" | \"evaluation\";\n message: string;\n stack?: string;\n file?: string;\n frame?: string;\n plugin?: string;\n loc?: { file?: string; line?: number; column?: number };\n};\n\n// ---------------------------------------------------------------------------\n// Error tracking server — tracks per-module errors and broadcasts the\n// highest-priority error (or null) to SSE clients.\n//\n// Vite's HMR operates per-module: a successful update for module A should not\n// clear an unrelated compile error in module B. We key errors by the file\n// that caused them so that clears are scoped to the module that was fixed.\n// ---------------------------------------------------------------------------\n\ntype SseClient = ServerResponse<IncomingMessage>;\n\nexport interface TempoErrorServer {\n /** The error currently broadcast to SSE clients (most recent across all modules). */\n readonly currentError: TempoViteError | null;\n /** Files with active compile errors. Failed transforms may not be present in\n * Vite's module graph, so recovery code must track them explicitly. */\n readonly errorFiles: readonly string[];\n clients: Set<SseClient>;\n setError(error: TempoViteError): void;\n /** Clear errors for exact module aliases present in the HMR update. Pathless\n * errors require `clearAll()` because no module update can prove recovery. */\n clearErrorForModules(updatedPaths: string[]): void;\n /** Clear all errors unconditionally (e.g. report-clear endpoint). */\n clearAll(): void;\n}\n\n/** Whether two errors describe the same failure of the same module: same kind,\n * same text, same position. */\nfunction isSameError(left: TempoViteError, right: TempoViteError): boolean {\n return (\n left.type === right.type &&\n left.message === right.message &&\n left.loc?.line === right.loc?.line &&\n left.loc?.column === right.loc?.column\n );\n}\n\nfunction createErrorServer(\n onErrorFile?: (file: string) => void,\n onState?: (error: TempoViteError | null) => void,\n): TempoErrorServer {\n // Per-module error map keyed by file path (or \"unknown\" for errors without a file)\n const errorsByFile = new Map<string, TempoViteError>();\n\n function getMostRecentError(): TempoViteError | null {\n if (errorsByFile.size === 0) return null;\n // Map iterates in insertion order; setError does delete+set to push to end,\n // so the last entry is the most recently set error\n let latest: TempoViteError | null = null;\n for (const err of errorsByFile.values()) latest = err;\n return latest;\n }\n\n function broadcastCurrentState(): void {\n onState?.(server.currentError);\n const data = JSON.stringify(server.currentError);\n for (const client of server.clients) {\n client.write(`data: ${data}\\n\\n`);\n }\n }\n\n const server: TempoErrorServer = {\n get currentError(): TempoViteError | null {\n return getMostRecentError();\n },\n get errorFiles(): readonly string[] {\n return [...errorsByFile.keys()].filter((file) => file !== \"unknown\");\n },\n clients: new Set(),\n\n setError(error: TempoViteError) {\n const key = error.file ?? error.loc?.file ?? \"unknown\";\n const recorded = errorsByFile.get(key);\n // Re-raising a module's unchanged error is not news. The recovery poll\n // re-runs the failing transform on a timer, and each failure travels\n // back through Vite's error pipeline; broadcasting those would make\n // every attempt look like a fresh error to the canvas host. A genuinely\n // different error for the same file still gets through.\n if (recorded && isSameError(recorded, error)) return;\n // Capture the revision that first made this module erroneous. Vite may\n // send the same error several times after the user has already repaired\n // the file; re-statting on those delayed duplicates would incorrectly\n // mark the repaired revision as covered by the failed transform.\n if (key !== \"unknown\" && !recorded) onErrorFile?.(key);\n // Delete + set to move to end of Map iteration order (most recent)\n errorsByFile.delete(key);\n errorsByFile.set(key, error);\n broadcastCurrentState();\n },\n\n clearErrorForModules(updatedPaths: string[]) {\n if (errorsByFile.size === 0) return;\n let changed = false;\n for (const errorKey of [...errorsByFile.keys()]) {\n // Each source origin supplies both its canonical-root-relative path and\n // absolute file alias. Unknown errors have no causal module identity and\n // therefore survive until the explicit report-clear signal.\n if (\n errorKey !== \"unknown\" &&\n updatedPaths.some((path) => moduleIdsMatch(errorKey, path))\n ) {\n errorsByFile.delete(errorKey);\n changed = true;\n }\n }\n if (changed) broadcastCurrentState();\n },\n\n clearAll() {\n // Broadcast null even if already empty — runtime evaluation errors\n // (caught by the frame preload's console.error interception) are\n // forwarded as diagnostics without going through the SSE pipeline.\n // Broadcasting null ensures the frame preload receives a clear signal.\n errorsByFile.clear();\n broadcastCurrentState();\n },\n };\n return server;\n}\n\nfunction moduleIdsMatch(left: string, right: string): boolean {\n const normalize = (value: string) =>\n cleanModuleId(value)\n .replace(/^file:\\/\\//, \"\")\n .replace(/^\\/@fs\\//, \"/\")\n .replace(/\\\\/g, \"/\")\n .replace(/^\\/+/, \"\");\n return normalize(left) === normalize(right);\n}\n\n/** Ceiling for a single file's compile-error recovery poll interval. The poll\n * starts at the sweep cadence and doubles on every failed validation, so a\n * file the user leaves broken settles at one transform attempt per ceiling\n * instead of one per sweep. */\nconst COMPILE_ERROR_POLL_MAX_INTERVAL_MS = 30_000;\n\n/** One host's compile errors and how they reach the page. */\nexport interface CompileErrorStream {\n /** Per-module error state (also the Vite plugin's `_tempoErrorServer`). */\n readonly errorServer: TempoErrorServer;\n /** Answers pages connected to `server`: a subscription on Vite's socket\n * gets the current state, and every later state goes out on it. */\n attach(server: ViteDevServer): void;\n /** Answers the stream's routes (the SSE fallback and the report\n * endpoints) and returns true; false for any other request. */\n handleRequest(req: IncomingMessage, res: ServerResponse): boolean;\n /** Records the `err` of an HMR `error` payload Vite is sending. */\n recordHmrError(err: Record<string, unknown> | undefined): void;\n hasActiveCompileError(file: string): boolean;\n /** Re-transforms a file with an active error; when it now compiles,\n * clears the error and reloads the page. */\n recover(server: ViteDevServer, file: string): Promise<boolean>;\n /** Retries recovery for every active error, backing off per file. */\n pollRecovery(server: ViteDevServer): Promise<void>;\n /** Drops the poll schedule (server teardown). */\n reset(): void;\n}\n\nexport function createCompileErrorStream(\n options: {\n /** Called once when a module first gets an error, with its file. */\n onErrorFile?: (file: string) => void;\n } = {},\n): CompileErrorStream {\n let attachedServer: ViteDevServer | undefined;\n const errorServer = createErrorServer(options.onErrorFile, (error) =>\n attachedServer?.ws.send(VITE_ERROR_STATE_EVENT, error),\n );\n const normalizedFileKey = (file: string): string => file.replace(/\\\\/g, \"/\");\n const hasActiveCompileError = (file: string): boolean =>\n errorServer.errorFiles.some((errorFile) => moduleIdsMatch(errorFile, file));\n /** Validate a file whose compile error is still active, and recover it only\n * if Vite can transform it again. A module whose evaluation never completed\n * registered no Fast Refresh boundaries, so in-place HMR cannot be assumed —\n * recovery is a full reload. */\n const recoverActiveCompileError = async (\n server: ViteDevServer,\n file: string,\n ): Promise<boolean> => {\n if (!hasActiveCompileError(file)) return false;\n const cleanFile = fsPathFromModuleId(file);\n const requestId = `/@fs/${cleanFile.replace(/^\\/+/, \"\")}`;\n const clientEnvironment = (\n server as ViteDevServer & {\n environments?: {\n client?: CanvasHostWrapperTransformer<unknown> & {\n hot: HmrSendTarget;\n };\n };\n }\n ).environments?.client;\n const transformer =\n clientEnvironment ??\n (server as unknown as CanvasHostWrapperTransformer<unknown>);\n try {\n // writeFile can expose its truncated revision before its final bytes.\n // A successful transform of that empty module is not a repaired canvas:\n // the browser would cache a namespace without its required default.\n const source = readFileSync(cleanFile, \"utf8\");\n const canvasModule = /\\.canvas\\.[cm]?[jt]sx?$/.test(cleanFile);\n const hasDefault = (code: string) => {\n const parsed = parseSync(cleanFile, code);\n return (\n !parsed.errors.length &&\n parsed.program.body.some(\n (node) =>\n node.type === \"ExportDefaultDeclaration\" ||\n (node.type === \"ExportNamedDeclaration\" &&\n node.exportKind !== \"type\" &&\n node.specifiers.some(\n (specifier) =>\n specifier.exportKind !== \"type\" &&\n (specifier.exported.type === \"Identifier\"\n ? specifier.exported.name\n : specifier.exported.value) === \"default\",\n )),\n )\n );\n };\n if (canvasModule && !hasDefault(source)) return false;\n // A failed transform can leave Vite's previous module result cached.\n // Validating that cache can falsely declare the repaired revision clean,\n // then reload the browser into a namespace that still lacks its exports.\n // Invalidate every node for this file so transformRequest is proof of the\n // current on-disk revision rather than proof that a stale result exists.\n let canonicalFile = cleanFile;\n try {\n canonicalFile = realpathSync(cleanFile);\n } catch {\n // Preserve Vite's original module id for virtual/test files and for a\n // file that disappears again while recovery is checking it.\n }\n const modules = new Set([\n ...(transformer.moduleGraph.getModulesByFile(canonicalFile) ?? []),\n ...(transformer.moduleGraph.getModulesByFile(cleanFile) ?? []),\n ]);\n for (const module of modules) {\n transformer.moduleGraph.invalidateModule(module);\n }\n const result = await transformer.transformRequest(requestId);\n if (!result) return false;\n if (readFileSync(cleanFile, \"utf8\") !== source) return false;\n if (\n canvasModule &&\n (typeof result !== \"object\" ||\n !(\"code\" in result) ||\n typeof result.code !== \"string\" ||\n !hasDefault(result.code))\n )\n return false;\n } catch {\n return false;\n }\n errorServer.clearErrorForModules([file, cleanFile, requestId]);\n server.config.logger.info(\n `[tempo] recovered compile-error module after validated transform: ${cleanFile}`,\n { timestamp: true },\n );\n (clientEnvironment?.hot ?? (server.ws as unknown as HmrSendTarget)).send({\n type: \"full-reload\",\n path: \"*\",\n });\n return true;\n };\n\n // Recovery normally rides the watcher \"change\" event for the repaired file.\n // This poll is the bounded fallback for a repair that produces no usable\n // signal at all: a module whose transform failed can be absent from Vite's\n // module graph, leaving both the watcher pipeline and the missed-change\n // sweep with nothing to observe. While a file's error is active it is\n // re-validated on the sweep's cadence, backing off per file so a file left\n // broken does not keep re-running a doomed transform.\n const compileErrorPollSchedule = new Map<\n string,\n { nextAttemptAtMs: number; intervalMs: number }\n >();\n const pollCompileErrorRecovery = async (\n server: ViteDevServer,\n ): Promise<void> => {\n const activeFiles = new Map(\n errorServer.errorFiles.map((file) => [\n normalizedFileKey(fsPathFromModuleId(file)),\n file,\n ]),\n );\n for (const key of [...compileErrorPollSchedule.keys()]) {\n if (!activeFiles.has(key)) compileErrorPollSchedule.delete(key);\n }\n const nowMs = Date.now();\n for (const [key, file] of activeFiles) {\n const schedule = compileErrorPollSchedule.get(key);\n if (schedule && nowMs < schedule.nextAttemptAtMs) continue;\n if (await recoverActiveCompileError(server, file)) {\n compileErrorPollSchedule.delete(key);\n continue;\n }\n const intervalMs =\n schedule?.intervalMs ?? MISSED_CHANGE_SWEEP_INTERVAL_MS;\n compileErrorPollSchedule.set(key, {\n nextAttemptAtMs: nowMs + intervalMs,\n intervalMs: Math.min(\n intervalMs * 2,\n COMPILE_ERROR_POLL_MAX_INTERVAL_MS,\n ),\n });\n }\n };\n\n return {\n errorServer,\n attach(server) {\n attachedServer = server;\n // Vite buffers a client's subscription until the socket connects. Reply\n // on that same ordered channel so startup errors and later updates have\n // no snapshot/broadcast gap. The SSE endpoint remains for older SDKs.\n server.ws.on?.(VITE_ERROR_SUBSCRIBE_EVENT, (_data, client) => {\n client.send(VITE_ERROR_STATE_EVENT, errorServer.currentError);\n });\n },\n handleRequest(req, res) {\n const url = req.url;\n if (url === \"/__tempo/report-error\" && req.method === \"POST\") {\n readBody(req).then((body) => {\n try {\n errorServer.setError(JSON.parse(body) as TempoViteError);\n } catch {\n // ignore malformed JSON\n }\n res.statusCode = 200;\n res.end(\"ok\");\n });\n return true;\n }\n\n if (url === \"/__tempo/report-clear\" && req.method === \"POST\") {\n errorServer.clearAll();\n res.statusCode = 200;\n res.end(\"ok\");\n return true;\n }\n\n // Allow CORS preflight for SSE endpoint (browser fetches from a different port)\n if (url === \"/__tempo/errors\" && req.method === \"OPTIONS\") {\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"*\",\n });\n res.end();\n return true;\n }\n\n if (url === \"/__tempo/errors\" && req.method === \"GET\") {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Access-Control-Allow-Origin\": \"*\",\n });\n\n // Send current state immediately\n res.write(`data: ${JSON.stringify(errorServer.currentError)}\\n\\n`);\n errorServer.clients.add(res);\n\n req.on(\"close\", () => {\n errorServer.clients.delete(res);\n });\n return true;\n }\n return false;\n },\n recordHmrError(err) {\n errorServer.setError({\n type: \"compile\",\n message: (err?.message as string) ?? \"Unknown error\",\n stack: err?.stack as string | undefined,\n file: (err?.id as string) ?? (err?.loc as { file?: string })?.file,\n frame: err?.frame as string | undefined,\n plugin: err?.plugin as string | undefined,\n loc: err?.loc as\n | { file?: string; line?: number; column?: number }\n | undefined,\n });\n },\n hasActiveCompileError,\n recover: recoverActiveCompileError,\n pollRecovery: pollCompileErrorRecovery,\n reset() {\n compileErrorPollSchedule.clear();\n },\n };\n}\n\n/**\n * The stream on a host with no other tap on Vite's HMR channel (the Nuxt\n * sidecar, R18): it serves the page client and the routes, records what\n * Vite sends (an `error` sets the module's error, an `update` clears the\n * errors of the modules it updates), recovers a repaired file on its watcher\n * update, and polls on the missed-change sweep's cadence for a repair that\n * produces no update at all (a file whose transform failed can be missing\n * from the module graph).\n */\nexport function compileErrorStreamPlugin(): Plugin {\n const stream = createCompileErrorStream();\n const observe = (payload: unknown): void => {\n if (typeof payload !== \"object\" || payload === null) return;\n const typed = payload as {\n type?: unknown;\n err?: Record<string, unknown>;\n updates?: Array<{ path?: unknown }>;\n };\n if (typed.type === \"error\") stream.recordHmrError(typed.err);\n if (typed.type === \"update\") {\n const paths = (typed.updates ?? [])\n .map((update) => update.path)\n .filter((path): path is string => typeof path === \"string\");\n stream.errorServer.clearErrorForModules(paths);\n }\n };\n const tap = (target: HmrSendTarget, tapped: WeakSet<object>): void => {\n if (tapped.has(target)) return;\n tapped.add(target);\n const send = target.send.bind(target);\n target.send = (...args: unknown[]) => {\n observe(args[0]);\n return send(...args);\n };\n };\n return {\n name: \"tempo-compile-error-stream\",\n apply: \"serve\",\n resolveId(id) {\n return id === VITE_ERROR_CLIENT_PATH ? VITE_ERROR_CLIENT_ID : null;\n },\n load(id) {\n return id === VITE_ERROR_CLIENT_ID ? VITE_ERROR_CLIENT_SOURCE : null;\n },\n configureServer(server) {\n stream.attach(server);\n server.middlewares.use((req, res, next) => {\n if (!stream.handleRequest(req, res)) next();\n });\n const tapped = new WeakSet<object>();\n tap(server.ws as unknown as HmrSendTarget, tapped);\n const poll = setInterval(() => {\n void stream.pollRecovery(server);\n }, MISSED_CHANGE_SWEEP_INTERVAL_MS);\n poll.unref?.();\n server.watcher.once(\"close\", () => {\n clearInterval(poll);\n stream.reset();\n });\n // Vite 7+ constructs environment transports after the immediate\n // configureServer hooks; its error middleware sends on the client\n // environment's channel.\n return () => {\n const clientHot = (\n server as ViteDevServer & {\n environments?: { client?: { hot?: HmrSendTarget } };\n }\n ).environments?.client?.hot;\n if (clientHot) tap(clientHot, tapped);\n };\n },\n hotUpdate: {\n order: \"post\",\n async handler(context) {\n if (this.environment.config.consumer !== \"client\") return;\n if (context.type !== \"update\") return;\n if (!stream.hasActiveCompileError(context.file)) return;\n // The full reload recovery sends replaces this update: the module\n // never finished evaluating, so it has no boundary to update.\n if (await stream.recover(context.server, context.file)) return [];\n },\n },\n };\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n","/**\n * The hot-update net a Tempo canvas host needs under a write burst: the\n * rapid same-file replay (`rapid-hot-update-replay.ts`), the missed-change\n * sweep (`missed-change-sweep.ts`) and the module-read gate between them,\n * wired once here. `tempoVitePlugin()` composes `createHotUpdateNet` into\n * its own hooks (adding the compile-error files to the sweep and the\n * compile-error recovery poll to its timer); the Nuxt module installs the\n * same net as the standalone `tempoHotUpdateNetPlugin()` (R13), because a\n * host without it loses watcher events in a burst (the sidecar logged two\n * HMR updates for the four writes of a write/undo/redo/undo round trip, and\n * the board waited on a receipt that never came).\n */\n\nimport { statSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport {\n createMissedChangeSweep,\n type SweepModuleView,\n} from \"./missed-change-sweep.ts\";\nimport { createRapidHotUpdateReplay } from \"./rapid-hot-update-replay.ts\";\n\nexport const HOT_UPDATE_NET_NAME = \"tempo-hot-update-net\";\nexport const HOT_UPDATE_NET_SWEEP_INTERVAL_MS = 3_000;\n\n/** A module id as a filesystem path: no query, no `/@fs/` prefix. */\nexport function fsPathFromModuleId(id: string): string {\n return cleanModuleId(id).replace(/^\\/@fs\\//, \"/\");\n}\n\n/** The single key every half of the net agrees on for a file: the watcher\n * event, the module read that must wait for it and the sweep's stat arrive\n * as differently-spelled ids for the same file. */\nfunction fileKey(file: string): string {\n return fsPathFromModuleId(file).replace(/\\\\/g, \"/\");\n}\n\nexport interface HotUpdateNet {\n /** Snapshot the delivered revision at watcher-event ingress, before\n * async update hooks can overlap a newer write. Coverage is watcher\n * delivery evidence, never browser acknowledgment. */\n recordCoverage(file: string): void;\n /** The fs mtime covered by the most recent watcher event for `file`. */\n lastHotUpdateMtimeMs(file: string): number | undefined;\n /** A hot update with modules: schedules one ordinary watcher replay after\n * a rapid same-file burst. */\n observeUpdate(server: ViteDevServer, file: string): void;\n /** The module-read gate: resolves once the file's burst, if any, settles. */\n settled(id: string): Promise<void>;\n /** Attach the coverage listeners ahead of every other watcher listener. */\n installCoverage(server: ViteDevServer): void;\n /** Start the periodic missed-change sweep over the files the server has\n * served. `listExtraFiles` adds files Vite has not served (a module whose\n * compile failed); `afterSweep` rides the same timer so the two periodic\n * passes never overlap. The interval ends when the HTTP server closes. */\n installSweep(\n server: ViteDevServer,\n options?: {\n sweepIntervalMs?: number;\n listExtraFiles?: () => readonly string[];\n afterSweep?: () => Promise<void>;\n },\n ): void;\n /** Teardown: cancel pending replays, release parked reads, drop coverage. */\n clear(): void;\n}\n\nexport function createHotUpdateNet(): HotUpdateNet {\n const replay = createRapidHotUpdateReplay();\n const covered = new Map<string, number>();\n const recordCoverage = (file: string): void => {\n const cleanFile = fsPathFromModuleId(file);\n const key = fileKey(file);\n try {\n covered.set(key, statSync(cleanFile).mtimeMs);\n } catch {\n covered.delete(key);\n }\n };\n return {\n recordCoverage,\n lastHotUpdateMtimeMs(file) {\n return covered.get(fileKey(file));\n },\n observeUpdate(server, file) {\n replay.observe(fileKey(file), () => {\n server.config.logger.info(\n `[tempo] replaying settled rapid watcher change: ${file}`,\n { timestamp: true },\n );\n server.watcher.emit(\"change\", file);\n });\n },\n settled(id) {\n return replay.settled(fileKey(id));\n },\n installCoverage(server) {\n for (const event of [\"change\", \"add\", \"unlink\"] as const)\n server.watcher?.prependListener?.(event, recordCoverage);\n },\n installSweep(server, options = {}) {\n const cacheDir = server.config.cacheDir\n ?.replace(/\\\\/g, \"/\")\n .replace(/\\/+$/, \"\");\n const sweep = createMissedChangeSweep({\n listServedFiles: () => {\n const files = new Map<string, Iterable<SweepModuleView>>(\n server.moduleGraph?.fileToModulesMap ??\n new Map<string, Set<SweepModuleView>>(),\n );\n for (const extra of options.listExtraFiles?.() ?? []) {\n const cleanFile = fsPathFromModuleId(extra);\n const file = isAbsolute(cleanFile)\n ? cleanFile\n : resolve(server.config.root, cleanFile);\n if (!files.has(file)) files.set(file, []);\n }\n // Optimized dependencies are generated and invalidated by Vite\n // itself, outside its source watcher. Replaying their rewrites as\n // source edits sends spurious React HMR/reloads while a new app is\n // optimizing imports.\n if (cacheDir) {\n for (const file of files.keys()) {\n if (file.replace(/\\\\/g, \"/\").startsWith(`${cacheDir}/`)) {\n files.delete(file);\n }\n }\n }\n dropUnwatched(server, files);\n return files.entries();\n },\n statMtimeMs: async (file) => {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return null;\n }\n },\n emitChange: (file) => {\n server.config?.logger?.info?.(\n `[tempo] re-emitting lost watcher change: ${file}`,\n { timestamp: true },\n );\n server.watcher?.emit?.(\"change\", file);\n },\n lastHotUpdateMtimeMs: (file) => covered.get(fileKey(file)),\n });\n let passRunning = false;\n const timer = setInterval(() => {\n if (passRunning) return;\n passRunning = true;\n void sweep\n .sweep()\n .then(() => options.afterSweep?.())\n .catch(() => {})\n .finally(() => {\n passRunning = false;\n });\n }, options.sweepIntervalMs ?? HOT_UPDATE_NET_SWEEP_INTERVAL_MS);\n timer.unref?.();\n server.httpServer?.once(\"close\", () => clearInterval(timer));\n },\n clear() {\n replay.clear();\n covered.clear();\n },\n };\n}\n\n/** Drop the served files this server's watcher leaves out: a file it does\n * not watch has no event to lose. The Nuxt sidecar serves the app's pages\n * through its route manifest while its watcher watches `app/pages` and\n * excludes the page files, so the sweep re-emitted every write to a page\n * (three times per revision) and the sidecar regenerated its routes for\n * nothing. Only positive evidence drops a file, its directory watched without\n * it; a directory the watcher spells differently (or a watcher without\n * chokidar's `getWatched`) keeps every file a candidate. */\nfunction dropUnwatched(\n server: ViteDevServer,\n files: Map<string, Iterable<SweepModuleView>>,\n): void {\n const watcher = server.watcher as\n | { getWatched?: () => Record<string, readonly string[]> }\n | undefined;\n const watched = watcher?.getWatched?.();\n if (!watched) return;\n for (const file of [...files.keys()]) {\n const entries = watched[dirname(file)];\n if (entries && !entries.includes(basename(file))) files.delete(file);\n }\n}\n\n/** The net as a plugin of its own, for a host whose Vite server Tempo does\n * not otherwise shape (the Nuxt sidecar and the app's own `nuxt dev`). */\nexport function tempoHotUpdateNetPlugin(\n options: { sweepIntervalMs?: number } = {},\n): Plugin {\n const net = createHotUpdateNet();\n return {\n name: HOT_UPDATE_NET_NAME,\n configureServer(server) {\n net.installCoverage(server);\n net.installSweep(server, { sweepIntervalMs: options.sweepIntervalMs });\n server.httpServer?.once(\"close\", () => net.clear());\n },\n // A module read during a burst waits for the terminal disk revision\n // (a transform hook would be too late: its bytes are already read).\n load: {\n async handler(id) {\n if (id.startsWith(\"\\0\")) return null;\n await net.settled(id);\n return null;\n },\n },\n hotUpdate: {\n order: \"post\",\n handler(context) {\n if (context.type === \"update\" && context.modules.length > 0)\n net.observeUpdate(context.server, context.file);\n },\n },\n // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.\n handleHotUpdate: {\n order: \"post\",\n handler(context) {\n if (context.modules.length > 0)\n net.observeUpdate(context.server, context.file);\n },\n },\n };\n}\n","/**\n * Missed file-change sweep — the dev server's self-healing net for LOST\n * watcher events.\n *\n * On loaded machines (CI runners under I/O pressure), chokidar can miss a\n * write entirely. Vite then serves the STALE cached transform of the file to\n * every request — including brand-new documents — forever: no error, no\n * retry, nothing observable client-side (CI-proven: three consecutive host\n * replacements all rendered a token 32s behind the file on disk).\n *\n * The filesystem's mtime is the ground truth the watcher merely relays, so\n * the sweep re-derives the event from it: every interval it stats the files\n * Vite has actually served (`moduleGraph.fileToModulesMap` — bounded by real\n * usage, no directory crawling) and re-emits the watcher \"change\" event\n * chokidar lost. Vite then runs its entire native pipeline (invalidate →\n * hot update → fetch) exactly as if the event had been delivered on time.\n *\n * Deciding a change was DELIVERED needs care under rapid same-file bursts\n * (TEM-1149: ~10 writes 40ms apart froze the canvas one revision behind):\n *\n * - Invalidation timestamps cannot vouch for a specific revision. The\n * guard \"some module's `lastInvalidationTimestamp >= mtime`\" is defeated\n * by a cross-revision interleave: write N's event is delivered at\n * `write(N) + watcher latency`, so whenever that latency exceeds the gap\n * to write N+1, the N invalidation lands at-or-after the N+1 mtime and\n * reads as \"N+1 delivered\" — while N+1's event was the one lost. Vite 7's\n * monotonic HMR clock (which deliberately runs ahead of wall time under\n * rapid calls) widens the window.\n * - The plugin therefore records the file mtime synchronously at watcher\n * event ingress (`lastHotUpdateMtimeMs`), before async update hooks can\n * overlap a newer write. A POST-hook stat could falsely certify that newer\n * revision while an older pending transform remains cacheable. The plugin\n * also schedules one ordinary trailing replay after a rapid same-file burst. Normal updates remain immediate;\n * the replay invalidates intermediate transforms after overlapping server\n * pipelines. A later write either gets its own event or advances past the\n * recorded revision and is recovered by this sweep.\n * The invalidation-timestamp guard remains only as a compatibility fallback\n * when no plugin coverage evidence is available.\n * - A re-emitted watcher event is retried until that server pipeline\n * acknowledges it, bounded per revision in case no listener can process\n * the event. This is intentionally NOT a browser/render acknowledgment:\n * React acceptance is registered synchronously by the separate refresh\n * boundary adapter; this sweep only repairs missing watcher events.\n *\n * Healthy edits never double-fire: the watcher update advances the coverage\n * record past the mtime, and the file is skipped. The\n * sweep never touches module contents, never reloads, and never walks\n * importers — it only restores a lost input signal.\n */\n\n/** What the sweep needs to read per served file. Mirrors the slice of\n * Vite's ModuleNode the decision depends on. */\nexport interface SweepModuleView {\n lastInvalidationTimestamp?: number;\n}\n\nexport interface MissedChangeSweepArgs {\n /** Absolute fs path → modules Vite associates with it. */\n listServedFiles(): Iterable<[string, Iterable<SweepModuleView>]>;\n /** fs mtime in ms, or null when the file is gone/unreadable (skipped —\n * deletions are prune territory, not this sweep's). */\n statMtimeMs(file: string): Promise<number | null>;\n /** Re-emit the lost watcher event. */\n emitChange(file: string): void;\n /** Watcher-pipeline evidence: the fs mtime covered by the most recent\n * hot update. `undefined` falls back to Vite's legacy\n * invalidation-timestamp guard. */\n lastHotUpdateMtimeMs?(file: string): number | undefined;\n /** Clock seam. */\n now?: () => number;\n /** How long a fresh write is given to arrive through the real watcher\n * before the sweep concludes it was lost. Well above chokidar's normal\n * delivery latency so healthy edits never double-fire. */\n watcherGraceMs?: number;\n /** How many times one revision may be re-emitted before going dormant\n * (until the file changes again). Bounds the blast radius when nothing\n * in the server's watcher pipeline can acknowledge the emit. */\n maxEmitsPerRevision?: number;\n}\n\nexport const MISSED_CHANGE_WATCHER_GRACE_MS = 1_000;\nexport const MISSED_CHANGE_MAX_EMITS_PER_REVISION = 3;\n\nexport interface MissedChangeSweep {\n /** Run one sweep pass. Returns the files re-emitted (diagnostics). */\n sweep(): Promise<string[]>;\n}\n\nexport function createMissedChangeSweep(\n args: MissedChangeSweepArgs,\n): MissedChangeSweep {\n const now = args.now ?? Date.now;\n const graceMs = args.watcherGraceMs ?? MISSED_CHANGE_WATCHER_GRACE_MS;\n const maxEmits =\n args.maxEmitsPerRevision ?? MISSED_CHANGE_MAX_EMITS_PER_REVISION;\n // Baseline per file: the mtime the previous pass observed. A file only\n // comes under watch once it ADVANCES past a recorded baseline — the first\n // observation of any file just records it, so a server that starts over\n // pre-existing files never mass-fires.\n const lastSeenMtimeMs = new Map<string, number>();\n // Files under convergence watch: an observed advance that has not yet\n // been proven delivered. Emits are counted per revision so an\n // unacknowledgeable watcher event goes dormant instead of looping.\n const pending = new Map<string, { mtimeMs: number; emits: number }>();\n\n return {\n async sweep() {\n const emitted: string[] = [];\n for (const [file, modules] of args.listServedFiles()) {\n const mtimeMs = await args.statMtimeMs(file);\n if (mtimeMs === null) {\n pending.delete(file);\n continue;\n }\n let previous = lastSeenMtimeMs.get(file);\n if (previous === undefined) {\n const coveredMtimeMs = args.lastHotUpdateMtimeMs?.(file);\n if (coveredMtimeMs === undefined || coveredMtimeMs >= mtimeMs) {\n lastSeenMtimeMs.set(file, mtimeMs);\n continue;\n }\n // The plugin has revision-specific evidence for this served file,\n // and disk is already newer on the sweep's first pass. This happens\n // when a module's initial transform failed and its repair lands\n // before the first interval: treating the repaired mtime as a fresh\n // baseline would permanently hide the lost watcher event. Seed the\n // baseline from the actually covered revision so the ordinary\n // grace/retry path below can recover the newer disk state.\n previous = coveredMtimeMs;\n lastSeenMtimeMs.set(file, coveredMtimeMs);\n }\n if (mtimeMs > previous) {\n // A write this fresh may still be in flight through the real\n // watcher; leave the baseline untouched so the next pass\n // re-judges it once the grace has passed.\n if (now() - mtimeMs < graceMs) continue;\n lastSeenMtimeMs.set(file, mtimeMs);\n } else if (mtimeMs < previous) {\n // mtime moved backwards (revert, mtime-preserving copy) — track\n // it so a future rewrite of the file registers as an advance.\n lastSeenMtimeMs.set(file, mtimeMs);\n }\n const entry = pending.get(file);\n if (mtimeMs <= previous && entry === undefined) continue;\n // Covered by the watcher pipeline? Prefer the revision-specific\n // plugin record; use Vite's timestamp only for legacy callers.\n const hotUpdateMtimeMs = args.lastHotUpdateMtimeMs?.(file);\n let delivered: boolean;\n if (hotUpdateMtimeMs !== undefined) {\n delivered = hotUpdateMtimeMs >= mtimeMs;\n } else {\n delivered = false;\n for (const module of modules) {\n if ((module.lastInvalidationTimestamp ?? 0) >= mtimeMs) {\n delivered = true;\n break;\n }\n }\n }\n if (delivered) {\n pending.delete(file);\n continue;\n }\n const revision =\n entry !== undefined && entry.mtimeMs === mtimeMs\n ? entry\n : { mtimeMs, emits: 0 };\n pending.set(file, revision);\n if (revision.emits >= maxEmits) continue;\n revision.emits += 1;\n args.emitChange(file);\n emitted.push(file);\n }\n return emitted;\n },\n };\n}\n","/**\n * Same-file HMR trailing replay.\n *\n * Vite's server starts overlapping hot-update pipelines during a rapid save\n * burst. Observing two or more same-file events schedules one ordinary watcher\n * replay after the burst, invalidating any intermediate cached transform. The\n * load gate also waits for the terminal disk revision before reading a file\n * whose burst is already in progress. A lone edit remains immediate.\n *\n * The replay itself arrives through the watcher. A one-event allowance keeps\n * it from manufacturing another burst when it overlaps one late real edit.\n * Further real edits still re-arm the mechanism.\n *\n * These are server-side guarantees. Vite's client processes update messages\n * serially, but React's asynchronous accept registration can still drop a\n * queued update's refresh callback; react-refresh-boundary.ts closes that\n * separate gap during module evaluation.\n */\n\nexport const RAPID_HOT_UPDATE_QUIET_MS = 100;\n\ntype Timer = ReturnType<typeof setTimeout>;\n\nexport interface RapidHotUpdateReplay {\n observe(file: string, replay: () => void): void;\n /**\n * Wait until a same-file burst settles before Vite reads module content.\n * Only a genuine burst (two or more events) engages the gate; a single edit\n * waits for nothing. Waiting in a transform hook would be too late because\n * its source bytes have already been read.\n */\n settled(file: string): Promise<void>;\n clear(): void;\n}\n\nexport function createRapidHotUpdateReplay(options?: {\n quietMs?: number;\n schedule?: (callback: () => void, ms: number) => Timer;\n cancel?: (timer: Timer) => void;\n}): RapidHotUpdateReplay {\n const quietMs = options?.quietMs ?? RAPID_HOT_UPDATE_QUIET_MS;\n const schedule = options?.schedule ?? setTimeout;\n const cancel = options?.cancel ?? clearTimeout;\n interface Burst {\n eventCount: number;\n timer?: Timer;\n replay: () => void;\n /** Resolved the moment this burst settles; absent until the burst is real\n * (2+ events), so a single edit allocates nothing and waits for nothing. */\n release?: () => void;\n gate?: Promise<void>;\n /** Fail-safe expiry. A parked module read is a stalled page, so a gate is\n * never allowed to outlive the burst that owns it — this only ever fires\n * if a release is somehow missed. Re-armed on every event so it tracks\n * the burst rather than cutting a long one short. */\n expiry?: Timer;\n }\n const bursts = new Map<string, Burst>();\n\n /** Open (or carry over) this burst's gate once the burst is real. Callers\n * awaiting `settled` block until the burst's quiet window elapses. */\n const armGate = (burst: Burst, previous: Burst | undefined): void => {\n if (burst.eventCount < 2) return;\n if (previous?.gate && previous.release) {\n // The same unsettled burst continuing — carry ONE gate across the whole\n // burst so a waiter armed on event 2 is not released by event 3.\n burst.gate = previous.gate;\n burst.release = previous.release;\n previous.release = undefined;\n if (previous.expiry) cancel(previous.expiry);\n } else {\n burst.gate = new Promise<void>((resolve) => {\n burst.release = resolve;\n });\n }\n burst.expiry = schedule(() => burst.release?.(), quietMs * 2);\n };\n\n return {\n observe(file, replay) {\n const previous = bursts.get(file);\n if (previous?.timer) cancel(previous.timer);\n const burst: Burst = {\n eventCount: (previous?.eventCount ?? 0) + 1,\n replay,\n };\n armGate(burst, previous);\n burst.timer = schedule(() => {\n if (bursts.get(file) !== burst) return;\n bursts.delete(file);\n // Release BEFORE replaying: the replay's own pipeline reads the file\n // through the same gate, so holding it here would deadlock the very\n // update that carries the terminal revision.\n if (burst.expiry) cancel(burst.expiry);\n burst.release?.();\n if (burst.eventCount < 2) return;\n\n // The replay re-enters this observer through Vite's watcher. Start\n // the next window at -1 so that synthetic event plus one late real\n // event still counts as a single real update, not a fresh burst.\n // Give the allowance its own expiry in case the watcher has no\n // listener; a later unrelated edit must not consume it forever.\n const replayAllowance: Burst = {\n eventCount: -1,\n replay: burst.replay,\n };\n replayAllowance.timer = schedule(() => {\n if (bursts.get(file) === replayAllowance) bursts.delete(file);\n }, quietMs);\n bursts.set(file, replayAllowance);\n burst.replay();\n }, quietMs);\n bursts.set(file, burst);\n },\n\n settled(file) {\n return bursts.get(file)?.gate ?? Promise.resolve();\n },\n\n clear() {\n for (const burst of bursts.values()) {\n if (burst.timer) cancel(burst.timer);\n if (burst.expiry) cancel(burst.expiry);\n // Never leave a module read parked on a gate that can no longer be\n // released — a torn-down server must not hang the next request.\n burst.release?.();\n }\n bursts.clear();\n },\n };\n}\n","// The server half of the canvas-host registration receipt: the\n// `/__tempo/canvas-host-registration` route that answers only once Vite\n// serves the generated host wrapper (and, for incremental hosts, the newly\n// registered canvas) from the bytes now on disk. The devserver rewrites\n// `.tempo/tempo-host.tsx` out of process and Vite keeps serving its cached\n// transform until its watcher reports the rename, so a host document loaded\n// in that window would never contain the new canvas.\n//\n// Every Tempo host that runs on a Vite dev server installs this one barrier:\n// `tempoVitePlugin()` from its middleware, and the Nuxt sidecar (whose Vite\n// runs inside Nuxt's dev server) through its own Vite plugin. The client half\n// lives in modules/component-render-pool/canvas-host-registration.ts.\n\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { relative, resolve } from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\n\nimport {\n CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER,\n CANVAS_HOST_REGISTRATION_ENDPOINT,\n normalizeCanvasRegistrationPath,\n} from \"./canvas-host-registration-contract.ts\";\nimport {\n createRegistrationTransforms,\n type RegistrationProgress,\n registrationReply,\n traceSlowRegistration,\n} from \"./canvas-host-registration-work.ts\";\nimport { fsPathFromModuleId } from \"./hot-update-net.ts\";\n\nconst CANVAS_HOST_WRAPPER_URL = \"/.tempo/tempo-host\";\n\nexport function readGeneratedCanvasPaths(source: string): string[] {\n const paths = new Set<string>();\n const canvasPathPattern = /\\bcanvasPath:\\s*(\"(?:\\\\.|[^\"\\\\])*\")/g;\n for (const match of source.matchAll(canvasPathPattern)) {\n try {\n const parsed = JSON.parse(match[1] ?? \"\") as unknown;\n if (typeof parsed !== \"string\") continue;\n const normalized = normalizeCanvasRegistrationPath(parsed);\n if (normalized) paths.add(normalized);\n } catch {\n // The generated wrapper always uses JSON string literals. A malformed\n // match is ignored so the requested path fails the explicit membership\n // check below instead of authorizing an unknown generation.\n }\n }\n return [...paths];\n}\n\nasync function synchronizeCanvasHostRegistrationTransform(\n server: ViteDevServer,\n canvasPath: string,\n): Promise<string | undefined> {\n const wrapperPath = resolve(server.config.root, \".tempo\", \"tempo-host.tsx\");\n let wrapperSource: string;\n try {\n wrapperSource = readFileSync(wrapperPath, \"utf8\");\n } catch (error) {\n throw new Error(\n `Canvas host wrapper is unavailable at ${wrapperPath}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n const registeredCanvasPaths = readGeneratedCanvasPaths(wrapperSource);\n if (!registeredCanvasPaths.includes(canvasPath)) {\n throw Object.assign(\n new Error(\n `Generated canvas host wrapper does not contain ${JSON.stringify(\n canvasPath,\n )}`,\n ),\n { statusCode: 409 },\n );\n }\n\n // Prefer the per-environment Vite 6+ module graph; the mixed server graph is\n // the same operations for the SDK's supported Vite 5 range.\n const canonicalWrapperPath = realpathSync(wrapperPath);\n // A registered path can be a reused preview slot. Its file was just\n // rewritten too, and the filesystem watcher may not have invalidated its\n // previous (often empty) transform yet. Warm that exact module before the\n // wrapper so a new document cannot import the slot's previous contents.\n const modulePattern =\n /\\bcanvasPath:\\s*(\"(?:\\\\.|[^\"\\\\])*\")\\s*,\\s*load:\\s*\\(\\)\\s*=>\\s*import\\(\\s*(\"(?:\\\\.|[^\"\\\\])*\")\\s*\\)/g;\n let moduleUrl: string | undefined;\n const transformer = server.environments?.client ?? server;\n for (const match of wrapperSource.matchAll(modulePattern)) {\n if (normalizeCanvasRegistrationPath(JSON.parse(match[1]!)) !== canvasPath)\n continue;\n const resolvedModule = await transformer.pluginContainer.resolveId(\n JSON.parse(match[2]!),\n wrapperPath,\n );\n if (!resolvedModule) throw new Error(`Cannot resolve canvas ${canvasPath}`);\n const modulePath = fsPathFromModuleId(resolvedModule.id);\n const fsUrl = `/@fs/${modulePath.replace(/^\\/+/, \"\")}`;\n // The URL the page imports, under Vite's public base (`/_nuxt/` in the\n // Nuxt sidecar); the transform request below speaks Vite's base-less\n // module URL.\n moduleUrl = `${viteBasePath(server)}${fsUrl.slice(1)}`;\n await retransformCanvasHostWrapper(\n server,\n transformer,\n realpathSync(modulePath),\n modulePath,\n fsUrl,\n );\n break;\n }\n await retransformCanvasHostWrapper(\n server,\n transformer,\n canonicalWrapperPath,\n wrapperPath,\n );\n return wrapperSource.includes(\"tempo-incremental-canvas-registration\")\n ? moduleUrl\n : undefined;\n}\n\n/** Vite's public base as a path ending in `/`. A dev server's base is a\n * path; one written as a full URL keeps only its path. */\nfunction viteBasePath(server: ViteDevServer): string {\n const base = server.config.base || \"/\";\n const path = base.startsWith(\"/\")\n ? base\n : new URL(base, \"http://tempo.invalid\").pathname;\n return path.endsWith(\"/\") ? path : `${path}/`;\n}\n\n/** The half of a Vite server this barrier drives, satisfied by both a Vite 6+\n * client environment and a Vite 5 dev server. */\nexport type CanvasHostWrapperTransformer<TModule> = {\n moduleGraph: {\n getModulesByFile(file: string): Set<TModule> | undefined;\n invalidateModule(module: TModule): void;\n };\n transformRequest(url: string): Promise<unknown>;\n};\n\nconst registrationTransforms = new WeakMap<\n object,\n ReturnType<typeof createRegistrationTransforms>\n>();\nconst registrationActivity = new WeakMap<ViteDevServer, number>();\n\nfunction registrationProgress(server: ViteDevServer): RegistrationProgress {\n // Vite 6+ exposes the optimizer on the client environment. Older versions\n // without these facts still report actual transform activity and retain the\n // client's bounded no-progress deadline.\n const optimizer = server.environments?.client?.depsOptimizer;\n const phase = optimizer?.scanProcessing\n ? \"scanning\"\n : Object.values(optimizer?.metadata.discovered ?? {}).some(\n (dep) => dep.processing,\n )\n ? \"bundling\"\n : \"transforming\";\n return {\n status: \"compiling\",\n phase,\n progress: registrationActivity.get(server) ?? 0,\n };\n}\n\n/**\n * Vite's official server contract stores transformed code in a module graph.\n * Reuse a receipt only while both disk bytes and graph transforms still match;\n * otherwise invalidate the file's nodes and await a fresh transform.\n */\nasync function retransformCanvasHostWrapper<TModule>(\n server: ViteDevServer,\n transformer: CanvasHostWrapperTransformer<TModule>,\n canonicalWrapperPath: string,\n wrapperPath: string,\n requestUrl = CANVAS_HOST_WRAPPER_URL,\n): Promise<void> {\n let confirm = registrationTransforms.get(transformer);\n if (!confirm) {\n confirm = createRegistrationTransforms();\n registrationTransforms.set(transformer, confirm);\n }\n await confirm(canonicalWrapperPath, () =>\n traceSlowRegistration(\n async () => {\n const modules = () =>\n transformer.moduleGraph.getModulesByFile(canonicalWrapperPath) ??\n transformer.moduleGraph.getModulesByFile(wrapperPath);\n for (const module of modules() ?? []) {\n transformer.moduleGraph.invalidateModule(module);\n }\n const result = await transformer.transformRequest(requestUrl);\n if (!result) {\n throw new Error(\n `Vite did not transform ${requestUrl} after registration`,\n );\n }\n // Retain the graph's actual transformed objects, not just a disk hash.\n // HMR, dependency re-optimization and explicit invalidation retire them.\n const transformed = [...(modules() ?? [])].map(\n (module) =>\n [\n module,\n (module as { transformResult?: unknown }).transformResult,\n ] as const,\n );\n return () =>\n transformed.length > 0 &&\n transformed.every(\n ([module, value]) =>\n value != null &&\n modules()?.has(module) &&\n (module as { transformResult?: unknown }).transformResult ===\n value,\n );\n },\n (status, elapsedMs) => {\n server.config.logger.info(\n `[tempo] canvas registration ${JSON.stringify({\n ...registrationProgress(server),\n status,\n module: relative(server.config.root, canonicalWrapperPath),\n elapsedMs,\n })}`,\n );\n },\n ),\n );\n}\n\nfunction writeCanvasRegistrationResponseHeaders(res: ServerResponse): void {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\n \"Access-Control-Expose-Headers\",\n CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER,\n );\n res.setHeader(CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER, \"1\");\n}\n\n/** Whether `file` is the generated wrapper at `wrapperPath`, generated for\n * incremental registration. A document admits each new canvas through the\n * module URL this barrier returns, so the wrapper's own rewrite is no update\n * for a loaded document: a Vite host returns no modules for it. */\nexport function isIncrementalWrapperFile(\n file: string,\n wrapperPath: string,\n): boolean {\n if (file.replace(/\\\\/g, \"/\") !== wrapperPath.replace(/\\\\/g, \"/\"))\n return false;\n try {\n return readFileSync(file, \"utf8\").includes(\n \"tempo-incremental-canvas-registration\",\n );\n } catch {\n return false;\n }\n}\n\n/**\n * The generated host already owns each lazy import. Refresh its loader when\n * a registered canvas changes, including self-accepted forwarded defaults:\n * the hot update gains the wrapper's modules, invalidated. Keep this in\n * Vite's graph: no evaluated-module registry or runtime HMR feed. Returns\n * nothing when `file` is no canvas the wrapper registers. `sourceRoot` is\n * what the wrapper's canvas paths are relative to.\n */\nexport function withRegisteredCanvasLoader<TModule>(\n file: string,\n paths: { wrapperPath: string; sourceRoot: string },\n graph: CanvasHostWrapperTransformer<TModule>[\"moduleGraph\"],\n modules: TModule[],\n): TModule[] | undefined {\n const canvasPath = relative(paths.sourceRoot, file).replace(/\\\\/g, \"/\");\n let source: string;\n try {\n source = readFileSync(paths.wrapperPath, \"utf8\");\n } catch {\n return;\n }\n if (!readGeneratedCanvasPaths(source).includes(canvasPath)) return;\n const wrappers = graph.getModulesByFile(paths.wrapperPath);\n if (!wrappers?.size) return;\n for (const wrapper of wrappers) graph.invalidateModule(wrapper);\n return [...new Set([...modules, ...wrappers])];\n}\n\n/** Forgets a previous server's receipts and progress. Call from\n * `configureServer`: Vite builds the replacement server on a restart before\n * closing the old one. */\nexport function resetCanvasHostRegistration(server: ViteDevServer): void {\n registrationActivity.set(server, 0);\n registrationTransforms.delete(server.environments?.client ?? server);\n}\n\n/** One transform's worth of progress for the 202 replies opted-in clients\n * poll: a responsive compiler must keep advancing this. Call from every\n * `transform` the host's Vite runs. */\nexport function noteCanvasHostRegistrationActivity(\n server: ViteDevServer,\n): void {\n registrationActivity.set(server, (registrationActivity.get(server) ?? 0) + 1);\n}\n\n/** Answers the registration route (its CORS preflight and the POST) and\n * returns true; returns false for any other request, which the caller passes\n * on. */\nexport function handleCanvasHostRegistrationRequest(\n viteServer: ViteDevServer,\n req: IncomingMessage,\n res: ServerResponse,\n): boolean {\n const url = req.url;\n if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === \"OPTIONS\") {\n writeCanvasRegistrationResponseHeaders(res);\n res.writeHead(204, {\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"content-type\",\n });\n res.end();\n return true;\n }\n\n if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === \"POST\") {\n writeCanvasRegistrationResponseHeaders(res);\n void readBody(req)\n .then(async (body) => {\n const parsed = JSON.parse(body) as {\n canvasPath?: unknown;\n poll?: unknown;\n };\n const canvasPath =\n typeof parsed.canvasPath === \"string\"\n ? normalizeCanvasRegistrationPath(parsed.canvasPath)\n : \"\";\n if (!canvasPath) {\n throw Object.assign(\n new Error(\"canvasPath must be a non-empty string\"),\n { statusCode: 400 },\n );\n }\n let moduleUrl: string | undefined;\n const progress = await registrationReply(\n synchronizeCanvasHostRegistrationTransform(\n viteServer,\n canvasPath,\n ).then((url) => {\n moduleUrl = url;\n }),\n () => registrationProgress(viteServer),\n parsed.poll === true,\n );\n res.statusCode = progress ? 202 : 200;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.end(\n JSON.stringify(\n progress ?? { canvasPath, ...(moduleUrl ? { moduleUrl } : {}) },\n ),\n );\n })\n .catch((error: unknown) => {\n res.statusCode =\n typeof error === \"object\" &&\n error !== null &&\n \"statusCode\" in error &&\n typeof error.statusCode === \"number\"\n ? error.statusCode\n : 500;\n res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n res.end(error instanceof Error ? error.message : String(error));\n });\n return true;\n }\n\n return false;\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n","// Wire vocabulary of the canvas-host registration receipt served by the Tempo\n// Vite plugin: the endpoint a client posts a canvas identity to, the response\n// header that proves this host implements the transform barrier at all, and\n// the identity normalization both sides must agree on.\n//\n// The client half lives in modules/component-render-pool/canvas-host-registration.ts.\n// tempo-sdk is published into user workspaces and cannot depend on a desktop-side\n// module, so that package mirrors these values and pins them against this file in\n// modules/component-render-pool/canvas-host-registration-contract.test.ts —\n// changing either copy alone fails that test.\n\nexport const CANVAS_HOST_REGISTRATION_ENDPOINT =\n \"/__tempo/canvas-host-registration\";\n\nexport const CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER =\n \"x-tempo-canvas-host-registration\";\n\n/**\n * Reduce a canvas identity to the workspace-relative, forward-slashed form the\n * generated host wrapper records, so a client's path and the runtime's\n * advertised paths compare as strings.\n */\nexport function normalizeCanvasRegistrationPath(canvasPath: string): string {\n return canvasPath\n .trim()\n .replace(/\\\\/g, \"/\")\n .replace(/^\\.\\/+/, \"\")\n .replace(/^\\/+/, \"\");\n}\n","import { readFileSync } from \"node:fs\";\n\n/** Fast/reused registrations stay silent. Slow work emits once while pending\n * and once when it settles, even if the client stopped polling meanwhile. */\nexport async function traceSlowRegistration<T>(\n work: () => Promise<T>,\n report: (status: \"pending\" | \"ready\" | \"error\", elapsedMs: number) => void,\n): Promise<T> {\n const startedAt = performance.now();\n let slow = false;\n const timer = setTimeout(() => {\n slow = true;\n report(\"pending\", Math.round(performance.now() - startedAt));\n }, 5_000);\n const settled = (status: \"ready\" | \"error\") => {\n const elapsedMs = Math.round(performance.now() - startedAt);\n // CPU-bound compilation can prevent the pending timer from firing before\n // its promise settles. Still record that expensive work.\n if (slow || elapsedMs >= 5_000) report(status, elapsedMs);\n };\n try {\n const result = await work();\n settled(\"ready\");\n return result;\n } catch (error) {\n settled(\"error\");\n throw error;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Receipts belong to one Vite environment. Disk bytes AND Vite's transform\n * identity must still match; a missed watcher or an invalidated graph cannot\n * turn a previous acknowledgement into permission to serve stale code. */\nexport function createRegistrationTransforms() {\n const receipts = new Map<\n string,\n {\n source: string;\n result: Promise<void>;\n pending: boolean;\n current: () => boolean;\n }\n >();\n return async function confirm(\n file: string,\n transform: () => Promise<() => boolean>,\n ): Promise<void> {\n const source = readFileSync(file, \"utf8\");\n const previous = receipts.get(file);\n if (\n previous?.source === source &&\n (previous.pending || previous.current())\n ) {\n return previous.result;\n }\n const receipt = {\n source,\n pending: true,\n current: () => false,\n result: Promise.resolve(),\n };\n // Publish before starting work so concurrent HTTP requests join it.\n receipts.set(file, receipt);\n receipt.result = Promise.resolve()\n .then(async () => {\n receipt.current = await transform();\n receipt.pending = false;\n })\n .catch((error) => {\n if (receipts.get(file) === receipt) receipts.delete(file);\n throw error;\n });\n return receipt.result;\n };\n}\n\nexport type RegistrationProgress = {\n status: \"compiling\";\n progress: number;\n phase: \"scanning\" | \"bundling\" | \"transforming\";\n};\n\n/** A quick acknowledgement is not a completed registration. Only opted-in\n * clients receive progress; released clients still await the final receipt. */\nexport async function registrationReply(\n work: Promise<void>,\n progress: () => RegistrationProgress,\n poll: boolean,\n intervalMs = 1_000,\n): Promise<RegistrationProgress | null> {\n if (!poll) {\n await work;\n return null;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work.then(() => null),\n new Promise<RegistrationProgress>((resolve) => {\n timer = setTimeout(() => resolve(progress()), intervalMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n","import { localPrebuiltAliases } from \"./local-prebuilt-aliases\";\nimport {\n applyManagedCanvasDependencyScan,\n excludeTempoHostFromAppDependencyScan,\n} from \"./canvas-dependency-scan\";\nimport {\n type CompileErrorStream,\n createCompileErrorStream,\n type TempoErrorServer,\n} from \"./compile-error-stream\";\nimport {\n type CanvasHostWrapperTransformer,\n handleCanvasHostRegistrationRequest,\n isIncrementalWrapperFile,\n noteCanvasHostRegistrationActivity,\n resetCanvasHostRegistration,\n withRegisteredCanvasLoader,\n} from \"./canvas-host-registration-barrier\";\nimport {\n existsSync,\n type FSWatcher as NodeFsWatcher,\n readFileSync,\n realpathSync,\n statSync,\n watch as watchFileSystem,\n} from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createFilter, type FilterPattern } from \"@rollup/pluginutils\";\nimport type { Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport type {\n ElementInfo,\n PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport { TEMPO_INTERACT_FRAME_NAME } from \"./canvas/interact-frame.ts\";\nimport { createJsxModuleAnnotation } from \"./jsx-module-annotation.ts\";\nimport { createPrunedModuleDeletionGuard } from \"./pruned-module-deletion.ts\";\nimport {\n createFlutterForwarding,\n FLUTTER_HOST_WATCH_IGNORE,\n readFlutterDevServerUrl,\n watchFlutterRelaunches,\n} from \"./flutter-proxy.ts\";\nimport { createHmrGenerationFence } from \"./hmr-generation-fence.ts\";\nimport {\n createTempoHostIdentity,\n TEMPO_HOST_IDENTITY_CAPABILITY_HEADER,\n TEMPO_HOST_IDENTITY_ENDPOINT,\n TEMPO_VUE_ANNOTATION_PLUGIN_NAME,\n TEMPO_WORKSPACE_NONCE_META_NAME,\n} from \"./host-identity.ts\";\nimport {\n createHotUpdateNet,\n fsPathFromModuleId,\n HOT_UPDATE_NET_SWEEP_INTERVAL_MS,\n} from \"./hot-update-net.ts\";\nimport { installSynchronousReactRefreshBoundary } from \"./react-refresh-boundary.ts\";\nimport { createSdkFileMatcher } from \"./sdk-package-files.ts\";\nimport { preservePendingViteModuleUpdates } from \"./vite-client-pending-updates.ts\";\nimport {\n createTailwindScanNet,\n type ScanNetCssEntry,\n} from \"./tailwind-scan-net.ts\";\nimport {\n VITE_ERROR_CLIENT_ID,\n VITE_ERROR_CLIENT_PATH,\n VITE_ERROR_CLIENT_SOURCE,\n} from \"./vite-error-transport.ts\";\n\nconst DEFAULT_INCLUDE: FilterPattern = [\"**/*.tsx\", \"**/*.jsx\"];\nconst DEFAULT_EXCLUDE: FilterPattern = [\"**/node_modules/**\"];\nconst ROOT_META_NAME = \"tempo-project-root\";\nconst SOURCE_IDENTITY_ROOT_META_NAME = \"tempo-source-identity-root\";\nconst INTERACT_PROJECTION_CLIENT_PATH = \"/@tempo/interact-projection\";\nconst INTERACT_PROJECTION_CLIENT_ID = \"\\0tempo:interact-projection\";\nconst INTERACT_PROJECTION_SDK_SPECIFIER =\n \"tempo-sdk/canvas/interact-projection\";\n\n/**\n * The interact-projection client module shipped INSIDE this plugin's own\n * package, located relative to this very file: `canvas/interact-projection.ts`\n * beside the source entry in a workspace checkout, `canvas/interact-projection.js`\n * beside `dist/index.js` in the published package.\n *\n * The virtual client module must never depend on the HOST APP's dependency\n * tree for this import: an app that doesn't declare tempo-sdk in its own\n * browser-resolvable node_modules (pnpm isolation, hoisted installs) — or\n * holds a version predating the `./canvas/interact-projection` export — would\n * otherwise break every route storyboard with\n * `Failed to resolve import \"tempo-sdk/canvas/interact-projection\"` (TEM-1224).\n */\nfunction resolveOwnInteractProjectionModule(): string | null {\n const selfDir = dirname(fileURLToPath(import.meta.url));\n for (const candidate of [\n join(selfDir, \"canvas\", \"interact-projection.ts\"),\n join(selfDir, \"canvas\", \"interact-projection.js\"),\n ]) {\n // Forward slashes: vite module ids are posix-style on every platform, and\n // importing `normalizePath` from \"vite\" would add a runtime vite import\n // the packed SDK cannot satisfy.\n if (existsSync(candidate)) return candidate.replace(/\\\\/g, \"/\");\n }\n return null;\n}\nconst INTERACT_PROJECTION_BOOTSTRAP = `\n(function() {\n if (window.parent === window || (window.name !== ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} && !window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) return;\n var roots = new Map();\n var existing = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;\n if (existing) {\n if (existing.__tempoPendingFiberRoots) return;\n existing.__tempoPendingFiberRoots = roots;\n var originalCommit = existing.onCommitFiberRoot && existing.onCommitFiberRoot.bind(existing);\n existing.onCommitFiberRoot = function(rendererId, root) {\n if (existing.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);\n if (originalCommit) originalCommit.apply(null, arguments);\n };\n return;\n }\n window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {\n supportsFiber: true,\n renderers: new Map(),\n __tempoPendingFiberRoots: roots,\n inject: function(renderer) {\n var id = this.renderers.size + 1;\n this.renderers.set(id, renderer);\n return id;\n },\n onCommitFiberRoot: function(rendererId, root) {\n if (this.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);\n },\n onCommitFiberUnmount: function() {},\n checkDCE: function() {},\n onScheduleFiberRoot: function() {}\n };\n})();`;\n\nfunction cleanModuleId(id: string): string {\n return id.replace(/[?#].*$/, \"\");\n}\n\n/** Strip Vite's module-id decorations (query/hash suffix, `/@fs/` prefix) down\n * to the filesystem path `statSync` and the watcher speak. */\n\nfunction isCanvasHostRequest(requestPath: string): boolean {\n const url = new URL(requestPath, \"http://tempo.local\");\n return url.pathname.replace(/\\/+$/, \"\") === \"/tempo-host\";\n}\n\nfunction isDeclarativeCanvasHostRequest(requestPath: string): boolean {\n if (!isCanvasHostRequest(requestPath)) return false;\n const params = new URL(requestPath, \"http://tempo.local\").searchParams;\n const canvasPath =\n params.get(\"canvasPath\")?.trim() ??\n params.get(\"pageFile\")?.trim() ??\n params.get(\"importPath\")?.trim();\n const storyboardId =\n params.get(\"storyboardId\")?.trim() ??\n params.get(\"exportName\")?.trim() ??\n params.get(\"importName\")?.trim();\n return !canvasPath || !storyboardId;\n}\n\ntype HmrSendTarget = {\n send: (...args: unknown[]) => unknown;\n};\n\ntype UnresolvedImport = {\n specifier: string;\n importer: string;\n packageName?: string;\n};\n\nconst MAX_UNRESOLVED_IMPORTS = 256;\n\n// Vite's default `resolve.extensions` order, used to prove an extensionless\n// relative import has become resolvable without asking Vite's resolver.\nconst RELATIVE_IMPORT_RESOLVE_EXTENSIONS = [\n \".mjs\",\n \".js\",\n \".mts\",\n \".ts\",\n \".jsx\",\n \".tsx\",\n \".json\",\n] as const;\nconst UNRESOLVED_IMPORT_WATCH_REARM_MS = 1_000;\n\nfunction isRelativeImportSpecifier(specifier: string): boolean {\n return specifier.startsWith(\"./\") || specifier.startsWith(\"../\");\n}\n\nfunction barePackageName(specifier: string): string | undefined {\n if (\n !specifier ||\n specifier.startsWith(\".\") ||\n specifier.startsWith(\"/\") ||\n specifier.startsWith(\"\\0\") ||\n specifier.startsWith(\"#\") ||\n specifier.includes(\":\")\n ) {\n return undefined;\n }\n\n const segments = specifier.split(\"/\");\n const packageName = specifier.startsWith(\"@\")\n ? segments.length >= 2 && segments[0] !== \"@\" && segments[1]\n ? `${segments[0]}/${segments[1]}`\n : undefined\n : segments[0];\n return packageName && /^@?[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(packageName)\n ? packageName\n : undefined;\n}\n\nfunction resolvedIdMatchesFile(id: string, file: string): boolean {\n const resolvedFile = fsPathFromModuleId(id);\n try {\n return realpathSync.native(resolvedFile) === realpathSync.native(file);\n } catch {\n return resolvedFile.replace(/\\\\/g, \"/\") === file.replace(/\\\\/g, \"/\");\n }\n}\n\nfunction resolveCanonicalRoot(root: string): string {\n try {\n return realpathSync.native(root);\n } catch {\n return root;\n }\n}\n\nfunction hasRootMetaTag(html: string): boolean {\n return /<meta[^>]+name=[\"']tempo-project-root[\"'][^>]*>/i.test(html);\n}\n\nfunction hasSourceIdentityRootMetaTag(html: string): boolean {\n return /<meta[^>]+name=[\"']tempo-source-identity-root[\"'][^>]*>/i.test(html);\n}\n\nfunction hasWorkspaceNonceMetaTag(html: string): boolean {\n return new RegExp(\n `<meta[^>]+name=[\"']${TEMPO_WORKSPACE_NONCE_META_NAME}[\"'][^>]*>`,\n \"i\",\n ).test(html);\n}\n\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface TempoAnnotateOptions {\n /** Annotation root when an app runs below the workspace root. */\n root?: string;\n /** Explicit integration-owned activation; otherwise TEMPO selects development instrumentation. */\n enabled?: boolean;\n computeAnnotatedProps?: ComputeAnnotatedProps;\n include?: FilterPattern;\n exclude?: FilterPattern;\n /** Root published for workspace-relative diagnostic source matching.\n * Defaults to Vite's resolved root. This does not change Vite URL paths,\n * JSX annotation paths, or `tempo-project-root`. */\n sourceIdentityRoot?: string;\n}\n\n/**\n * Whether this server runs `tempoVuePlugin()` enabled. It is a separate\n * plugin the app adds beside this one, so this plugin being active proves\n * nothing about `.vue` stamps; a Vue app's route verification needs both.\n */\nfunction runsVueSourceAnnotation(\n plugins: readonly { name?: string; api?: unknown }[] | undefined,\n): boolean {\n return (plugins ?? []).some(\n (plugin) =>\n plugin.name === TEMPO_VUE_ANNOTATION_PLUGIN_NAME &&\n (plugin.api as { enabled?: unknown } | undefined)?.enabled === true,\n );\n}\n\nfunction handleTempoMiddleware(\n compileErrors: CompileErrorStream,\n viteServer: ViteDevServer,\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) {\n const url = req.url;\n if (!url?.startsWith(\"/__tempo/\")) return next();\n\n if (url === TEMPO_HOST_IDENTITY_ENDPOINT && req.method === \"GET\") {\n const identity = createTempoHostIdentity(\"vite\", {\n root: viteServer.config?.root,\n pluginActive: true,\n ...(runsVueSourceAnnotation(viteServer.config?.plugins)\n ? { capabilities: { vueSourceAnnotation: 1 } }\n : {}),\n });\n res.statusCode = 200;\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.setHeader(TEMPO_HOST_IDENTITY_CAPABILITY_HEADER, \"1\");\n res.end(JSON.stringify(identity));\n return;\n }\n\n if (handleCanvasHostRegistrationRequest(viteServer, req, res)) return;\n if (compileErrors.handleRequest(req, res)) return;\n\n next();\n}\n\n/** How often the missed-change sweep re-derives lost watcher events from\n * fs mtimes (see missed-change-sweep.ts). Stat-only over the files Vite has\n * actually served, so each pass costs microseconds per file. */\nconst MISSED_CHANGE_SWEEP_INTERVAL_MS = HOT_UPDATE_NET_SWEEP_INTERVAL_MS;\n\n/** Install the Tailwind new-file rescan net (see tailwind-scan-net.ts): a\n * watcher event for a scannable source file that some Tailwind-scanning CSS\n * module does not yet track as a watch dep re-emits the watcher \"change\"\n * for that CSS file, forcing the Tailwind plugin to re-run its scanner and\n * register the file. Without this, classes written into a file created\n * after the scanner's last pass never compile (TEM-1242 — drawn frames\n * rendering 0×0 in canvases/components created mid-session). */\nfunction installTailwindScanNet(server: ViteDevServer): void {\n const net = createTailwindScanNet({\n listCssEntries: function* (): Iterable<ScanNetCssEntry> {\n const fileToModules =\n server.moduleGraph?.fileToModulesMap ??\n new Map<string, Set<TailwindScanModuleView>>();\n for (const [file, modules] of fileToModules) {\n if (!file.endsWith(\".css\")) continue;\n // The Tailwind plugin registers every scanned file (and its source\n // globs) via addWatchFile; Vite folds those into the CSS module's\n // importedModules — glob patterns appear as nodes whose file/url is\n // the pattern itself. One entry PER module node (query variants,\n // environments): each node has its own Tailwind scanner instance,\n // and unioning them would let a node that already tracks a file\n // mask a sibling whose scanner predates it.\n for (const module of modules as Iterable<TailwindScanModuleView>) {\n const deps: string[] = [];\n for (const imported of module.importedModules ?? []) {\n const dep = imported.file ?? imported.url ?? imported.id;\n if (dep) deps.push(dep);\n }\n yield { cssFile: file, deps };\n }\n }\n },\n emitChange: (cssFile) => {\n server.config?.logger?.info?.(\n `[tempo] new source file outside the Tailwind scan — re-emitting change: ${cssFile}`,\n { timestamp: true },\n );\n server.watcher?.emit?.(\"change\", cssFile);\n },\n });\n const onWatcherFile = (file: string) => {\n net.handleWatcherFile(file);\n };\n server.watcher?.on?.(\"add\", onWatcherFile);\n server.watcher?.on?.(\"change\", onWatcherFile);\n server.httpServer?.once(\"close\", () => {\n server.watcher?.off?.(\"add\", onWatcherFile);\n server.watcher?.off?.(\"change\", onWatcherFile);\n net.dispose();\n });\n}\n\n/** The slice of Vite's ModuleNode the Tailwind scan net reads: the imported\n * modules its transform registered (addWatchFile'd scan files and source\n * globs land there). */\ninterface TailwindScanModuleView {\n importedModules?: Iterable<{\n file?: string | null;\n url?: string;\n id?: string | null;\n }>;\n}\n\nexport function tempoVitePlugin(options: TempoAnnotateOptions = {}): Plugin {\n // The plugin is a complete no-op unless the TEMPO env var is set.\n // This lets users keep tempoVitePlugin() in their vite config permanently\n // while only paying for annotation when running via Tempo's start script\n // (which sets TEMPO=true).\n const enabled = options.enabled ?? !!process.env.TEMPO;\n // Tempo's canvas dev server sets this when the project declares a Flutter\n // app: the origin of its `flutter run -d web-server` (flutter-proxy.ts).\n const flutterTarget = enabled ? readFlutterDevServerUrl(process.env) : null;\n\n const include =\n options.include === undefined ? DEFAULT_INCLUDE : options.include;\n const exclude =\n options.exclude === undefined ? DEFAULT_EXCLUDE : options.exclude;\n // The SDK's own modules are never transformed, however the project\n // resolves them and whatever include/exclude it configures.\n const isSdkFile = createSdkFileMatcher();\n const userFilter = createFilter(include, exclude);\n const filter = (id: string) => userFilter(id) && !isSdkFile(id);\n const userControlsFilter = createFilter(\n [\"**/*.tsx\", \"**/*.jsx\", \"**/*.ts\", \"**/*.js\"],\n exclude,\n );\n const controlsFilter = (id: string) =>\n userControlsFilter(id) && !isSdkFile(id);\n // Astro component descriptors read controls metadata from files the host\n // never imports; a change to one of them invalidates the descriptor.\n const astroDescriptorDependencies = new Map<string, Set<string>>();\n const invalidateAstroDescriptors = <TModule>(\n file: string,\n graph: {\n getModuleById(id: string): TModule | undefined;\n invalidateModule(module: TModule): void;\n },\n modules: TModule[],\n ) => {\n const affected = new Set(modules);\n for (const [id, dependencies] of astroDescriptorDependencies)\n if (dependencies.has(file)) {\n const module = graph.getModuleById(id);\n if (module) {\n graph.invalidateModule(module);\n affected.add(module);\n }\n }\n return [...affected];\n };\n\n let canonicalRoot = process.cwd();\n // The per-module annotation, shared with the Nuxt sidecar (R12). It owns\n // the controls-declaring modules and the default-export identities served,\n // which the post-order hot-update hooks below compare.\n const jsxModuleAnnotation = createJsxModuleAnnotation({\n stampedFilepath: (cleanId) =>\n filter(cleanId) ? relative(canonicalRoot, cleanId) : null,\n transformsControls: controlsFilter,\n computeAnnotatedProps: options.computeAnnotatedProps,\n });\n let sourceIdentityRoot = canonicalRoot;\n let command: ResolvedConfig[\"command\"] = \"serve\";\n let hmrEnabled = true;\n const compileErrors = createCompileErrorStream({\n onErrorFile: (file) => pinErroneousRevisionCoverage(file),\n });\n const unresolvedImports = new Map<string, UnresolvedImport>();\n let devServer: ViteDevServer | undefined;\n const unresolvedImportWatchers = new Map<\n string,\n { watcher: NodeFsWatcher; recursive: boolean }\n >();\n let unresolvedImportResolutionScheduled = false;\n let unresolvedImportResolutionRunning = false;\n let rerunUnresolvedImportResolution = false;\n let unresolvedImportWatchRearmTimer: ReturnType<typeof setTimeout> | null =\n null;\n const processedUpdatePayloads = new WeakSet<object>();\n const prunedModuleDeletion = createPrunedModuleDeletionGuard();\n const hmrGenerationFence = createHmrGenerationFence();\n // Vite launches watcher-event pipelines concurrently. Preserve normal HMR\n // latency, but replay one terminal update after a rapid same-file burst so\n // an earlier pipeline can never remain applied last in the browser.\n // Revision-specific evidence consumed by the missed-change sweep lives in\n // the net too: watcher-event coverage, not a claim that a browser visibly\n // rendered the revision; rapid client application races are repaired by\n // the trailing replay. One home with the Nuxt module (hot-update-net.ts).\n const hotUpdateNet = createHotUpdateNet();\n const recordHotUpdateCoverage = hotUpdateNet.recordCoverage;\n /** Pin the revision that broke a module as watcher-covered. Coverage is what\n * separates a repair from the break itself: the broken revision counts as\n * covered so only a LATER revision on disk reads as a repair. The pin\n * happens once per error — Vite re-sends the same error after the user has\n * already fixed the file, and re-stamping on that duplicate would move\n * coverage onto the repaired revision and hide the repair for good. */\n const pinErroneousRevisionCoverage = (file: string): void => {\n recordHotUpdateCoverage(file);\n };\n // Silent stale-rename repair: rewriting a default export's identity\n // (rename, named → anonymous) keeps the module a valid Fast Refresh\n // boundary, so Vite self-accepts the update while react-refresh finds no\n // family continuation — the OLD component keeps rendering with no error\n // for any client-side recovery to latch on. Only a document reload heals\n // it, so when the identity Vite last served provably changed on disk,\n // send one public full-reload (same shape as the missing-import fallback\n // above). Exactly-once: the cache advances on every comparison, so a\n // given rewrite can fire only on the hot update that delivered it, and\n // the reload's re-transform retains that advanced identity.\n const repairDefaultExportIdentityRewrite = async (context: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean> => {\n if (!(await jsxModuleAnnotation.defaultExportIdentityRewritten(context)))\n return false;\n devServer?.ws.send({ type: \"full-reload\", path: \"*\" });\n return true;\n };\n\n // The incremental wrapper's HMR rules, shared with the Nuxt sidecar\n // (canvas-host-registration-barrier.ts).\n const wrapperPath = () => resolve(canonicalRoot, \".tempo\", \"tempo-host.tsx\");\n const isIncrementalRegistration = (file: string) =>\n isIncrementalWrapperFile(file, wrapperPath());\n const invalidateCanvasLoader = <TModule>(\n file: string,\n graph: CanvasHostWrapperTransformer<TModule>[\"moduleGraph\"],\n modules: TModule[],\n ): TModule[] | undefined =>\n withRegisteredCanvasLoader(\n file,\n { wrapperPath: wrapperPath(), sourceRoot: sourceIdentityRoot },\n graph,\n modules,\n );\n\n const rememberUnresolvedImport = (\n specifier: string,\n importer: string,\n packageName?: string,\n ): void => {\n const key = `${importer}\\0${specifier}`;\n unresolvedImports.delete(key);\n unresolvedImports.set(key, { specifier, importer, packageName });\n while (unresolvedImports.size > MAX_UNRESOLVED_IMPORTS) {\n const oldestKey = unresolvedImports.keys().next().value;\n if (oldestKey === undefined) break;\n unresolvedImports.delete(oldestKey);\n }\n syncUnresolvedImportWatcher();\n };\n\n const forgetUnresolvedImportsFrom = (file: string): void => {\n for (const [key, unresolved] of unresolvedImports) {\n if (resolvedIdMatchesFile(unresolved.importer, file)) {\n unresolvedImports.delete(key);\n }\n }\n syncUnresolvedImportWatcher();\n };\n\n const closeUnresolvedImportWatcher = (path: string): void => {\n unresolvedImportWatchers.get(path)?.watcher.close();\n unresolvedImportWatchers.delete(path);\n };\n\n const cancelUnresolvedImportWatchRearm = (): void => {\n if (unresolvedImportWatchRearmTimer === null) return;\n clearTimeout(unresolvedImportWatchRearmTimer);\n unresolvedImportWatchRearmTimer = null;\n };\n\n const scheduleUnresolvedImportWatchRearm = (): void => {\n if (\n unresolvedImportWatchRearmTimer !== null ||\n !devServer ||\n unresolvedImports.size === 0\n ) {\n return;\n }\n unresolvedImportWatchRearmTimer = setTimeout(() => {\n unresolvedImportWatchRearmTimer = null;\n if (devServer && unresolvedImports.size > 0) {\n syncUnresolvedImportWatcher();\n // The rearm tick is also a bounded fallback when the platform cannot\n // allocate another fs watcher (for example EMFILE under a busy dev\n // session). Resolver success still gates importer reprocessing.\n scheduleUnresolvedImportResolution();\n }\n }, UNRESOLVED_IMPORT_WATCH_REARM_MS);\n unresolvedImportWatchRearmTimer.unref?.();\n };\n\n const closeUnresolvedImportWatchers = (): void => {\n cancelUnresolvedImportWatchRearm();\n for (const path of [...unresolvedImportWatchers.keys()]) {\n closeUnresolvedImportWatcher(path);\n }\n };\n\n const hasUnresolvedBarePackages = (): boolean =>\n [...unresolvedImports.values()].some(\n (unresolved) => unresolved.packageName !== undefined,\n );\n\n const packageWatchTarget = (\n unresolved: UnresolvedImport & { packageName: string },\n ): string => {\n let candidate = dirname(cleanModuleId(unresolved.importer));\n let nearestPackageRoot: string | undefined;\n while (true) {\n try {\n if (statSync(join(candidate, \"node_modules\")).isDirectory()) {\n return join(candidate, \"node_modules\", unresolved.packageName);\n }\n } catch {\n // Keep walking through the same lookup ancestry Vite/Node uses.\n }\n if (nearestPackageRoot === undefined) {\n try {\n if (statSync(join(candidate, \"package.json\")).isFile()) {\n nearestPackageRoot = candidate;\n }\n } catch {\n // The importer may live above the nearest package boundary.\n }\n }\n const parent = dirname(candidate);\n if (parent === candidate) break;\n candidate = parent;\n }\n return join(\n nearestPackageRoot ?? canonicalRoot,\n \"node_modules\",\n unresolved.packageName,\n );\n };\n\n const unresolvedImportWatchTarget = (\n unresolved: UnresolvedImport,\n ): string => {\n return unresolved.packageName\n ? packageWatchTarget(\n unresolved as UnresolvedImport & { packageName: string },\n )\n : resolve(\n dirname(cleanModuleId(unresolved.importer)),\n cleanModuleId(unresolved.specifier),\n );\n };\n\n const nearestExistingDirectory = (target: string): string | undefined => {\n let candidate = target;\n while (true) {\n try {\n if (statSync(candidate).isDirectory()) return candidate;\n } catch {\n // Promote the one watcher as missing directories are created.\n }\n const parent = dirname(candidate);\n if (parent === candidate) return undefined;\n candidate = parent;\n }\n };\n\n function syncUnresolvedImportWatcher(): void {\n if (!devServer || unresolvedImports.size === 0) {\n closeUnresolvedImportWatchers();\n return;\n }\n\n const desired = new Map<string, { recursive: boolean }>();\n for (const unresolved of unresolvedImports.values()) {\n const target = unresolvedImportWatchTarget(unresolved);\n const watchPath = nearestExistingDirectory(target);\n if (!watchPath) continue;\n const previous = desired.get(watchPath);\n desired.set(watchPath, {\n recursive: previous?.recursive === true || watchPath === target,\n });\n }\n\n for (const [path, existing] of [...unresolvedImportWatchers]) {\n const next = desired.get(path);\n if (!next || next.recursive !== existing.recursive) {\n closeUnresolvedImportWatcher(path);\n }\n }\n for (const [path, options] of desired) {\n if (unresolvedImportWatchers.has(path)) continue;\n try {\n const watcher = watchFileSystem(\n path,\n { recursive: options.recursive },\n scheduleUnresolvedImportResolution,\n );\n unresolvedImportWatchers.set(path, {\n watcher,\n recursive: options.recursive,\n });\n watcher.on(\"error\", () => {\n closeUnresolvedImportWatcher(path);\n scheduleUnresolvedImportWatchRearm();\n });\n if (options.recursive) scheduleUnresolvedImportResolution();\n } catch {\n closeUnresolvedImportWatcher(path);\n scheduleUnresolvedImportWatchRearm();\n }\n }\n if (\n [...desired.keys()].every((path) => unresolvedImportWatchers.has(path))\n ) {\n cancelUnresolvedImportWatchRearm();\n }\n }\n\n function scheduleUnresolvedImportResolution(): void {\n if (\n unresolvedImportResolutionScheduled ||\n unresolvedImportResolutionRunning\n ) {\n rerunUnresolvedImportResolution = true;\n return;\n }\n unresolvedImportResolutionScheduled = true;\n queueMicrotask(() => {\n unresolvedImportResolutionScheduled = false;\n void runUnresolvedImportResolution();\n });\n }\n\n async function runUnresolvedImportResolution(): Promise<void> {\n const server = devServer;\n if (!server || unresolvedImportResolutionRunning) return;\n unresolvedImportResolutionRunning = true;\n try {\n do {\n rerunUnresolvedImportResolution = false;\n syncUnresolvedImportWatcher();\n let resolvedImportInPass = false;\n\n for (const [key, unresolved] of [...unresolvedImports]) {\n let file: string | undefined;\n if (isRelativeImportSpecifier(unresolved.specifier)) {\n const suffixIndex = unresolved.specifier.search(/[?#]/);\n const relativePath =\n suffixIndex < 0\n ? unresolved.specifier\n : unresolved.specifier.slice(0, suffixIndex);\n const candidate = resolve(\n dirname(cleanModuleId(unresolved.importer)),\n relativePath,\n );\n // Extensionless imports (`./LateDep`) are the common shape for\n // source files, so the exact path is probed alongside Vite's\n // default extension and directory-index resolutions.\n const probes = [\n candidate,\n ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map(\n (extension) => `${candidate}${extension}`,\n ),\n ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map((extension) =>\n join(candidate, `index${extension}`),\n ),\n ];\n for (const probe of probes) {\n try {\n if (statSync(probe).isFile()) {\n file = probe;\n break;\n }\n } catch {\n // The relative dependency is still missing at this probe.\n }\n }\n }\n if (!file && unresolved.packageName) {\n try {\n file = createRequire(cleanModuleId(unresolved.importer)).resolve(\n unresolved.specifier,\n );\n } catch {\n // The package or selected entry is still missing.\n }\n }\n if (!file) continue;\n // Transfer the resolver-proven file to Vite's watcher before the\n // temporary missing-import watcher closes. Outside-root query\n // modules otherwise recover once but silently miss their next edit.\n server.watcher.add(file);\n unresolvedImports.delete(key);\n compileErrors.errorServer.clearErrorForModules([unresolved.importer]);\n resolvedImportInPass = true;\n }\n if (resolvedImportInPass) {\n // The importer's failed transform is not cached, so a document reload\n // re-requests it through the normal pipeline. Importer re-execution\n // belongs to Vite; replaying module graphs couples this plugin to\n // private APIs.\n server.ws.send({ type: \"full-reload\", path: \"*\" });\n }\n syncUnresolvedImportWatcher();\n } while (rerunUnresolvedImportResolution);\n } finally {\n unresolvedImportResolutionRunning = false;\n }\n }\n\n return {\n name: \"tempo-annotate\",\n apply: \"serve\",\n enforce: \"pre\",\n config(config, environment) {\n if (!enabled || environment.command !== \"serve\") return;\n applyManagedCanvasDependencyScan(config);\n excludeTempoHostFromAppDependencyScan(config);\n // An app whose own entries reach the generated tempo/ host still scans\n // it, and the host can have a different React major installed. Keep\n // its imports on the app's runtime so Vite cannot prebundle React 18 DOM\n // with React 19 JSX. Vite merges this array with the app's dedupe.\n const dedupe = [\"react\", \"react-dom\"].filter(\n (name) => !config.resolve?.dedupe?.includes(name),\n );\n const localAliases = localPrebuiltAliases(config.root);\n // Preserve an explicit app choice. Dev maps identify participating\n // imported CSS originals; projection forwards compact identities only.\n return {\n resolve: {\n dedupe,\n ...(localAliases.length ? { alias: localAliases } : {}),\n },\n ...(config.css?.devSourcemap === undefined\n ? { css: { devSourcemap: true } }\n : {}),\n // Vite concatenates this with the app's own ignored list. An app\n // that turned watching off (watch: null) keeps it off.\n ...(flutterTarget && config.server?.watch !== null\n ? { server: { watch: { ignored: [FLUTTER_HOST_WATCH_IGNORE] } } }\n : {}),\n };\n },\n resolveId: {\n order: \"pre\",\n async handler(id, importer, resolveOptions) {\n if (id.endsWith(\".astro?tempo-component\")) {\n const resolved = await this.resolve(\n id.slice(0, -\"?tempo-component\".length),\n importer,\n { ...resolveOptions, skipSelf: true },\n );\n if (!resolved) return null;\n return `\\0tempo:astro-component:${encodeURIComponent(resolved.id)}.js`;\n }\n if (enabled && id === VITE_ERROR_CLIENT_PATH) {\n return VITE_ERROR_CLIENT_ID;\n }\n if (id === INTERACT_PROJECTION_CLIENT_PATH) {\n return INTERACT_PROJECTION_CLIENT_ID;\n }\n if (\n id === INTERACT_PROJECTION_SDK_SPECIFIER &&\n importer === INTERACT_PROJECTION_CLIENT_ID\n ) {\n // Prefer the app's own resolution (its tempo-sdk install, or a test\n // alias) so integrated apps behave exactly as before; fall back to\n // this plugin's own copy of the module when the app can't resolve it.\n const resolved = await this.resolve(id, importer, {\n ...resolveOptions,\n skipSelf: true,\n });\n if (resolved) return resolved;\n return resolveOwnInteractProjectionModule();\n }\n if (enabled && importer && !importer.startsWith(\"\\0\")) {\n const packageName = barePackageName(id);\n if (!isRelativeImportSpecifier(id) && !packageName) return null;\n // Delegate through Vite's complete resolver while this pre hook can\n // still observe thrown package-entry failures. A post hook is never\n // reached when vite:resolve throws, which previously left no target\n // for the event-driven unresolved-import watcher.\n try {\n const resolved = await this.resolve(id, importer, {\n ...resolveOptions,\n skipSelf: true,\n });\n if (!resolved) rememberUnresolvedImport(id, importer, packageName);\n return resolved;\n } catch (error) {\n rememberUnresolvedImport(id, importer, packageName);\n throw error;\n }\n }\n return null;\n },\n },\n\n // `order: \"pre\"` + a null return: this hook never loads anything of its\n // own for a project file, it only decides WHEN Vite core is allowed to\n // read it. Awaiting the burst gate here (rather than in `transform`) is\n // what makes the content terminal — by `transform` the bytes have already\n // been read, so delaying there would ship a stale revision late instead of\n // not shipping it at all.\n load: {\n order: \"pre\",\n async handler(id) {\n if (id.startsWith(\"\\0tempo:astro-component:\")) {\n // An Astro server module must never enter the React host's browser graph.\n const file = decodeURIComponent(\n id.slice(\"\\0tempo:astro-component:\".length, -3),\n );\n const { readAstroControlsMetadata } = await import(\n \"./astro/controls-reader\"\n );\n const controls = await readAstroControlsMetadata(\n file,\n async (specifier, importer) =>\n (await this.resolve(specifier, importer, { skipSelf: true }))\n ?.id ?? null,\n // These files are read as metadata, never executed in the host.\n // Vite turns load-hook addWatchFile entries into implicit imports,\n // including optional controls files that do not exist yet.\n (dependency) => devServer?.watcher.add(dependency),\n [\n resolve(sourceIdentityRoot, \"tempo/controls.ts\"),\n resolve(canonicalRoot, \"controls.ts\"),\n ],\n );\n astroDescriptorDependencies.set(id, new Set(controls.dependencies));\n return `export default {kind:\"astro-component\",module:${JSON.stringify(file.replaceAll(\"\\\\\", \"/\"))},__tempoAstroControls:${JSON.stringify(controls).replaceAll(\"<\", \"\\\\u003c\")}};`;\n }\n if (enabled && id === VITE_ERROR_CLIENT_ID) {\n return VITE_ERROR_CLIENT_SOURCE;\n }\n if (id === INTERACT_PROJECTION_CLIENT_ID) {\n return `import { installTempoInteractProjectionSource } from ${JSON.stringify(INTERACT_PROJECTION_SDK_SPECIFIER)};\nlet stop;\nconst releaseOwner = () => {\n if (window.__tempoInteractProjectionOwner === \"vite\") delete window.__tempoInteractProjectionOwner;\n};\nif (window.parent !== window && !window.__tempoInteractProjectionOwner && (window.name === ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} || window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) {\n window.__tempoInteractProjectionOwner = \"vite\";\n const stopSource = installTempoInteractProjectionSource();\n stop = () => {\n stopSource();\n releaseOwner();\n };\n}\nif (import.meta.hot) import.meta.hot.dispose(() => {\n stop?.();\n releaseOwner();\n});`;\n }\n if (!enabled || command === \"build\" || id.startsWith(\"\\0\")) return null;\n await hotUpdateNet.settled(id);\n return null;\n },\n },\n\n // Expose error server for testing\n _tempoErrorServer: compileErrors.errorServer,\n // Test seam pinning the exact evidence the missed-change sweep reads.\n _tempoHotUpdateState: {\n lastHotUpdateMtimeMs(file: string) {\n return hotUpdateNet.lastHotUpdateMtimeMs(file);\n },\n },\n _tempoUnresolvedImportState: {\n get size() {\n return unresolvedImports.size;\n },\n get barePackageCount() {\n return [...unresolvedImports.values()].filter(\n (unresolved) => unresolved.packageName !== undefined,\n ).length;\n },\n get hasBarePackageWatcher() {\n return unresolvedImportWatchers.size > 0 && hasUnresolvedBarePackages();\n },\n get barePackageWatchPath() {\n return hasUnresolvedBarePackages()\n ? unresolvedImportWatchers.keys().next().value\n : undefined;\n },\n get hasUnresolvedImportWatcher() {\n return unresolvedImportWatchers.size > 0;\n },\n get unresolvedImportWatchPath() {\n return unresolvedImportWatchers.keys().next().value;\n },\n get unresolvedImportWatchPaths() {\n return [...unresolvedImportWatchers.keys()];\n },\n get hasUnresolvedImportWatchRearm() {\n return unresolvedImportWatchRearmTimer !== null;\n },\n emitUnresolvedImportWatcherErrorForTesting() {\n for (const { watcher } of unresolvedImportWatchers.values()) {\n watcher.emit(\n \"error\",\n new Error(\"Simulated unresolved-import watcher failure\"),\n );\n }\n },\n },\n\n configResolved(resolvedConfig) {\n if (!enabled) return;\n\n command = resolvedConfig.command;\n hmrEnabled = resolvedConfig.server?.hmr !== false;\n if (command === \"serve\" && hmrEnabled) {\n installSynchronousReactRefreshBoundary(resolvedConfig.plugins ?? []);\n }\n canonicalRoot = resolveCanonicalRoot(options.root ?? resolvedConfig.root);\n sourceIdentityRoot = options.sourceIdentityRoot\n ? resolveCanonicalRoot(\n resolve(resolvedConfig.root, options.sourceIdentityRoot),\n )\n : canonicalRoot;\n },\n\n configureServer(server: ViteDevServer) {\n if (!enabled) return;\n resetCanvasHostRegistration(server);\n // Snapshot the delivered revision BEFORE Vite starts async watchChange /\n // hot-update hooks. A late POST hook may see a newer, lost write while a\n // transform of this event's older bytes is still pending and cacheable.\n // Coverage is watcher delivery evidence, never browser acknowledgment.\n hotUpdateNet.installCoverage(server);\n // Chokidar owns these listeners: its close() removes all listeners.\n // Do not retain a shared teardown callback here. Vite constructs the\n // replacement server before closing the old one during restart.\n // A managed sidecar's source identity root is commonly its parent repo,\n // outside Vite's host root. Custom/legacy vite configs may carry the\n // plugin's `sourceIdentityRoot` without the generated template's matching\n // `server.fs.allow`; Linux then resolves the canvas import correctly but\n // refuses to serve the resulting /@fs path. The interact-projection\n // fallback can likewise point inside this plugin's own package outside\n // the app root (hoisted or linked installs). Extend the resolved allow\n // list with both explicit roots so every path the enabled plugin owns can\n // actually be served. Behind the `enabled` gate: a disabled plugin stays\n // a no-op and never widens the app's file-serving surface.\n const ownInteractModule = resolveOwnInteractProjectionModule();\n // Optional chaining: unit tests drive this hook with partial server\n // mocks that carry no resolved `server.fs` config.\n const allow = server.config?.server?.fs?.allow;\n if (Array.isArray(allow)) {\n const requiredRoots = [\n sourceIdentityRoot,\n ...(ownInteractModule ? [dirname(ownInteractModule)] : []),\n ];\n for (const requiredRoot of requiredRoots) {\n if (!allow.includes(requiredRoot)) allow.push(requiredRoot);\n }\n }\n devServer = server;\n compileErrors.attach(server);\n syncUnresolvedImportWatcher();\n server.watcher?.once?.(\"close\", closeUnresolvedImportWatchers);\n server.httpServer?.once(\"close\", closeUnresolvedImportWatchers);\n server.middlewares.use((req, res, next) => {\n const graph = server.environments?.client?.moduleGraph;\n if (\n graph &&\n req.url &&\n (req.method === \"GET\" || req.method === \"HEAD\")\n ) {\n const observeResponse = prunedModuleDeletion.observeRequest(\n graph,\n req.url,\n server.config.base,\n req.headers[\"sec-fetch-dest\"],\n req.headers[\"if-none-match\"],\n );\n if (observeResponse)\n res.once(\"finish\", () => {\n void observeResponse(\n res.statusCode,\n res.getHeader(\"content-type\"),\n res.getHeader(\"etag\"),\n );\n });\n }\n const name = req.url?.match(\n /^\\/tempo-assets\\/([a-zA-Z0-9._-]+)(?:\\?.*)?$/,\n )?.[1];\n if (name) {\n const file = [\"public\", \"static\"]\n .map((directory) =>\n join(sourceIdentityRoot, directory, \"tempo-assets\", name),\n )\n .find((file) => existsSync(file));\n if (file) req.url = `/@fs/${file.replace(/\\\\/g, \"/\")}`;\n }\n handleTempoMiddleware(compileErrors, server, req, res, next);\n });\n\n const flutterForwarding = flutterTarget\n ? createFlutterForwarding({\n target: flutterTarget,\n config: server.config,\n })\n : null;\n if (flutterForwarding) {\n server.middlewares.use(flutterForwarding.prefix);\n // Flutter's debug client reconnects over a WebSocket at a root path.\n // Middleware mode has no http server of its own to listen on.\n server.httpServer?.on(\"upgrade\", flutterForwarding.upgrade);\n }\n if (flutterTarget) {\n // An engine is bound to the `flutter run` process it booted against;\n // after the dev server relaunches Flutter, only a fresh host page\n // gets hot reloads again.\n const stopRelaunchWatch = watchFlutterRelaunches({\n target: flutterTarget,\n onRelaunch() {\n server.config.logger.info(\n \"[tempo] Flutter dev server relaunched; reloading the canvas host page\",\n );\n server.ws.send({ type: \"full-reload\" });\n },\n });\n server.httpServer?.once(\"close\", stopRelaunchWatch);\n server.watcher?.once?.(\"close\", stopRelaunchWatch);\n }\n\n // The compile-error recovery poll rides the sweep's interval: both are\n // periodic recovery passes over the same cadence, and one timer keeps\n // them from overlapping each other.\n hotUpdateNet.installSweep(server, {\n sweepIntervalMs: MISSED_CHANGE_SWEEP_INTERVAL_MS,\n listExtraFiles: () => compileErrors.errorServer.errorFiles,\n afterSweep: () => compileErrors.pollRecovery(server),\n });\n\n installTailwindScanNet(server);\n\n // Intercept outgoing HMR messages to capture errors and clears\n // server-side, so we don't depend on client-side script execution\n // (which fails in contexts where import.meta.hot is unavailable,\n // e.g. Electron WebContentsViews).\n //\n // In Vite 7, error middleware calls environment.hot.send() which may\n // be a different wrapper than server.ws. Intercept both to ensure\n // errors are captured regardless of which path Vite uses. This is\n // Error observation never triggers recovery. The same transport tap\n // records exact client prune nodes for the scoped deletion guard below;\n // it does not traverse importers or send replacement updates.\n const interceptHmrSend = (target: HmrSendTarget) => {\n const orig = target.send.bind(target);\n target.send = ((...args: unknown[]) => {\n const payload = args[0];\n if (\n typeof payload === \"object\" &&\n payload !== null &&\n \"type\" in payload\n ) {\n const typed = payload as {\n type: string;\n err?: Record<string, unknown>;\n };\n if (typed.type === \"prune\") {\n const graph = server.environments?.client?.moduleGraph;\n if (graph)\n prunedModuleDeletion.observePrune(\n graph,\n (typed as { paths?: string[] }).paths ?? [],\n );\n }\n if (typed.type === \"error\") {\n compileErrors.recordHmrError(typed.err);\n } else if (\n typed.type === \"update\" &&\n !processedUpdatePayloads.has(payload)\n ) {\n processedUpdatePayloads.add(payload);\n const updatePayload = typed as {\n updates?: Array<{\n type?: string;\n path?: string;\n acceptedPath?: string;\n timestamp?: number;\n }>;\n };\n const updates = updatePayload.updates;\n const acceptedUpdates = updates\n ? hmrGenerationFence.filter(updates)\n : undefined;\n if (\n updates &&\n acceptedUpdates &&\n acceptedUpdates.length !== updates.length\n ) {\n updatePayload.updates = acceptedUpdates;\n }\n const paths =\n acceptedUpdates\n ?.map((u) => u.path)\n .filter((p): p is string => typeof p === \"string\") ?? [];\n compileErrors.errorServer.clearErrorForModules(paths);\n // An entirely stale payload has no work left for the browser.\n // Suppress it here so a delayed server pipeline cannot arrive\n // after the terminal replay and put the penultimate revision\n // back on screen.\n if (\n updates &&\n updates.length > 0 &&\n acceptedUpdates?.length === 0\n ) {\n return;\n }\n }\n }\n return orig(...args);\n }) as typeof orig;\n };\n\n interceptHmrSend(server.ws as unknown as HmrSendTarget);\n // Vite 7 constructs environment transports after the immediate\n // configureServer hooks. Install that interception from the documented\n // post hook, before the server begins accepting requests.\n return () => {\n const clientHot = (\n server as ViteDevServer & {\n environments?: { client?: { hot?: HmrSendTarget } };\n }\n ).environments?.client?.hot;\n if (clientHot && clientHot !== server.ws) {\n interceptHmrSend(clientHot);\n }\n // After Vite's own middlewares: Flutter gets only what Vite could not\n // serve (Flutter's root-relative hot-reload and module requests).\n if (flutterForwarding) {\n server.middlewares.use(flutterForwarding.fallthrough);\n }\n };\n },\n\n closeBundle() {\n astroDescriptorDependencies.clear();\n devServer = undefined;\n hotUpdateNet.clear();\n hmrGenerationFence.clear();\n prunedModuleDeletion.clear();\n compileErrors.reset();\n closeUnresolvedImportWatchers();\n },\n\n hotUpdate: {\n order: \"post\",\n async handler(context) {\n const affected = invalidateAstroDescriptors(\n context.file,\n this.environment.moduleGraph,\n context.modules,\n );\n if (!enabled || this.environment.config.consumer !== \"client\")\n return affected;\n context.modules.splice(0, context.modules.length, ...affected);\n if (isIncrementalRegistration(context.file)) return [];\n // These private modules are written before their host registration and\n // first import. A delayed watcher \"add\" can arrive while Vite has made\n // their module node but has not analyzed its Fast Refresh boundary yet;\n // Vite then treats it as a dead end and reloads every open preview. There\n // is no previous version to update on creation. Host registration loads\n // the new module; subsequent writes still use the normal HMR pipeline.\n if (\n context.type === \"create\" &&\n /\\/\\.tempo\\/asset-edit-previews\\/\\d+\\/index\\.canvas\\.tsx$/.test(\n context.file.replace(/\\\\/g, \"/\"),\n )\n ) {\n return [];\n }\n if (context.type === \"update\" && context.modules.length > 0)\n hotUpdateNet.observeUpdate(context.server, context.file);\n if (context.type !== \"create\") {\n forgetUnresolvedImportsFrom(context.file);\n }\n // The `await` reorders everything below it against the watcher\n // pipelines Vite runs concurrently, so only a file that actually has\n // an active error may pay for it.\n if (\n context.type === \"update\" &&\n compileErrors.hasActiveCompileError(context.file) &&\n (await compileErrors.recover(context.server, context.file))\n ) {\n // The full reload just sent replaces this update: the module never\n // finished evaluating, so it has no Fast Refresh boundary to apply\n // an in-place update to.\n return [];\n }\n if (context.type === \"delete\") {\n jsxModuleAnnotation.forgetDefaultExportIdentity(context.file);\n // A React self-accept boundary survives prune. Importing its deleted\n // file would poison this document's module map even after Undo.\n // Invalidate server bytes but leave the already-applied parent update\n // and all live/entry deletions on Vite's normal delivery path.\n if (\n prunedModuleDeletion.suppressDeletion(\n this.environment.moduleGraph,\n context.modules,\n )\n )\n return [];\n return;\n }\n if (\n context.type === \"update\" &&\n (await repairDefaultExportIdentityRewrite(context))\n ) {\n // The stale boundary cannot apply this update; the full reload\n // just sent re-fetches everything through the normal pipeline.\n return [];\n }\n if (context.type === \"update\") {\n return invalidateCanvasLoader(\n context.file,\n this.environment.moduleGraph,\n context.modules,\n );\n }\n },\n },\n\n // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.\n handleHotUpdate: {\n order: \"post\",\n async handler(context) {\n const affected = invalidateAstroDescriptors(\n context.file,\n context.server.moduleGraph,\n context.modules,\n );\n context.modules.splice(0, context.modules.length, ...affected);\n if (!enabled) return;\n if (isIncrementalRegistration(context.file)) return [];\n if (context.modules.length > 0)\n hotUpdateNet.observeUpdate(context.server, context.file);\n forgetUnresolvedImportsFrom(context.file);\n if (\n compileErrors.hasActiveCompileError(context.file) &&\n (await compileErrors.recover(context.server, context.file))\n ) {\n return [];\n }\n if (await repairDefaultExportIdentityRewrite(context)) {\n return [];\n }\n return invalidateCanvasLoader(\n context.file,\n context.server.moduleGraph,\n context.modules,\n );\n },\n },\n\n transformIndexHtml(html, context) {\n if (!enabled || command !== \"serve\") {\n return;\n }\n\n const tags: Array<{\n tag: string;\n attrs?: Record<string, string>;\n children?: string;\n injectTo: \"head\" | \"head-prepend\";\n }> = [];\n if (hmrEnabled) {\n tags.push({\n tag: \"script\",\n attrs: { type: \"module\", src: VITE_ERROR_CLIENT_PATH },\n injectTo: \"head-prepend\",\n });\n }\n if (!hasRootMetaTag(html)) {\n tags.push({\n tag: \"meta\",\n attrs: {\n name: ROOT_META_NAME,\n content: canonicalRoot,\n },\n injectTo: \"head\" as const,\n });\n }\n if (!hasSourceIdentityRootMetaTag(html)) {\n tags.push({\n tag: \"meta\",\n attrs: {\n name: SOURCE_IDENTITY_ROOT_META_NAME,\n content: sourceIdentityRoot,\n },\n injectTo: \"head\" as const,\n });\n }\n const workspaceNonce = createTempoHostIdentity(\"vite\", {\n root: canonicalRoot,\n pluginActive: true,\n }).workspaceNonce;\n if (workspaceNonce && !hasWorkspaceNonceMetaTag(html)) {\n tags.push({\n tag: \"meta\",\n attrs: {\n name: TEMPO_WORKSPACE_NONCE_META_NAME,\n content: workspaceNonce,\n },\n injectTo: \"head\" as const,\n });\n }\n const requestPath = context?.originalUrl ?? context?.path;\n const isDeclarativeCanvasHost = requestPath\n ? isDeclarativeCanvasHostRequest(requestPath)\n : false;\n if (requestPath && !isDeclarativeCanvasHost) {\n tags.push({\n tag: \"script\",\n children: INTERACT_PROJECTION_BOOTSTRAP,\n injectTo: \"head-prepend\" as const,\n });\n tags.push({\n tag: \"script\",\n attrs: { type: \"module\", src: INTERACT_PROJECTION_CLIENT_PATH },\n injectTo: \"head-prepend\" as const,\n });\n }\n return tags.length > 0 ? tags : undefined;\n },\n\n async transform(source, id) {\n if (!enabled || command === \"build\") {\n return null;\n }\n\n if (devServer) noteCanvasHostRegistrationActivity(devServer);\n\n if (id.startsWith(\"\\0\")) {\n return null;\n }\n\n const cleanId = cleanModuleId(id);\n if (\n cleanId.replace(/\\\\/g, \"/\").endsWith(\"/vite/dist/client/client.mjs\")\n ) {\n const code = preservePendingViteModuleUpdates(source);\n return code === source ? null : { code, map: null };\n }\n return jsxModuleAnnotation.annotateJsxModule(this, source, cleanId);\n },\n } as Plugin & {\n _tempoErrorServer: TempoErrorServer;\n _tempoHotUpdateState: {\n lastHotUpdateMtimeMs(file: string): number | undefined;\n };\n _tempoUnresolvedImportState: {\n readonly size: number;\n readonly barePackageCount: number;\n readonly hasBarePackageWatcher: boolean;\n readonly barePackageWatchPath: string | undefined;\n readonly hasUnresolvedImportWatcher: boolean;\n readonly unresolvedImportWatchPath: string | undefined;\n readonly unresolvedImportWatchPaths: readonly string[];\n };\n };\n}\n\n/** @deprecated Use `tempoVitePlugin` instead. */\nexport const tempoAnnotate = tempoVitePlugin;\n\nexport type { ElementInfo, PropValue };\nexport type { TempoErrorServer, TempoViteError } from \"./compile-error-stream\";\n\nexport type {\n StoryboardLayout,\n TempoCanvasConfig,\n TempoHtmlStoryboard,\n TempoPage,\n TempoRouteStoryboard,\n TempoStoryboard,\n} from \"./page.ts\";\n","/**\n * The per-module JSX annotation a Tempo canvas host applies in its Vite\n * transform: Tempo's JSX stamps, the storyboard component references, the\n * canvas controls HMR transform and the module version record a write's\n * receipt is matched against, all certified against the raw bytes this\n * transform chain loaded (\"Vite source freshness\" in CLAUDE.md).\n *\n * One home for every Vite canvas host. `tempoVitePlugin()` calls it from its\n * transform with the project's include/exclude filter; the Nuxt sidecar's R12\n * plugin (`nuxt.ts`) calls it with the canvas-file filter. A second, thinner\n * copy in the sidecar had no freshness witness (a write racing a transform\n * could stamp stale offsets), no controls transform (canvas controls did not\n * work) and no default-export identity (renames never reloaded).\n *\n * The instance owns the state the transform keeps between calls: which\n * modules have declared controls, and the default-export identity each file\n * was served with, which the host's post-order hot-update hook compares\n * through `defaultExportIdentityRewritten`.\n */\n\nimport {\n closeSync,\n fstatSync,\n openSync,\n readFileSync,\n realpathSync,\n type Stats,\n} from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { annotateFile } from \"../../modules/annotation/annotate-file.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport {\n appendModuleVersionRecord,\n cleanModuleId,\n type ComputeAnnotatedProps,\n computeTempoAnnotatedProps,\n} from \"./annotation-strategy.ts\";\nimport { transformControlsForHmr } from \"./assets/controls-transform.ts\";\nimport { canvasComponentAnnotations } from \"./canvas-component-reference.ts\";\nimport { parseCanvasFile } from \"./canvas/parser.ts\";\nimport {\n type DefaultExportIdentity,\n isDefaultExportIdentityRewrite,\n readDefaultExportIdentity,\n} from \"./default-export-identity.ts\";\nimport { fsPathFromModuleId } from \"./hot-update-net.ts\";\n\n/** The parts of Vite's transform context the annotation reads. Both are\n * optional because a plain test context, or a transform run outside Vite,\n * has neither; without a source map the chain simply cannot certify a\n * rewritten source. */\nexport interface JsxModuleTransformContext {\n getCombinedSourcemap?: () => {\n sources: readonly string[];\n sourcesContent?: readonly (string | null | undefined)[] | null;\n };\n resolve?(\n specifier: string,\n importer: string,\n options: { skipSelf: boolean },\n ): Promise<{ id: string } | null>;\n}\n\nexport interface JsxModuleAnnotationOptions {\n /** The `data-tempo-filepath` a module's stamps carry (relative to the host\n * root the page's `tempo-project-root` meta names), or null when the module\n * is not the host's to annotate. Read on every transform, so a host whose\n * root resolves late (Vite's `configResolved`) sees the resolved one. */\n stampedFilepath(cleanId: string): string | null;\n /** Whether a module's `defineControls` calls get the HMR disposal wrapper.\n * Wider than annotation: shared and component-file controls live in plain\n * `.ts`/`.js` modules too. */\n transformsControls(cleanId: string): boolean;\n /** Replaces the default stamps (`tempoVitePlugin({ computeAnnotatedProps })`). */\n computeAnnotatedProps?: ComputeAnnotatedProps;\n}\n\nexport interface JsxModuleAnnotation {\n /** The transformed module, or null to leave it untouched (not the host's,\n * unparsable, or nothing to change). `cleanId` is the module id without\n * its query or hash. */\n annotateJsxModule(\n context: JsxModuleTransformContext,\n source: string,\n cleanId: string,\n ): Promise<{ code: string; map: null } | null>;\n /** Compare the default-export identity a served file had with the one now\n * on disk, advancing the record. True means the identity provably changed\n * (rename, named to anonymous), which only a document reload heals. Run it\n * from a post-order hot-update hook; `read` is Vite's settled read. */\n defaultExportIdentityRewritten(change: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean>;\n /** Drop a deleted file's identity record. */\n forgetDefaultExportIdentity(file: string): void;\n}\n\nexport function createJsxModuleAnnotation(\n options: JsxModuleAnnotationOptions,\n): JsxModuleAnnotation {\n // Keep cleanup when the last declaration is removed during this server\n // session. This is module-side-effect ownership, not a rendering protocol.\n const controlsModules = new Set<string>();\n function transformControls(source: string, id: string) {\n const code = transformControlsForHmr(source, id, controlsModules.has(id));\n if (code !== source) controlsModules.add(id);\n return code;\n }\n\n // Default-export identity before the latest hot update, keyed by canonical\n // fs path (module ids and watcher paths disagree on /@fs/ and symlinks).\n // Seeded by the first transform, advanced only by hot-update comparisons.\n const defaultExportIdentityByFile = new Map<\n string,\n DefaultExportIdentity | null\n >();\n\n const canonicalIdentityKey = (idOrFile: string): string => {\n const file = fsPathFromModuleId(idOrFile);\n try {\n return realpathSync.native(file);\n } catch {\n return file.replace(/\\\\/g, \"/\");\n }\n };\n\n async function annotateJsxModule(\n context: JsxModuleTransformContext,\n source: string,\n cleanId: string,\n ): Promise<{ code: string; map: null } | null> {\n const controlsSource = options.transformsControls(cleanId)\n ? transformControls(source, cleanId)\n : source;\n const filepath = options.stampedFilepath(cleanId);\n if (filepath === null) {\n if (controlsSource !== source) return { code: controlsSource, map: null };\n return null;\n }\n\n try {\n // A transform can be delayed behind another plugin while disk advances.\n // Only the raw bytes carried by this transform chain can acknowledge a\n // write. A fresh stat/hash attached to older code would release previews\n // under a host that never rendered the acknowledged revision.\n const descriptor = openSync(cleanId, \"r\");\n let snapshot: {\n before: Stats;\n after: Stats;\n rawSource: string;\n };\n try {\n const before = fstatSync(descriptor);\n const rawSource = readFileSync(descriptor, \"utf8\");\n snapshot = { before, rawSource, after: fstatSync(descriptor) };\n } finally {\n closeSync(descriptor);\n }\n const { before, after, rawSource } = snapshot;\n const stable = [\"mtimeMs\", \"ctimeMs\", \"size\", \"ino\", \"dev\"] as const;\n let loadedSource: string | undefined =\n source === rawSource ? source : undefined;\n if (\n loadedSource === undefined &&\n typeof context.getCombinedSourcemap === \"function\"\n ) {\n try {\n const map = context.getCombinedSourcemap();\n const sourceRoot = (map as { sourceRoot?: unknown }).sourceRoot;\n const matches = map.sources.flatMap((path, index) => {\n const sourcePath = path.startsWith(\"file:\")\n ? fileURLToPath(path)\n : path;\n const file = isAbsolute(sourcePath)\n ? sourcePath\n : resolve(\n dirname(cleanId),\n typeof sourceRoot === \"string\" ? sourceRoot : \"\",\n sourcePath,\n );\n let sameFile =\n cleanModuleId(file).replace(/\\\\/g, \"/\") ===\n cleanId.replace(/\\\\/g, \"/\");\n if (!sameFile) {\n try {\n // Vite may preserve a symlink while an upstream source map\n // names its real path. Compare physical source ownership,\n // without sharing provenance between transform chains.\n sameFile =\n realpathSync.native(file) === realpathSync.native(cleanId);\n } catch {\n // An unresolved map source is not an ownership witness.\n }\n }\n return sameFile && typeof map.sourcesContent?.[index] === \"string\"\n ? [map.sourcesContent[index]!]\n : [];\n });\n if (matches.length === 1) loadedSource = matches[0];\n } catch {\n // A custom transform without usable raw provenance cannot certify\n // freshness. Rendering and runtime capabilities remain useful.\n }\n }\n const witnessed =\n loadedSource === rawSource &&\n stable.every((key) => before[key] === after[key]);\n const modifiedtsMs = witnessed ? Math.trunc(before.mtimeMs) : 0;\n const sourceVersion = witnessed ? sourceVersionHash(rawSource) : \"\";\n const identityKey = canonicalIdentityKey(cleanId);\n // A concurrent host request can transform the new revision before\n // the watcher's post-order hook compares it. Keep the old identity\n // until that comparison so a rename cannot silently consume its own\n // required reload.\n if (!defaultExportIdentityByFile.has(identityKey)) {\n defaultExportIdentityByFile.set(\n identityKey,\n readDefaultExportIdentity(rawSource),\n );\n }\n\n const resolvedComponents = new Map<string, string>();\n if (\n source.includes(\"tempo-sdk/canvas\") &&\n typeof context.resolve === \"function\"\n ) {\n const imports = parseCanvasFile(cleanId, source).storyboards.flatMap(\n (board) => board.component?.import?.source ?? [],\n );\n await Promise.all(\n [...new Set(imports)].map(async (specifier) => {\n const resolved = await context.resolve!(specifier, cleanId, {\n skipSelf: true,\n });\n if (resolved) resolvedComponents.set(specifier, resolved.id);\n }),\n );\n }\n const componentReferences = canvasComponentAnnotations(\n cleanId,\n source,\n resolvedComponents,\n );\n const result = annotateFile(source, cleanId, (info) => {\n const props = {\n ...componentReferences.get(info.element.openingElement.start),\n ...computeTempoAnnotatedProps({\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps: options.computeAnnotatedProps,\n }),\n };\n if (!witnessed) {\n // An unversioned offset is still accepted by some released\n // structural writers. Withhold the entire source address, not\n // merely its freshness, until this chain can certify its bytes.\n delete props[\"data-tempo-filepath\"];\n delete props[\"data-tempo-position\"];\n delete props[\"data-tempo-expr\"];\n delete props[\"data-tempo-modifiedts\"];\n delete props[\"data-tempo-source-version\"];\n }\n return props;\n });\n\n // A file that does not parse stays untouched; Vite reports the error.\n if (result.parseResult.errors.length > 0) return null;\n // A file with no annotated element still records its evaluation: a\n // write that removed its last element is the case that needs it.\n const annotated =\n result.elementsAnnotated === 0 ? source : result.annotatedSource;\n const withControls = options.transformsControls(cleanId)\n ? transformControls(annotated, cleanId)\n : annotated;\n return {\n code: witnessed\n ? appendModuleVersionRecord(\n withControls,\n filepath,\n modifiedtsMs,\n sourceVersion,\n )\n : withControls,\n map: null,\n };\n } catch {\n return null;\n }\n }\n\n async function defaultExportIdentityRewritten(change: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean> {\n const { file } = change;\n const key = canonicalIdentityKey(file);\n if (!defaultExportIdentityByFile.has(key)) return false; // Never served.\n let source: string;\n try {\n source = readFileSync(file, \"utf8\");\n // A watcher can fire between a save's truncate and write. Vite's read\n // waits for that write to settle; caching the temporary empty source\n // here would erase the served identity and miss its required reload.\n // Keep ordinary nonempty comparisons synchronous so concurrent watcher\n // pipelines cannot reorder them around an unnecessary async read.\n if (source.length === 0) source = await change.read();\n } catch {\n return false;\n }\n const before = defaultExportIdentityByFile.get(key);\n if (before === undefined) return false; // Deleted while the read waited.\n const after = readDefaultExportIdentity(source);\n defaultExportIdentityByFile.set(key, after);\n return isDefaultExportIdentityRewrite(before, after);\n }\n\n return {\n annotateJsxModule,\n defaultExportIdentityRewritten,\n forgetDefaultExportIdentity(file) {\n defaultExportIdentityByFile.delete(canonicalIdentityKey(file));\n },\n };\n}\n","import { parseControlsFile } from \"./parser\";\n\n/** Replace this module's registrations before reevaluation. Vite disposes\n * accepted boundaries, but can reevaluate their intermediate imports without\n * calling dispose. hot.data also covers that path. One callback owns ALL calls\n * in a file: registering a callback per call would overwrite the previous one. */\nexport function transformControlsForHmr(\n source: string,\n filePath: string,\n previouslyDefinedControls = false,\n): string {\n const calls = source.includes(\"defineControls\")\n ? parseControlsFile(filePath, source)\n : [];\n if (!calls.length && !previouslyDefinedControls) return source;\n for (const { start, end } of calls.reverse()) {\n source =\n source.slice(0, start) +\n `((dispose) => { if (import.meta.hot && typeof dispose === \"function\") import.meta.hot.data.__tempoControlsDisposers.push(dispose); })(${source.slice(start, end)})` +\n source.slice(end);\n }\n return `if (import.meta.hot) {\n for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();\n import.meta.hot.data.__tempoControlsDisposers = [];\n import.meta.hot.dispose(() => {\n for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();\n import.meta.hot.data.__tempoControlsDisposers = [];\n });\n}\n${source}`;\n}\n","import { realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, normalize, posix, resolve } from \"node:path\";\nimport {\n parseFlutterPreview,\n FLUTTER_PREVIEW_KEY_ATTRIBUTE,\n} from \"./canvas/flutter-preview\";\nimport {\n canonicalPathAllowMissing,\n flutterPreviewKey,\n} from \"./flutter-preview-path\";\nimport { parseCanvasFile } from \"./canvas/parser\";\n\nexport const COMPONENT_REFERENCE_ATTRIBUTE = \"data-tempo-component-reference\";\nfunction moduleIdentity(\n file: string,\n specifier: string,\n resolved?: ReadonlyMap<string, string>,\n): string {\n const resolvedId = resolved?.get(specifier);\n const bundled = resolvedId?.startsWith(\"\\0tempo:astro-component:\")\n ? decodeURIComponent(\n resolvedId.slice(\"\\0tempo:astro-component:\".length, -3),\n )\n : resolvedId;\n // Match Vite's module-graph timestamp normalization. Other query parameters\n // and fragments can select different modules and remain part of identity.\n const target =\n bundled === undefined\n ? specifier\n : bundled.replace(/\\bt=\\d{13}&?\\b/, \"\").replace(/[?&]$/, \"\");\n if (target.startsWith(\"\\0\")) return target;\n const suffixAt = target.search(/[?#]/);\n let path = (suffixAt < 0 ? target : target.slice(0, suffixAt)).replace(\n /\\\\/g,\n \"/\",\n );\n const suffix =\n suffixAt < 0 || target.endsWith(\".astro?tempo-component\")\n ? \"\"\n : target.slice(suffixAt);\n if (bundled === undefined && path.startsWith(\".\"))\n path = resolve(dirname(file), path);\n // Bare or virtual module IDs are opaque; path.normalize can change their\n // meaning. Only filesystem paths receive filesystem canonicalization.\n if (!isAbsolute(path) && !/^[A-Za-z]:\\//.test(path)) return target;\n if (bundled !== undefined) {\n try {\n path = realpathSync.native(path);\n } catch {\n /* The resolver may return a virtual absolute path. */\n }\n }\n return normalize(path).replace(/\\\\/g, \"/\") + suffix;\n}\n/** Static references carry provenance. Inline/dynamic expressions remain owned\n * by their storyboard; body and props never participate in source identity. */\nexport function canvasComponentAnnotations(\n file: string,\n source: string,\n resolved?: ReadonlyMap<string, string>,\n hostRoot?: string,\n): ReadonlyMap<number, Readonly<Record<string, string>>> {\n const result = new Map<number, Readonly<Record<string, string>>>();\n if (!source.includes(\"tempo-sdk/canvas\")) return result;\n const parsed = parseCanvasFile(file, source);\n for (const board of parsed.storyboards) {\n if (board.kind !== \"component\" || board.openingElementSpan === undefined)\n continue;\n // A Flutter board is an instance board (user decision 2026-10-19): its\n // preview function is the component it instantiates, always outside the\n // canvas folder, so the canvas selects the board first and shows the\n // root widget's internals beneath it, as for `component={X}` with an\n // imported X. The reference's identity is the preview key itself.\n const flutterPreview = board.preview\n ? parseFlutterPreview(board.preview)\n : null;\n if (flutterPreview && !(\"error\" in flutterPreview) && hostRoot) {\n let key: string;\n try {\n const absolute = resolve(\n dirname(canonicalPathAllowMissing(file)),\n flutterPreview.file,\n );\n key = flutterPreviewKey(\n hostRoot,\n absolute,\n flutterPreview.functionName,\n );\n } catch {\n // An inaccessible or dangling reference fails only this board. Do not\n // reject the entire canvas module or invent an uncanonicalized key.\n continue;\n }\n result.set(board.openingElementSpan.start, {\n [FLUTTER_PREVIEW_KEY_ATTRIBUTE]: key,\n [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([\n \"flutter\",\n key.slice(0, key.lastIndexOf(\"#\")),\n flutterPreview.functionName,\n ]),\n \"data-tempo-external-component\": \"true\",\n });\n continue;\n }\n const ref = board.component;\n if (!ref?.localName) continue;\n const member = ref.expression.match(\n /^\\s*([$\\w]+)(?:\\s*\\.\\s*([$\\w]+))?\\s*$/,\n );\n if (!member) continue;\n let name: string;\n if (ref.import) {\n if (ref.import.kind === \"namespace\") {\n if (!member[2]) continue;\n name = member[2];\n } else {\n if (member[2]) continue;\n name = ref.import.importedName;\n }\n } else {\n if (member[2]) continue;\n name = ref.localName;\n }\n // Match the canvas-config reader's V1 rule using the authored specifier,\n // before bundler resolution changes aliases into filesystem paths.\n const specifier = ref.import?.source\n .replace(/\\\\/g, \"/\")\n .replace(/[?#].*/, \"\");\n const canvasDir = posix.dirname(file.replace(/\\\\/g, \"/\"));\n const external =\n specifier !== undefined &&\n (!specifier.startsWith(\".\") ||\n !posix.join(canvasDir, specifier).startsWith(`${canvasDir}/`));\n result.set(board.openingElementSpan.start, {\n [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([\n ref.import ? \"import\" : \"local\",\n moduleIdentity(file, ref.import?.source ?? file, resolved),\n name,\n ]),\n ...(external ? { \"data-tempo-external-component\": \"true\" } : {}),\n });\n }\n return result;\n}\n","/**\n * Default-export identity reader — the dev server's repair signal for the\n * silent stale-rename class.\n *\n * Changing a default export's identity (rename, named → anonymous) without\n * touching its importer follows @vitejs/plugin-react's public contract: the\n * module still looks like a valid Fast Refresh boundary, so Vite self-accepts\n * the update, react-refresh finds no family continuation for the mounted\n * component, and the visible output silently keeps rendering the OLD code —\n * no error, no invalidation, nothing observable client-side. Any full\n * document reload heals it.\n *\n * These helpers extract a conservative string-level fingerprint of a module's\n * default-export identity so the Vite plugin can compare consecutive\n * hot-update deliveries of the same file and issue ONE public full-reload\n * when the identity provably changed. False negatives are acceptable (manual\n * refresh remains available); a false positive costs a gratuitous reload, so\n * any shape the reader is not confident about parses to null and never\n * participates in the comparison — except that a confidently-read ANONYMOUS\n * default (function, class, or arrow) makes every later update of the file a\n * rewrite: react-refresh has no family for a nameless component, so nothing\n * short of a reload can ever converge the mounted instance.\n */\n\nexport interface DefaultExportIdentity {\n kind: \"function\" | \"class\" | \"identifier\";\n /** Binding name; null for anonymous function/class default exports. */\n name: string | null;\n}\n\nconst FUNCTION_DEFAULT_RE =\n /^(?:async\\s+)?function(?:\\s*\\*)?(?:\\s+([A-Za-z_$][\\w$]*))?\\s*\\(/;\nconst CLASS_DEFAULT_RE =\n /^(?:abstract\\s+)?class(?:\\s+([A-Za-z_$][\\w$]*))?(?=[\\s{])/;\n// An anonymous arrow default (`export default () => ...`, `async (p) =>`,\n// `props => ...`). Same identity class as an anonymous `function` default:\n// no binding name exists, so react-refresh can never register a family for\n// it. Params with nested parentheses (a destructuring default calling a\n// function) fall back to null — conservative, like every other unreadable\n// shape.\nconst ARROW_DEFAULT_RE = /^(?:async\\s+)?(?:\\([^()]*\\)|[A-Za-z_$][\\w$]*)\\s*=>/;\n// A bare identifier re-export (`export default StatefulCounter;`). The\n// terminator check rejects longer expressions (`styled.div`, `memo(App)`,\n// `new Foo()`), which have no single binding name to compare.\nconst IDENTIFIER_DEFAULT_RE = /^([A-Za-z_$][\\w$]*)[ \\t]*(?:;|\\r?\\n|$)/;\n\n/**\n * Reads the first `export default` in the source and classifies its identity.\n * Returns null when there is none or its shape carries no comparable binding\n * name (arrow functions, call expressions, object/JSX literals, ...). Purely\n * lexical: an `export default` inside a comment or string can fool it, but a\n * spurious match only matters if the fingerprint CHANGES between two edits.\n */\nexport function readDefaultExportIdentity(\n source: string,\n): DefaultExportIdentity | null {\n const start = /\\bexport\\s+default\\s+/.exec(source);\n if (!start) return null;\n const tail = source.slice(start.index + start[0].length);\n\n const fn = FUNCTION_DEFAULT_RE.exec(tail);\n if (fn) return { kind: \"function\", name: fn[1] ?? null };\n\n const cls = CLASS_DEFAULT_RE.exec(tail);\n if (cls) return { kind: \"class\", name: cls[1] ?? null };\n\n if (ARROW_DEFAULT_RE.test(tail)) return { kind: \"function\", name: null };\n\n const identifier = IDENTIFIER_DEFAULT_RE.exec(tail);\n if (identifier) return { kind: \"identifier\", name: identifier[1] };\n\n return null;\n}\n\n/**\n * True when two confidently-read identities differ in a way that produces\n * the silent stale render: the binding name changed (including named →\n * anonymous and back) while both sides still look like React components.\n * Lower-cased (non-component) renames are excluded — a module that stops\n * being all-components stops being a Fast Refresh boundary, so Vite's own\n * propagation already handles it.\n *\n * An ANONYMOUS function/class default on the BEFORE side is a rewrite for\n * every subsequent update, whatever the after side reads as: with no binding\n * name react-refresh never registered a family for the mounted component, so\n * no later hot update — same-shape edit, wrapper, rename — can ever reach it\n * in place. The only heal is the reload this verdict triggers.\n */\nexport function isDefaultExportIdentityRewrite(\n before: DefaultExportIdentity | null,\n after: DefaultExportIdentity | null,\n): boolean {\n if (!before) return false;\n if (before.name === null) return true;\n if (!after) return false;\n if (before.name === after.name) return false;\n return isComponentShaped(before) && isComponentShaped(after);\n}\n\nfunction isComponentShaped(identity: DefaultExportIdentity): boolean {\n return identity.name === null || /^[A-Z]/.test(identity.name);\n}\n","import type { EnvironmentModuleGraph, EnvironmentModuleNode } from \"vite\";\n\n/** An outgoing prune is evidence of removal; zero importers alone is not. */\nexport function createPrunedModuleDeletionGuard() {\n let sequence = 0;\n let activeReceipts = 0;\n let receipts = new WeakMap<EnvironmentModuleNode, number>();\n return {\n observePrune(graph: EnvironmentModuleGraph, paths: readonly string[]) {\n const receipt = ++sequence;\n for (const path of paths) {\n const module = graph.urlToModuleMap.get(path);\n if (module) {\n if (!receipts.has(module)) activeReceipts++;\n receipts.set(module, receipt);\n }\n }\n },\n observeRequest(\n graph: EnvironmentModuleGraph,\n url: string,\n base: string,\n fetchDestination?: string | string[],\n ifNoneMatch?: string | string[],\n ) {\n if (\n !activeReceipts ||\n [\"document\", \"iframe\", \"frame\"].includes(String(fetchDestination))\n )\n return;\n const requestSequence = sequence;\n // Observe the response, never delay a request or run a resolver merely\n // because an endpoint/asset was fetched. Vite's module responses carry\n // transform ETags; its cached304 response uses the request's ETag.\n return async (\n status: number,\n contentType: string | number | string[] | undefined,\n responseEtag: string | number | string[] | undefined,\n ) => {\n if (!activeReceipts || status < 200 || status >= 400) return;\n if (\n status !== 304 &&\n !/^text\\/(?:javascript|css)(?:;|$)/i.test(String(contentType))\n )\n return;\n const etag = status === 304 ? ifNoneMatch : responseEtag;\n if (typeof etag !== \"string\" || !graph.getModuleByEtag(etag)) return;\n // Match Vite's base + transform middleware spelling. Resolution owns\n // aliases and transport-only import/t queries; semantic queries stay.\n let moduleUrl = url;\n if (base !== \"/\" && moduleUrl.startsWith(base))\n moduleUrl = `/${moduleUrl.slice(base.length)}`;\n try {\n moduleUrl = decodeURI(moduleUrl).replace(/__x00__/g, \"\\0\");\n if (moduleUrl.startsWith(\"/@id/\")) moduleUrl = moduleUrl.slice(5);\n const [, id] = await graph.resolveUrl(moduleUrl);\n const module = graph.getModuleById(id);\n if (\n module &&\n module.transformResult?.etag === etag &&\n (receipts.get(module) ?? Infinity) <= requestSequence\n ) {\n receipts.delete(module);\n activeReceipts--;\n }\n } catch {\n // Observation must not change normal resolution/URI errors.\n }\n };\n },\n suppressDeletion(\n graph: EnvironmentModuleGraph,\n modules: EnvironmentModuleNode[],\n ) {\n if (\n !modules.length ||\n !modules.every(\n (module) => receipts.has(module) && module.importers.size === 0,\n )\n )\n return false;\n const invalidated = new Set<EnvironmentModuleNode>();\n for (const module of modules) graph.invalidateModule(module, invalidated);\n return true;\n },\n clear() {\n receipts = new WeakMap();\n activeReceipts = 0;\n // Keep sequence monotonic: an old in-flight response cannot retire a\n // receipt from a later server lifetime.\n },\n };\n}\n","import { existsSync } from \"node:fs\";\nimport {\n type IncomingHttpHeaders,\n type IncomingMessage,\n request as httpRequest,\n type ServerResponse,\n} from \"node:http\";\nimport { connect } from \"node:net\";\nimport { extname, join, posix } from \"node:path\";\nimport { type Duplex, pipeline } from \"node:stream\";\nimport type { ResolvedConfig } from \"vite\";\n\n/**\n * Routes the Flutter dev server (`flutter run -d web-server`) through the\n * canvas host's origin, so `FlutterStoryboard` boots the engine from the same\n * origin as the host page.\n *\n * Three routes reach Flutter, all through one forwarder:\n * - HTTP under `/__tempo/flutter/`, the prefix the generated bootstrap loads\n * the app from (`entrypointBaseUrl` and `assetBase`), prefix stripped;\n * - any root HTTP request Vite had nothing to serve. Flutter's debug loader\n * bakes `/` as the app root: hot reload fetches `/reloaded_sources.json`\n * and DDC modules such as `/packages/<pkg>/x.dart.lib.js` from the page's\n * origin whatever the entrypoint base, so the prefix alone breaks hot\n * reload;\n * - every WebSocket upgrade except Vite's own. The DWDS client injected on\n * the web-server device connects over a WebSocket at a root path.\n *\n * Active only when Tempo started the canvas host with `TEMPO` and\n * `TEMPO_FLUTTER_URL` set, so hand-written hosts such as the canvas demo get\n * it too. Vite's own `server.proxy` is not used: it logs a stack trace for\n * every refused connection, and the page probes repeatedly while Flutter is\n * still compiling.\n */\n\nexport const FLUTTER_PROXY_PREFIX = \"/__tempo/flutter\";\n\n/** The body of every 502 a Flutter route answers while Flutter is down. */\nexport const FLUTTER_UNREACHABLE_BODY = { error: \"flutter_unreachable\" };\n\n/**\n * The generated Flutter host project (`tempo/.flutter-host/`) lives inside\n * the canvas host's Vite root; its `.dart_tool/` and `build/` churn on every\n * Flutter compile and must never trigger Vite.\n */\nexport const FLUTTER_HOST_WATCH_IGNORE = \"**/.flutter-host/**\";\n\ntype Middleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n) => void;\n\ntype Logger = { warn(message: string): void; info(message: string): void };\n\n/** The Flutter dev server's origin, or null when this host serves no Flutter. */\nexport function readFlutterDevServerUrl(\n env: NodeJS.ProcessEnv,\n logger: Pick<Logger, \"warn\"> = console,\n): URL | null {\n const raw = env.TEMPO_FLUTTER_URL?.trim();\n if (!raw) return null;\n try {\n const url = new URL(raw);\n if (url.protocol === \"http:\") return url;\n } catch {\n // Reported below with the value that failed.\n }\n logger.warn(\n `[tempo] ignoring TEMPO_FLUTTER_URL=${JSON.stringify(raw)}: expected an http:// origin such as http://127.0.0.1:<port>`,\n );\n return null;\n}\n\n/** The dev server's status endpoint on TEMPO_FLUTTER_URL: 200\n * `{ status: \"starting\" | \"ready\" | \"reloading\" | \"failed\", spawn, error }`,\n * where `spawn` counts `flutter run` processes. */\nexport const FLUTTER_STATUS_PATH = \"/__tempo_flutter_status\";\n\n/**\n * Calls `onRelaunch` when Flutter comes up as a different `flutter run`\n * process than the one last seen ready. A page that loaded the bootstrap is\n * bound to the process it booted against (its DWDS debug connection); after\n * a relaunch (a crash, a pubspec change) that engine never gets another hot\n * reload, so the canvas host page must load again. Returns the stop.\n */\nexport function watchFlutterRelaunches(options: {\n target: URL;\n onRelaunch(): void;\n intervalMs?: number;\n}): () => void {\n const intervalMs = options.intervalMs ?? 3_000;\n const statusUrl = new URL(FLUTTER_STATUS_PATH, options.target.origin);\n let lastReadySpawn: number | null = null;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n async function poll() {\n try {\n const response = await fetch(statusUrl, {\n signal: AbortSignal.timeout(intervalMs),\n });\n const status = response.ok\n ? ((await response.json()) as { status?: unknown; spawn?: unknown })\n : null;\n if (\n !stopped &&\n status?.status === \"ready\" &&\n typeof status.spawn === \"number\"\n ) {\n const relaunched =\n lastReadySpawn !== null && status.spawn !== lastReadySpawn;\n lastReadySpawn = status.spawn;\n if (relaunched) options.onRelaunch();\n }\n } catch {\n // The dev server is down or restarting; the next poll asks again.\n }\n if (stopped) return;\n timer = setTimeout(poll, intervalMs);\n // Never keep the Vite process alive on its own.\n timer.unref?.();\n }\n\n void poll();\n return () => {\n stopped = true;\n if (timer) clearTimeout(timer);\n };\n}\n\nfunction stripFlutterPrefix(path: string): string {\n const stripped = path.slice(FLUTTER_PROXY_PREFIX.length);\n return stripped.startsWith(\"/\") ? stripped : `/${stripped}`;\n}\n\nfunction isUnderFlutterPrefix(path: string): boolean {\n if (!path.startsWith(FLUTTER_PROXY_PREFIX)) return false;\n const next = path.charAt(FLUTTER_PROXY_PREFIX.length);\n return next === \"\" || next === \"/\" || next === \"?\";\n}\n\nexport function createFlutterForwarding(options: {\n target: URL;\n config: Pick<ResolvedConfig, \"root\" | \"base\" | \"logger\" | \"server\">;\n}): {\n /** Install before Vite's middlewares: answers everything under the prefix. */\n prefix: Middleware;\n /** Install after Vite's middlewares: answers what Vite could not serve. */\n fallthrough: Middleware;\n /** The http server's `upgrade` listener. */\n upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void;\n} {\n const { target, config } = options;\n const isViteUpgrade = createViteUpgradeMatcher(config);\n let reachable = true;\n\n function noteReachable() {\n if (reachable) return;\n reachable = true;\n config.logger.info(\n `[tempo] Flutter dev server reachable at ${target.origin}`,\n );\n }\n\n function noteUnreachable(error: Error) {\n if (!reachable) return;\n reachable = false;\n config.logger.warn(\n `[tempo] Flutter dev server unreachable at ${target.origin} (${(error as NodeJS.ErrnoException).code ?? error.message}); answering 502 until it is up`,\n );\n }\n\n function forward(\n req: IncomingMessage,\n res: ServerResponse,\n path: string,\n ): void {\n const upstream = httpRequest(\n {\n hostname: target.hostname,\n port: target.port,\n method: req.method,\n path,\n headers: { ...endToEndHeaders(req.headers), host: target.host },\n },\n (response) => {\n noteReachable();\n res.writeHead(\n response.statusCode ?? 502,\n response.statusMessage,\n endToEndHeaders(response.headers),\n );\n // A body that breaks off upstream must end the browser's response\n // too: `pipe` would leave a sized response waiting forever, where\n // `pipeline` destroys it.\n pipeline(response, res, () => {});\n },\n );\n upstream.on(\"error\", (error) => {\n if (res.headersSent || res.destroyed) {\n res.destroy();\n return;\n }\n noteUnreachable(error);\n res.writeHead(502, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(FLUTTER_UNREACHABLE_BODY));\n });\n // A page that goes away mid-stream (a long-lived event stream, a\n // navigation) must not leave the upstream request open.\n res.on(\"close\", () => {\n if (!res.writableFinished) upstream.destroy();\n });\n req.pipe(upstream);\n }\n\n // Replays the handshake as received (Host rewritten) and then pipes both\n // directions untouched: the WebSocket protocol is Flutter's business.\n function forwardUpgrade(\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n path: string,\n ): void {\n let connected = false;\n const upstream = connect(\n { host: target.hostname, port: Number(target.port) || 80 },\n () => {\n connected = true;\n noteReachable();\n upstream.write(upgradeRequestHead(req, path, target.host));\n if (head.length > 0) upstream.write(head);\n upstream.pipe(socket);\n socket.pipe(upstream);\n },\n );\n upstream.on(\"error\", (error) => {\n if (connected) {\n socket.destroy();\n return;\n }\n noteUnreachable(error);\n const body = JSON.stringify(FLUTTER_UNREACHABLE_BODY);\n socket.end(\n `HTTP/1.1 502 Bad Gateway\\r\\nContent-Type: application/json\\r\\nContent-Length: ${Buffer.byteLength(body)}\\r\\nConnection: close\\r\\n\\r\\n${body}`,\n );\n });\n // Before the connection, `close` follows `error`: let the 502 flush.\n upstream.on(\"close\", () => {\n if (connected) socket.destroy();\n });\n socket.on(\"error\", () => upstream.destroy());\n socket.on(\"close\", () => upstream.destroy());\n }\n\n return {\n prefix(req, res, next) {\n const url = req.url ?? \"/\";\n if (!isUnderFlutterPrefix(url)) return next();\n forward(req, res, stripFlutterPrefix(url));\n },\n fallthrough(req, res, next) {\n // Vite's SPA fallback rewrites `req.url` to /index.html for any request\n // accepting `*/*` before this runs, so the decision and the forwarded\n // path both come from the URL the client asked for.\n const originalUrl =\n (req as IncomingMessage & { originalUrl?: string }).originalUrl ??\n req.url ??\n \"/\";\n const pathname = decodePathname(originalUrl);\n const isViteOwned =\n pathname === null ||\n pathname.startsWith(\"/@\") ||\n pathname.startsWith(\"/__tempo/\") ||\n isCanvasHostPage(pathname) ||\n isHtmlNavigation(req.headers.accept, pathname) ||\n rootHasHtmlPage(config.root, pathname);\n if (isViteOwned) return next();\n forward(req, res, originalUrl);\n },\n upgrade(req, socket, head) {\n const url = req.url ?? \"/\";\n if (isViteUpgrade(req, url)) return;\n const path = isUnderFlutterPrefix(url) ? stripFlutterPrefix(url) : url;\n forwardUpgrade(req, socket, head, path);\n },\n };\n}\n\n/**\n * Upgrades another listener on the same http server answers: Vite's HMR and\n * ping sockets, and the app's own `server.proxy` WebSocket entries. Two\n * listeners answering one upgrade would corrupt the socket.\n */\nfunction createViteUpgradeMatcher(\n config: Pick<ResolvedConfig, \"base\" | \"server\">,\n): (req: IncomingMessage, url: string) => boolean {\n const hmr = config.server.hmr;\n const hmrPath =\n typeof hmr === \"object\" && hmr.path\n ? posix.join(config.base || \"/\", hmr.path)\n : null;\n const proxyContexts = Object.keys(config.server.proxy ?? {});\n return (req, url) => {\n const protocol = req.headers[\"sec-websocket-protocol\"] ?? \"\";\n if (protocol.includes(\"vite-hmr\") || protocol.includes(\"vite-ping\")) {\n return true;\n }\n if (hmrPath !== null && decodePathname(url) === hmrPath) return true;\n // Vite's own proxy matching: a key starting with ^ is a RegExp.\n return proxyContexts.some((context) =>\n context.startsWith(\"^\")\n ? new RegExp(context).test(url)\n : url.startsWith(context),\n );\n };\n}\n\nfunction upgradeRequestHead(\n req: IncomingMessage,\n path: string,\n host: string,\n): string {\n const lines = [`${req.method ?? \"GET\"} ${path} HTTP/${req.httpVersion}`];\n for (let index = 0; index < req.rawHeaders.length; index += 2) {\n const name = req.rawHeaders[index] ?? \"\";\n const value =\n name.toLowerCase() === \"host\" ? host : req.rawHeaders[index + 1];\n lines.push(`${name}: ${value}`);\n }\n return `${lines.join(\"\\r\\n\")}\\r\\n\\r\\n`;\n}\n\n/**\n * The canvas host page, Tempo's own route (`isCanvasHostRequest` in\n * index.ts), which Flutter never serves. Vite's SPA fallback answers it with\n * the host's index.html for any Accept, so a request that does not ask for\n * text/html still belongs to Vite: canvas_validate's reachability check and\n * curl send a wildcard Accept, and were answered by Flutter (503\n * flutter_starting while it compiled, then Flutter's own index.html).\n */\nfunction isCanvasHostPage(pathname: string): boolean {\n return pathname.replace(/\\/+$/, \"\") === \"/tempo-host\";\n}\n\n/** A browser asking for a page, which Vite answers with its own HTML. */\nfunction isHtmlNavigation(\n accept: string | undefined,\n pathname: string,\n): boolean {\n return Boolean(accept?.includes(\"text/html\")) && extname(pathname) === \"\";\n}\n\n/** Mirrors Vite's HTML fallback: the host's own page for this path, if any. */\nfunction rootHasHtmlPage(root: string, pathname: string): boolean {\n // The pathname is decoded, so `%2e%2e` arrives as `..`, which the URL\n // parser did not resolve; a page outside the root is never Vite's.\n if (pathname.split(\"/\").includes(\"..\")) return false;\n if (pathname.endsWith(\".html\")) return existsSync(join(root, pathname));\n if (pathname.endsWith(\"/\")) {\n return existsSync(join(root, pathname, \"index.html\"));\n }\n return existsSync(join(root, `${pathname}.html`));\n}\n\nfunction decodePathname(url: string): string | null {\n try {\n return decodeURIComponent(new URL(url, \"http://host\").pathname);\n } catch {\n return null;\n }\n}\n\nconst HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/** Headers that describe the message rather than this one connection. */\nfunction endToEndHeaders(headers: IncomingHttpHeaders): IncomingHttpHeaders {\n const forwarded: IncomingHttpHeaders = {};\n for (const [name, value] of Object.entries(headers)) {\n if (value === undefined || HOP_BY_HOP_HEADERS.has(name)) continue;\n forwarded[name] = value;\n }\n return forwarded;\n}\n","/**\n * Monotonic fence for Vite HMR update records.\n *\n * Vite gives every filesystem update a monotonic timestamp, but its server\n * pipelines may finish out of order. The browser processes websocket payloads\n * in arrival order, so an older pipeline that is sent after a newer one can\n * permanently put stale code back on screen. Remembering the newest timestamp\n * sent for each accepted module turns that partial order into a hard rule:\n * once generation N crosses the websocket boundary, no generation below N\n * may follow it.\n *\n * Equal timestamps remain valid because one source event can produce several\n * accept-boundary payloads. Records without Vite's identity/timestamp fields\n * pass through untouched for compatibility with older or custom channels.\n */\n\nexport interface HmrGenerationRecord {\n type?: unknown;\n path?: unknown;\n acceptedPath?: unknown;\n timestamp?: unknown;\n}\n\nexport interface HmrGenerationFence {\n filter<T extends HmrGenerationRecord>(updates: readonly T[]): T[];\n clear(): void;\n}\n\nfunction generationIdentity(update: HmrGenerationRecord): string | null {\n const type = typeof update.type === \"string\" ? update.type : null;\n const acceptedPath =\n typeof update.acceptedPath === \"string\"\n ? update.acceptedPath\n : typeof update.path === \"string\"\n ? update.path\n : null;\n if (!type || !acceptedPath) return null;\n return `${type}\\0${acceptedPath}`;\n}\n\nexport function createHmrGenerationFence(): HmrGenerationFence {\n const newestTimestampByIdentity = new Map<string, number>();\n\n return {\n filter(updates) {\n const accepted: (typeof updates)[number][] = [];\n for (const update of updates) {\n const identity = generationIdentity(update);\n const timestamp = update.timestamp;\n if (\n identity === null ||\n typeof timestamp !== \"number\" ||\n !Number.isFinite(timestamp)\n ) {\n accepted.push(update);\n continue;\n }\n\n const newestTimestamp = newestTimestampByIdentity.get(identity);\n if (newestTimestamp !== undefined && timestamp < newestTimestamp) {\n continue;\n }\n if (newestTimestamp === undefined || timestamp > newestTimestamp) {\n newestTimestampByIdentity.set(identity, timestamp);\n }\n accepted.push(update);\n }\n return accepted;\n },\n\n clear() {\n newestTimestampByIdentity.clear();\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\nconst installed = new WeakSet<Plugin>();\n\n/**\n * @vitejs/plugin-react 4/5 registers its HMR accept callback in an asynchronous\n * self-import continuation. Vite resets the old callbacks when the updated\n * module starts evaluating, but its next queued update can arrive before that\n * continuation runs. That update imports successfully with no callback and\n * never schedules React Refresh.\n *\n * Register acceptance during evaluation, retaining the plugin's own export\n * registration and boundary validation once the self-import resolves. This\n * changes only the known React-generated footer, before Vite import analysis;\n * other frameworks and newer footer shapes pass through unchanged.\n */\nexport function installSynchronousReactRefreshBoundary(\n plugins: readonly Plugin[],\n): void {\n for (const plugin of plugins) {\n if (\n plugin.name === \"vite:react-refresh\" &&\n plugin.load &&\n !installed.has(plugin)\n ) {\n installed.add(plugin);\n const hook = plugin.load;\n const load = typeof hook === \"function\" ? hook : hook.handler;\n const wrapped: typeof load = async function (...args) {\n const result = await load.apply(this, args);\n if (!result || args[0] !== \"/@react-refresh\") return result;\n const source = typeof result === \"string\" ? result : result.code;\n // Use the runtime's authority, including families registered during\n // evaluation whose reconciler mapping is not installed until refresh.\n // Unknown/newer runtimes retain ordinary loader replacement behavior.\n if (\n !source ||\n !/\\b(?:let|const) allFamiliesByType = new WeakMap\\(\\)/.test(source) ||\n !source.includes(\"function performReactRefresh()\")\n )\n return result;\n const code = `${source}\nglobalThis[Symbol.for(\"tempo.react-refresh.family\")] = (type) => allFamiliesByType.get(type);\n`;\n return typeof result === \"string\" ? code : { ...result, code };\n };\n plugin.load =\n typeof hook === \"function\" ? wrapped : { ...hook, handler: wrapped };\n }\n if (\n plugin.name !== \"vite:react-babel\" ||\n !plugin.transform ||\n installed.has(plugin)\n )\n continue;\n installed.add(plugin);\n const hook = plugin.transform;\n const transform = typeof hook === \"function\" ? hook : hook.handler;\n const wrapped: typeof transform = async function (...args) {\n const result = await transform.apply(this, args);\n if (!result) return result;\n const source = typeof result === \"string\" ? result : result.code;\n if (!source) return result;\n const code = source.replace(\n /RefreshRuntime\\.__hmr_import\\(import\\.meta\\.url\\)\\.then\\(\\(currentExports\\) => \\{\\n(\\s*RefreshRuntime\\.registerExportsForReactRefresh\\([^\\n]+\\);)\\n\\s*import\\.meta\\.hot\\.accept\\(\\(nextExports\\) => \\{([\\s\\S]*?)\\n\\s*\\}\\);\\n\\s*\\}\\);/,\n (\n _match,\n register: string,\n accept: string,\n ) => `const __tempoReactRefreshExports = RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {\n${register}\n return currentExports;\n });\n import.meta.hot.accept(async (nextExports) => {\n const currentExports = await __tempoReactRefreshExports;${accept}\n });`,\n );\n return code === source\n ? result\n : typeof result === \"string\"\n ? code\n : { ...result, code };\n };\n plugin.transform =\n typeof hook === \"function\" ? wrapped : { ...hook, handler: wrapped };\n }\n}\n","/**\n * Vite drops an update when its boundary has not evaluated in this document\n * yet. A cold canvas host can already be fetching that boundary: the old\n * response then finishes after the edit, with no later update to repair it.\n *\n * Keep the update on Vite's own module record until acceptDeps registers the\n * boundary, then replay it through the ordinary Vite queue. This introduces\n * no Tempo HMR protocol, import registry, or framework refresh mechanism.\n * Unknown client shapes pass through unchanged.\n */\nexport function preservePendingViteModuleUpdates(source: string): string {\n const missingBoundary =\n /(const mod = this\\.hotModulesMap\\.get\\(path\\);\\s*)if \\(!mod\\)\\s*(?:return;|\\{\\s*return;\\s*\\})/;\n const registeredBoundary =\n \"this.hmrClient.hotModulesMap.set(this.ownerPath, mod);\";\n if (!missingBoundary.test(source) || !source.includes(registeredBoundary)) {\n return source;\n }\n return source\n .replace(\n missingBoundary,\n `$1if (!mod || mod.pendingUpdates) {\n const pending = mod || {\n id: path,\n callbacks: [],\n pendingUpdates: new Map(),\n };\n pending.pendingUpdates.set(acceptedPath, update);\n this.hotModulesMap.set(path, pending);\n return;\n }`,\n )\n .replace(\n registeredBoundary,\n `${registeredBoundary}\n if (mod.pendingUpdates) {\n const pendingUpdates = [...mod.pendingUpdates.values()];\n delete mod.pendingUpdates;\n queueMicrotask(() => {\n for (const update of pendingUpdates) {\n void this.hmrClient.queueUpdate(update).catch((error) => {\n this.hmrClient.logger.error(error);\n });\n }\n });\n }`,\n );\n}\n","/**\n * Tailwind new-file rescan net — closes the scan-registry hole that turns\n * drawn frames into 0×0 husks (TEM-1242).\n *\n * @tailwindcss/vite (≤4.3.3 observed; the shape is inherent to its design)\n * regenerates CSS only when a file its LAST scan enumerated changes: every\n * scanned file is registered as a watch dep of the CSS module, and the scan\n * itself only re-runs inside a CSS re-transform. A source file created AFTER\n * that scan is therefore invisible — its edits trigger no CSS rebuild, so\n * Tailwind classes written into it (`w-[148px]` from the canvas draw tools,\n * classes in an AI-authored component, a teammate's new canvas arriving via\n * git) compile to nothing until some OTHER registered file changes. On the\n * canvas this renders as the drawn frame collapsing to 0×0 once HMR swaps\n * the inline-sized placeholder for the className-only canonical element.\n *\n * The net restores the missing input signal, in the same spirit as the\n * missed-change sweep: when a scannable source file sees a watcher event and\n * some Tailwind-scanning CSS module does NOT list that file among its watch\n * deps, re-emit the watcher \"change\" for the CSS file. Vite re-transforms\n * it, the Tailwind plugin re-runs its scanner (a fresh walk of its sources),\n * the new file joins the registry, and the missing utilities land as a\n * normal CSS hot update. Files the scanner already tracks are skipped — for\n * those Vite re-transforms the CSS on its own, so steady-state editing costs\n * this net nothing.\n *\n * A CSS module counts as \"Tailwind-scanning\" when its recorded watch deps\n * contain a glob or a non-CSS source file — only a class scanner registers\n * source files as deps of a stylesheet. This reads the module graph's\n * transform receipts instead of sniffing file contents, so `@import\n * \"tailwindcss\"` indirection (Tempo's generated `tempo/globals.css`, a\n * host-level `styles.css`) needs no special-casing.\n *\n * Guard rails on the re-emit:\n *\n * - LEADING-EDGE flush: the first poke goes out immediately (next tick), so\n * the CSS repair rides as close as possible behind the component's own\n * HMR update — the canonical render is className-only, so every tick of\n * delay is a tick of visible 0×0. Follow-up events within the debounce\n * window coalesce into one trailing re-emit (a git checkout materializing\n * hundreds of files costs two rebuilds, not hundreds).\n * - Per-(CSS file, source file) poke CAP: a file genuinely outside an\n * entry's source scope is never registered by the rescan we force, so\n * without a bound every subsequent edit of that file would rebuild that\n * unrelated CSS forever. Two pokes per pair (the second covers an event\n * racing the first rescan's transform), then the pair goes silent. The\n * cap is deliberately count-based rather than matching the file against\n * the entry's own source globs: the glob nodes Vite records are lossy\n * (the auto-detection root registers as a literal `*`), and a false\n * negative in glob matching would silently resurrect the 0×0 bug the net\n * exists to fix.\n * - Watcher events for CSS files are ignored outright, so the net can never\n * feed back into itself.\n */\n\n/** Extensions the Tailwind scanner reads class candidates from — the set a\n * newly created file must have for its absence from the scan registry to\n * matter. Deliberately conservative: covers what Tempo's canvas writes and\n * the common source shapes around it. */\nconst SCANNABLE_EXTENSIONS = new Set([\n \"ts\",\n \"tsx\",\n \"js\",\n \"jsx\",\n \"mjs\",\n \"cjs\",\n \"html\",\n \"mdx\",\n \"md\",\n \"svelte\",\n \"vue\",\n \"astro\",\n]);\n\n/** Path segments that never hold user source. Watcher events under these are\n * dropped before any module-graph work. */\nconst IGNORED_PATH_SEGMENTS = [\n \"/node_modules/\",\n \"/.git/\",\n \"/.vite/\",\n \"/.tempo/\",\n];\n\nexport const TAILWIND_SCAN_NET_DEBOUNCE_MS = 100;\n\n/** How many times one (CSS file, source file) pair may be poked before it\n * goes silent — the out-of-scope backstop described above. */\nexport const TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR = 2;\n\n/** Ceiling on remembered (CSS file, source file) poke counts. Reaching it\n * clears the ledger (a brief re-poke window for previously-capped pairs)\n * rather than letting a pathological session grow it without bound. */\nconst POKE_LEDGER_MAX_ENTRIES = 20_000;\n\n/** One CSS module node's view in Vite's module graph: the CSS file it\n * belongs to and the watch deps that node's transform registered. A CSS\n * file with several nodes (query variants, environments) yields several\n * entries — deliberately NOT unioned, so one node that already tracks a\n * file cannot mask a sibling node whose scanner predates it. Nodes with no\n * completed transform carry no deps and decide nothing — their first\n * transform scans the disk as-is. */\nexport interface ScanNetCssEntry {\n cssFile: string;\n /** Watch deps this node's transform recorded (absolute paths and/or glob\n * patterns, as the scanning plugin registered them). Null when the node\n * has no completed transform yet. */\n deps: readonly string[] | null;\n}\n\nexport interface CreateTailwindScanNetArgs {\n /** Enumerate the CSS module-node entries currently in the module graph. */\n listCssEntries(): Iterable<ScanNetCssEntry>;\n /** Re-emit the watcher \"change\" for a CSS file. */\n emitChange(cssFile: string): void;\n /** Debounce window for coalescing event bursts into one re-emit. */\n debounceMs?: number;\n /** Poke cap per (CSS file, source file) pair. */\n maxPokesPerPair?: number;\n}\n\nexport interface TailwindScanNet {\n /** Feed a watcher \"add\"/\"change\" event. Returns true when the event\n * scheduled (or joined) a pending CSS re-emit — a test/diagnostic\n * convenience, not part of the control flow. */\n handleWatcherFile(file: string): boolean;\n /** Cancel any pending re-emit. */\n dispose(): void;\n}\n\nfunction normalizeSlashes(path: string): string {\n return path.replace(/\\\\/g, \"/\");\n}\n\nfunction fileExtension(path: string): string {\n const base = path.slice(path.lastIndexOf(\"/\") + 1);\n const dot = base.lastIndexOf(\".\");\n return dot <= 0 ? \"\" : base.slice(dot + 1).toLowerCase();\n}\n\nexport function isScannableSourceFile(file: string): boolean {\n const normalized = normalizeSlashes(file);\n if (!SCANNABLE_EXTENSIONS.has(fileExtension(normalized))) return false;\n return !IGNORED_PATH_SEGMENTS.some((segment) =>\n normalized.includes(segment),\n );\n}\n\n/** Whether a dep entry marks its CSS module as a class scanner: a glob\n * pattern, or a concrete non-CSS source file. Plain stylesheets only ever\n * register CSS imports and url() assets. */\nfunction isScanDep(dep: string): boolean {\n if (dep.includes(\"*\")) return true;\n const ext = fileExtension(normalizeSlashes(dep));\n return ext !== \"\" && ext !== \"css\" && SCANNABLE_EXTENSIONS.has(ext);\n}\n\n/** Whether `file` needs the CSS entry re-emitted: the entry scans classes,\n * but its last scan did not register the file. */\nexport function cssEntryNeedsRescanFor(\n entry: ScanNetCssEntry,\n file: string,\n): boolean {\n if (entry.deps === null) return false;\n const normalizedFile = normalizeSlashes(file);\n let scansClasses = false;\n for (const dep of entry.deps) {\n const normalizedDep = normalizeSlashes(dep);\n if (normalizedDep === normalizedFile) return false;\n if (!scansClasses && isScanDep(normalizedDep)) scansClasses = true;\n }\n return scansClasses;\n}\n\nexport function createTailwindScanNet(\n args: CreateTailwindScanNetArgs,\n): TailwindScanNet {\n const debounceMs = args.debounceMs ?? TAILWIND_SCAN_NET_DEBOUNCE_MS;\n const maxPokesPerPair =\n args.maxPokesPerPair ?? TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR;\n const pendingCssFiles = new Set<string>();\n // (CSS file, source file) → pokes issued so far. A pair is counted at most\n // once per flush window (chokidar often fires add+change back-to-back for\n // one write; that must not burn the whole cap before any rescan ran).\n const pokeLedger = new Map<string, number>();\n const countedThisWindow = new Set<string>();\n let flushTimer: ReturnType<typeof setTimeout> | null = null;\n let lastFlushAt = Number.NEGATIVE_INFINITY;\n let disposed = false;\n\n const flush = () => {\n flushTimer = null;\n lastFlushAt = Date.now();\n countedThisWindow.clear();\n const cssFiles = [...pendingCssFiles];\n pendingCssFiles.clear();\n for (const cssFile of cssFiles) {\n args.emitChange(cssFile);\n }\n };\n\n return {\n handleWatcherFile(file: string): boolean {\n if (disposed) return false;\n if (!isScannableSourceFile(file)) return false;\n let scheduled = false;\n for (const entry of args.listCssEntries()) {\n if (!cssEntryNeedsRescanFor(entry, file)) continue;\n // Several module nodes of one CSS file may each demand the rescan;\n // the pair is still one poke.\n const pairKey = `${entry.cssFile}\\0${normalizeSlashes(file)}`;\n if (!countedThisWindow.has(pairKey)) {\n const pokes = pokeLedger.get(pairKey) ?? 0;\n if (pokes >= maxPokesPerPair) continue;\n if (pokeLedger.size >= POKE_LEDGER_MAX_ENTRIES) pokeLedger.clear();\n pokeLedger.set(pairKey, pokes + 1);\n countedThisWindow.add(pairKey);\n }\n pendingCssFiles.add(entry.cssFile);\n scheduled = true;\n }\n if (scheduled && flushTimer === null) {\n // Leading edge: a quiet net flushes on the next tick so the CSS\n // repair trails the component's own HMR update as tightly as\n // possible. Within the debounce window of a flush, further events\n // coalesce into one trailing re-emit.\n const sinceLastFlush = Date.now() - lastFlushAt;\n const delay = sinceLastFlush >= debounceMs ? 0 : debounceMs;\n flushTimer = setTimeout(flush, delay);\n flushTimer.unref?.();\n }\n return scheduled;\n },\n dispose(): void {\n disposed = true;\n pendingCssFiles.clear();\n pokeLedger.clear();\n countedThisWindow.clear();\n if (flushTimer !== null) {\n clearTimeout(flushTimer);\n flushTimer = null;\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,MAAM,eAAe;AAMvB,SAAS,qBAAqB,MAA0B;AAC7D,MAAI,QAAQ,IAAI,8BAA8B,iBAAkB,QAAO,CAAC;AACxE,QAAM,MAAM,QAAQ,QAAQ,QAAQ,IAAI,GAAG,wBAAwB;AACnE,MAAI,CAAC,WAAW,KAAK,KAAK,6BAA6B,CAAC,EAAG,QAAO,CAAC;AACnE,SAAO,CAAC,UAAU,QAAQ,EAAE,QAAQ,CAAC,UAAU;AAC7C,UAAM,cAAc,KAAK,KAAK,QAAQ,OAAO,UAAU;AACvD,WAAO,WAAW,WAAW,IACzB,CAAC,EAAE,MAAM,IAAI,OAAO,cAAc,KAAK,G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AAyB;AAC3C,aAAK,KAAK;AAAA,UACR,KAAK;AAAA,UACL,UAAU;AAAA,UACV,UAAU;AAAA,QACZ,CAAC;AACD,aAAK,KAAK;AAAA,UACR,KAAK;AAAA,UACL,OAAO,EAAE,MAAM,UAAU,KAAK,gCAAgC;AAAA,UAC9D,UAAU;AAAA,QACZ,CAAC;AAAA,MACH;AACA,aAAO,KAAK,SAAS,IAAI,OAAO;AAAA,IAClC;AAAA,IAEA,MAAM,UAAU,QAAQ,IAAI;AAC1B,UAAI,CAAC,WAAW,YAAY,SAAS;AACnC,eAAO;AAAA,MACT;AAEA,UAAI,UAAW,oCAAmC,SAAS;AAE3D,UAAI,GAAG,WAAW,IAAI,GAAG;AACvB,eAAO;AAAA,MACT;AAEA,YAAM,UAAUF,eAAc,EAAE;AAChC,UACE,QAAQ,QAAQ,OAAO,GAAG,EAAE,SAAS,8BAA8B,GACnE;AACA,cAAM,OAAO,iCAAiC,MAAM;AACpD,eAAO,SAAS,SAAS,OAAO,EAAE,MAAM,KAAK,KAAK;AAAA,MACpD;AACA,aAAO,oBAAoB,kBAAkB,MAAM,QAAQ,OAAO;AAAA,IACpE;AAAA,EACF;AAeF;AAGO,IAAM,gBAAgB;","names":["existsSync","join","resolve","resolve","resolve","resolve","normalize","resolve","readFileSync","realpathSync","relative","resolve","readFileSync","resolve","resolve","readFileSync","realpathSync","relative","readBody","url","existsSync","realpathSync","statSync","dirname","join","relative","resolve","fileURLToPath","readFileSync","realpathSync","dirname","isAbsolute","resolve","realpathSync","dirname","isAbsolute","resolve","resolve","dirname","isAbsolute","realpathSync","realpathSync","before","rawSource","readFileSync","isAbsolute","resolve","dirname","existsSync","join","posix","hook","wrapped","dirname","fileURLToPath","join","existsSync","cleanModuleId","realpathSync","MISSED_CHANGE_SWEEP_INTERVAL_MS","relative","resolve","statSync","options","file"]}
|
|
1
|
+
{"version":3,"sources":["../local-prebuilt-aliases.ts","../canvas-dependency-scan.ts","../compile-error-stream.ts","../hot-update-net.ts","../missed-change-sweep.ts","../rapid-hot-update-replay.ts","../canvas-host-registration-barrier.ts","../canvas-host-registration-contract.ts","../canvas-host-registration-work.ts","../index.ts","../jsx-module-annotation.ts","../assets/controls-transform.ts","../canvas-component-reference.ts","../default-export-identity.ts","../pruned-module-deletion.ts","../flutter-proxy.ts","../hmr-generation-fence.ts","../react-refresh-boundary.ts","../vite-client-pending-updates.ts","../tailwind-scan-net.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\n/** A development client explicitly installs its prebuilt SDK into the host.\n * Monorepo canvases can otherwise alias these entries to a different checkout,\n * silently bypassing that installed build (and every SDK fix being tested).\n * Ordinary published clients keep the project's own resolution choices. */\nexport function localPrebuiltAliases(root: string | undefined) {\n if (process.env.TEMPO_MONOREPO_SDK_SOURCE !== \"local-prebuilt\") return [];\n const sdk = resolve(root ?? process.cwd(), \"node_modules/tempo-sdk\");\n if (!existsSync(join(sdk, \".tempo-prebuilt-source.json\"))) return [];\n return [\"canvas\", \"assets\"].flatMap((entry) => {\n const replacement = join(sdk, \"dist\", entry, \"index.js\");\n return existsSync(replacement)\n ? [{ find: new RegExp(`^tempo-sdk/${entry}$`), replacement }]\n : [];\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { join, relative, resolve } from \"node:path\";\nimport type { UserConfig } from \"vite\";\n\n/** The launcher supplies these only to the canvas server, never the user's\n * app server. Adapt legacy generated globs in memory without rewriting an\n * editable config or discarding custom optimizer entries/exclusions. */\nexport function applyManagedCanvasDependencyScan(\n config: UserConfig,\n env: NodeJS.ProcessEnv = process.env,\n): void {\n const host = env.TEMPO_CANVAS_HOST_ROOT;\n const canvases = env.TEMPO_CANVAS_SOURCE_ROOT;\n if (\n !host ||\n !canvases ||\n resolve(config.root ?? process.cwd()) !== resolve(host)\n )\n return;\n const legacyGlob = [\n relative(host, canvases).replace(/\\\\/g, \"/\"),\n \"**/index.canvas.tsx\",\n ]\n .filter(Boolean)\n .join(\"/\");\n const entries = config.optimizeDeps?.entries;\n const retained = (\n entries === undefined\n ? []\n : typeof entries === \"string\"\n ? [entries]\n : entries\n ).filter(\n (entry) => entry.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\") !== legacyGlob,\n );\n config.optimizeDeps ??= {};\n config.optimizeDeps.entries = [...new Set([\"index.html\", ...retained])];\n // The generated host and projection scripts are injected after the HTML\n // scan. Bundle their shared runtime with React before either is requested;\n // a late SDK optimization can otherwise load a second React chunk while\n // the first renderer is already mounted (especially with React 18).\n for (const client of [\n \"tempo-sdk/canvas\",\n \"tempo-sdk/canvas/interact-projection\",\n ]) {\n if (\n config.optimizeDeps.exclude?.some(\n (id) => client === id || client.startsWith(`${id}/`),\n )\n )\n continue;\n config.optimizeDeps.include = [\n ...new Set([...(config.optimizeDeps.include ?? []), client]),\n ];\n }\n}\n\n/** The canvas host's folder in a project, which Tempo always names `tempo/`. */\nconst TEMPO_HOST_DIR = \"tempo\";\n\n/**\n * Keep the app's own dependency scan out of Tempo's canvas host. With no\n * `optimizeDeps.entries` and no build input, Vite crawls every `**\\/*.html`\n * under the app root, and an app at the project root holds the host in\n * `tempo/`: its `tempo/index.html` imports the React canvas host and\n * `tempo-sdk/canvas`. A Vue or Svelte app then fails the scan on `react` (the\n * trial agent added `optimizeDeps.entries` by hand), and every app prebundles\n * the host's dependencies, or fails on them before `tempo/` is installed.\n *\n * The replacement is Vite's own default crawl (its `__tests__`/`coverage`\n * ignores become `!` patterns, because Vite drops them once entries are\n * explicit) minus the host. Entries or an input the app sets are its own and\n * stay untouched; so does an app whose root holds no Tempo host (the host\n * itself, or a subfolder app whose host sits above its root).\n */\nexport function excludeTempoHostFromAppDependencyScan(\n config: UserConfig,\n): void {\n if (config.optimizeDeps?.entries !== undefined) return;\n if (config.build?.rollupOptions?.input !== undefined) return;\n const root = resolve(config.root ?? process.cwd());\n const hostConfig = join(root, TEMPO_HOST_DIR, \"tempo.config.json\");\n if (!existsSync(hostConfig)) return;\n config.optimizeDeps ??= {};\n config.optimizeDeps.entries = [\n \"**/*.html\",\n \"!**/__tests__/**\",\n \"!**/coverage/**\",\n `!${TEMPO_HOST_DIR}/**`,\n ];\n}\n","// The compile-error stream of a Tempo host on a Vite dev server: Vite's\n// compile errors, kept per module, cleared by the HMR update that repairs the\n// module (or by a validated re-transform when no update can), and delivered\n// to the canvas host page, whose problem tracker turns them into board\n// problems (`canvas/runtime-problems.ts`). The page subscribes on Vite's own\n// HMR socket through the client module in vite-error-transport.ts; the\n// `/__tempo/errors` SSE route remains for pages without that client.\n//\n// `tempoVitePlugin()` drives the stream from its own HMR tap; a host without\n// that plugin (the Nuxt sidecar) installs `compileErrorStreamPlugin()`.\n\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { parseSync } from \"oxc-parser\";\nimport type { Plugin, ViteDevServer } from \"vite\";\n\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport type { CanvasHostWrapperTransformer } from \"./canvas-host-registration-barrier.ts\";\nimport {\n fsPathFromModuleId,\n HOT_UPDATE_NET_SWEEP_INTERVAL_MS,\n} from \"./hot-update-net.ts\";\nimport {\n VITE_ERROR_CLIENT_ID,\n VITE_ERROR_CLIENT_PATH,\n VITE_ERROR_CLIENT_SOURCE,\n VITE_ERROR_STATE_EVENT,\n VITE_ERROR_SUBSCRIBE_EVENT,\n} from \"./vite-error-transport.ts\";\n\ntype HmrSendTarget = {\n send: (...args: unknown[]) => unknown;\n};\n\n/** The poll's starting cadence: the missed-change sweep's, which drives it\n * on the Vite host. */\nconst MISSED_CHANGE_SWEEP_INTERVAL_MS = HOT_UPDATE_NET_SWEEP_INTERVAL_MS;\n\n/** Error payload captured from Vite's HMR error events or console interception. */\nexport type TempoViteError = {\n type: \"compile\" | \"evaluation\";\n message: string;\n stack?: string;\n file?: string;\n frame?: string;\n plugin?: string;\n loc?: { file?: string; line?: number; column?: number };\n};\n\n// ---------------------------------------------------------------------------\n// Error tracking server — tracks per-module errors and broadcasts the\n// highest-priority error (or null) to SSE clients.\n//\n// Vite's HMR operates per-module: a successful update for module A should not\n// clear an unrelated compile error in module B. We key errors by the file\n// that caused them so that clears are scoped to the module that was fixed.\n// ---------------------------------------------------------------------------\n\ntype SseClient = ServerResponse<IncomingMessage>;\n\nexport interface TempoErrorServer {\n /** The error currently broadcast to SSE clients (most recent across all modules). */\n readonly currentError: TempoViteError | null;\n /** Files with active compile errors. Failed transforms may not be present in\n * Vite's module graph, so recovery code must track them explicitly. */\n readonly errorFiles: readonly string[];\n clients: Set<SseClient>;\n setError(error: TempoViteError): void;\n /** Clear errors for exact module aliases present in the HMR update. Pathless\n * errors require `clearAll()` because no module update can prove recovery. */\n clearErrorForModules(updatedPaths: string[]): void;\n /** Clear all errors unconditionally (e.g. report-clear endpoint). */\n clearAll(): void;\n}\n\n/** Whether two errors describe the same failure of the same module: same kind,\n * same text, same position. */\nfunction isSameError(left: TempoViteError, right: TempoViteError): boolean {\n return (\n left.type === right.type &&\n left.message === right.message &&\n left.loc?.line === right.loc?.line &&\n left.loc?.column === right.loc?.column\n );\n}\n\nfunction createErrorServer(\n onErrorFile?: (file: string) => void,\n onState?: (error: TempoViteError | null) => void,\n): TempoErrorServer {\n // Per-module error map keyed by file path (or \"unknown\" for errors without a file)\n const errorsByFile = new Map<string, TempoViteError>();\n\n function getMostRecentError(): TempoViteError | null {\n if (errorsByFile.size === 0) return null;\n // Map iterates in insertion order; setError does delete+set to push to end,\n // so the last entry is the most recently set error\n let latest: TempoViteError | null = null;\n for (const err of errorsByFile.values()) latest = err;\n return latest;\n }\n\n function broadcastCurrentState(): void {\n onState?.(server.currentError);\n const data = JSON.stringify(server.currentError);\n for (const client of server.clients) {\n client.write(`data: ${data}\\n\\n`);\n }\n }\n\n const server: TempoErrorServer = {\n get currentError(): TempoViteError | null {\n return getMostRecentError();\n },\n get errorFiles(): readonly string[] {\n return [...errorsByFile.keys()].filter((file) => file !== \"unknown\");\n },\n clients: new Set(),\n\n setError(error: TempoViteError) {\n const key = error.file ?? error.loc?.file ?? \"unknown\";\n const recorded = errorsByFile.get(key);\n // Re-raising a module's unchanged error is not news. The recovery poll\n // re-runs the failing transform on a timer, and each failure travels\n // back through Vite's error pipeline; broadcasting those would make\n // every attempt look like a fresh error to the canvas host. A genuinely\n // different error for the same file still gets through.\n if (recorded && isSameError(recorded, error)) return;\n // Capture the revision that first made this module erroneous. Vite may\n // send the same error several times after the user has already repaired\n // the file; re-statting on those delayed duplicates would incorrectly\n // mark the repaired revision as covered by the failed transform.\n if (key !== \"unknown\" && !recorded) onErrorFile?.(key);\n // Delete + set to move to end of Map iteration order (most recent)\n errorsByFile.delete(key);\n errorsByFile.set(key, error);\n broadcastCurrentState();\n },\n\n clearErrorForModules(updatedPaths: string[]) {\n if (errorsByFile.size === 0) return;\n let changed = false;\n for (const errorKey of [...errorsByFile.keys()]) {\n // Each source origin supplies both its canonical-root-relative path and\n // absolute file alias. Unknown errors have no causal module identity and\n // therefore survive until the explicit report-clear signal.\n if (\n errorKey !== \"unknown\" &&\n updatedPaths.some((path) => moduleIdsMatch(errorKey, path))\n ) {\n errorsByFile.delete(errorKey);\n changed = true;\n }\n }\n if (changed) broadcastCurrentState();\n },\n\n clearAll() {\n // Broadcast null even if already empty — runtime evaluation errors\n // (caught by the frame preload's console.error interception) are\n // forwarded as diagnostics without going through the SSE pipeline.\n // Broadcasting null ensures the frame preload receives a clear signal.\n errorsByFile.clear();\n broadcastCurrentState();\n },\n };\n return server;\n}\n\nfunction moduleIdsMatch(left: string, right: string): boolean {\n const normalize = (value: string) =>\n cleanModuleId(value)\n .replace(/^file:\\/\\//, \"\")\n .replace(/^\\/@fs\\//, \"/\")\n .replace(/\\\\/g, \"/\")\n .replace(/^\\/+/, \"\");\n return normalize(left) === normalize(right);\n}\n\n/** Ceiling for a single file's compile-error recovery poll interval. The poll\n * starts at the sweep cadence and doubles on every failed validation, so a\n * file the user leaves broken settles at one transform attempt per ceiling\n * instead of one per sweep. */\nconst COMPILE_ERROR_POLL_MAX_INTERVAL_MS = 30_000;\n\n/** One host's compile errors and how they reach the page. */\nexport interface CompileErrorStream {\n /** Per-module error state (also the Vite plugin's `_tempoErrorServer`). */\n readonly errorServer: TempoErrorServer;\n /** Answers pages connected to `server`: a subscription on Vite's socket\n * gets the current state, and every later state goes out on it. */\n attach(server: ViteDevServer): void;\n /** Answers the stream's routes (the SSE fallback and the report\n * endpoints) and returns true; false for any other request. */\n handleRequest(req: IncomingMessage, res: ServerResponse): boolean;\n /** Records the `err` of an HMR `error` payload Vite is sending. */\n recordHmrError(err: Record<string, unknown> | undefined): void;\n hasActiveCompileError(file: string): boolean;\n /** Re-transforms a file with an active error; when it now compiles,\n * clears the error and reloads the page. */\n recover(server: ViteDevServer, file: string): Promise<boolean>;\n /** Retries recovery for every active error, backing off per file. */\n pollRecovery(server: ViteDevServer): Promise<void>;\n /** Drops the poll schedule (server teardown). */\n reset(): void;\n}\n\nexport function createCompileErrorStream(\n options: {\n /** Called once when a module first gets an error, with its file. */\n onErrorFile?: (file: string) => void;\n } = {},\n): CompileErrorStream {\n let attachedServer: ViteDevServer | undefined;\n const errorServer = createErrorServer(options.onErrorFile, (error) =>\n attachedServer?.ws.send(VITE_ERROR_STATE_EVENT, error),\n );\n const normalizedFileKey = (file: string): string => file.replace(/\\\\/g, \"/\");\n const hasActiveCompileError = (file: string): boolean =>\n errorServer.errorFiles.some((errorFile) => moduleIdsMatch(errorFile, file));\n /** Validate a file whose compile error is still active, and recover it only\n * if Vite can transform it again. A module whose evaluation never completed\n * registered no Fast Refresh boundaries, so in-place HMR cannot be assumed —\n * recovery is a full reload. */\n const recoverActiveCompileError = async (\n server: ViteDevServer,\n file: string,\n ): Promise<boolean> => {\n if (!hasActiveCompileError(file)) return false;\n const cleanFile = fsPathFromModuleId(file);\n const requestId = `/@fs/${cleanFile.replace(/^\\/+/, \"\")}`;\n const clientEnvironment = (\n server as ViteDevServer & {\n environments?: {\n client?: CanvasHostWrapperTransformer<unknown> & {\n hot: HmrSendTarget;\n };\n };\n }\n ).environments?.client;\n const transformer =\n clientEnvironment ??\n (server as unknown as CanvasHostWrapperTransformer<unknown>);\n try {\n // writeFile can expose its truncated revision before its final bytes.\n // A successful transform of that empty module is not a repaired canvas:\n // the browser would cache a namespace without its required default.\n const source = readFileSync(cleanFile, \"utf8\");\n const canvasModule = /\\.canvas\\.[cm]?[jt]sx?$/.test(cleanFile);\n const hasDefault = (code: string) => {\n const parsed = parseSync(cleanFile, code);\n return (\n !parsed.errors.length &&\n parsed.program.body.some(\n (node) =>\n node.type === \"ExportDefaultDeclaration\" ||\n (node.type === \"ExportNamedDeclaration\" &&\n node.exportKind !== \"type\" &&\n node.specifiers.some(\n (specifier) =>\n specifier.exportKind !== \"type\" &&\n (specifier.exported.type === \"Identifier\"\n ? specifier.exported.name\n : specifier.exported.value) === \"default\",\n )),\n )\n );\n };\n if (canvasModule && !hasDefault(source)) return false;\n // A failed transform can leave Vite's previous module result cached.\n // Validating that cache can falsely declare the repaired revision clean,\n // then reload the browser into a namespace that still lacks its exports.\n // Invalidate every node for this file so transformRequest is proof of the\n // current on-disk revision rather than proof that a stale result exists.\n let canonicalFile = cleanFile;\n try {\n canonicalFile = realpathSync(cleanFile);\n } catch {\n // Preserve Vite's original module id for virtual/test files and for a\n // file that disappears again while recovery is checking it.\n }\n const modules = new Set([\n ...(transformer.moduleGraph.getModulesByFile(canonicalFile) ?? []),\n ...(transformer.moduleGraph.getModulesByFile(cleanFile) ?? []),\n ]);\n for (const module of modules) {\n transformer.moduleGraph.invalidateModule(module);\n }\n const result = await transformer.transformRequest(requestId);\n if (!result) return false;\n if (readFileSync(cleanFile, \"utf8\") !== source) return false;\n if (\n canvasModule &&\n (typeof result !== \"object\" ||\n !(\"code\" in result) ||\n typeof result.code !== \"string\" ||\n !hasDefault(result.code))\n )\n return false;\n } catch {\n return false;\n }\n errorServer.clearErrorForModules([file, cleanFile, requestId]);\n server.config.logger.info(\n `[tempo] recovered compile-error module after validated transform: ${cleanFile}`,\n { timestamp: true },\n );\n (clientEnvironment?.hot ?? (server.ws as unknown as HmrSendTarget)).send({\n type: \"full-reload\",\n path: \"*\",\n });\n return true;\n };\n\n // Recovery normally rides the watcher \"change\" event for the repaired file.\n // This poll is the bounded fallback for a repair that produces no usable\n // signal at all: a module whose transform failed can be absent from Vite's\n // module graph, leaving both the watcher pipeline and the missed-change\n // sweep with nothing to observe. While a file's error is active it is\n // re-validated on the sweep's cadence, backing off per file so a file left\n // broken does not keep re-running a doomed transform.\n const compileErrorPollSchedule = new Map<\n string,\n { nextAttemptAtMs: number; intervalMs: number }\n >();\n const pollCompileErrorRecovery = async (\n server: ViteDevServer,\n ): Promise<void> => {\n const activeFiles = new Map(\n errorServer.errorFiles.map((file) => [\n normalizedFileKey(fsPathFromModuleId(file)),\n file,\n ]),\n );\n for (const key of [...compileErrorPollSchedule.keys()]) {\n if (!activeFiles.has(key)) compileErrorPollSchedule.delete(key);\n }\n const nowMs = Date.now();\n for (const [key, file] of activeFiles) {\n const schedule = compileErrorPollSchedule.get(key);\n if (schedule && nowMs < schedule.nextAttemptAtMs) continue;\n if (await recoverActiveCompileError(server, file)) {\n compileErrorPollSchedule.delete(key);\n continue;\n }\n const intervalMs =\n schedule?.intervalMs ?? MISSED_CHANGE_SWEEP_INTERVAL_MS;\n compileErrorPollSchedule.set(key, {\n nextAttemptAtMs: nowMs + intervalMs,\n intervalMs: Math.min(\n intervalMs * 2,\n COMPILE_ERROR_POLL_MAX_INTERVAL_MS,\n ),\n });\n }\n };\n\n return {\n errorServer,\n attach(server) {\n attachedServer = server;\n // Vite buffers a client's subscription until the socket connects. Reply\n // on that same ordered channel so startup errors and later updates have\n // no snapshot/broadcast gap. The SSE endpoint remains for older SDKs.\n server.ws.on?.(VITE_ERROR_SUBSCRIBE_EVENT, (_data, client) => {\n client.send(VITE_ERROR_STATE_EVENT, errorServer.currentError);\n });\n },\n handleRequest(req, res) {\n const url = req.url;\n if (url === \"/__tempo/report-error\" && req.method === \"POST\") {\n readBody(req).then((body) => {\n try {\n errorServer.setError(JSON.parse(body) as TempoViteError);\n } catch {\n // ignore malformed JSON\n }\n res.statusCode = 200;\n res.end(\"ok\");\n });\n return true;\n }\n\n if (url === \"/__tempo/report-clear\" && req.method === \"POST\") {\n errorServer.clearAll();\n res.statusCode = 200;\n res.end(\"ok\");\n return true;\n }\n\n // Allow CORS preflight for SSE endpoint (browser fetches from a different port)\n if (url === \"/__tempo/errors\" && req.method === \"OPTIONS\") {\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"*\",\n });\n res.end();\n return true;\n }\n\n if (url === \"/__tempo/errors\" && req.method === \"GET\") {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Access-Control-Allow-Origin\": \"*\",\n });\n\n // Send current state immediately\n res.write(`data: ${JSON.stringify(errorServer.currentError)}\\n\\n`);\n errorServer.clients.add(res);\n\n req.on(\"close\", () => {\n errorServer.clients.delete(res);\n });\n return true;\n }\n return false;\n },\n recordHmrError(err) {\n errorServer.setError({\n type: \"compile\",\n message: (err?.message as string) ?? \"Unknown error\",\n stack: err?.stack as string | undefined,\n file: (err?.id as string) ?? (err?.loc as { file?: string })?.file,\n frame: err?.frame as string | undefined,\n plugin: err?.plugin as string | undefined,\n loc: err?.loc as\n | { file?: string; line?: number; column?: number }\n | undefined,\n });\n },\n hasActiveCompileError,\n recover: recoverActiveCompileError,\n pollRecovery: pollCompileErrorRecovery,\n reset() {\n compileErrorPollSchedule.clear();\n },\n };\n}\n\n/**\n * The stream on a host with no other tap on Vite's HMR channel (the Nuxt\n * sidecar, R18): it serves the page client and the routes, records what\n * Vite sends (an `error` sets the module's error, an `update` clears the\n * errors of the modules it updates), recovers a repaired file on its watcher\n * update, and polls on the missed-change sweep's cadence for a repair that\n * produces no update at all (a file whose transform failed can be missing\n * from the module graph).\n */\nexport function compileErrorStreamPlugin(): Plugin {\n const stream = createCompileErrorStream();\n const observe = (payload: unknown): void => {\n if (typeof payload !== \"object\" || payload === null) return;\n const typed = payload as {\n type?: unknown;\n err?: Record<string, unknown>;\n updates?: Array<{ path?: unknown }>;\n };\n if (typed.type === \"error\") stream.recordHmrError(typed.err);\n if (typed.type === \"update\") {\n const paths = (typed.updates ?? [])\n .map((update) => update.path)\n .filter((path): path is string => typeof path === \"string\");\n stream.errorServer.clearErrorForModules(paths);\n }\n };\n const tap = (target: HmrSendTarget, tapped: WeakSet<object>): void => {\n if (tapped.has(target)) return;\n tapped.add(target);\n const send = target.send.bind(target);\n target.send = (...args: unknown[]) => {\n observe(args[0]);\n return send(...args);\n };\n };\n return {\n name: \"tempo-compile-error-stream\",\n apply: \"serve\",\n resolveId(id) {\n return id === VITE_ERROR_CLIENT_PATH ? VITE_ERROR_CLIENT_ID : null;\n },\n load(id) {\n return id === VITE_ERROR_CLIENT_ID ? VITE_ERROR_CLIENT_SOURCE : null;\n },\n configureServer(server) {\n stream.attach(server);\n server.middlewares.use((req, res, next) => {\n if (!stream.handleRequest(req, res)) next();\n });\n const tapped = new WeakSet<object>();\n tap(server.ws as unknown as HmrSendTarget, tapped);\n const poll = setInterval(() => {\n void stream.pollRecovery(server);\n }, MISSED_CHANGE_SWEEP_INTERVAL_MS);\n poll.unref?.();\n server.watcher.once(\"close\", () => {\n clearInterval(poll);\n stream.reset();\n });\n // Vite 7+ constructs environment transports after the immediate\n // configureServer hooks; its error middleware sends on the client\n // environment's channel.\n return () => {\n const clientHot = (\n server as ViteDevServer & {\n environments?: { client?: { hot?: HmrSendTarget } };\n }\n ).environments?.client?.hot;\n if (clientHot) tap(clientHot, tapped);\n };\n },\n hotUpdate: {\n order: \"post\",\n async handler(context) {\n if (this.environment.config.consumer !== \"client\") return;\n if (context.type !== \"update\") return;\n if (!stream.hasActiveCompileError(context.file)) return;\n // The full reload recovery sends replaces this update: the module\n // never finished evaluating, so it has no boundary to update.\n if (await stream.recover(context.server, context.file)) return [];\n },\n },\n };\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n","/**\n * The hot-update net a Tempo canvas host needs under a write burst: the\n * rapid same-file replay (`rapid-hot-update-replay.ts`), the missed-change\n * sweep (`missed-change-sweep.ts`) and the module-read gate between them,\n * wired once here. `tempoVitePlugin()` composes `createHotUpdateNet` into\n * its own hooks (adding the compile-error files to the sweep and the\n * compile-error recovery poll to its timer); the Nuxt module installs the\n * same net as the standalone `tempoHotUpdateNetPlugin()` (R13), because a\n * host without it loses watcher events in a burst (the sidecar logged two\n * HMR updates for the four writes of a write/undo/redo/undo round trip, and\n * the board waited on a receipt that never came).\n */\n\nimport { statSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport {\n createMissedChangeSweep,\n type SweepModuleView,\n} from \"./missed-change-sweep.ts\";\nimport { createRapidHotUpdateReplay } from \"./rapid-hot-update-replay.ts\";\n\nexport const HOT_UPDATE_NET_NAME = \"tempo-hot-update-net\";\nexport const HOT_UPDATE_NET_SWEEP_INTERVAL_MS = 3_000;\n\n/** A module id as a filesystem path: no query, no `/@fs/` prefix. */\nexport function fsPathFromModuleId(id: string): string {\n return cleanModuleId(id).replace(/^\\/@fs\\//, \"/\");\n}\n\n/** The single key every half of the net agrees on for a file: the watcher\n * event, the module read that must wait for it and the sweep's stat arrive\n * as differently-spelled ids for the same file. */\nfunction fileKey(file: string): string {\n return fsPathFromModuleId(file).replace(/\\\\/g, \"/\");\n}\n\nexport interface HotUpdateNet {\n /** Snapshot the delivered revision at watcher-event ingress, before\n * async update hooks can overlap a newer write. Coverage is watcher\n * delivery evidence, never browser acknowledgment. */\n recordCoverage(file: string): void;\n /** The fs mtime covered by the most recent watcher event for `file`. */\n lastHotUpdateMtimeMs(file: string): number | undefined;\n /** A hot update with modules: schedules one ordinary watcher replay after\n * a rapid same-file burst. */\n observeUpdate(server: ViteDevServer, file: string): void;\n /** The module-read gate: resolves once the file's burst, if any, settles. */\n settled(id: string): Promise<void>;\n /** Attach the coverage listeners ahead of every other watcher listener. */\n installCoverage(server: ViteDevServer): void;\n /** Start the periodic missed-change sweep over the files the server has\n * served. `listExtraFiles` adds files Vite has not served (a module whose\n * compile failed); `afterSweep` rides the same timer so the two periodic\n * passes never overlap. The interval ends when the HTTP server closes. */\n installSweep(\n server: ViteDevServer,\n options?: {\n sweepIntervalMs?: number;\n listExtraFiles?: () => readonly string[];\n afterSweep?: () => Promise<void>;\n },\n ): void;\n /** Teardown: cancel pending replays, release parked reads, drop coverage. */\n clear(): void;\n}\n\nexport function createHotUpdateNet(): HotUpdateNet {\n const replay = createRapidHotUpdateReplay();\n const covered = new Map<string, number>();\n const recordCoverage = (file: string): void => {\n const cleanFile = fsPathFromModuleId(file);\n const key = fileKey(file);\n try {\n covered.set(key, statSync(cleanFile).mtimeMs);\n } catch {\n covered.delete(key);\n }\n };\n return {\n recordCoverage,\n lastHotUpdateMtimeMs(file) {\n return covered.get(fileKey(file));\n },\n observeUpdate(server, file) {\n replay.observe(fileKey(file), () => {\n server.config.logger.info(\n `[tempo] replaying settled rapid watcher change: ${file}`,\n { timestamp: true },\n );\n server.watcher.emit(\"change\", file);\n });\n },\n settled(id) {\n return replay.settled(fileKey(id));\n },\n installCoverage(server) {\n for (const event of [\"change\", \"add\", \"unlink\"] as const)\n server.watcher?.prependListener?.(event, recordCoverage);\n },\n installSweep(server, options = {}) {\n const cacheDir = server.config.cacheDir\n ?.replace(/\\\\/g, \"/\")\n .replace(/\\/+$/, \"\");\n const sweep = createMissedChangeSweep({\n listServedFiles: () => {\n const files = new Map<string, Iterable<SweepModuleView>>(\n server.moduleGraph?.fileToModulesMap ??\n new Map<string, Set<SweepModuleView>>(),\n );\n for (const extra of options.listExtraFiles?.() ?? []) {\n const cleanFile = fsPathFromModuleId(extra);\n const file = isAbsolute(cleanFile)\n ? cleanFile\n : resolve(server.config.root, cleanFile);\n if (!files.has(file)) files.set(file, []);\n }\n // Optimized dependencies are generated and invalidated by Vite\n // itself, outside its source watcher. Replaying their rewrites as\n // source edits sends spurious React HMR/reloads while a new app is\n // optimizing imports.\n if (cacheDir) {\n for (const file of files.keys()) {\n if (file.replace(/\\\\/g, \"/\").startsWith(`${cacheDir}/`)) {\n files.delete(file);\n }\n }\n }\n dropUnwatched(server, files);\n return files.entries();\n },\n statMtimeMs: async (file) => {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return null;\n }\n },\n emitChange: (file) => {\n server.config?.logger?.info?.(\n `[tempo] re-emitting lost watcher change: ${file}`,\n { timestamp: true },\n );\n server.watcher?.emit?.(\"change\", file);\n },\n lastHotUpdateMtimeMs: (file) => covered.get(fileKey(file)),\n });\n let passRunning = false;\n const timer = setInterval(() => {\n if (passRunning) return;\n passRunning = true;\n void sweep\n .sweep()\n .then(() => options.afterSweep?.())\n .catch(() => {})\n .finally(() => {\n passRunning = false;\n });\n }, options.sweepIntervalMs ?? HOT_UPDATE_NET_SWEEP_INTERVAL_MS);\n timer.unref?.();\n server.httpServer?.once(\"close\", () => clearInterval(timer));\n },\n clear() {\n replay.clear();\n covered.clear();\n },\n };\n}\n\n/** Drop the served files this server's watcher leaves out: a file it does\n * not watch has no event to lose. The Nuxt sidecar serves the app's pages\n * through its route manifest while its watcher watches `app/pages` and\n * excludes the page files, so the sweep re-emitted every write to a page\n * (three times per revision) and the sidecar regenerated its routes for\n * nothing. Only positive evidence drops a file, its directory watched without\n * it; a directory the watcher spells differently (or a watcher without\n * chokidar's `getWatched`) keeps every file a candidate. */\nfunction dropUnwatched(\n server: ViteDevServer,\n files: Map<string, Iterable<SweepModuleView>>,\n): void {\n const watcher = server.watcher as\n | { getWatched?: () => Record<string, readonly string[]> }\n | undefined;\n const watched = watcher?.getWatched?.();\n if (!watched) return;\n for (const file of [...files.keys()]) {\n const entries = watched[dirname(file)];\n if (entries && !entries.includes(basename(file))) files.delete(file);\n }\n}\n\n/** The net as a plugin of its own, for a host whose Vite server Tempo does\n * not otherwise shape (the Nuxt sidecar and the app's own `nuxt dev`). */\nexport function tempoHotUpdateNetPlugin(\n options: { sweepIntervalMs?: number } = {},\n): Plugin {\n const net = createHotUpdateNet();\n return {\n name: HOT_UPDATE_NET_NAME,\n configureServer(server) {\n net.installCoverage(server);\n net.installSweep(server, { sweepIntervalMs: options.sweepIntervalMs });\n server.httpServer?.once(\"close\", () => net.clear());\n },\n // A module read during a burst waits for the terminal disk revision\n // (a transform hook would be too late: its bytes are already read).\n load: {\n async handler(id) {\n if (id.startsWith(\"\\0\")) return null;\n await net.settled(id);\n return null;\n },\n },\n hotUpdate: {\n order: \"post\",\n handler(context) {\n if (context.type === \"update\" && context.modules.length > 0)\n net.observeUpdate(context.server, context.file);\n },\n },\n // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.\n handleHotUpdate: {\n order: \"post\",\n handler(context) {\n if (context.modules.length > 0)\n net.observeUpdate(context.server, context.file);\n },\n },\n };\n}\n","/**\n * Missed file-change sweep — the dev server's self-healing net for LOST\n * watcher events.\n *\n * On loaded machines (CI runners under I/O pressure), chokidar can miss a\n * write entirely. Vite then serves the STALE cached transform of the file to\n * every request — including brand-new documents — forever: no error, no\n * retry, nothing observable client-side (CI-proven: three consecutive host\n * replacements all rendered a token 32s behind the file on disk).\n *\n * The filesystem's mtime is the ground truth the watcher merely relays, so\n * the sweep re-derives the event from it: every interval it stats the files\n * Vite has actually served (`moduleGraph.fileToModulesMap` — bounded by real\n * usage, no directory crawling) and re-emits the watcher \"change\" event\n * chokidar lost. Vite then runs its entire native pipeline (invalidate →\n * hot update → fetch) exactly as if the event had been delivered on time.\n *\n * Deciding a change was DELIVERED needs care under rapid same-file bursts\n * (TEM-1149: ~10 writes 40ms apart froze the canvas one revision behind):\n *\n * - Invalidation timestamps cannot vouch for a specific revision. The\n * guard \"some module's `lastInvalidationTimestamp >= mtime`\" is defeated\n * by a cross-revision interleave: write N's event is delivered at\n * `write(N) + watcher latency`, so whenever that latency exceeds the gap\n * to write N+1, the N invalidation lands at-or-after the N+1 mtime and\n * reads as \"N+1 delivered\" — while N+1's event was the one lost. Vite 7's\n * monotonic HMR clock (which deliberately runs ahead of wall time under\n * rapid calls) widens the window.\n * - The plugin therefore records the file mtime synchronously at watcher\n * event ingress (`lastHotUpdateMtimeMs`), before async update hooks can\n * overlap a newer write. A POST-hook stat could falsely certify that newer\n * revision while an older pending transform remains cacheable. The plugin\n * also schedules one ordinary trailing replay after a rapid same-file burst. Normal updates remain immediate;\n * the replay invalidates intermediate transforms after overlapping server\n * pipelines. A later write either gets its own event or advances past the\n * recorded revision and is recovered by this sweep.\n * The invalidation-timestamp guard remains only as a compatibility fallback\n * when no plugin coverage evidence is available.\n * - A re-emitted watcher event is retried until that server pipeline\n * acknowledges it, bounded per revision in case no listener can process\n * the event. This is intentionally NOT a browser/render acknowledgment:\n * React acceptance is registered synchronously by the separate refresh\n * boundary adapter; this sweep only repairs missing watcher events.\n *\n * Healthy edits never double-fire: the watcher update advances the coverage\n * record past the mtime, and the file is skipped. The\n * sweep never touches module contents, never reloads, and never walks\n * importers — it only restores a lost input signal.\n */\n\n/** What the sweep needs to read per served file. Mirrors the slice of\n * Vite's ModuleNode the decision depends on. */\nexport interface SweepModuleView {\n lastInvalidationTimestamp?: number;\n}\n\nexport interface MissedChangeSweepArgs {\n /** Absolute fs path → modules Vite associates with it. */\n listServedFiles(): Iterable<[string, Iterable<SweepModuleView>]>;\n /** fs mtime in ms, or null when the file is gone/unreadable (skipped —\n * deletions are prune territory, not this sweep's). */\n statMtimeMs(file: string): Promise<number | null>;\n /** Re-emit the lost watcher event. */\n emitChange(file: string): void;\n /** Watcher-pipeline evidence: the fs mtime covered by the most recent\n * hot update. `undefined` falls back to Vite's legacy\n * invalidation-timestamp guard. */\n lastHotUpdateMtimeMs?(file: string): number | undefined;\n /** Clock seam. */\n now?: () => number;\n /** How long a fresh write is given to arrive through the real watcher\n * before the sweep concludes it was lost. Well above chokidar's normal\n * delivery latency so healthy edits never double-fire. */\n watcherGraceMs?: number;\n /** How many times one revision may be re-emitted before going dormant\n * (until the file changes again). Bounds the blast radius when nothing\n * in the server's watcher pipeline can acknowledge the emit. */\n maxEmitsPerRevision?: number;\n}\n\nexport const MISSED_CHANGE_WATCHER_GRACE_MS = 1_000;\nexport const MISSED_CHANGE_MAX_EMITS_PER_REVISION = 3;\n\nexport interface MissedChangeSweep {\n /** Run one sweep pass. Returns the files re-emitted (diagnostics). */\n sweep(): Promise<string[]>;\n}\n\nexport function createMissedChangeSweep(\n args: MissedChangeSweepArgs,\n): MissedChangeSweep {\n const now = args.now ?? Date.now;\n const graceMs = args.watcherGraceMs ?? MISSED_CHANGE_WATCHER_GRACE_MS;\n const maxEmits =\n args.maxEmitsPerRevision ?? MISSED_CHANGE_MAX_EMITS_PER_REVISION;\n // Baseline per file: the mtime the previous pass observed. A file only\n // comes under watch once it ADVANCES past a recorded baseline — the first\n // observation of any file just records it, so a server that starts over\n // pre-existing files never mass-fires.\n const lastSeenMtimeMs = new Map<string, number>();\n // Files under convergence watch: an observed advance that has not yet\n // been proven delivered. Emits are counted per revision so an\n // unacknowledgeable watcher event goes dormant instead of looping.\n const pending = new Map<string, { mtimeMs: number; emits: number }>();\n\n return {\n async sweep() {\n const emitted: string[] = [];\n for (const [file, modules] of args.listServedFiles()) {\n const mtimeMs = await args.statMtimeMs(file);\n if (mtimeMs === null) {\n pending.delete(file);\n continue;\n }\n let previous = lastSeenMtimeMs.get(file);\n if (previous === undefined) {\n const coveredMtimeMs = args.lastHotUpdateMtimeMs?.(file);\n if (coveredMtimeMs === undefined || coveredMtimeMs >= mtimeMs) {\n lastSeenMtimeMs.set(file, mtimeMs);\n continue;\n }\n // The plugin has revision-specific evidence for this served file,\n // and disk is already newer on the sweep's first pass. This happens\n // when a module's initial transform failed and its repair lands\n // before the first interval: treating the repaired mtime as a fresh\n // baseline would permanently hide the lost watcher event. Seed the\n // baseline from the actually covered revision so the ordinary\n // grace/retry path below can recover the newer disk state.\n previous = coveredMtimeMs;\n lastSeenMtimeMs.set(file, coveredMtimeMs);\n }\n if (mtimeMs > previous) {\n // A write this fresh may still be in flight through the real\n // watcher; leave the baseline untouched so the next pass\n // re-judges it once the grace has passed.\n if (now() - mtimeMs < graceMs) continue;\n lastSeenMtimeMs.set(file, mtimeMs);\n } else if (mtimeMs < previous) {\n // mtime moved backwards (revert, mtime-preserving copy) — track\n // it so a future rewrite of the file registers as an advance.\n lastSeenMtimeMs.set(file, mtimeMs);\n }\n const entry = pending.get(file);\n if (mtimeMs <= previous && entry === undefined) continue;\n // Covered by the watcher pipeline? Prefer the revision-specific\n // plugin record; use Vite's timestamp only for legacy callers.\n const hotUpdateMtimeMs = args.lastHotUpdateMtimeMs?.(file);\n let delivered: boolean;\n if (hotUpdateMtimeMs !== undefined) {\n delivered = hotUpdateMtimeMs >= mtimeMs;\n } else {\n delivered = false;\n for (const module of modules) {\n if ((module.lastInvalidationTimestamp ?? 0) >= mtimeMs) {\n delivered = true;\n break;\n }\n }\n }\n if (delivered) {\n pending.delete(file);\n continue;\n }\n const revision =\n entry !== undefined && entry.mtimeMs === mtimeMs\n ? entry\n : { mtimeMs, emits: 0 };\n pending.set(file, revision);\n if (revision.emits >= maxEmits) continue;\n revision.emits += 1;\n args.emitChange(file);\n emitted.push(file);\n }\n return emitted;\n },\n };\n}\n","/**\n * Same-file HMR trailing replay.\n *\n * Vite's server starts overlapping hot-update pipelines during a rapid save\n * burst. Observing two or more same-file events schedules one ordinary watcher\n * replay after the burst, invalidating any intermediate cached transform. The\n * load gate also waits for the terminal disk revision before reading a file\n * whose burst is already in progress. A lone edit remains immediate.\n *\n * The replay itself arrives through the watcher. A one-event allowance keeps\n * it from manufacturing another burst when it overlaps one late real edit.\n * Further real edits still re-arm the mechanism.\n *\n * These are server-side guarantees. Vite's client processes update messages\n * serially, but React's asynchronous accept registration can still drop a\n * queued update's refresh callback; react-refresh-boundary.ts closes that\n * separate gap during module evaluation.\n */\n\nexport const RAPID_HOT_UPDATE_QUIET_MS = 100;\n\ntype Timer = ReturnType<typeof setTimeout>;\n\nexport interface RapidHotUpdateReplay {\n observe(file: string, replay: () => void): void;\n /**\n * Wait until a same-file burst settles before Vite reads module content.\n * Only a genuine burst (two or more events) engages the gate; a single edit\n * waits for nothing. Waiting in a transform hook would be too late because\n * its source bytes have already been read.\n */\n settled(file: string): Promise<void>;\n clear(): void;\n}\n\nexport function createRapidHotUpdateReplay(options?: {\n quietMs?: number;\n schedule?: (callback: () => void, ms: number) => Timer;\n cancel?: (timer: Timer) => void;\n}): RapidHotUpdateReplay {\n const quietMs = options?.quietMs ?? RAPID_HOT_UPDATE_QUIET_MS;\n const schedule = options?.schedule ?? setTimeout;\n const cancel = options?.cancel ?? clearTimeout;\n interface Burst {\n eventCount: number;\n timer?: Timer;\n replay: () => void;\n /** Resolved the moment this burst settles; absent until the burst is real\n * (2+ events), so a single edit allocates nothing and waits for nothing. */\n release?: () => void;\n gate?: Promise<void>;\n /** Fail-safe expiry. A parked module read is a stalled page, so a gate is\n * never allowed to outlive the burst that owns it — this only ever fires\n * if a release is somehow missed. Re-armed on every event so it tracks\n * the burst rather than cutting a long one short. */\n expiry?: Timer;\n }\n const bursts = new Map<string, Burst>();\n\n /** Open (or carry over) this burst's gate once the burst is real. Callers\n * awaiting `settled` block until the burst's quiet window elapses. */\n const armGate = (burst: Burst, previous: Burst | undefined): void => {\n if (burst.eventCount < 2) return;\n if (previous?.gate && previous.release) {\n // The same unsettled burst continuing — carry ONE gate across the whole\n // burst so a waiter armed on event 2 is not released by event 3.\n burst.gate = previous.gate;\n burst.release = previous.release;\n previous.release = undefined;\n if (previous.expiry) cancel(previous.expiry);\n } else {\n burst.gate = new Promise<void>((resolve) => {\n burst.release = resolve;\n });\n }\n burst.expiry = schedule(() => burst.release?.(), quietMs * 2);\n };\n\n return {\n observe(file, replay) {\n const previous = bursts.get(file);\n if (previous?.timer) cancel(previous.timer);\n const burst: Burst = {\n eventCount: (previous?.eventCount ?? 0) + 1,\n replay,\n };\n armGate(burst, previous);\n burst.timer = schedule(() => {\n if (bursts.get(file) !== burst) return;\n bursts.delete(file);\n // Release BEFORE replaying: the replay's own pipeline reads the file\n // through the same gate, so holding it here would deadlock the very\n // update that carries the terminal revision.\n if (burst.expiry) cancel(burst.expiry);\n burst.release?.();\n if (burst.eventCount < 2) return;\n\n // The replay re-enters this observer through Vite's watcher. Start\n // the next window at -1 so that synthetic event plus one late real\n // event still counts as a single real update, not a fresh burst.\n // Give the allowance its own expiry in case the watcher has no\n // listener; a later unrelated edit must not consume it forever.\n const replayAllowance: Burst = {\n eventCount: -1,\n replay: burst.replay,\n };\n replayAllowance.timer = schedule(() => {\n if (bursts.get(file) === replayAllowance) bursts.delete(file);\n }, quietMs);\n bursts.set(file, replayAllowance);\n burst.replay();\n }, quietMs);\n bursts.set(file, burst);\n },\n\n settled(file) {\n return bursts.get(file)?.gate ?? Promise.resolve();\n },\n\n clear() {\n for (const burst of bursts.values()) {\n if (burst.timer) cancel(burst.timer);\n if (burst.expiry) cancel(burst.expiry);\n // Never leave a module read parked on a gate that can no longer be\n // released — a torn-down server must not hang the next request.\n burst.release?.();\n }\n bursts.clear();\n },\n };\n}\n","// The server half of the canvas-host registration receipt: the\n// `/__tempo/canvas-host-registration` route that answers only once Vite\n// serves the generated host wrapper (and, for incremental hosts, the newly\n// registered canvas) from the bytes now on disk. The devserver rewrites\n// `.tempo/tempo-host.tsx` out of process and Vite keeps serving its cached\n// transform until its watcher reports the rename, so a host document loaded\n// in that window would never contain the new canvas.\n//\n// Every Tempo host that runs on a Vite dev server installs this one barrier:\n// `tempoVitePlugin()` from its middleware, and the Nuxt sidecar (whose Vite\n// runs inside Nuxt's dev server) through its own Vite plugin. The client half\n// lives in modules/component-render-pool/canvas-host-registration.ts.\n\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { relative, resolve } from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\n\nimport {\n CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER,\n CANVAS_HOST_REGISTRATION_ENDPOINT,\n normalizeCanvasRegistrationPath,\n} from \"./canvas-host-registration-contract.ts\";\nimport {\n createRegistrationTransforms,\n type RegistrationProgress,\n registrationReply,\n traceSlowRegistration,\n} from \"./canvas-host-registration-work.ts\";\nimport { fsPathFromModuleId } from \"./hot-update-net.ts\";\n\nconst CANVAS_HOST_WRAPPER_URL = \"/.tempo/tempo-host\";\n\nexport function readGeneratedCanvasPaths(source: string): string[] {\n const paths = new Set<string>();\n const canvasPathPattern = /\\bcanvasPath:\\s*(\"(?:\\\\.|[^\"\\\\])*\")/g;\n for (const match of source.matchAll(canvasPathPattern)) {\n try {\n const parsed = JSON.parse(match[1] ?? \"\") as unknown;\n if (typeof parsed !== \"string\") continue;\n const normalized = normalizeCanvasRegistrationPath(parsed);\n if (normalized) paths.add(normalized);\n } catch {\n // The generated wrapper always uses JSON string literals. A malformed\n // match is ignored so the requested path fails the explicit membership\n // check below instead of authorizing an unknown generation.\n }\n }\n return [...paths];\n}\n\nasync function synchronizeCanvasHostRegistrationTransform(\n server: ViteDevServer,\n canvasPath: string,\n): Promise<string | undefined> {\n const wrapperPath = resolve(server.config.root, \".tempo\", \"tempo-host.tsx\");\n let wrapperSource: string;\n try {\n wrapperSource = readFileSync(wrapperPath, \"utf8\");\n } catch (error) {\n throw new Error(\n `Canvas host wrapper is unavailable at ${wrapperPath}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n const registeredCanvasPaths = readGeneratedCanvasPaths(wrapperSource);\n if (!registeredCanvasPaths.includes(canvasPath)) {\n throw Object.assign(\n new Error(\n `Generated canvas host wrapper does not contain ${JSON.stringify(\n canvasPath,\n )}`,\n ),\n { statusCode: 409 },\n );\n }\n\n // Prefer the per-environment Vite 6+ module graph; the mixed server graph is\n // the same operations for the SDK's supported Vite 5 range.\n const canonicalWrapperPath = realpathSync(wrapperPath);\n // A registered path can be a reused preview slot. Its file was just\n // rewritten too, and the filesystem watcher may not have invalidated its\n // previous (often empty) transform yet. Warm that exact module before the\n // wrapper so a new document cannot import the slot's previous contents.\n const modulePattern =\n /\\bcanvasPath:\\s*(\"(?:\\\\.|[^\"\\\\])*\")\\s*,\\s*load:\\s*\\(\\)\\s*=>\\s*import\\(\\s*(\"(?:\\\\.|[^\"\\\\])*\")\\s*\\)/g;\n let moduleUrl: string | undefined;\n const transformer = server.environments?.client ?? server;\n for (const match of wrapperSource.matchAll(modulePattern)) {\n if (normalizeCanvasRegistrationPath(JSON.parse(match[1]!)) !== canvasPath)\n continue;\n const resolvedModule = await transformer.pluginContainer.resolveId(\n JSON.parse(match[2]!),\n wrapperPath,\n );\n if (!resolvedModule) throw new Error(`Cannot resolve canvas ${canvasPath}`);\n const modulePath = fsPathFromModuleId(resolvedModule.id);\n const fsUrl = `/@fs/${modulePath.replace(/^\\/+/, \"\")}`;\n // The URL the page imports, under Vite's public base (`/_nuxt/` in the\n // Nuxt sidecar); the transform request below speaks Vite's base-less\n // module URL.\n moduleUrl = `${viteBasePath(server)}${fsUrl.slice(1)}`;\n await retransformCanvasHostWrapper(\n server,\n transformer,\n realpathSync(modulePath),\n modulePath,\n fsUrl,\n );\n break;\n }\n await retransformCanvasHostWrapper(\n server,\n transformer,\n canonicalWrapperPath,\n wrapperPath,\n );\n return wrapperSource.includes(\"tempo-incremental-canvas-registration\")\n ? moduleUrl\n : undefined;\n}\n\n/** Vite's public base as a path ending in `/`. A dev server's base is a\n * path; one written as a full URL keeps only its path. */\nfunction viteBasePath(server: ViteDevServer): string {\n const base = server.config.base || \"/\";\n const path = base.startsWith(\"/\")\n ? base\n : new URL(base, \"http://tempo.invalid\").pathname;\n return path.endsWith(\"/\") ? path : `${path}/`;\n}\n\n/** The half of a Vite server this barrier drives, satisfied by both a Vite 6+\n * client environment and a Vite 5 dev server. */\nexport type CanvasHostWrapperTransformer<TModule> = {\n moduleGraph: {\n getModulesByFile(file: string): Set<TModule> | undefined;\n invalidateModule(module: TModule): void;\n };\n transformRequest(url: string): Promise<unknown>;\n};\n\nconst registrationTransforms = new WeakMap<\n object,\n ReturnType<typeof createRegistrationTransforms>\n>();\nconst registrationActivity = new WeakMap<ViteDevServer, number>();\n\nfunction registrationProgress(server: ViteDevServer): RegistrationProgress {\n // Vite 6+ exposes the optimizer on the client environment. Older versions\n // without these facts still report actual transform activity and retain the\n // client's bounded no-progress deadline.\n const optimizer = server.environments?.client?.depsOptimizer;\n const phase = optimizer?.scanProcessing\n ? \"scanning\"\n : Object.values(optimizer?.metadata.discovered ?? {}).some(\n (dep) => dep.processing,\n )\n ? \"bundling\"\n : \"transforming\";\n return {\n status: \"compiling\",\n phase,\n progress: registrationActivity.get(server) ?? 0,\n };\n}\n\n/**\n * Vite's official server contract stores transformed code in a module graph.\n * Reuse a receipt only while both disk bytes and graph transforms still match;\n * otherwise invalidate the file's nodes and await a fresh transform.\n */\nasync function retransformCanvasHostWrapper<TModule>(\n server: ViteDevServer,\n transformer: CanvasHostWrapperTransformer<TModule>,\n canonicalWrapperPath: string,\n wrapperPath: string,\n requestUrl = CANVAS_HOST_WRAPPER_URL,\n): Promise<void> {\n let confirm = registrationTransforms.get(transformer);\n if (!confirm) {\n confirm = createRegistrationTransforms();\n registrationTransforms.set(transformer, confirm);\n }\n await confirm(canonicalWrapperPath, () =>\n traceSlowRegistration(\n async () => {\n const modules = () =>\n transformer.moduleGraph.getModulesByFile(canonicalWrapperPath) ??\n transformer.moduleGraph.getModulesByFile(wrapperPath);\n for (const module of modules() ?? []) {\n transformer.moduleGraph.invalidateModule(module);\n }\n const result = await transformer.transformRequest(requestUrl);\n if (!result) {\n throw new Error(\n `Vite did not transform ${requestUrl} after registration`,\n );\n }\n // Retain the graph's actual transformed objects, not just a disk hash.\n // HMR, dependency re-optimization and explicit invalidation retire them.\n const transformed = [...(modules() ?? [])].map(\n (module) =>\n [\n module,\n (module as { transformResult?: unknown }).transformResult,\n ] as const,\n );\n return () =>\n transformed.length > 0 &&\n transformed.every(\n ([module, value]) =>\n value != null &&\n modules()?.has(module) &&\n (module as { transformResult?: unknown }).transformResult ===\n value,\n );\n },\n (status, elapsedMs) => {\n server.config.logger.info(\n `[tempo] canvas registration ${JSON.stringify({\n ...registrationProgress(server),\n status,\n module: relative(server.config.root, canonicalWrapperPath),\n elapsedMs,\n })}`,\n );\n },\n ),\n );\n}\n\nfunction writeCanvasRegistrationResponseHeaders(res: ServerResponse): void {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\n \"Access-Control-Expose-Headers\",\n CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER,\n );\n res.setHeader(CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER, \"1\");\n}\n\n/** Whether `file` is the generated wrapper at `wrapperPath`, generated for\n * incremental registration. A document admits each new canvas through the\n * module URL this barrier returns, so the wrapper's own rewrite is no update\n * for a loaded document: a Vite host returns no modules for it. */\nexport function isIncrementalWrapperFile(\n file: string,\n wrapperPath: string,\n): boolean {\n if (file.replace(/\\\\/g, \"/\") !== wrapperPath.replace(/\\\\/g, \"/\"))\n return false;\n try {\n return readFileSync(file, \"utf8\").includes(\n \"tempo-incremental-canvas-registration\",\n );\n } catch {\n return false;\n }\n}\n\n/**\n * The generated host already owns each lazy import. Refresh its loader when\n * a registered canvas changes, including self-accepted forwarded defaults:\n * the hot update gains the wrapper's modules, invalidated. Keep this in\n * Vite's graph: no evaluated-module registry or runtime HMR feed. Returns\n * nothing when `file` is no canvas the wrapper registers. `sourceRoot` is\n * what the wrapper's canvas paths are relative to.\n */\nexport function withRegisteredCanvasLoader<TModule>(\n file: string,\n paths: { wrapperPath: string; sourceRoot: string },\n graph: CanvasHostWrapperTransformer<TModule>[\"moduleGraph\"],\n modules: TModule[],\n): TModule[] | undefined {\n const canvasPath = relative(paths.sourceRoot, file).replace(/\\\\/g, \"/\");\n let source: string;\n try {\n source = readFileSync(paths.wrapperPath, \"utf8\");\n } catch {\n return;\n }\n if (!readGeneratedCanvasPaths(source).includes(canvasPath)) return;\n const wrappers = graph.getModulesByFile(paths.wrapperPath);\n if (!wrappers?.size) return;\n for (const wrapper of wrappers) graph.invalidateModule(wrapper);\n return [...new Set([...modules, ...wrappers])];\n}\n\n/** Forgets a previous server's receipts and progress. Call from\n * `configureServer`: Vite builds the replacement server on a restart before\n * closing the old one. */\nexport function resetCanvasHostRegistration(server: ViteDevServer): void {\n registrationActivity.set(server, 0);\n registrationTransforms.delete(server.environments?.client ?? server);\n}\n\n/** One transform's worth of progress for the 202 replies opted-in clients\n * poll: a responsive compiler must keep advancing this. Call from every\n * `transform` the host's Vite runs. */\nexport function noteCanvasHostRegistrationActivity(\n server: ViteDevServer,\n): void {\n registrationActivity.set(server, (registrationActivity.get(server) ?? 0) + 1);\n}\n\n/** Answers the registration route (its CORS preflight and the POST) and\n * returns true; returns false for any other request, which the caller passes\n * on. */\nexport function handleCanvasHostRegistrationRequest(\n viteServer: ViteDevServer,\n req: IncomingMessage,\n res: ServerResponse,\n): boolean {\n const url = req.url;\n if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === \"OPTIONS\") {\n writeCanvasRegistrationResponseHeaders(res);\n res.writeHead(204, {\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"content-type\",\n });\n res.end();\n return true;\n }\n\n if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === \"POST\") {\n writeCanvasRegistrationResponseHeaders(res);\n void readBody(req)\n .then(async (body) => {\n const parsed = JSON.parse(body) as {\n canvasPath?: unknown;\n poll?: unknown;\n };\n const canvasPath =\n typeof parsed.canvasPath === \"string\"\n ? normalizeCanvasRegistrationPath(parsed.canvasPath)\n : \"\";\n if (!canvasPath) {\n throw Object.assign(\n new Error(\"canvasPath must be a non-empty string\"),\n { statusCode: 400 },\n );\n }\n let moduleUrl: string | undefined;\n const progress = await registrationReply(\n synchronizeCanvasHostRegistrationTransform(\n viteServer,\n canvasPath,\n ).then((url) => {\n moduleUrl = url;\n }),\n () => registrationProgress(viteServer),\n parsed.poll === true,\n );\n res.statusCode = progress ? 202 : 200;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.end(\n JSON.stringify(\n progress ?? { canvasPath, ...(moduleUrl ? { moduleUrl } : {}) },\n ),\n );\n })\n .catch((error: unknown) => {\n res.statusCode =\n typeof error === \"object\" &&\n error !== null &&\n \"statusCode\" in error &&\n typeof error.statusCode === \"number\"\n ? error.statusCode\n : 500;\n res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n res.end(error instanceof Error ? error.message : String(error));\n });\n return true;\n }\n\n return false;\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n","// Wire vocabulary of the canvas-host registration receipt served by the Tempo\n// Vite plugin: the endpoint a client posts a canvas identity to, the response\n// header that proves this host implements the transform barrier at all, and\n// the identity normalization both sides must agree on.\n//\n// The client half lives in modules/component-render-pool/canvas-host-registration.ts.\n// tempo-sdk is published into user workspaces and cannot depend on a desktop-side\n// module, so that package mirrors these values and pins them against this file in\n// modules/component-render-pool/canvas-host-registration-contract.test.ts —\n// changing either copy alone fails that test.\n\nexport const CANVAS_HOST_REGISTRATION_ENDPOINT =\n \"/__tempo/canvas-host-registration\";\n\nexport const CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER =\n \"x-tempo-canvas-host-registration\";\n\n/**\n * Reduce a canvas identity to the workspace-relative, forward-slashed form the\n * generated host wrapper records, so a client's path and the runtime's\n * advertised paths compare as strings.\n */\nexport function normalizeCanvasRegistrationPath(canvasPath: string): string {\n return canvasPath\n .trim()\n .replace(/\\\\/g, \"/\")\n .replace(/^\\.\\/+/, \"\")\n .replace(/^\\/+/, \"\");\n}\n","import { readFileSync } from \"node:fs\";\n\n/** Fast/reused registrations stay silent. Slow work emits once while pending\n * and once when it settles, even if the client stopped polling meanwhile. */\nexport async function traceSlowRegistration<T>(\n work: () => Promise<T>,\n report: (status: \"pending\" | \"ready\" | \"error\", elapsedMs: number) => void,\n): Promise<T> {\n const startedAt = performance.now();\n let slow = false;\n const timer = setTimeout(() => {\n slow = true;\n report(\"pending\", Math.round(performance.now() - startedAt));\n }, 5_000);\n const settled = (status: \"ready\" | \"error\") => {\n const elapsedMs = Math.round(performance.now() - startedAt);\n // CPU-bound compilation can prevent the pending timer from firing before\n // its promise settles. Still record that expensive work.\n if (slow || elapsedMs >= 5_000) report(status, elapsedMs);\n };\n try {\n const result = await work();\n settled(\"ready\");\n return result;\n } catch (error) {\n settled(\"error\");\n throw error;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Receipts belong to one Vite environment. Disk bytes AND Vite's transform\n * identity must still match; a missed watcher or an invalidated graph cannot\n * turn a previous acknowledgement into permission to serve stale code. */\nexport function createRegistrationTransforms() {\n const receipts = new Map<\n string,\n {\n source: string;\n result: Promise<void>;\n pending: boolean;\n current: () => boolean;\n }\n >();\n return async function confirm(\n file: string,\n transform: () => Promise<() => boolean>,\n ): Promise<void> {\n const source = readFileSync(file, \"utf8\");\n const previous = receipts.get(file);\n if (\n previous?.source === source &&\n (previous.pending || previous.current())\n ) {\n return previous.result;\n }\n const receipt = {\n source,\n pending: true,\n current: () => false,\n result: Promise.resolve(),\n };\n // Publish before starting work so concurrent HTTP requests join it.\n receipts.set(file, receipt);\n receipt.result = Promise.resolve()\n .then(async () => {\n receipt.current = await transform();\n receipt.pending = false;\n })\n .catch((error) => {\n if (receipts.get(file) === receipt) receipts.delete(file);\n throw error;\n });\n return receipt.result;\n };\n}\n\nexport type RegistrationProgress = {\n status: \"compiling\";\n progress: number;\n phase: \"scanning\" | \"bundling\" | \"transforming\";\n};\n\n/** A quick acknowledgement is not a completed registration. Only opted-in\n * clients receive progress; released clients still await the final receipt. */\nexport async function registrationReply(\n work: Promise<void>,\n progress: () => RegistrationProgress,\n poll: boolean,\n intervalMs = 1_000,\n): Promise<RegistrationProgress | null> {\n if (!poll) {\n await work;\n return null;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work.then(() => null),\n new Promise<RegistrationProgress>((resolve) => {\n timer = setTimeout(() => resolve(progress()), intervalMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n","import { localPrebuiltAliases } from \"./local-prebuilt-aliases\";\nimport {\n applyManagedCanvasDependencyScan,\n excludeTempoHostFromAppDependencyScan,\n} from \"./canvas-dependency-scan\";\nimport {\n type CompileErrorStream,\n createCompileErrorStream,\n type TempoErrorServer,\n} from \"./compile-error-stream\";\nimport {\n type CanvasHostWrapperTransformer,\n handleCanvasHostRegistrationRequest,\n isIncrementalWrapperFile,\n noteCanvasHostRegistrationActivity,\n resetCanvasHostRegistration,\n withRegisteredCanvasLoader,\n} from \"./canvas-host-registration-barrier\";\nimport {\n existsSync,\n type FSWatcher as NodeFsWatcher,\n readFileSync,\n realpathSync,\n statSync,\n watch as watchFileSystem,\n} from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createFilter, type FilterPattern } from \"@rollup/pluginutils\";\nimport type { Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport type {\n ElementInfo,\n PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport { TEMPO_INTERACT_FRAME_NAME } from \"./canvas/interact-frame.ts\";\nimport { createJsxModuleAnnotation } from \"./jsx-module-annotation.ts\";\nimport { createPrunedModuleDeletionGuard } from \"./pruned-module-deletion.ts\";\nimport {\n createFlutterForwarding,\n FLUTTER_HOST_WATCH_IGNORE,\n readFlutterDevServerUrl,\n watchFlutterRelaunches,\n} from \"./flutter-proxy.ts\";\nimport { createHmrGenerationFence } from \"./hmr-generation-fence.ts\";\nimport {\n createTempoHostIdentity,\n TEMPO_HOST_IDENTITY_CAPABILITY_HEADER,\n TEMPO_HOST_IDENTITY_ENDPOINT,\n TEMPO_VUE_ANNOTATION_PLUGIN_NAME,\n TEMPO_WORKSPACE_NONCE_META_NAME,\n} from \"./host-identity.ts\";\nimport {\n createHotUpdateNet,\n fsPathFromModuleId,\n HOT_UPDATE_NET_SWEEP_INTERVAL_MS,\n} from \"./hot-update-net.ts\";\nimport { installSynchronousReactRefreshBoundary } from \"./react-refresh-boundary.ts\";\nimport { createSdkFileMatcher } from \"./sdk-package-files.ts\";\nimport { preservePendingViteModuleUpdates } from \"./vite-client-pending-updates.ts\";\nimport {\n createTailwindScanNet,\n type ScanNetCssEntry,\n} from \"./tailwind-scan-net.ts\";\nimport {\n VITE_ERROR_CLIENT_ID,\n VITE_ERROR_CLIENT_PATH,\n VITE_ERROR_CLIENT_SOURCE,\n} from \"./vite-error-transport.ts\";\n\nconst DEFAULT_INCLUDE: FilterPattern = [\"**/*.tsx\", \"**/*.jsx\"];\nconst DEFAULT_EXCLUDE: FilterPattern = [\"**/node_modules/**\"];\nconst ROOT_META_NAME = \"tempo-project-root\";\nconst SOURCE_IDENTITY_ROOT_META_NAME = \"tempo-source-identity-root\";\nconst INTERACT_PROJECTION_CLIENT_PATH = \"/@tempo/interact-projection\";\nconst INTERACT_PROJECTION_CLIENT_ID = \"\\0tempo:interact-projection\";\nconst INTERACT_PROJECTION_SDK_SPECIFIER =\n \"tempo-sdk/canvas/interact-projection\";\n\n/**\n * The interact-projection client module shipped INSIDE this plugin's own\n * package, located relative to this very file: `canvas/interact-projection.ts`\n * beside the source entry in a workspace checkout, `canvas/interact-projection.js`\n * beside `dist/index.js` in the published package.\n *\n * The virtual client module must never depend on the HOST APP's dependency\n * tree for this import: an app that doesn't declare tempo-sdk in its own\n * browser-resolvable node_modules (pnpm isolation, hoisted installs) — or\n * holds a version predating the `./canvas/interact-projection` export — would\n * otherwise break every route storyboard with\n * `Failed to resolve import \"tempo-sdk/canvas/interact-projection\"` (TEM-1224).\n */\nfunction resolveOwnInteractProjectionModule(): string | null {\n const selfDir = dirname(fileURLToPath(import.meta.url));\n for (const candidate of [\n join(selfDir, \"canvas\", \"interact-projection.ts\"),\n join(selfDir, \"canvas\", \"interact-projection.js\"),\n ]) {\n // Forward slashes: vite module ids are posix-style on every platform, and\n // importing `normalizePath` from \"vite\" would add a runtime vite import\n // the packed SDK cannot satisfy.\n if (existsSync(candidate)) return candidate.replace(/\\\\/g, \"/\");\n }\n return null;\n}\nconst INTERACT_PROJECTION_BOOTSTRAP = `\n(function() {\n if (window.parent === window || (window.name !== ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} && !window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) return;\n var roots = new Map();\n var existing = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;\n if (existing) {\n if (existing.__tempoPendingFiberRoots) return;\n existing.__tempoPendingFiberRoots = roots;\n var originalCommit = existing.onCommitFiberRoot && existing.onCommitFiberRoot.bind(existing);\n existing.onCommitFiberRoot = function(rendererId, root) {\n if (existing.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);\n if (originalCommit) originalCommit.apply(null, arguments);\n };\n return;\n }\n window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {\n supportsFiber: true,\n renderers: new Map(),\n __tempoPendingFiberRoots: roots,\n inject: function(renderer) {\n var id = this.renderers.size + 1;\n this.renderers.set(id, renderer);\n return id;\n },\n onCommitFiberRoot: function(rendererId, root) {\n if (this.__tempoPendingFiberRoots === roots) roots.set(rendererId, root);\n },\n onCommitFiberUnmount: function() {},\n checkDCE: function() {},\n onScheduleFiberRoot: function() {}\n };\n})();`;\n\nfunction cleanModuleId(id: string): string {\n return id.replace(/[?#].*$/, \"\");\n}\n\n/** Strip Vite's module-id decorations (query/hash suffix, `/@fs/` prefix) down\n * to the filesystem path `statSync` and the watcher speak. */\n\nfunction isCanvasHostRequest(requestPath: string): boolean {\n const url = new URL(requestPath, \"http://tempo.local\");\n return url.pathname.replace(/\\/+$/, \"\") === \"/tempo-host\";\n}\n\nfunction isDeclarativeCanvasHostRequest(requestPath: string): boolean {\n if (!isCanvasHostRequest(requestPath)) return false;\n const params = new URL(requestPath, \"http://tempo.local\").searchParams;\n const canvasPath =\n params.get(\"canvasPath\")?.trim() ??\n params.get(\"pageFile\")?.trim() ??\n params.get(\"importPath\")?.trim();\n const storyboardId =\n params.get(\"storyboardId\")?.trim() ??\n params.get(\"exportName\")?.trim() ??\n params.get(\"importName\")?.trim();\n return !canvasPath || !storyboardId;\n}\n\ntype HmrSendTarget = {\n send: (...args: unknown[]) => unknown;\n};\n\ntype UnresolvedImport = {\n specifier: string;\n importer: string;\n packageName?: string;\n};\n\nconst MAX_UNRESOLVED_IMPORTS = 256;\n\n// Vite's default `resolve.extensions` order, used to prove an extensionless\n// relative import has become resolvable without asking Vite's resolver.\nconst RELATIVE_IMPORT_RESOLVE_EXTENSIONS = [\n \".mjs\",\n \".js\",\n \".mts\",\n \".ts\",\n \".jsx\",\n \".tsx\",\n \".json\",\n] as const;\nconst UNRESOLVED_IMPORT_WATCH_REARM_MS = 1_000;\n\nfunction isRelativeImportSpecifier(specifier: string): boolean {\n return specifier.startsWith(\"./\") || specifier.startsWith(\"../\");\n}\n\nfunction barePackageName(specifier: string): string | undefined {\n if (\n !specifier ||\n specifier.startsWith(\".\") ||\n specifier.startsWith(\"/\") ||\n specifier.startsWith(\"\\0\") ||\n specifier.startsWith(\"#\") ||\n specifier.includes(\":\")\n ) {\n return undefined;\n }\n\n const segments = specifier.split(\"/\");\n const packageName = specifier.startsWith(\"@\")\n ? segments.length >= 2 && segments[0] !== \"@\" && segments[1]\n ? `${segments[0]}/${segments[1]}`\n : undefined\n : segments[0];\n return packageName && /^@?[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(packageName)\n ? packageName\n : undefined;\n}\n\nfunction resolvedIdMatchesFile(id: string, file: string): boolean {\n const resolvedFile = fsPathFromModuleId(id);\n try {\n return realpathSync.native(resolvedFile) === realpathSync.native(file);\n } catch {\n return resolvedFile.replace(/\\\\/g, \"/\") === file.replace(/\\\\/g, \"/\");\n }\n}\n\nfunction resolveCanonicalRoot(root: string): string {\n try {\n return realpathSync.native(root);\n } catch {\n return root;\n }\n}\n\nfunction hasRootMetaTag(html: string): boolean {\n return /<meta[^>]+name=[\"']tempo-project-root[\"'][^>]*>/i.test(html);\n}\n\nfunction hasSourceIdentityRootMetaTag(html: string): boolean {\n return /<meta[^>]+name=[\"']tempo-source-identity-root[\"'][^>]*>/i.test(html);\n}\n\nfunction hasWorkspaceNonceMetaTag(html: string): boolean {\n return new RegExp(\n `<meta[^>]+name=[\"']${TEMPO_WORKSPACE_NONCE_META_NAME}[\"'][^>]*>`,\n \"i\",\n ).test(html);\n}\n\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface TempoAnnotateOptions {\n /** Annotation root when an app runs below the workspace root. */\n root?: string;\n /** Explicit integration-owned activation; otherwise TEMPO selects development instrumentation. */\n enabled?: boolean;\n computeAnnotatedProps?: ComputeAnnotatedProps;\n include?: FilterPattern;\n exclude?: FilterPattern;\n /** Root published for workspace-relative diagnostic source matching.\n * Defaults to Vite's resolved root. This does not change Vite URL paths,\n * JSX annotation paths, or `tempo-project-root`. */\n sourceIdentityRoot?: string;\n}\n\n/**\n * Whether this server runs `tempoVuePlugin()` enabled. It is a separate\n * plugin the app adds beside this one, so this plugin being active proves\n * nothing about `.vue` stamps; a Vue app's route verification needs both.\n */\nfunction runsVueSourceAnnotation(\n plugins: readonly { name?: string; api?: unknown }[] | undefined,\n): boolean {\n return (plugins ?? []).some(\n (plugin) =>\n plugin.name === TEMPO_VUE_ANNOTATION_PLUGIN_NAME &&\n (plugin.api as { enabled?: unknown } | undefined)?.enabled === true,\n );\n}\n\nfunction handleTempoMiddleware(\n compileErrors: CompileErrorStream,\n viteServer: ViteDevServer,\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) {\n const url = req.url;\n if (!url?.startsWith(\"/__tempo/\")) return next();\n\n if (url === TEMPO_HOST_IDENTITY_ENDPOINT && req.method === \"GET\") {\n const identity = createTempoHostIdentity(\"vite\", {\n root: viteServer.config?.root,\n pluginActive: true,\n ...(runsVueSourceAnnotation(viteServer.config?.plugins)\n ? { capabilities: { vueSourceAnnotation: 1 } }\n : {}),\n });\n res.statusCode = 200;\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.setHeader(TEMPO_HOST_IDENTITY_CAPABILITY_HEADER, \"1\");\n res.end(JSON.stringify(identity));\n return;\n }\n\n if (handleCanvasHostRegistrationRequest(viteServer, req, res)) return;\n if (compileErrors.handleRequest(req, res)) return;\n\n next();\n}\n\n/** How often the missed-change sweep re-derives lost watcher events from\n * fs mtimes (see missed-change-sweep.ts). Stat-only over the files Vite has\n * actually served, so each pass costs microseconds per file. */\nconst MISSED_CHANGE_SWEEP_INTERVAL_MS = HOT_UPDATE_NET_SWEEP_INTERVAL_MS;\n\n/** Install the Tailwind new-file rescan net (see tailwind-scan-net.ts): a\n * watcher event for a scannable source file that some Tailwind-scanning CSS\n * module does not yet track as a watch dep re-emits the watcher \"change\"\n * for that CSS file, forcing the Tailwind plugin to re-run its scanner and\n * register the file. Without this, classes written into a file created\n * after the scanner's last pass never compile (TEM-1242 — drawn frames\n * rendering 0×0 in canvases/components created mid-session). */\nfunction installTailwindScanNet(server: ViteDevServer): void {\n const net = createTailwindScanNet({\n listCssEntries: function* (): Iterable<ScanNetCssEntry> {\n const fileToModules =\n server.moduleGraph?.fileToModulesMap ??\n new Map<string, Set<TailwindScanModuleView>>();\n for (const [file, modules] of fileToModules) {\n if (!file.endsWith(\".css\")) continue;\n // The Tailwind plugin registers every scanned file (and its source\n // globs) via addWatchFile; Vite folds those into the CSS module's\n // importedModules — glob patterns appear as nodes whose file/url is\n // the pattern itself. One entry PER module node (query variants,\n // environments): each node has its own Tailwind scanner instance,\n // and unioning them would let a node that already tracks a file\n // mask a sibling whose scanner predates it.\n for (const module of modules as Iterable<TailwindScanModuleView>) {\n const deps: string[] = [];\n for (const imported of module.importedModules ?? []) {\n const dep = imported.file ?? imported.url ?? imported.id;\n if (dep) deps.push(dep);\n }\n yield { cssFile: file, deps };\n }\n }\n },\n emitChange: (cssFile) => {\n server.config?.logger?.info?.(\n `[tempo] new source file outside the Tailwind scan — re-emitting change: ${cssFile}`,\n { timestamp: true },\n );\n server.watcher?.emit?.(\"change\", cssFile);\n },\n });\n const onWatcherFile = (file: string) => {\n net.handleWatcherFile(file);\n };\n server.watcher?.on?.(\"add\", onWatcherFile);\n server.watcher?.on?.(\"change\", onWatcherFile);\n server.httpServer?.once(\"close\", () => {\n server.watcher?.off?.(\"add\", onWatcherFile);\n server.watcher?.off?.(\"change\", onWatcherFile);\n net.dispose();\n });\n}\n\n/** The slice of Vite's ModuleNode the Tailwind scan net reads: the imported\n * modules its transform registered (addWatchFile'd scan files and source\n * globs land there). */\ninterface TailwindScanModuleView {\n importedModules?: Iterable<{\n file?: string | null;\n url?: string;\n id?: string | null;\n }>;\n}\n\nexport function tempoVitePlugin(options: TempoAnnotateOptions = {}): Plugin {\n // The plugin is a complete no-op unless the TEMPO env var is set.\n // This lets users keep tempoVitePlugin() in their vite config permanently\n // while only paying for annotation when running via Tempo's start script\n // (which sets TEMPO=true).\n const enabled = options.enabled ?? !!process.env.TEMPO;\n // Tempo's canvas dev server sets this when the project declares a Flutter\n // app: the origin of its `flutter run -d web-server` (flutter-proxy.ts).\n const flutterTarget = enabled ? readFlutterDevServerUrl(process.env) : null;\n\n const include =\n options.include === undefined ? DEFAULT_INCLUDE : options.include;\n const exclude =\n options.exclude === undefined ? DEFAULT_EXCLUDE : options.exclude;\n // The SDK's own modules are never transformed, however the project\n // resolves them and whatever include/exclude it configures.\n const isSdkFile = createSdkFileMatcher();\n const userFilter = createFilter(include, exclude);\n const filter = (id: string) => userFilter(id) && !isSdkFile(id);\n const userControlsFilter = createFilter(\n [\"**/*.tsx\", \"**/*.jsx\", \"**/*.ts\", \"**/*.js\"],\n exclude,\n );\n const controlsFilter = (id: string) =>\n userControlsFilter(id) && !isSdkFile(id);\n // Astro component descriptors read controls metadata from files the host\n // never imports; a change to one of them invalidates the descriptor.\n const astroDescriptorDependencies = new Map<string, Set<string>>();\n const invalidateAstroDescriptors = <TModule>(\n file: string,\n graph: {\n getModuleById(id: string): TModule | undefined;\n invalidateModule(module: TModule): void;\n },\n modules: TModule[],\n ) => {\n const affected = new Set(modules);\n for (const [id, dependencies] of astroDescriptorDependencies)\n if (dependencies.has(file)) {\n const module = graph.getModuleById(id);\n if (module) {\n graph.invalidateModule(module);\n affected.add(module);\n }\n }\n return [...affected];\n };\n\n let canonicalRoot = process.cwd();\n // The per-module annotation, shared with the Nuxt sidecar (R12). It owns\n // the controls-declaring modules and the default-export identities served,\n // which the post-order hot-update hooks below compare.\n const jsxModuleAnnotation = createJsxModuleAnnotation({\n stampedFilepath: (cleanId) =>\n filter(cleanId) ? relative(canonicalRoot, cleanId) : null,\n transformsControls: controlsFilter,\n computeAnnotatedProps: options.computeAnnotatedProps,\n });\n let sourceIdentityRoot = canonicalRoot;\n let command: ResolvedConfig[\"command\"] = \"serve\";\n let hmrEnabled = true;\n const compileErrors = createCompileErrorStream({\n onErrorFile: (file) => pinErroneousRevisionCoverage(file),\n });\n const unresolvedImports = new Map<string, UnresolvedImport>();\n let devServer: ViteDevServer | undefined;\n const unresolvedImportWatchers = new Map<\n string,\n { watcher: NodeFsWatcher; recursive: boolean }\n >();\n let unresolvedImportResolutionScheduled = false;\n let unresolvedImportResolutionRunning = false;\n let rerunUnresolvedImportResolution = false;\n let unresolvedImportWatchRearmTimer: ReturnType<typeof setTimeout> | null =\n null;\n const processedUpdatePayloads = new WeakSet<object>();\n const prunedModuleDeletion = createPrunedModuleDeletionGuard();\n const hmrGenerationFence = createHmrGenerationFence();\n // Vite launches watcher-event pipelines concurrently. Preserve normal HMR\n // latency, but replay one terminal update after a rapid same-file burst so\n // an earlier pipeline can never remain applied last in the browser.\n // Revision-specific evidence consumed by the missed-change sweep lives in\n // the net too: watcher-event coverage, not a claim that a browser visibly\n // rendered the revision; rapid client application races are repaired by\n // the trailing replay. One home with the Nuxt module (hot-update-net.ts).\n const hotUpdateNet = createHotUpdateNet();\n const recordHotUpdateCoverage = hotUpdateNet.recordCoverage;\n /** Pin the revision that broke a module as watcher-covered. Coverage is what\n * separates a repair from the break itself: the broken revision counts as\n * covered so only a LATER revision on disk reads as a repair. The pin\n * happens once per error — Vite re-sends the same error after the user has\n * already fixed the file, and re-stamping on that duplicate would move\n * coverage onto the repaired revision and hide the repair for good. */\n const pinErroneousRevisionCoverage = (file: string): void => {\n recordHotUpdateCoverage(file);\n };\n // Silent stale-rename repair: rewriting a default export's identity\n // (rename, named → anonymous) keeps the module a valid Fast Refresh\n // boundary, so Vite self-accepts the update while react-refresh finds no\n // family continuation — the OLD component keeps rendering with no error\n // for any client-side recovery to latch on. Only a document reload heals\n // it, so when the identity Vite last served provably changed on disk,\n // send one public full-reload (same shape as the missing-import fallback\n // above). Exactly-once: the cache advances on every comparison, so a\n // given rewrite can fire only on the hot update that delivered it, and\n // the reload's re-transform retains that advanced identity.\n const repairDefaultExportIdentityRewrite = async (context: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean> => {\n if (!(await jsxModuleAnnotation.defaultExportIdentityRewritten(context)))\n return false;\n devServer?.ws.send({ type: \"full-reload\", path: \"*\" });\n return true;\n };\n\n // The incremental wrapper's HMR rules, shared with the Nuxt sidecar\n // (canvas-host-registration-barrier.ts).\n const wrapperPath = () => resolve(canonicalRoot, \".tempo\", \"tempo-host.tsx\");\n const isIncrementalRegistration = (file: string) =>\n isIncrementalWrapperFile(file, wrapperPath());\n const invalidateCanvasLoader = <TModule>(\n file: string,\n graph: CanvasHostWrapperTransformer<TModule>[\"moduleGraph\"],\n modules: TModule[],\n ): TModule[] | undefined =>\n withRegisteredCanvasLoader(\n file,\n { wrapperPath: wrapperPath(), sourceRoot: sourceIdentityRoot },\n graph,\n modules,\n );\n\n const rememberUnresolvedImport = (\n specifier: string,\n importer: string,\n packageName?: string,\n ): void => {\n const key = `${importer}\\0${specifier}`;\n unresolvedImports.delete(key);\n unresolvedImports.set(key, { specifier, importer, packageName });\n while (unresolvedImports.size > MAX_UNRESOLVED_IMPORTS) {\n const oldestKey = unresolvedImports.keys().next().value;\n if (oldestKey === undefined) break;\n unresolvedImports.delete(oldestKey);\n }\n syncUnresolvedImportWatcher();\n };\n\n const forgetUnresolvedImportsFrom = (file: string): void => {\n for (const [key, unresolved] of unresolvedImports) {\n if (resolvedIdMatchesFile(unresolved.importer, file)) {\n unresolvedImports.delete(key);\n }\n }\n syncUnresolvedImportWatcher();\n };\n\n const closeUnresolvedImportWatcher = (path: string): void => {\n unresolvedImportWatchers.get(path)?.watcher.close();\n unresolvedImportWatchers.delete(path);\n };\n\n const cancelUnresolvedImportWatchRearm = (): void => {\n if (unresolvedImportWatchRearmTimer === null) return;\n clearTimeout(unresolvedImportWatchRearmTimer);\n unresolvedImportWatchRearmTimer = null;\n };\n\n const scheduleUnresolvedImportWatchRearm = (): void => {\n if (\n unresolvedImportWatchRearmTimer !== null ||\n !devServer ||\n unresolvedImports.size === 0\n ) {\n return;\n }\n unresolvedImportWatchRearmTimer = setTimeout(() => {\n unresolvedImportWatchRearmTimer = null;\n if (devServer && unresolvedImports.size > 0) {\n syncUnresolvedImportWatcher();\n // The rearm tick is also a bounded fallback when the platform cannot\n // allocate another fs watcher (for example EMFILE under a busy dev\n // session). Resolver success still gates importer reprocessing.\n scheduleUnresolvedImportResolution();\n }\n }, UNRESOLVED_IMPORT_WATCH_REARM_MS);\n unresolvedImportWatchRearmTimer.unref?.();\n };\n\n const closeUnresolvedImportWatchers = (): void => {\n cancelUnresolvedImportWatchRearm();\n for (const path of [...unresolvedImportWatchers.keys()]) {\n closeUnresolvedImportWatcher(path);\n }\n };\n\n const hasUnresolvedBarePackages = (): boolean =>\n [...unresolvedImports.values()].some(\n (unresolved) => unresolved.packageName !== undefined,\n );\n\n const packageWatchTarget = (\n unresolved: UnresolvedImport & { packageName: string },\n ): string => {\n let candidate = dirname(cleanModuleId(unresolved.importer));\n let nearestPackageRoot: string | undefined;\n while (true) {\n try {\n if (statSync(join(candidate, \"node_modules\")).isDirectory()) {\n return join(candidate, \"node_modules\", unresolved.packageName);\n }\n } catch {\n // Keep walking through the same lookup ancestry Vite/Node uses.\n }\n if (nearestPackageRoot === undefined) {\n try {\n if (statSync(join(candidate, \"package.json\")).isFile()) {\n nearestPackageRoot = candidate;\n }\n } catch {\n // The importer may live above the nearest package boundary.\n }\n }\n const parent = dirname(candidate);\n if (parent === candidate) break;\n candidate = parent;\n }\n return join(\n nearestPackageRoot ?? canonicalRoot,\n \"node_modules\",\n unresolved.packageName,\n );\n };\n\n const unresolvedImportWatchTarget = (\n unresolved: UnresolvedImport,\n ): string => {\n return unresolved.packageName\n ? packageWatchTarget(\n unresolved as UnresolvedImport & { packageName: string },\n )\n : resolve(\n dirname(cleanModuleId(unresolved.importer)),\n cleanModuleId(unresolved.specifier),\n );\n };\n\n const nearestExistingDirectory = (target: string): string | undefined => {\n let candidate = target;\n while (true) {\n try {\n if (statSync(candidate).isDirectory()) return candidate;\n } catch {\n // Promote the one watcher as missing directories are created.\n }\n const parent = dirname(candidate);\n if (parent === candidate) return undefined;\n candidate = parent;\n }\n };\n\n function syncUnresolvedImportWatcher(): void {\n if (!devServer || unresolvedImports.size === 0) {\n closeUnresolvedImportWatchers();\n return;\n }\n\n const desired = new Map<string, { recursive: boolean }>();\n for (const unresolved of unresolvedImports.values()) {\n const target = unresolvedImportWatchTarget(unresolved);\n const watchPath = nearestExistingDirectory(target);\n if (!watchPath) continue;\n const previous = desired.get(watchPath);\n desired.set(watchPath, {\n recursive: previous?.recursive === true || watchPath === target,\n });\n }\n\n for (const [path, existing] of [...unresolvedImportWatchers]) {\n const next = desired.get(path);\n if (!next || next.recursive !== existing.recursive) {\n closeUnresolvedImportWatcher(path);\n }\n }\n for (const [path, options] of desired) {\n if (unresolvedImportWatchers.has(path)) continue;\n try {\n const watcher = watchFileSystem(\n path,\n { recursive: options.recursive },\n scheduleUnresolvedImportResolution,\n );\n unresolvedImportWatchers.set(path, {\n watcher,\n recursive: options.recursive,\n });\n watcher.on(\"error\", () => {\n closeUnresolvedImportWatcher(path);\n scheduleUnresolvedImportWatchRearm();\n });\n if (options.recursive) scheduleUnresolvedImportResolution();\n } catch {\n closeUnresolvedImportWatcher(path);\n scheduleUnresolvedImportWatchRearm();\n }\n }\n if (\n [...desired.keys()].every((path) => unresolvedImportWatchers.has(path))\n ) {\n cancelUnresolvedImportWatchRearm();\n }\n }\n\n function scheduleUnresolvedImportResolution(): void {\n if (\n unresolvedImportResolutionScheduled ||\n unresolvedImportResolutionRunning\n ) {\n rerunUnresolvedImportResolution = true;\n return;\n }\n unresolvedImportResolutionScheduled = true;\n queueMicrotask(() => {\n unresolvedImportResolutionScheduled = false;\n void runUnresolvedImportResolution();\n });\n }\n\n async function runUnresolvedImportResolution(): Promise<void> {\n const server = devServer;\n if (!server || unresolvedImportResolutionRunning) return;\n unresolvedImportResolutionRunning = true;\n try {\n do {\n rerunUnresolvedImportResolution = false;\n syncUnresolvedImportWatcher();\n let resolvedImportInPass = false;\n\n for (const [key, unresolved] of [...unresolvedImports]) {\n let file: string | undefined;\n if (isRelativeImportSpecifier(unresolved.specifier)) {\n const suffixIndex = unresolved.specifier.search(/[?#]/);\n const relativePath =\n suffixIndex < 0\n ? unresolved.specifier\n : unresolved.specifier.slice(0, suffixIndex);\n const candidate = resolve(\n dirname(cleanModuleId(unresolved.importer)),\n relativePath,\n );\n // Extensionless imports (`./LateDep`) are the common shape for\n // source files, so the exact path is probed alongside Vite's\n // default extension and directory-index resolutions.\n const probes = [\n candidate,\n ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map(\n (extension) => `${candidate}${extension}`,\n ),\n ...RELATIVE_IMPORT_RESOLVE_EXTENSIONS.map((extension) =>\n join(candidate, `index${extension}`),\n ),\n ];\n for (const probe of probes) {\n try {\n if (statSync(probe).isFile()) {\n file = probe;\n break;\n }\n } catch {\n // The relative dependency is still missing at this probe.\n }\n }\n }\n if (!file && unresolved.packageName) {\n try {\n file = createRequire(cleanModuleId(unresolved.importer)).resolve(\n unresolved.specifier,\n );\n } catch {\n // The package or selected entry is still missing.\n }\n }\n if (!file) continue;\n // Transfer the resolver-proven file to Vite's watcher before the\n // temporary missing-import watcher closes. Outside-root query\n // modules otherwise recover once but silently miss their next edit.\n server.watcher.add(file);\n unresolvedImports.delete(key);\n compileErrors.errorServer.clearErrorForModules([unresolved.importer]);\n resolvedImportInPass = true;\n }\n if (resolvedImportInPass) {\n // The importer's failed transform is not cached, so a document reload\n // re-requests it through the normal pipeline. Importer re-execution\n // belongs to Vite; replaying module graphs couples this plugin to\n // private APIs.\n server.ws.send({ type: \"full-reload\", path: \"*\" });\n }\n syncUnresolvedImportWatcher();\n } while (rerunUnresolvedImportResolution);\n } finally {\n unresolvedImportResolutionRunning = false;\n }\n }\n\n return {\n name: \"tempo-annotate\",\n apply: \"serve\",\n enforce: \"pre\",\n config(config, environment) {\n if (!enabled || environment.command !== \"serve\") return;\n applyManagedCanvasDependencyScan(config);\n excludeTempoHostFromAppDependencyScan(config);\n // An app whose own entries reach the generated tempo/ host still scans\n // it, and the host can have a different React major installed. Keep\n // its imports on the app's runtime so Vite cannot prebundle React 18 DOM\n // with React 19 JSX. Vite merges this array with the app's dedupe.\n const dedupe = [\"react\", \"react-dom\"].filter(\n (name) => !config.resolve?.dedupe?.includes(name),\n );\n const localAliases = localPrebuiltAliases(config.root);\n // Preserve an explicit app choice. Dev maps identify participating\n // imported CSS originals; projection forwards compact identities only.\n return {\n resolve: {\n dedupe,\n ...(localAliases.length ? { alias: localAliases } : {}),\n },\n ...(config.css?.devSourcemap === undefined\n ? { css: { devSourcemap: true } }\n : {}),\n // Vite concatenates this with the app's own ignored list. An app\n // that turned watching off (watch: null) keeps it off.\n ...(flutterTarget && config.server?.watch !== null\n ? { server: { watch: { ignored: [FLUTTER_HOST_WATCH_IGNORE] } } }\n : {}),\n };\n },\n resolveId: {\n order: \"pre\",\n async handler(id, importer, resolveOptions) {\n if (id.endsWith(\".astro?tempo-component\")) {\n const resolved = await this.resolve(\n id.slice(0, -\"?tempo-component\".length),\n importer,\n { ...resolveOptions, skipSelf: true },\n );\n if (!resolved) return null;\n return `\\0tempo:astro-component:${encodeURIComponent(resolved.id)}.js`;\n }\n if (enabled && id === VITE_ERROR_CLIENT_PATH) {\n return VITE_ERROR_CLIENT_ID;\n }\n if (id === INTERACT_PROJECTION_CLIENT_PATH) {\n return INTERACT_PROJECTION_CLIENT_ID;\n }\n if (\n id === INTERACT_PROJECTION_SDK_SPECIFIER &&\n importer === INTERACT_PROJECTION_CLIENT_ID\n ) {\n // Prefer the app's own resolution (its tempo-sdk install, or a test\n // alias) so integrated apps behave exactly as before; fall back to\n // this plugin's own copy of the module when the app can't resolve it.\n const resolved = await this.resolve(id, importer, {\n ...resolveOptions,\n skipSelf: true,\n });\n if (resolved) return resolved;\n return resolveOwnInteractProjectionModule();\n }\n if (enabled && importer && !importer.startsWith(\"\\0\")) {\n const packageName = barePackageName(id);\n if (!isRelativeImportSpecifier(id) && !packageName) return null;\n // Delegate through Vite's complete resolver while this pre hook can\n // still observe thrown package-entry failures. A post hook is never\n // reached when vite:resolve throws, which previously left no target\n // for the event-driven unresolved-import watcher.\n try {\n const resolved = await this.resolve(id, importer, {\n ...resolveOptions,\n skipSelf: true,\n });\n if (!resolved) rememberUnresolvedImport(id, importer, packageName);\n return resolved;\n } catch (error) {\n rememberUnresolvedImport(id, importer, packageName);\n throw error;\n }\n }\n return null;\n },\n },\n\n // `order: \"pre\"` + a null return: this hook never loads anything of its\n // own for a project file, it only decides WHEN Vite core is allowed to\n // read it. Awaiting the burst gate here (rather than in `transform`) is\n // what makes the content terminal — by `transform` the bytes have already\n // been read, so delaying there would ship a stale revision late instead of\n // not shipping it at all.\n load: {\n order: \"pre\",\n async handler(id) {\n if (id.startsWith(\"\\0tempo:astro-component:\")) {\n // An Astro server module must never enter the React host's browser graph.\n const file = decodeURIComponent(\n id.slice(\"\\0tempo:astro-component:\".length, -3),\n );\n const { readAstroControlsMetadata } = await import(\n \"./astro/controls-reader\"\n );\n const controls = await readAstroControlsMetadata(\n file,\n async (specifier, importer) =>\n (await this.resolve(specifier, importer, { skipSelf: true }))\n ?.id ?? null,\n // These files are read as metadata, never executed in the host.\n // Vite turns load-hook addWatchFile entries into implicit imports,\n // including optional controls files that do not exist yet.\n (dependency) => devServer?.watcher.add(dependency),\n [\n resolve(sourceIdentityRoot, \"tempo/controls.ts\"),\n resolve(canonicalRoot, \"controls.ts\"),\n ],\n );\n astroDescriptorDependencies.set(id, new Set(controls.dependencies));\n return `export default {kind:\"astro-component\",module:${JSON.stringify(file.replaceAll(\"\\\\\", \"/\"))},__tempoAstroControls:${JSON.stringify(controls).replaceAll(\"<\", \"\\\\u003c\")}};`;\n }\n if (enabled && id === VITE_ERROR_CLIENT_ID) {\n return VITE_ERROR_CLIENT_SOURCE;\n }\n if (id === INTERACT_PROJECTION_CLIENT_ID) {\n return `import { installTempoInteractProjectionSource } from ${JSON.stringify(INTERACT_PROJECTION_SDK_SPECIFIER)};\nlet stop;\nconst releaseOwner = () => {\n if (window.__tempoInteractProjectionOwner === \"vite\") delete window.__tempoInteractProjectionOwner;\n};\nif (window.parent !== window && !window.__tempoInteractProjectionOwner && (window.name === ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} || window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) {\n window.__tempoInteractProjectionOwner = \"vite\";\n const stopSource = installTempoInteractProjectionSource();\n stop = () => {\n stopSource();\n releaseOwner();\n };\n}\nif (import.meta.hot) import.meta.hot.dispose(() => {\n stop?.();\n releaseOwner();\n});`;\n }\n if (!enabled || command === \"build\" || id.startsWith(\"\\0\")) return null;\n await hotUpdateNet.settled(id);\n return null;\n },\n },\n\n // Expose error server for testing\n _tempoErrorServer: compileErrors.errorServer,\n // Test seam pinning the exact evidence the missed-change sweep reads.\n _tempoHotUpdateState: {\n lastHotUpdateMtimeMs(file: string) {\n return hotUpdateNet.lastHotUpdateMtimeMs(file);\n },\n },\n _tempoUnresolvedImportState: {\n get size() {\n return unresolvedImports.size;\n },\n get barePackageCount() {\n return [...unresolvedImports.values()].filter(\n (unresolved) => unresolved.packageName !== undefined,\n ).length;\n },\n get hasBarePackageWatcher() {\n return unresolvedImportWatchers.size > 0 && hasUnresolvedBarePackages();\n },\n get barePackageWatchPath() {\n return hasUnresolvedBarePackages()\n ? unresolvedImportWatchers.keys().next().value\n : undefined;\n },\n get hasUnresolvedImportWatcher() {\n return unresolvedImportWatchers.size > 0;\n },\n get unresolvedImportWatchPath() {\n return unresolvedImportWatchers.keys().next().value;\n },\n get unresolvedImportWatchPaths() {\n return [...unresolvedImportWatchers.keys()];\n },\n get hasUnresolvedImportWatchRearm() {\n return unresolvedImportWatchRearmTimer !== null;\n },\n emitUnresolvedImportWatcherErrorForTesting() {\n for (const { watcher } of unresolvedImportWatchers.values()) {\n watcher.emit(\n \"error\",\n new Error(\"Simulated unresolved-import watcher failure\"),\n );\n }\n },\n },\n\n configResolved(resolvedConfig) {\n if (!enabled) return;\n\n command = resolvedConfig.command;\n hmrEnabled = resolvedConfig.server?.hmr !== false;\n if (command === \"serve\" && hmrEnabled) {\n installSynchronousReactRefreshBoundary(resolvedConfig.plugins ?? []);\n }\n canonicalRoot = resolveCanonicalRoot(options.root ?? resolvedConfig.root);\n sourceIdentityRoot = options.sourceIdentityRoot\n ? resolveCanonicalRoot(\n resolve(resolvedConfig.root, options.sourceIdentityRoot),\n )\n : canonicalRoot;\n },\n\n configureServer(server: ViteDevServer) {\n if (!enabled) return;\n resetCanvasHostRegistration(server);\n // Snapshot the delivered revision BEFORE Vite starts async watchChange /\n // hot-update hooks. A late POST hook may see a newer, lost write while a\n // transform of this event's older bytes is still pending and cacheable.\n // Coverage is watcher delivery evidence, never browser acknowledgment.\n hotUpdateNet.installCoverage(server);\n // Chokidar owns these listeners: its close() removes all listeners.\n // Do not retain a shared teardown callback here. Vite constructs the\n // replacement server before closing the old one during restart.\n // A managed sidecar's source identity root is commonly its parent repo,\n // outside Vite's host root. Custom/legacy vite configs may carry the\n // plugin's `sourceIdentityRoot` without the generated template's matching\n // `server.fs.allow`; Linux then resolves the canvas import correctly but\n // refuses to serve the resulting /@fs path. The interact-projection\n // fallback can likewise point inside this plugin's own package outside\n // the app root (hoisted or linked installs). Extend the resolved allow\n // list with both explicit roots so every path the enabled plugin owns can\n // actually be served. Behind the `enabled` gate: a disabled plugin stays\n // a no-op and never widens the app's file-serving surface.\n const ownInteractModule = resolveOwnInteractProjectionModule();\n // Optional chaining: unit tests drive this hook with partial server\n // mocks that carry no resolved `server.fs` config.\n const allow = server.config?.server?.fs?.allow;\n if (Array.isArray(allow)) {\n const requiredRoots = [\n sourceIdentityRoot,\n ...(ownInteractModule ? [dirname(ownInteractModule)] : []),\n ];\n for (const requiredRoot of requiredRoots) {\n if (!allow.includes(requiredRoot)) allow.push(requiredRoot);\n }\n }\n devServer = server;\n compileErrors.attach(server);\n syncUnresolvedImportWatcher();\n server.watcher?.once?.(\"close\", closeUnresolvedImportWatchers);\n server.httpServer?.once(\"close\", closeUnresolvedImportWatchers);\n server.middlewares.use((req, res, next) => {\n const graph = server.environments?.client?.moduleGraph;\n if (\n graph &&\n req.url &&\n (req.method === \"GET\" || req.method === \"HEAD\")\n ) {\n const observeResponse = prunedModuleDeletion.observeRequest(\n graph,\n req.url,\n server.config.base,\n req.headers[\"sec-fetch-dest\"],\n req.headers[\"if-none-match\"],\n );\n if (observeResponse)\n res.once(\"finish\", () => {\n void observeResponse(\n res.statusCode,\n res.getHeader(\"content-type\"),\n res.getHeader(\"etag\"),\n );\n });\n }\n const name = req.url?.match(\n /^\\/tempo-assets\\/([a-zA-Z0-9._-]+)(?:\\?.*)?$/,\n )?.[1];\n if (name) {\n const file = [\"public\", \"static\"]\n .map((directory) =>\n join(sourceIdentityRoot, directory, \"tempo-assets\", name),\n )\n .find((file) => existsSync(file));\n if (file) req.url = `/@fs/${file.replace(/\\\\/g, \"/\")}`;\n }\n handleTempoMiddleware(compileErrors, server, req, res, next);\n });\n\n const flutterForwarding = flutterTarget\n ? createFlutterForwarding({\n target: flutterTarget,\n config: server.config,\n })\n : null;\n if (flutterForwarding) {\n server.middlewares.use(flutterForwarding.prefix);\n // Flutter's debug client reconnects over a WebSocket at a root path.\n // Middleware mode has no http server of its own to listen on.\n server.httpServer?.on(\"upgrade\", flutterForwarding.upgrade);\n }\n if (flutterTarget) {\n // An engine is bound to the `flutter run` process it booted against;\n // after the dev server relaunches Flutter, only a fresh host page\n // gets hot reloads again.\n const stopRelaunchWatch = watchFlutterRelaunches({\n target: flutterTarget,\n onRelaunch() {\n server.config.logger.info(\n \"[tempo] Flutter dev server relaunched; reloading the canvas host page\",\n );\n server.ws.send({ type: \"full-reload\" });\n },\n });\n server.httpServer?.once(\"close\", stopRelaunchWatch);\n server.watcher?.once?.(\"close\", stopRelaunchWatch);\n }\n\n // The compile-error recovery poll rides the sweep's interval: both are\n // periodic recovery passes over the same cadence, and one timer keeps\n // them from overlapping each other.\n hotUpdateNet.installSweep(server, {\n sweepIntervalMs: MISSED_CHANGE_SWEEP_INTERVAL_MS,\n listExtraFiles: () => compileErrors.errorServer.errorFiles,\n afterSweep: () => compileErrors.pollRecovery(server),\n });\n\n installTailwindScanNet(server);\n\n // Intercept outgoing HMR messages to capture errors and clears\n // server-side, so we don't depend on client-side script execution\n // (which fails in contexts where import.meta.hot is unavailable,\n // e.g. Electron WebContentsViews).\n //\n // In Vite 7, error middleware calls environment.hot.send() which may\n // be a different wrapper than server.ws. Intercept both to ensure\n // errors are captured regardless of which path Vite uses. This is\n // Error observation never triggers recovery. The same transport tap\n // records exact client prune nodes for the scoped deletion guard below;\n // it does not traverse importers or send replacement updates.\n const interceptHmrSend = (target: HmrSendTarget) => {\n const orig = target.send.bind(target);\n target.send = ((...args: unknown[]) => {\n const payload = args[0];\n if (\n typeof payload === \"object\" &&\n payload !== null &&\n \"type\" in payload\n ) {\n const typed = payload as {\n type: string;\n err?: Record<string, unknown>;\n };\n if (typed.type === \"prune\") {\n const graph = server.environments?.client?.moduleGraph;\n if (graph)\n prunedModuleDeletion.observePrune(\n graph,\n (typed as { paths?: string[] }).paths ?? [],\n );\n }\n if (typed.type === \"error\") {\n compileErrors.recordHmrError(typed.err);\n } else if (\n typed.type === \"update\" &&\n !processedUpdatePayloads.has(payload)\n ) {\n processedUpdatePayloads.add(payload);\n const updatePayload = typed as {\n updates?: Array<{\n type?: string;\n path?: string;\n acceptedPath?: string;\n timestamp?: number;\n }>;\n };\n const updates = updatePayload.updates;\n const acceptedUpdates = updates\n ? hmrGenerationFence.filter(updates)\n : undefined;\n if (\n updates &&\n acceptedUpdates &&\n acceptedUpdates.length !== updates.length\n ) {\n updatePayload.updates = acceptedUpdates;\n }\n const paths =\n acceptedUpdates\n ?.map((u) => u.path)\n .filter((p): p is string => typeof p === \"string\") ?? [];\n compileErrors.errorServer.clearErrorForModules(paths);\n // An entirely stale payload has no work left for the browser.\n // Suppress it here so a delayed server pipeline cannot arrive\n // after the terminal replay and put the penultimate revision\n // back on screen.\n if (\n updates &&\n updates.length > 0 &&\n acceptedUpdates?.length === 0\n ) {\n return;\n }\n }\n }\n return orig(...args);\n }) as typeof orig;\n };\n\n interceptHmrSend(server.ws as unknown as HmrSendTarget);\n // Vite 7 constructs environment transports after the immediate\n // configureServer hooks. Install that interception from the documented\n // post hook, before the server begins accepting requests.\n return () => {\n const clientHot = (\n server as ViteDevServer & {\n environments?: { client?: { hot?: HmrSendTarget } };\n }\n ).environments?.client?.hot;\n if (clientHot && clientHot !== server.ws) {\n interceptHmrSend(clientHot);\n }\n // After Vite's own middlewares: Flutter gets only what Vite could not\n // serve (Flutter's root-relative hot-reload and module requests).\n if (flutterForwarding) {\n server.middlewares.use(flutterForwarding.fallthrough);\n }\n };\n },\n\n closeBundle() {\n astroDescriptorDependencies.clear();\n devServer = undefined;\n hotUpdateNet.clear();\n hmrGenerationFence.clear();\n prunedModuleDeletion.clear();\n compileErrors.reset();\n closeUnresolvedImportWatchers();\n },\n\n hotUpdate: {\n order: \"post\",\n async handler(context) {\n const affected = invalidateAstroDescriptors(\n context.file,\n this.environment.moduleGraph,\n context.modules,\n );\n if (!enabled || this.environment.config.consumer !== \"client\")\n return affected;\n context.modules.splice(0, context.modules.length, ...affected);\n if (isIncrementalRegistration(context.file)) return [];\n // These private modules are written before their host registration and\n // first import. A delayed watcher \"add\" can arrive while Vite has made\n // their module node but has not analyzed its Fast Refresh boundary yet;\n // Vite then treats it as a dead end and reloads every open preview. There\n // is no previous version to update on creation. Host registration loads\n // the new module; subsequent writes still use the normal HMR pipeline.\n if (\n context.type === \"create\" &&\n /\\/\\.tempo\\/asset-edit-previews\\/\\d+\\/index\\.canvas\\.tsx$/.test(\n context.file.replace(/\\\\/g, \"/\"),\n )\n ) {\n return [];\n }\n if (context.type === \"update\" && context.modules.length > 0)\n hotUpdateNet.observeUpdate(context.server, context.file);\n if (context.type !== \"create\") {\n forgetUnresolvedImportsFrom(context.file);\n }\n // The `await` reorders everything below it against the watcher\n // pipelines Vite runs concurrently, so only a file that actually has\n // an active error may pay for it.\n if (\n context.type === \"update\" &&\n compileErrors.hasActiveCompileError(context.file) &&\n (await compileErrors.recover(context.server, context.file))\n ) {\n // The full reload just sent replaces this update: the module never\n // finished evaluating, so it has no Fast Refresh boundary to apply\n // an in-place update to.\n return [];\n }\n if (context.type === \"delete\") {\n jsxModuleAnnotation.forgetDefaultExportIdentity(context.file);\n // A React self-accept boundary survives prune. Importing its deleted\n // file would poison this document's module map even after Undo.\n // Invalidate server bytes but leave the already-applied parent update\n // and all live/entry deletions on Vite's normal delivery path.\n if (\n prunedModuleDeletion.suppressDeletion(\n this.environment.moduleGraph,\n context.modules,\n )\n )\n return [];\n return;\n }\n if (\n context.type === \"update\" &&\n (await repairDefaultExportIdentityRewrite(context))\n ) {\n // The stale boundary cannot apply this update; the full reload\n // just sent re-fetches everything through the normal pipeline.\n return [];\n }\n if (context.type === \"update\") {\n return invalidateCanvasLoader(\n context.file,\n this.environment.moduleGraph,\n context.modules,\n );\n }\n },\n },\n\n // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.\n handleHotUpdate: {\n order: \"post\",\n async handler(context) {\n const affected = invalidateAstroDescriptors(\n context.file,\n context.server.moduleGraph,\n context.modules,\n );\n context.modules.splice(0, context.modules.length, ...affected);\n if (!enabled) return;\n if (isIncrementalRegistration(context.file)) return [];\n if (context.modules.length > 0)\n hotUpdateNet.observeUpdate(context.server, context.file);\n forgetUnresolvedImportsFrom(context.file);\n if (\n compileErrors.hasActiveCompileError(context.file) &&\n (await compileErrors.recover(context.server, context.file))\n ) {\n return [];\n }\n if (await repairDefaultExportIdentityRewrite(context)) {\n return [];\n }\n return invalidateCanvasLoader(\n context.file,\n context.server.moduleGraph,\n context.modules,\n );\n },\n },\n\n transformIndexHtml(html, context) {\n if (!enabled || command !== \"serve\") {\n return;\n }\n\n const tags: Array<{\n tag: string;\n attrs?: Record<string, string>;\n children?: string;\n injectTo: \"head\" | \"head-prepend\";\n }> = [];\n if (hmrEnabled) {\n tags.push({\n tag: \"script\",\n attrs: { type: \"module\", src: VITE_ERROR_CLIENT_PATH },\n injectTo: \"head-prepend\",\n });\n }\n if (!hasRootMetaTag(html)) {\n tags.push({\n tag: \"meta\",\n attrs: {\n name: ROOT_META_NAME,\n content: canonicalRoot,\n },\n injectTo: \"head\" as const,\n });\n }\n if (!hasSourceIdentityRootMetaTag(html)) {\n tags.push({\n tag: \"meta\",\n attrs: {\n name: SOURCE_IDENTITY_ROOT_META_NAME,\n content: sourceIdentityRoot,\n },\n injectTo: \"head\" as const,\n });\n }\n const workspaceNonce = createTempoHostIdentity(\"vite\", {\n root: canonicalRoot,\n pluginActive: true,\n }).workspaceNonce;\n if (workspaceNonce && !hasWorkspaceNonceMetaTag(html)) {\n tags.push({\n tag: \"meta\",\n attrs: {\n name: TEMPO_WORKSPACE_NONCE_META_NAME,\n content: workspaceNonce,\n },\n injectTo: \"head\" as const,\n });\n }\n const requestPath = context?.originalUrl ?? context?.path;\n const isDeclarativeCanvasHost = requestPath\n ? isDeclarativeCanvasHostRequest(requestPath)\n : false;\n if (requestPath && !isDeclarativeCanvasHost) {\n tags.push({\n tag: \"script\",\n children: INTERACT_PROJECTION_BOOTSTRAP,\n injectTo: \"head-prepend\" as const,\n });\n tags.push({\n tag: \"script\",\n attrs: { type: \"module\", src: INTERACT_PROJECTION_CLIENT_PATH },\n injectTo: \"head-prepend\" as const,\n });\n }\n return tags.length > 0 ? tags : undefined;\n },\n\n async transform(source, id) {\n if (!enabled || command === \"build\") {\n return null;\n }\n\n if (devServer) noteCanvasHostRegistrationActivity(devServer);\n\n if (id.startsWith(\"\\0\")) {\n return null;\n }\n\n const cleanId = cleanModuleId(id);\n if (\n cleanId.replace(/\\\\/g, \"/\").endsWith(\"/vite/dist/client/client.mjs\")\n ) {\n const code = preservePendingViteModuleUpdates(source);\n return code === source ? null : { code, map: null };\n }\n return jsxModuleAnnotation.annotateJsxModule(this, source, cleanId);\n },\n } as Plugin & {\n _tempoErrorServer: TempoErrorServer;\n _tempoHotUpdateState: {\n lastHotUpdateMtimeMs(file: string): number | undefined;\n };\n _tempoUnresolvedImportState: {\n readonly size: number;\n readonly barePackageCount: number;\n readonly hasBarePackageWatcher: boolean;\n readonly barePackageWatchPath: string | undefined;\n readonly hasUnresolvedImportWatcher: boolean;\n readonly unresolvedImportWatchPath: string | undefined;\n readonly unresolvedImportWatchPaths: readonly string[];\n };\n };\n}\n\n/** @deprecated Use `tempoVitePlugin` instead. */\nexport const tempoAnnotate = tempoVitePlugin;\n\nexport type { ElementInfo, PropValue };\nexport type { TempoErrorServer, TempoViteError } from \"./compile-error-stream\";\n\nexport type {\n StoryboardLayout,\n TempoCanvasConfig,\n TempoHtmlStoryboard,\n TempoPage,\n TempoRouteStoryboard,\n TempoStoryboard,\n} from \"./page.ts\";\n","/**\n * The per-module JSX annotation a Tempo canvas host applies in its Vite\n * transform: Tempo's JSX stamps, the storyboard component references, the\n * canvas controls HMR transform and the module version record a write's\n * receipt is matched against, all certified against the raw bytes this\n * transform chain loaded (\"Vite source freshness\" in CLAUDE.md).\n *\n * One home for every Vite canvas host. `tempoVitePlugin()` calls it from its\n * transform with the project's include/exclude filter; the Nuxt sidecar's R12\n * plugin (`nuxt.ts`) calls it with the canvas-file filter. A second, thinner\n * copy in the sidecar had no freshness witness (a write racing a transform\n * could stamp stale offsets), no controls transform (canvas controls did not\n * work) and no default-export identity (renames never reloaded).\n *\n * The instance owns the state the transform keeps between calls: which\n * modules have declared controls, and the default-export identity each file\n * was served with, which the host's post-order hot-update hook compares\n * through `defaultExportIdentityRewritten`.\n */\n\nimport {\n closeSync,\n fstatSync,\n openSync,\n readFileSync,\n realpathSync,\n type Stats,\n} from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { annotateFile } from \"../../modules/annotation/annotate-file.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport {\n appendModuleVersionRecord,\n cleanModuleId,\n type ComputeAnnotatedProps,\n computeTempoAnnotatedProps,\n} from \"./annotation-strategy.ts\";\nimport { transformControlsForHmr } from \"./assets/controls-transform.ts\";\nimport { canvasComponentAnnotations } from \"./canvas-component-reference.ts\";\nimport { parseCanvasFile } from \"./canvas/parser.ts\";\nimport {\n type DefaultExportIdentity,\n isDefaultExportIdentityRewrite,\n readDefaultExportIdentity,\n} from \"./default-export-identity.ts\";\nimport { fsPathFromModuleId } from \"./hot-update-net.ts\";\n\n/** The parts of Vite's transform context the annotation reads. Both are\n * optional because a plain test context, or a transform run outside Vite,\n * has neither; without a source map the chain simply cannot certify a\n * rewritten source. */\nexport interface JsxModuleTransformContext {\n getCombinedSourcemap?: () => {\n sources: readonly string[];\n sourcesContent?: readonly (string | null | undefined)[] | null;\n };\n resolve?(\n specifier: string,\n importer: string,\n options: { skipSelf: boolean },\n ): Promise<{ id: string } | null>;\n}\n\nexport interface JsxModuleAnnotationOptions {\n /** The `data-tempo-filepath` a module's stamps carry (relative to the host\n * root the page's `tempo-project-root` meta names), or null when the module\n * is not the host's to annotate. Read on every transform, so a host whose\n * root resolves late (Vite's `configResolved`) sees the resolved one. */\n stampedFilepath(cleanId: string): string | null;\n /** Whether a module's `defineControls` calls get the HMR disposal wrapper.\n * Wider than annotation: shared and component-file controls live in plain\n * `.ts`/`.js` modules too. */\n transformsControls(cleanId: string): boolean;\n /** Replaces the default stamps (`tempoVitePlugin({ computeAnnotatedProps })`). */\n computeAnnotatedProps?: ComputeAnnotatedProps;\n}\n\nexport interface JsxModuleAnnotation {\n /** The transformed module, or null to leave it untouched (not the host's,\n * unparsable, or nothing to change). `cleanId` is the module id without\n * its query or hash. */\n annotateJsxModule(\n context: JsxModuleTransformContext,\n source: string,\n cleanId: string,\n ): Promise<{ code: string; map: null } | null>;\n /** Compare the default-export identity a served file had with the one now\n * on disk, advancing the record. True means the identity provably changed\n * (rename, named to anonymous), which only a document reload heals. Run it\n * from a post-order hot-update hook; `read` is Vite's settled read. */\n defaultExportIdentityRewritten(change: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean>;\n /** Drop a deleted file's identity record. */\n forgetDefaultExportIdentity(file: string): void;\n}\n\nexport function createJsxModuleAnnotation(\n options: JsxModuleAnnotationOptions,\n): JsxModuleAnnotation {\n // Keep cleanup when the last declaration is removed during this server\n // session. This is module-side-effect ownership, not a rendering protocol.\n const controlsModules = new Set<string>();\n function transformControls(source: string, id: string) {\n const code = transformControlsForHmr(source, id, controlsModules.has(id));\n if (code !== source) controlsModules.add(id);\n return code;\n }\n\n // Default-export identity before the latest hot update, keyed by canonical\n // fs path (module ids and watcher paths disagree on /@fs/ and symlinks).\n // Seeded by the first transform, advanced only by hot-update comparisons.\n const defaultExportIdentityByFile = new Map<\n string,\n DefaultExportIdentity | null\n >();\n\n const canonicalIdentityKey = (idOrFile: string): string => {\n const file = fsPathFromModuleId(idOrFile);\n try {\n return realpathSync.native(file);\n } catch {\n return file.replace(/\\\\/g, \"/\");\n }\n };\n\n async function annotateJsxModule(\n context: JsxModuleTransformContext,\n source: string,\n cleanId: string,\n ): Promise<{ code: string; map: null } | null> {\n const controlsSource = options.transformsControls(cleanId)\n ? transformControls(source, cleanId)\n : source;\n const filepath = options.stampedFilepath(cleanId);\n if (filepath === null) {\n if (controlsSource !== source) return { code: controlsSource, map: null };\n return null;\n }\n\n try {\n // A transform can be delayed behind another plugin while disk advances.\n // Only the raw bytes carried by this transform chain can acknowledge a\n // write. A fresh stat/hash attached to older code would release previews\n // under a host that never rendered the acknowledged revision.\n const descriptor = openSync(cleanId, \"r\");\n let snapshot: {\n before: Stats;\n after: Stats;\n rawSource: string;\n };\n try {\n const before = fstatSync(descriptor);\n const rawSource = readFileSync(descriptor, \"utf8\");\n snapshot = { before, rawSource, after: fstatSync(descriptor) };\n } finally {\n closeSync(descriptor);\n }\n const { before, after, rawSource } = snapshot;\n const stable = [\"mtimeMs\", \"ctimeMs\", \"size\", \"ino\", \"dev\"] as const;\n let loadedSource: string | undefined =\n source === rawSource ? source : undefined;\n if (\n loadedSource === undefined &&\n typeof context.getCombinedSourcemap === \"function\"\n ) {\n try {\n const map = context.getCombinedSourcemap();\n const sourceRoot = (map as { sourceRoot?: unknown }).sourceRoot;\n const matches = map.sources.flatMap((path, index) => {\n const sourcePath = path.startsWith(\"file:\")\n ? fileURLToPath(path)\n : path;\n const file = isAbsolute(sourcePath)\n ? sourcePath\n : resolve(\n dirname(cleanId),\n typeof sourceRoot === \"string\" ? sourceRoot : \"\",\n sourcePath,\n );\n let sameFile =\n cleanModuleId(file).replace(/\\\\/g, \"/\") ===\n cleanId.replace(/\\\\/g, \"/\");\n if (!sameFile) {\n try {\n // Vite may preserve a symlink while an upstream source map\n // names its real path. Compare physical source ownership,\n // without sharing provenance between transform chains.\n sameFile =\n realpathSync.native(file) === realpathSync.native(cleanId);\n } catch {\n // An unresolved map source is not an ownership witness.\n }\n }\n return sameFile && typeof map.sourcesContent?.[index] === \"string\"\n ? [map.sourcesContent[index]!]\n : [];\n });\n if (matches.length === 1) loadedSource = matches[0];\n } catch {\n // A custom transform without usable raw provenance cannot certify\n // freshness. Rendering and runtime capabilities remain useful.\n }\n }\n const witnessed =\n loadedSource === rawSource &&\n stable.every((key) => before[key] === after[key]);\n const modifiedtsMs = witnessed ? Math.trunc(before.mtimeMs) : 0;\n const sourceVersion = witnessed ? sourceVersionHash(rawSource) : \"\";\n const identityKey = canonicalIdentityKey(cleanId);\n // A concurrent host request can transform the new revision before\n // the watcher's post-order hook compares it. Keep the old identity\n // until that comparison so a rename cannot silently consume its own\n // required reload.\n if (!defaultExportIdentityByFile.has(identityKey)) {\n defaultExportIdentityByFile.set(\n identityKey,\n readDefaultExportIdentity(rawSource),\n );\n }\n\n const resolvedComponents = new Map<string, string>();\n if (\n source.includes(\"tempo-sdk/canvas\") &&\n typeof context.resolve === \"function\"\n ) {\n const imports = parseCanvasFile(cleanId, source).storyboards.flatMap(\n (board) => board.component?.import?.source ?? [],\n );\n await Promise.all(\n [...new Set(imports)].map(async (specifier) => {\n const resolved = await context.resolve!(specifier, cleanId, {\n skipSelf: true,\n });\n if (resolved) resolvedComponents.set(specifier, resolved.id);\n }),\n );\n }\n const componentReferences = canvasComponentAnnotations(\n cleanId,\n source,\n resolvedComponents,\n );\n const result = annotateFile(source, cleanId, (info) => {\n const props = {\n ...componentReferences.get(info.element.openingElement.start),\n ...computeTempoAnnotatedProps({\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps: options.computeAnnotatedProps,\n }),\n };\n if (!witnessed) {\n // An unversioned offset is still accepted by some released\n // structural writers. Withhold the entire source address, not\n // merely its freshness, until this chain can certify its bytes.\n delete props[\"data-tempo-filepath\"];\n delete props[\"data-tempo-position\"];\n delete props[\"data-tempo-source-tag\"];\n delete props[\"data-tempo-expr\"];\n delete props[\"data-tempo-modifiedts\"];\n delete props[\"data-tempo-source-version\"];\n }\n return props;\n });\n\n // A file that does not parse stays untouched; Vite reports the error.\n if (result.parseResult.errors.length > 0) return null;\n // A file with no annotated element still records its evaluation: a\n // write that removed its last element is the case that needs it.\n const annotated =\n result.elementsAnnotated === 0 ? source : result.annotatedSource;\n const withControls = options.transformsControls(cleanId)\n ? transformControls(annotated, cleanId)\n : annotated;\n return {\n code: witnessed\n ? appendModuleVersionRecord(\n withControls,\n filepath,\n modifiedtsMs,\n sourceVersion,\n )\n : withControls,\n map: null,\n };\n } catch {\n return null;\n }\n }\n\n async function defaultExportIdentityRewritten(change: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean> {\n const { file } = change;\n const key = canonicalIdentityKey(file);\n if (!defaultExportIdentityByFile.has(key)) return false; // Never served.\n let source: string;\n try {\n source = readFileSync(file, \"utf8\");\n // A watcher can fire between a save's truncate and write. Vite's read\n // waits for that write to settle; caching the temporary empty source\n // here would erase the served identity and miss its required reload.\n // Keep ordinary nonempty comparisons synchronous so concurrent watcher\n // pipelines cannot reorder them around an unnecessary async read.\n if (source.length === 0) source = await change.read();\n } catch {\n return false;\n }\n const before = defaultExportIdentityByFile.get(key);\n if (before === undefined) return false; // Deleted while the read waited.\n const after = readDefaultExportIdentity(source);\n defaultExportIdentityByFile.set(key, after);\n return isDefaultExportIdentityRewrite(before, after);\n }\n\n return {\n annotateJsxModule,\n defaultExportIdentityRewritten,\n forgetDefaultExportIdentity(file) {\n defaultExportIdentityByFile.delete(canonicalIdentityKey(file));\n },\n };\n}\n","import { parseControlsFile } from \"./parser\";\n\n/** Replace this module's registrations before reevaluation. Vite disposes\n * accepted boundaries, but can reevaluate their intermediate imports without\n * calling dispose. hot.data also covers that path. One callback owns ALL calls\n * in a file: registering a callback per call would overwrite the previous one. */\nexport function transformControlsForHmr(\n source: string,\n filePath: string,\n previouslyDefinedControls = false,\n): string {\n const calls = source.includes(\"defineControls\")\n ? parseControlsFile(filePath, source)\n : [];\n if (!calls.length && !previouslyDefinedControls) return source;\n for (const { start, end } of calls.reverse()) {\n source =\n source.slice(0, start) +\n `((dispose) => { if (import.meta.hot && typeof dispose === \"function\") import.meta.hot.data.__tempoControlsDisposers.push(dispose); })(${source.slice(start, end)})` +\n source.slice(end);\n }\n return `if (import.meta.hot) {\n for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();\n import.meta.hot.data.__tempoControlsDisposers = [];\n import.meta.hot.dispose(() => {\n for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();\n import.meta.hot.data.__tempoControlsDisposers = [];\n });\n}\n${source}`;\n}\n","import { realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, normalize, posix, resolve } from \"node:path\";\nimport {\n parseFlutterPreview,\n FLUTTER_PREVIEW_KEY_ATTRIBUTE,\n} from \"./canvas/flutter-preview\";\nimport {\n canonicalPathAllowMissing,\n flutterPreviewKey,\n} from \"./flutter-preview-path\";\nimport { parseCanvasFile } from \"./canvas/parser\";\n\nexport const COMPONENT_REFERENCE_ATTRIBUTE = \"data-tempo-component-reference\";\nfunction moduleIdentity(\n file: string,\n specifier: string,\n resolved?: ReadonlyMap<string, string>,\n): string {\n const resolvedId = resolved?.get(specifier);\n const bundled = resolvedId?.startsWith(\"\\0tempo:astro-component:\")\n ? decodeURIComponent(\n resolvedId.slice(\"\\0tempo:astro-component:\".length, -3),\n )\n : resolvedId;\n // Match Vite's module-graph timestamp normalization. Other query parameters\n // and fragments can select different modules and remain part of identity.\n const target =\n bundled === undefined\n ? specifier\n : bundled.replace(/\\bt=\\d{13}&?\\b/, \"\").replace(/[?&]$/, \"\");\n if (target.startsWith(\"\\0\")) return target;\n const suffixAt = target.search(/[?#]/);\n let path = (suffixAt < 0 ? target : target.slice(0, suffixAt)).replace(\n /\\\\/g,\n \"/\",\n );\n const suffix =\n suffixAt < 0 || target.endsWith(\".astro?tempo-component\")\n ? \"\"\n : target.slice(suffixAt);\n if (bundled === undefined && path.startsWith(\".\"))\n path = resolve(dirname(file), path);\n // Bare or virtual module IDs are opaque; path.normalize can change their\n // meaning. Only filesystem paths receive filesystem canonicalization.\n if (!isAbsolute(path) && !/^[A-Za-z]:\\//.test(path)) return target;\n if (bundled !== undefined) {\n try {\n path = realpathSync.native(path);\n } catch {\n /* The resolver may return a virtual absolute path. */\n }\n }\n return normalize(path).replace(/\\\\/g, \"/\") + suffix;\n}\n/** Static references carry provenance. Inline/dynamic expressions remain owned\n * by their storyboard; body and props never participate in source identity. */\nexport function canvasComponentAnnotations(\n file: string,\n source: string,\n resolved?: ReadonlyMap<string, string>,\n hostRoot?: string,\n): ReadonlyMap<number, Readonly<Record<string, string>>> {\n const result = new Map<number, Readonly<Record<string, string>>>();\n if (!source.includes(\"tempo-sdk/canvas\")) return result;\n const parsed = parseCanvasFile(file, source);\n for (const board of parsed.storyboards) {\n if (board.kind !== \"component\" || board.openingElementSpan === undefined)\n continue;\n // A Flutter board is an instance board (user decision 2026-10-19): its\n // preview function is the component it instantiates, always outside the\n // canvas folder, so the canvas selects the board first and shows the\n // root widget's internals beneath it, as for `component={X}` with an\n // imported X. The reference's identity is the preview key itself.\n const flutterPreview = board.preview\n ? parseFlutterPreview(board.preview)\n : null;\n if (flutterPreview && !(\"error\" in flutterPreview) && hostRoot) {\n let key: string;\n try {\n const absolute = resolve(\n dirname(canonicalPathAllowMissing(file)),\n flutterPreview.file,\n );\n key = flutterPreviewKey(\n hostRoot,\n absolute,\n flutterPreview.functionName,\n );\n } catch {\n // An inaccessible or dangling reference fails only this board. Do not\n // reject the entire canvas module or invent an uncanonicalized key.\n continue;\n }\n result.set(board.openingElementSpan.start, {\n [FLUTTER_PREVIEW_KEY_ATTRIBUTE]: key,\n [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([\n \"flutter\",\n key.slice(0, key.lastIndexOf(\"#\")),\n flutterPreview.functionName,\n ]),\n \"data-tempo-external-component\": \"true\",\n });\n continue;\n }\n const ref = board.component;\n if (!ref?.localName) continue;\n const member = ref.expression.match(\n /^\\s*([$\\w]+)(?:\\s*\\.\\s*([$\\w]+))?\\s*$/,\n );\n if (!member) continue;\n let name: string;\n if (ref.import) {\n if (ref.import.kind === \"namespace\") {\n if (!member[2]) continue;\n name = member[2];\n } else {\n if (member[2]) continue;\n name = ref.import.importedName;\n }\n } else {\n if (member[2]) continue;\n name = ref.localName;\n }\n // Match the canvas-config reader's V1 rule using the authored specifier,\n // before bundler resolution changes aliases into filesystem paths.\n const specifier = ref.import?.source\n .replace(/\\\\/g, \"/\")\n .replace(/[?#].*/, \"\");\n const canvasDir = posix.dirname(file.replace(/\\\\/g, \"/\"));\n const external =\n specifier !== undefined &&\n (!specifier.startsWith(\".\") ||\n !posix.join(canvasDir, specifier).startsWith(`${canvasDir}/`));\n result.set(board.openingElementSpan.start, {\n [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([\n ref.import ? \"import\" : \"local\",\n moduleIdentity(file, ref.import?.source ?? file, resolved),\n name,\n ]),\n ...(external ? { \"data-tempo-external-component\": \"true\" } : {}),\n });\n }\n return result;\n}\n","/**\n * Default-export identity reader — the dev server's repair signal for the\n * silent stale-rename class.\n *\n * Changing a default export's identity (rename, named → anonymous) without\n * touching its importer follows @vitejs/plugin-react's public contract: the\n * module still looks like a valid Fast Refresh boundary, so Vite self-accepts\n * the update, react-refresh finds no family continuation for the mounted\n * component, and the visible output silently keeps rendering the OLD code —\n * no error, no invalidation, nothing observable client-side. Any full\n * document reload heals it.\n *\n * These helpers extract a conservative string-level fingerprint of a module's\n * default-export identity so the Vite plugin can compare consecutive\n * hot-update deliveries of the same file and issue ONE public full-reload\n * when the identity provably changed. False negatives are acceptable (manual\n * refresh remains available); a false positive costs a gratuitous reload, so\n * any shape the reader is not confident about parses to null and never\n * participates in the comparison — except that a confidently-read ANONYMOUS\n * default (function, class, or arrow) makes every later update of the file a\n * rewrite: react-refresh has no family for a nameless component, so nothing\n * short of a reload can ever converge the mounted instance.\n */\n\nexport interface DefaultExportIdentity {\n kind: \"function\" | \"class\" | \"identifier\";\n /** Binding name; null for anonymous function/class default exports. */\n name: string | null;\n}\n\nconst FUNCTION_DEFAULT_RE =\n /^(?:async\\s+)?function(?:\\s*\\*)?(?:\\s+([A-Za-z_$][\\w$]*))?\\s*\\(/;\nconst CLASS_DEFAULT_RE =\n /^(?:abstract\\s+)?class(?:\\s+([A-Za-z_$][\\w$]*))?(?=[\\s{])/;\n// An anonymous arrow default (`export default () => ...`, `async (p) =>`,\n// `props => ...`). Same identity class as an anonymous `function` default:\n// no binding name exists, so react-refresh can never register a family for\n// it. Params with nested parentheses (a destructuring default calling a\n// function) fall back to null — conservative, like every other unreadable\n// shape.\nconst ARROW_DEFAULT_RE = /^(?:async\\s+)?(?:\\([^()]*\\)|[A-Za-z_$][\\w$]*)\\s*=>/;\n// A bare identifier re-export (`export default StatefulCounter;`). The\n// terminator check rejects longer expressions (`styled.div`, `memo(App)`,\n// `new Foo()`), which have no single binding name to compare.\nconst IDENTIFIER_DEFAULT_RE = /^([A-Za-z_$][\\w$]*)[ \\t]*(?:;|\\r?\\n|$)/;\n\n/**\n * Reads the first `export default` in the source and classifies its identity.\n * Returns null when there is none or its shape carries no comparable binding\n * name (arrow functions, call expressions, object/JSX literals, ...). Purely\n * lexical: an `export default` inside a comment or string can fool it, but a\n * spurious match only matters if the fingerprint CHANGES between two edits.\n */\nexport function readDefaultExportIdentity(\n source: string,\n): DefaultExportIdentity | null {\n const start = /\\bexport\\s+default\\s+/.exec(source);\n if (!start) return null;\n const tail = source.slice(start.index + start[0].length);\n\n const fn = FUNCTION_DEFAULT_RE.exec(tail);\n if (fn) return { kind: \"function\", name: fn[1] ?? null };\n\n const cls = CLASS_DEFAULT_RE.exec(tail);\n if (cls) return { kind: \"class\", name: cls[1] ?? null };\n\n if (ARROW_DEFAULT_RE.test(tail)) return { kind: \"function\", name: null };\n\n const identifier = IDENTIFIER_DEFAULT_RE.exec(tail);\n if (identifier) return { kind: \"identifier\", name: identifier[1] };\n\n return null;\n}\n\n/**\n * True when two confidently-read identities differ in a way that produces\n * the silent stale render: the binding name changed (including named →\n * anonymous and back) while both sides still look like React components.\n * Lower-cased (non-component) renames are excluded — a module that stops\n * being all-components stops being a Fast Refresh boundary, so Vite's own\n * propagation already handles it.\n *\n * An ANONYMOUS function/class default on the BEFORE side is a rewrite for\n * every subsequent update, whatever the after side reads as: with no binding\n * name react-refresh never registered a family for the mounted component, so\n * no later hot update — same-shape edit, wrapper, rename — can ever reach it\n * in place. The only heal is the reload this verdict triggers.\n */\nexport function isDefaultExportIdentityRewrite(\n before: DefaultExportIdentity | null,\n after: DefaultExportIdentity | null,\n): boolean {\n if (!before) return false;\n if (before.name === null) return true;\n if (!after) return false;\n if (before.name === after.name) return false;\n return isComponentShaped(before) && isComponentShaped(after);\n}\n\nfunction isComponentShaped(identity: DefaultExportIdentity): boolean {\n return identity.name === null || /^[A-Z]/.test(identity.name);\n}\n","import type { EnvironmentModuleGraph, EnvironmentModuleNode } from \"vite\";\n\n/** An outgoing prune is evidence of removal; zero importers alone is not. */\nexport function createPrunedModuleDeletionGuard() {\n let sequence = 0;\n let activeReceipts = 0;\n let receipts = new WeakMap<EnvironmentModuleNode, number>();\n return {\n observePrune(graph: EnvironmentModuleGraph, paths: readonly string[]) {\n const receipt = ++sequence;\n for (const path of paths) {\n const module = graph.urlToModuleMap.get(path);\n if (module) {\n if (!receipts.has(module)) activeReceipts++;\n receipts.set(module, receipt);\n }\n }\n },\n observeRequest(\n graph: EnvironmentModuleGraph,\n url: string,\n base: string,\n fetchDestination?: string | string[],\n ifNoneMatch?: string | string[],\n ) {\n if (\n !activeReceipts ||\n [\"document\", \"iframe\", \"frame\"].includes(String(fetchDestination))\n )\n return;\n const requestSequence = sequence;\n // Observe the response, never delay a request or run a resolver merely\n // because an endpoint/asset was fetched. Vite's module responses carry\n // transform ETags; its cached304 response uses the request's ETag.\n return async (\n status: number,\n contentType: string | number | string[] | undefined,\n responseEtag: string | number | string[] | undefined,\n ) => {\n if (!activeReceipts || status < 200 || status >= 400) return;\n if (\n status !== 304 &&\n !/^text\\/(?:javascript|css)(?:;|$)/i.test(String(contentType))\n )\n return;\n const etag = status === 304 ? ifNoneMatch : responseEtag;\n if (typeof etag !== \"string\" || !graph.getModuleByEtag(etag)) return;\n // Match Vite's base + transform middleware spelling. Resolution owns\n // aliases and transport-only import/t queries; semantic queries stay.\n let moduleUrl = url;\n if (base !== \"/\" && moduleUrl.startsWith(base))\n moduleUrl = `/${moduleUrl.slice(base.length)}`;\n try {\n moduleUrl = decodeURI(moduleUrl).replace(/__x00__/g, \"\\0\");\n if (moduleUrl.startsWith(\"/@id/\")) moduleUrl = moduleUrl.slice(5);\n const [, id] = await graph.resolveUrl(moduleUrl);\n const module = graph.getModuleById(id);\n if (\n module &&\n module.transformResult?.etag === etag &&\n (receipts.get(module) ?? Infinity) <= requestSequence\n ) {\n receipts.delete(module);\n activeReceipts--;\n }\n } catch {\n // Observation must not change normal resolution/URI errors.\n }\n };\n },\n suppressDeletion(\n graph: EnvironmentModuleGraph,\n modules: EnvironmentModuleNode[],\n ) {\n if (\n !modules.length ||\n !modules.every(\n (module) => receipts.has(module) && module.importers.size === 0,\n )\n )\n return false;\n const invalidated = new Set<EnvironmentModuleNode>();\n for (const module of modules) graph.invalidateModule(module, invalidated);\n return true;\n },\n clear() {\n receipts = new WeakMap();\n activeReceipts = 0;\n // Keep sequence monotonic: an old in-flight response cannot retire a\n // receipt from a later server lifetime.\n },\n };\n}\n","import { existsSync } from \"node:fs\";\nimport {\n type IncomingHttpHeaders,\n type IncomingMessage,\n request as httpRequest,\n type ServerResponse,\n} from \"node:http\";\nimport { connect } from \"node:net\";\nimport { extname, join, posix } from \"node:path\";\nimport { type Duplex, pipeline } from \"node:stream\";\nimport type { ResolvedConfig } from \"vite\";\n\n/**\n * Routes the Flutter dev server (`flutter run -d web-server`) through the\n * canvas host's origin, so `FlutterStoryboard` boots the engine from the same\n * origin as the host page.\n *\n * Three routes reach Flutter, all through one forwarder:\n * - HTTP under `/__tempo/flutter/`, the prefix the generated bootstrap loads\n * the app from (`entrypointBaseUrl` and `assetBase`), prefix stripped;\n * - any root HTTP request Vite had nothing to serve. Flutter's debug loader\n * bakes `/` as the app root: hot reload fetches `/reloaded_sources.json`\n * and DDC modules such as `/packages/<pkg>/x.dart.lib.js` from the page's\n * origin whatever the entrypoint base, so the prefix alone breaks hot\n * reload;\n * - every WebSocket upgrade except Vite's own. The DWDS client injected on\n * the web-server device connects over a WebSocket at a root path.\n *\n * Active only when Tempo started the canvas host with `TEMPO` and\n * `TEMPO_FLUTTER_URL` set, so hand-written hosts such as the canvas demo get\n * it too. Vite's own `server.proxy` is not used: it logs a stack trace for\n * every refused connection, and the page probes repeatedly while Flutter is\n * still compiling.\n */\n\nexport const FLUTTER_PROXY_PREFIX = \"/__tempo/flutter\";\n\n/** The body of every 502 a Flutter route answers while Flutter is down. */\nexport const FLUTTER_UNREACHABLE_BODY = { error: \"flutter_unreachable\" };\n\n/**\n * The generated Flutter host project (`tempo/.flutter-host/`) lives inside\n * the canvas host's Vite root; its `.dart_tool/` and `build/` churn on every\n * Flutter compile and must never trigger Vite.\n */\nexport const FLUTTER_HOST_WATCH_IGNORE = \"**/.flutter-host/**\";\n\ntype Middleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n) => void;\n\ntype Logger = { warn(message: string): void; info(message: string): void };\n\n/** The Flutter dev server's origin, or null when this host serves no Flutter. */\nexport function readFlutterDevServerUrl(\n env: NodeJS.ProcessEnv,\n logger: Pick<Logger, \"warn\"> = console,\n): URL | null {\n const raw = env.TEMPO_FLUTTER_URL?.trim();\n if (!raw) return null;\n try {\n const url = new URL(raw);\n if (url.protocol === \"http:\") return url;\n } catch {\n // Reported below with the value that failed.\n }\n logger.warn(\n `[tempo] ignoring TEMPO_FLUTTER_URL=${JSON.stringify(raw)}: expected an http:// origin such as http://127.0.0.1:<port>`,\n );\n return null;\n}\n\n/** The dev server's status endpoint on TEMPO_FLUTTER_URL: 200\n * `{ status: \"starting\" | \"ready\" | \"reloading\" | \"failed\", spawn, error }`,\n * where `spawn` counts `flutter run` processes. */\nexport const FLUTTER_STATUS_PATH = \"/__tempo_flutter_status\";\n\n/**\n * Calls `onRelaunch` when Flutter comes up as a different `flutter run`\n * process than the one last seen ready. A page that loaded the bootstrap is\n * bound to the process it booted against (its DWDS debug connection); after\n * a relaunch (a crash, a pubspec change) that engine never gets another hot\n * reload, so the canvas host page must load again. Returns the stop.\n */\nexport function watchFlutterRelaunches(options: {\n target: URL;\n onRelaunch(): void;\n intervalMs?: number;\n}): () => void {\n const intervalMs = options.intervalMs ?? 3_000;\n const statusUrl = new URL(FLUTTER_STATUS_PATH, options.target.origin);\n let lastReadySpawn: number | null = null;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n async function poll() {\n try {\n const response = await fetch(statusUrl, {\n signal: AbortSignal.timeout(intervalMs),\n });\n const status = response.ok\n ? ((await response.json()) as { status?: unknown; spawn?: unknown })\n : null;\n if (\n !stopped &&\n status?.status === \"ready\" &&\n typeof status.spawn === \"number\"\n ) {\n const relaunched =\n lastReadySpawn !== null && status.spawn !== lastReadySpawn;\n lastReadySpawn = status.spawn;\n if (relaunched) options.onRelaunch();\n }\n } catch {\n // The dev server is down or restarting; the next poll asks again.\n }\n if (stopped) return;\n timer = setTimeout(poll, intervalMs);\n // Never keep the Vite process alive on its own.\n timer.unref?.();\n }\n\n void poll();\n return () => {\n stopped = true;\n if (timer) clearTimeout(timer);\n };\n}\n\nfunction stripFlutterPrefix(path: string): string {\n const stripped = path.slice(FLUTTER_PROXY_PREFIX.length);\n return stripped.startsWith(\"/\") ? stripped : `/${stripped}`;\n}\n\nfunction isUnderFlutterPrefix(path: string): boolean {\n if (!path.startsWith(FLUTTER_PROXY_PREFIX)) return false;\n const next = path.charAt(FLUTTER_PROXY_PREFIX.length);\n return next === \"\" || next === \"/\" || next === \"?\";\n}\n\nexport function createFlutterForwarding(options: {\n target: URL;\n config: Pick<ResolvedConfig, \"root\" | \"base\" | \"logger\" | \"server\">;\n}): {\n /** Install before Vite's middlewares: answers everything under the prefix. */\n prefix: Middleware;\n /** Install after Vite's middlewares: answers what Vite could not serve. */\n fallthrough: Middleware;\n /** The http server's `upgrade` listener. */\n upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void;\n} {\n const { target, config } = options;\n const isViteUpgrade = createViteUpgradeMatcher(config);\n let reachable = true;\n\n function noteReachable() {\n if (reachable) return;\n reachable = true;\n config.logger.info(\n `[tempo] Flutter dev server reachable at ${target.origin}`,\n );\n }\n\n function noteUnreachable(error: Error) {\n if (!reachable) return;\n reachable = false;\n config.logger.warn(\n `[tempo] Flutter dev server unreachable at ${target.origin} (${(error as NodeJS.ErrnoException).code ?? error.message}); answering 502 until it is up`,\n );\n }\n\n function forward(\n req: IncomingMessage,\n res: ServerResponse,\n path: string,\n ): void {\n const upstream = httpRequest(\n {\n hostname: target.hostname,\n port: target.port,\n method: req.method,\n path,\n headers: { ...endToEndHeaders(req.headers), host: target.host },\n },\n (response) => {\n noteReachable();\n res.writeHead(\n response.statusCode ?? 502,\n response.statusMessage,\n endToEndHeaders(response.headers),\n );\n // A body that breaks off upstream must end the browser's response\n // too: `pipe` would leave a sized response waiting forever, where\n // `pipeline` destroys it.\n pipeline(response, res, () => {});\n },\n );\n upstream.on(\"error\", (error) => {\n if (res.headersSent || res.destroyed) {\n res.destroy();\n return;\n }\n noteUnreachable(error);\n res.writeHead(502, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(FLUTTER_UNREACHABLE_BODY));\n });\n // A page that goes away mid-stream (a long-lived event stream, a\n // navigation) must not leave the upstream request open.\n res.on(\"close\", () => {\n if (!res.writableFinished) upstream.destroy();\n });\n req.pipe(upstream);\n }\n\n // Replays the handshake as received (Host rewritten) and then pipes both\n // directions untouched: the WebSocket protocol is Flutter's business.\n function forwardUpgrade(\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n path: string,\n ): void {\n let connected = false;\n const upstream = connect(\n { host: target.hostname, port: Number(target.port) || 80 },\n () => {\n connected = true;\n noteReachable();\n upstream.write(upgradeRequestHead(req, path, target.host));\n if (head.length > 0) upstream.write(head);\n upstream.pipe(socket);\n socket.pipe(upstream);\n },\n );\n upstream.on(\"error\", (error) => {\n if (connected) {\n socket.destroy();\n return;\n }\n noteUnreachable(error);\n const body = JSON.stringify(FLUTTER_UNREACHABLE_BODY);\n socket.end(\n `HTTP/1.1 502 Bad Gateway\\r\\nContent-Type: application/json\\r\\nContent-Length: ${Buffer.byteLength(body)}\\r\\nConnection: close\\r\\n\\r\\n${body}`,\n );\n });\n // Before the connection, `close` follows `error`: let the 502 flush.\n upstream.on(\"close\", () => {\n if (connected) socket.destroy();\n });\n socket.on(\"error\", () => upstream.destroy());\n socket.on(\"close\", () => upstream.destroy());\n }\n\n return {\n prefix(req, res, next) {\n const url = req.url ?? \"/\";\n if (!isUnderFlutterPrefix(url)) return next();\n forward(req, res, stripFlutterPrefix(url));\n },\n fallthrough(req, res, next) {\n // Vite's SPA fallback rewrites `req.url` to /index.html for any request\n // accepting `*/*` before this runs, so the decision and the forwarded\n // path both come from the URL the client asked for.\n const originalUrl =\n (req as IncomingMessage & { originalUrl?: string }).originalUrl ??\n req.url ??\n \"/\";\n const pathname = decodePathname(originalUrl);\n const isViteOwned =\n pathname === null ||\n pathname.startsWith(\"/@\") ||\n pathname.startsWith(\"/__tempo/\") ||\n isCanvasHostPage(pathname) ||\n isHtmlNavigation(req.headers.accept, pathname) ||\n rootHasHtmlPage(config.root, pathname);\n if (isViteOwned) return next();\n forward(req, res, originalUrl);\n },\n upgrade(req, socket, head) {\n const url = req.url ?? \"/\";\n if (isViteUpgrade(req, url)) return;\n const path = isUnderFlutterPrefix(url) ? stripFlutterPrefix(url) : url;\n forwardUpgrade(req, socket, head, path);\n },\n };\n}\n\n/**\n * Upgrades another listener on the same http server answers: Vite's HMR and\n * ping sockets, and the app's own `server.proxy` WebSocket entries. Two\n * listeners answering one upgrade would corrupt the socket.\n */\nfunction createViteUpgradeMatcher(\n config: Pick<ResolvedConfig, \"base\" | \"server\">,\n): (req: IncomingMessage, url: string) => boolean {\n const hmr = config.server.hmr;\n const hmrPath =\n typeof hmr === \"object\" && hmr.path\n ? posix.join(config.base || \"/\", hmr.path)\n : null;\n const proxyContexts = Object.keys(config.server.proxy ?? {});\n return (req, url) => {\n const protocol = req.headers[\"sec-websocket-protocol\"] ?? \"\";\n if (protocol.includes(\"vite-hmr\") || protocol.includes(\"vite-ping\")) {\n return true;\n }\n if (hmrPath !== null && decodePathname(url) === hmrPath) return true;\n // Vite's own proxy matching: a key starting with ^ is a RegExp.\n return proxyContexts.some((context) =>\n context.startsWith(\"^\")\n ? new RegExp(context).test(url)\n : url.startsWith(context),\n );\n };\n}\n\nfunction upgradeRequestHead(\n req: IncomingMessage,\n path: string,\n host: string,\n): string {\n const lines = [`${req.method ?? \"GET\"} ${path} HTTP/${req.httpVersion}`];\n for (let index = 0; index < req.rawHeaders.length; index += 2) {\n const name = req.rawHeaders[index] ?? \"\";\n const value =\n name.toLowerCase() === \"host\" ? host : req.rawHeaders[index + 1];\n lines.push(`${name}: ${value}`);\n }\n return `${lines.join(\"\\r\\n\")}\\r\\n\\r\\n`;\n}\n\n/**\n * The canvas host page, Tempo's own route (`isCanvasHostRequest` in\n * index.ts), which Flutter never serves. Vite's SPA fallback answers it with\n * the host's index.html for any Accept, so a request that does not ask for\n * text/html still belongs to Vite: canvas_validate's reachability check and\n * curl send a wildcard Accept, and were answered by Flutter (503\n * flutter_starting while it compiled, then Flutter's own index.html).\n */\nfunction isCanvasHostPage(pathname: string): boolean {\n return pathname.replace(/\\/+$/, \"\") === \"/tempo-host\";\n}\n\n/** A browser asking for a page, which Vite answers with its own HTML. */\nfunction isHtmlNavigation(\n accept: string | undefined,\n pathname: string,\n): boolean {\n return Boolean(accept?.includes(\"text/html\")) && extname(pathname) === \"\";\n}\n\n/** Mirrors Vite's HTML fallback: the host's own page for this path, if any. */\nfunction rootHasHtmlPage(root: string, pathname: string): boolean {\n // The pathname is decoded, so `%2e%2e` arrives as `..`, which the URL\n // parser did not resolve; a page outside the root is never Vite's.\n if (pathname.split(\"/\").includes(\"..\")) return false;\n if (pathname.endsWith(\".html\")) return existsSync(join(root, pathname));\n if (pathname.endsWith(\"/\")) {\n return existsSync(join(root, pathname, \"index.html\"));\n }\n return existsSync(join(root, `${pathname}.html`));\n}\n\nfunction decodePathname(url: string): string | null {\n try {\n return decodeURIComponent(new URL(url, \"http://host\").pathname);\n } catch {\n return null;\n }\n}\n\nconst HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/** Headers that describe the message rather than this one connection. */\nfunction endToEndHeaders(headers: IncomingHttpHeaders): IncomingHttpHeaders {\n const forwarded: IncomingHttpHeaders = {};\n for (const [name, value] of Object.entries(headers)) {\n if (value === undefined || HOP_BY_HOP_HEADERS.has(name)) continue;\n forwarded[name] = value;\n }\n return forwarded;\n}\n","/**\n * Monotonic fence for Vite HMR update records.\n *\n * Vite gives every filesystem update a monotonic timestamp, but its server\n * pipelines may finish out of order. The browser processes websocket payloads\n * in arrival order, so an older pipeline that is sent after a newer one can\n * permanently put stale code back on screen. Remembering the newest timestamp\n * sent for each accepted module turns that partial order into a hard rule:\n * once generation N crosses the websocket boundary, no generation below N\n * may follow it.\n *\n * Equal timestamps remain valid because one source event can produce several\n * accept-boundary payloads. Records without Vite's identity/timestamp fields\n * pass through untouched for compatibility with older or custom channels.\n */\n\nexport interface HmrGenerationRecord {\n type?: unknown;\n path?: unknown;\n acceptedPath?: unknown;\n timestamp?: unknown;\n}\n\nexport interface HmrGenerationFence {\n filter<T extends HmrGenerationRecord>(updates: readonly T[]): T[];\n clear(): void;\n}\n\nfunction generationIdentity(update: HmrGenerationRecord): string | null {\n const type = typeof update.type === \"string\" ? update.type : null;\n const acceptedPath =\n typeof update.acceptedPath === \"string\"\n ? update.acceptedPath\n : typeof update.path === \"string\"\n ? update.path\n : null;\n if (!type || !acceptedPath) return null;\n return `${type}\\0${acceptedPath}`;\n}\n\nexport function createHmrGenerationFence(): HmrGenerationFence {\n const newestTimestampByIdentity = new Map<string, number>();\n\n return {\n filter(updates) {\n const accepted: (typeof updates)[number][] = [];\n for (const update of updates) {\n const identity = generationIdentity(update);\n const timestamp = update.timestamp;\n if (\n identity === null ||\n typeof timestamp !== \"number\" ||\n !Number.isFinite(timestamp)\n ) {\n accepted.push(update);\n continue;\n }\n\n const newestTimestamp = newestTimestampByIdentity.get(identity);\n if (newestTimestamp !== undefined && timestamp < newestTimestamp) {\n continue;\n }\n if (newestTimestamp === undefined || timestamp > newestTimestamp) {\n newestTimestampByIdentity.set(identity, timestamp);\n }\n accepted.push(update);\n }\n return accepted;\n },\n\n clear() {\n newestTimestampByIdentity.clear();\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\nconst installed = new WeakSet<Plugin>();\n\n/**\n * @vitejs/plugin-react 4/5 registers its HMR accept callback in an asynchronous\n * self-import continuation. Vite resets the old callbacks when the updated\n * module starts evaluating, but its next queued update can arrive before that\n * continuation runs. That update imports successfully with no callback and\n * never schedules React Refresh.\n *\n * Register acceptance during evaluation, retaining the plugin's own export\n * registration and boundary validation once the self-import resolves. This\n * changes only the known React-generated footer, before Vite import analysis;\n * other frameworks and newer footer shapes pass through unchanged.\n */\nexport function installSynchronousReactRefreshBoundary(\n plugins: readonly Plugin[],\n): void {\n for (const plugin of plugins) {\n if (\n plugin.name === \"vite:react-refresh\" &&\n plugin.load &&\n !installed.has(plugin)\n ) {\n installed.add(plugin);\n const hook = plugin.load;\n const load = typeof hook === \"function\" ? hook : hook.handler;\n const wrapped: typeof load = async function (...args) {\n const result = await load.apply(this, args);\n if (!result || args[0] !== \"/@react-refresh\") return result;\n const source = typeof result === \"string\" ? result : result.code;\n // Use the runtime's authority, including families registered during\n // evaluation whose reconciler mapping is not installed until refresh.\n // Unknown/newer runtimes retain ordinary loader replacement behavior.\n if (\n !source ||\n !/\\b(?:let|const) allFamiliesByType = new WeakMap\\(\\)/.test(source) ||\n !source.includes(\"function performReactRefresh()\")\n )\n return result;\n const code = `${source}\nglobalThis[Symbol.for(\"tempo.react-refresh.family\")] = (type) => allFamiliesByType.get(type);\n`;\n return typeof result === \"string\" ? code : { ...result, code };\n };\n plugin.load =\n typeof hook === \"function\" ? wrapped : { ...hook, handler: wrapped };\n }\n if (\n plugin.name !== \"vite:react-babel\" ||\n !plugin.transform ||\n installed.has(plugin)\n )\n continue;\n installed.add(plugin);\n const hook = plugin.transform;\n const transform = typeof hook === \"function\" ? hook : hook.handler;\n const wrapped: typeof transform = async function (...args) {\n const result = await transform.apply(this, args);\n if (!result) return result;\n const source = typeof result === \"string\" ? result : result.code;\n if (!source) return result;\n const code = source.replace(\n /RefreshRuntime\\.__hmr_import\\(import\\.meta\\.url\\)\\.then\\(\\(currentExports\\) => \\{\\n(\\s*RefreshRuntime\\.registerExportsForReactRefresh\\([^\\n]+\\);)\\n\\s*import\\.meta\\.hot\\.accept\\(\\(nextExports\\) => \\{([\\s\\S]*?)\\n\\s*\\}\\);\\n\\s*\\}\\);/,\n (\n _match,\n register: string,\n accept: string,\n ) => `const __tempoReactRefreshExports = RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {\n${register}\n return currentExports;\n });\n import.meta.hot.accept(async (nextExports) => {\n const currentExports = await __tempoReactRefreshExports;${accept}\n });`,\n );\n return code === source\n ? result\n : typeof result === \"string\"\n ? code\n : { ...result, code };\n };\n plugin.transform =\n typeof hook === \"function\" ? wrapped : { ...hook, handler: wrapped };\n }\n}\n","/**\n * Vite drops an update when its boundary has not evaluated in this document\n * yet. A cold canvas host can already be fetching that boundary: the old\n * response then finishes after the edit, with no later update to repair it.\n *\n * Keep the update on Vite's own module record until acceptDeps registers the\n * boundary, then replay it through the ordinary Vite queue. This introduces\n * no Tempo HMR protocol, import registry, or framework refresh mechanism.\n * Unknown client shapes pass through unchanged.\n */\nexport function preservePendingViteModuleUpdates(source: string): string {\n const missingBoundary =\n /(const mod = this\\.hotModulesMap\\.get\\(path\\);\\s*)if \\(!mod\\)\\s*(?:return;|\\{\\s*return;\\s*\\})/;\n const registeredBoundary =\n \"this.hmrClient.hotModulesMap.set(this.ownerPath, mod);\";\n if (!missingBoundary.test(source) || !source.includes(registeredBoundary)) {\n return source;\n }\n return source\n .replace(\n missingBoundary,\n `$1if (!mod || mod.pendingUpdates) {\n const pending = mod || {\n id: path,\n callbacks: [],\n pendingUpdates: new Map(),\n };\n pending.pendingUpdates.set(acceptedPath, update);\n this.hotModulesMap.set(path, pending);\n return;\n }`,\n )\n .replace(\n registeredBoundary,\n `${registeredBoundary}\n if (mod.pendingUpdates) {\n const pendingUpdates = [...mod.pendingUpdates.values()];\n delete mod.pendingUpdates;\n queueMicrotask(() => {\n for (const update of pendingUpdates) {\n void this.hmrClient.queueUpdate(update).catch((error) => {\n this.hmrClient.logger.error(error);\n });\n }\n });\n }`,\n );\n}\n","/**\n * Tailwind new-file rescan net — closes the scan-registry hole that turns\n * drawn frames into 0×0 husks (TEM-1242).\n *\n * @tailwindcss/vite (≤4.3.3 observed; the shape is inherent to its design)\n * regenerates CSS only when a file its LAST scan enumerated changes: every\n * scanned file is registered as a watch dep of the CSS module, and the scan\n * itself only re-runs inside a CSS re-transform. A source file created AFTER\n * that scan is therefore invisible — its edits trigger no CSS rebuild, so\n * Tailwind classes written into it (`w-[148px]` from the canvas draw tools,\n * classes in an AI-authored component, a teammate's new canvas arriving via\n * git) compile to nothing until some OTHER registered file changes. On the\n * canvas this renders as the drawn frame collapsing to 0×0 once HMR swaps\n * the inline-sized placeholder for the className-only canonical element.\n *\n * The net restores the missing input signal, in the same spirit as the\n * missed-change sweep: when a scannable source file sees a watcher event and\n * some Tailwind-scanning CSS module does NOT list that file among its watch\n * deps, re-emit the watcher \"change\" for the CSS file. Vite re-transforms\n * it, the Tailwind plugin re-runs its scanner (a fresh walk of its sources),\n * the new file joins the registry, and the missing utilities land as a\n * normal CSS hot update. Files the scanner already tracks are skipped — for\n * those Vite re-transforms the CSS on its own, so steady-state editing costs\n * this net nothing.\n *\n * A CSS module counts as \"Tailwind-scanning\" when its recorded watch deps\n * contain a glob or a non-CSS source file — only a class scanner registers\n * source files as deps of a stylesheet. This reads the module graph's\n * transform receipts instead of sniffing file contents, so `@import\n * \"tailwindcss\"` indirection (Tempo's generated `tempo/globals.css`, a\n * host-level `styles.css`) needs no special-casing.\n *\n * Guard rails on the re-emit:\n *\n * - LEADING-EDGE flush: the first poke goes out immediately (next tick), so\n * the CSS repair rides as close as possible behind the component's own\n * HMR update — the canonical render is className-only, so every tick of\n * delay is a tick of visible 0×0. Follow-up events within the debounce\n * window coalesce into one trailing re-emit (a git checkout materializing\n * hundreds of files costs two rebuilds, not hundreds).\n * - Per-(CSS file, source file) poke CAP: a file genuinely outside an\n * entry's source scope is never registered by the rescan we force, so\n * without a bound every subsequent edit of that file would rebuild that\n * unrelated CSS forever. Two pokes per pair (the second covers an event\n * racing the first rescan's transform), then the pair goes silent. The\n * cap is deliberately count-based rather than matching the file against\n * the entry's own source globs: the glob nodes Vite records are lossy\n * (the auto-detection root registers as a literal `*`), and a false\n * negative in glob matching would silently resurrect the 0×0 bug the net\n * exists to fix.\n * - Watcher events for CSS files are ignored outright, so the net can never\n * feed back into itself.\n */\n\n/** Extensions the Tailwind scanner reads class candidates from — the set a\n * newly created file must have for its absence from the scan registry to\n * matter. Deliberately conservative: covers what Tempo's canvas writes and\n * the common source shapes around it. */\nconst SCANNABLE_EXTENSIONS = new Set([\n \"ts\",\n \"tsx\",\n \"js\",\n \"jsx\",\n \"mjs\",\n \"cjs\",\n \"html\",\n \"mdx\",\n \"md\",\n \"svelte\",\n \"vue\",\n \"astro\",\n]);\n\n/** Path segments that never hold user source. Watcher events under these are\n * dropped before any module-graph work. */\nconst IGNORED_PATH_SEGMENTS = [\n \"/node_modules/\",\n \"/.git/\",\n \"/.vite/\",\n \"/.tempo/\",\n];\n\nexport const TAILWIND_SCAN_NET_DEBOUNCE_MS = 100;\n\n/** How many times one (CSS file, source file) pair may be poked before it\n * goes silent — the out-of-scope backstop described above. */\nexport const TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR = 2;\n\n/** Ceiling on remembered (CSS file, source file) poke counts. Reaching it\n * clears the ledger (a brief re-poke window for previously-capped pairs)\n * rather than letting a pathological session grow it without bound. */\nconst POKE_LEDGER_MAX_ENTRIES = 20_000;\n\n/** One CSS module node's view in Vite's module graph: the CSS file it\n * belongs to and the watch deps that node's transform registered. A CSS\n * file with several nodes (query variants, environments) yields several\n * entries — deliberately NOT unioned, so one node that already tracks a\n * file cannot mask a sibling node whose scanner predates it. Nodes with no\n * completed transform carry no deps and decide nothing — their first\n * transform scans the disk as-is. */\nexport interface ScanNetCssEntry {\n cssFile: string;\n /** Watch deps this node's transform recorded (absolute paths and/or glob\n * patterns, as the scanning plugin registered them). Null when the node\n * has no completed transform yet. */\n deps: readonly string[] | null;\n}\n\nexport interface CreateTailwindScanNetArgs {\n /** Enumerate the CSS module-node entries currently in the module graph. */\n listCssEntries(): Iterable<ScanNetCssEntry>;\n /** Re-emit the watcher \"change\" for a CSS file. */\n emitChange(cssFile: string): void;\n /** Debounce window for coalescing event bursts into one re-emit. */\n debounceMs?: number;\n /** Poke cap per (CSS file, source file) pair. */\n maxPokesPerPair?: number;\n}\n\nexport interface TailwindScanNet {\n /** Feed a watcher \"add\"/\"change\" event. Returns true when the event\n * scheduled (or joined) a pending CSS re-emit — a test/diagnostic\n * convenience, not part of the control flow. */\n handleWatcherFile(file: string): boolean;\n /** Cancel any pending re-emit. */\n dispose(): void;\n}\n\nfunction normalizeSlashes(path: string): string {\n return path.replace(/\\\\/g, \"/\");\n}\n\nfunction fileExtension(path: string): string {\n const base = path.slice(path.lastIndexOf(\"/\") + 1);\n const dot = base.lastIndexOf(\".\");\n return dot <= 0 ? \"\" : base.slice(dot + 1).toLowerCase();\n}\n\nexport function isScannableSourceFile(file: string): boolean {\n const normalized = normalizeSlashes(file);\n if (!SCANNABLE_EXTENSIONS.has(fileExtension(normalized))) return false;\n return !IGNORED_PATH_SEGMENTS.some((segment) =>\n normalized.includes(segment),\n );\n}\n\n/** Whether a dep entry marks its CSS module as a class scanner: a glob\n * pattern, or a concrete non-CSS source file. Plain stylesheets only ever\n * register CSS imports and url() assets. */\nfunction isScanDep(dep: string): boolean {\n if (dep.includes(\"*\")) return true;\n const ext = fileExtension(normalizeSlashes(dep));\n return ext !== \"\" && ext !== \"css\" && SCANNABLE_EXTENSIONS.has(ext);\n}\n\n/** Whether `file` needs the CSS entry re-emitted: the entry scans classes,\n * but its last scan did not register the file. */\nexport function cssEntryNeedsRescanFor(\n entry: ScanNetCssEntry,\n file: string,\n): boolean {\n if (entry.deps === null) return false;\n const normalizedFile = normalizeSlashes(file);\n let scansClasses = false;\n for (const dep of entry.deps) {\n const normalizedDep = normalizeSlashes(dep);\n if (normalizedDep === normalizedFile) return false;\n if (!scansClasses && isScanDep(normalizedDep)) scansClasses = true;\n }\n return scansClasses;\n}\n\nexport function createTailwindScanNet(\n args: CreateTailwindScanNetArgs,\n): TailwindScanNet {\n const debounceMs = args.debounceMs ?? TAILWIND_SCAN_NET_DEBOUNCE_MS;\n const maxPokesPerPair =\n args.maxPokesPerPair ?? TAILWIND_SCAN_NET_MAX_POKES_PER_PAIR;\n const pendingCssFiles = new Set<string>();\n // (CSS file, source file) → pokes issued so far. A pair is counted at most\n // once per flush window (chokidar often fires add+change back-to-back for\n // one write; that must not burn the whole cap before any rescan ran).\n const pokeLedger = new Map<string, number>();\n const countedThisWindow = new Set<string>();\n let flushTimer: ReturnType<typeof setTimeout> | null = null;\n let lastFlushAt = Number.NEGATIVE_INFINITY;\n let disposed = false;\n\n const flush = () => {\n flushTimer = null;\n lastFlushAt = Date.now();\n countedThisWindow.clear();\n const cssFiles = [...pendingCssFiles];\n pendingCssFiles.clear();\n for (const cssFile of cssFiles) {\n args.emitChange(cssFile);\n }\n };\n\n return {\n handleWatcherFile(file: string): boolean {\n if (disposed) return false;\n if (!isScannableSourceFile(file)) return false;\n let scheduled = false;\n for (const entry of args.listCssEntries()) {\n if (!cssEntryNeedsRescanFor(entry, file)) continue;\n // Several module nodes of one CSS file may each demand the rescan;\n // the pair is still one poke.\n const pairKey = `${entry.cssFile}\\0${normalizeSlashes(file)}`;\n if (!countedThisWindow.has(pairKey)) {\n const pokes = pokeLedger.get(pairKey) ?? 0;\n if (pokes >= maxPokesPerPair) continue;\n if (pokeLedger.size >= POKE_LEDGER_MAX_ENTRIES) pokeLedger.clear();\n pokeLedger.set(pairKey, pokes + 1);\n countedThisWindow.add(pairKey);\n }\n pendingCssFiles.add(entry.cssFile);\n scheduled = true;\n }\n if (scheduled && flushTimer === null) {\n // Leading edge: a quiet net flushes on the next tick so the CSS\n // repair trails the component's own HMR update as tightly as\n // possible. Within the debounce window of a flush, further events\n // coalesce into one trailing re-emit.\n const sinceLastFlush = Date.now() - lastFlushAt;\n const delay = sinceLastFlush >= debounceMs ? 0 : debounceMs;\n flushTimer = setTimeout(flush, delay);\n flushTimer.unref?.();\n }\n return scheduled;\n },\n dispose(): void {\n disposed = true;\n pendingCssFiles.clear();\n pokeLedger.clear();\n countedThis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AAK,KAAK;AAAA,MACpD;AACA,aAAO,oBAAoB,kBAAkB,MAAM,QAAQ,OAAO;AAAA,IACpE;AAAA,EACF;AAeF;AAGO,IAAM,gBAAgB;","names":["existsSync","join","resolve","resolve","resolve","resolve","normalize","resolve","readFileSync","realpathSync","relative","resolve","readFileSync","resolve","resolve","readFileSync","realpathSync","relative","readBody","url","existsSync","realpathSync","statSync","dirname","join","relative","resolve","fileURLToPath","readFileSync","realpathSync","dirname","isAbsolute","resolve","realpathSync","dirname","isAbsolute","resolve","resolve","dirname","isAbsolute","realpathSync","realpathSync","before","rawSource","readFileSync","isAbsolute","resolve","dirname","existsSync","join","posix","hook","wrapped","dirname","fileURLToPath","join","existsSync","cleanModuleId","realpathSync","MISSED_CHANGE_SWEEP_INTERVAL_MS","relative","resolve","statSync","options","file"]}
|