tempo-sdk 0.0.19 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../index.ts","../../../modules/annotation/annotate-file.ts","../../../modules/file-parser/utils.ts","../../../modules/file-parser/walk.ts","../../../modules/file-parser/scope-analyzer/types.ts","../../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts","../../../modules/annotation/source-version.ts","../annotation-strategy.ts"],"sourcesContent":["import { realpathSync, statSync } from \"node:fs\";\nimport { relative } from \"node:path\";\n\nimport {\n annotateFile,\n type ElementInfo,\n type PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport { createFilter, type FilterPattern } from \"@rollup/pluginutils\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport { computeTempoAnnotatedProps } from \"./annotation-strategy.ts\";\n\nconst DEFAULT_INCLUDE: FilterPattern = [\"**/*.tsx\", \"**/*.jsx\"];\nconst DEFAULT_EXCLUDE: FilterPattern = [\"**/node_modules/**\"];\nconst ROOT_META_NAME = \"tempo-project-root\";\n\nfunction cleanModuleId(id: string): string {\n return id.replace(/[?#].*$/, \"\");\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\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\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface TempoAnnotateOptions {\n computeAnnotatedProps?: ComputeAnnotatedProps;\n include?: FilterPattern;\n exclude?: FilterPattern;\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 clients: Set<SseClient>;\n setError(error: TempoViteError): void;\n /** Clear errors for modules present in the HMR update. */\n clearErrorForModules(updatedPaths: string[]): void;\n /** Clear all errors unconditionally (e.g. report-clear endpoint). */\n clearAll(): void;\n}\n\nfunction createErrorServer(): 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 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 clients: new Set(),\n\n setError(error: TempoViteError) {\n const key = error.file ?? error.loc?.file ?? \"unknown\";\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 // An error is cleared when the module that caused it appears in the\n // HMR update's path list. We check with endsWith because Vite update\n // paths are root-relative while error file paths may be absolute.\n if (\n errorKey === \"unknown\" ||\n updatedPaths.some((p) => errorKey.endsWith(p) || p.endsWith(errorKey))\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 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\nfunction handleErrorMiddleware(\n errorServer: TempoErrorServer,\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/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;\n }\n\n if (url === \"/__tempo/report-clear\" && req.method === \"POST\") {\n errorServer.clearAll();\n res.statusCode = 200;\n res.end(\"ok\");\n return;\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;\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;\n }\n\n next();\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 = !!process.env.TEMPO;\n\n const include =\n options.include === undefined ? DEFAULT_INCLUDE : options.include;\n const exclude =\n options.exclude === undefined ? DEFAULT_EXCLUDE : options.exclude;\n const filter = createFilter(include, exclude);\n\n let canonicalRoot = process.cwd();\n let command: ResolvedConfig[\"command\"] = \"serve\";\n const errorServer = createErrorServer();\n\n return {\n name: \"tempo-annotate\",\n enforce: \"pre\",\n\n // Expose error server for testing\n _tempoErrorServer: errorServer,\n\n configResolved(resolvedConfig) {\n if (!enabled) return;\n\n command = resolvedConfig.command;\n canonicalRoot = resolveCanonicalRoot(resolvedConfig.root);\n },\n\n configureServer(server: ViteDevServer) {\n if (!enabled) return;\n server.middlewares.use((req, res, next) => {\n handleErrorMiddleware(errorServer, req, res, next);\n });\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.\n const interceptHmrSend = (target: { send: Function }) => {\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 === \"error\") {\n const err = typed.err;\n errorServer.setError({\n type: \"compile\",\n message: (err?.message as string) ?? \"Unknown error\",\n stack: err?.stack as string | undefined,\n file:\n (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 } else if (typed.type === \"update\") {\n const updates = (typed as { updates?: Array<{ path?: string }> })\n .updates;\n const paths =\n updates\n ?.map((u) => u.path)\n .filter((p): p is string => typeof p === \"string\") ?? [];\n errorServer.clearErrorForModules(paths);\n }\n }\n return (orig as Function)(...args);\n }) as typeof orig;\n };\n\n interceptHmrSend(server.ws as { send: Function });\n const clientHot = (server as any).environments?.client?.hot;\n if (clientHot && clientHot !== server.ws) {\n interceptHmrSend(clientHot as { send: Function });\n }\n },\n\n transformIndexHtml(html) {\n if (!enabled || command !== \"serve\") {\n return;\n }\n\n if (hasRootMetaTag(html)) {\n return;\n }\n\n return [\n {\n tag: \"meta\",\n attrs: {\n name: ROOT_META_NAME,\n content: canonicalRoot,\n },\n injectTo: \"head\" as const,\n },\n ];\n },\n\n transform(source, id) {\n if (!enabled || command === \"build\") {\n return null;\n }\n\n if (id.startsWith(\"\\0\")) {\n return null;\n }\n\n const cleanId = cleanModuleId(id);\n if (!filter(cleanId)) {\n return null;\n }\n\n try {\n const filepath = relative(canonicalRoot, cleanId);\n const modifiedtsMs = Math.trunc(statSync(cleanId).mtimeMs);\n // Hash the exact source being transformed once per file; every element\n // in this file carries the same version token.\n const sourceVersion = sourceVersionHash(source);\n\n const result = annotateFile(source, cleanId, (info) =>\n computeTempoAnnotatedProps({\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps: options.computeAnnotatedProps,\n }),\n );\n\n if (result.elementsAnnotated === 0) {\n return null;\n }\n\n return {\n code: result.annotatedSource,\n map: null,\n };\n } catch {\n return null;\n }\n },\n } as Plugin & { _tempoErrorServer: TempoErrorServer };\n}\n\n/** @deprecated Use `tempoVitePlugin` instead. */\nexport const tempoAnnotate = tempoVitePlugin;\n\nexport type { ElementInfo, PropValue };\n\nexport type {\n TempoCanvasConfig,\n TempoPage,\n StoryboardLayout,\n TempoStoryboard,\n TempoRouteStoryboard,\n TempoHtmlStoryboard,\n} from \"./page.ts\";\n","import { parseSync, type JSXElement, type ParseResult } from 'oxc-parser';\nimport { getTagName, walk } from '@modules/file-parser';\n\nexport interface ElementInfo {\n element: JSXElement;\n /** e.g. \"div\", \"Button\", \"Foo.Bar\" */\n tagName: string;\n}\n\n/** Supported prop value types. `undefined` values are skipped. */\nexport type PropValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ((...args: unknown[]) => unknown)\n | object;\n\nfunction formatPropValue(value: PropValue): string | null {\n if (value === undefined) return null;\n if (typeof value === 'function') return value.toString();\n return JSON.stringify(value);\n}\n\nfunction formatProps(props: Record<string, PropValue>): string {\n return Object.entries(props)\n .map(([key, value]) => {\n const formatted = formatPropValue(value);\n if (formatted === null) return null;\n return ` ${key}={${formatted}}`;\n })\n .filter((s): s is string => s !== null)\n .join('');\n}\n\nfunction getExistingAttributeNames(element: JSXElement): Set<string> {\n const names = new Set<string>();\n\n for (const attr of element.openingElement.attributes ?? []) {\n if (attr.type !== 'JSXAttribute') continue;\n names.add(getTagName(attr.name));\n }\n\n return names;\n}\n\nfunction removeExistingProps(\n props: Record<string, PropValue>,\n existingNames: Set<string>\n): Record<string, PropValue> {\n return Object.fromEntries(\n Object.entries(props).filter(([key]) => !existingNames.has(key))\n );\n}\n\nexport interface AnnotateFileResult {\n annotatedSource: string;\n elementsAnnotated: number;\n /** The oxc-parser result. Check `parseResult.errors` for any parse errors. */\n parseResult: ParseResult;\n}\n\n/** Tag names that represent React fragments and should not be annotated */\nconst FRAGMENT_TAG_NAMES = new Set(['Fragment', 'React.Fragment']);\n\n/**\n * Annotates JSX elements in a source file by inserting additional props.\n *\n * Visits every JSXElement in source order and calls the handler to compute\n * props to insert. Props are inserted at the end of each opening tag.\n *\n * Fragments are skipped since they don't render DOM elements:\n * - JSX shorthand fragments (`<>...</>`) are a separate AST node type\n * - `React.Fragment` and `Fragment` are skipped by tag name\n */\nexport function annotateFile(\n source: string,\n filename: string,\n computeAnnotatedProps: (info: ElementInfo) => Record<string, PropValue>\n): AnnotateFileResult {\n const parseResult = parseSync(filename, source);\n const insertions: { position: number; text: string }[] = [];\n\n // Walk the AST to find all JSXElement nodes\n // Uses our own walker instead of oxc-parser's Visitor (CJS/ESM interop issue in Electron)\n walk(parseResult.program, {\n JSXElement(node: unknown) {\n const element = node as JSXElement;\n const tagName = getTagName(element.openingElement.name);\n if (FRAGMENT_TAG_NAMES.has(tagName)) return;\n\n const props = removeExistingProps(\n computeAnnotatedProps({ element, tagName }),\n getExistingAttributeNames(element)\n );\n if (Object.keys(props).length === 0) return;\n\n const openingElement = element.openingElement;\n\n // Insert before \">\" or \"/>\" at end of opening tag, skipping whitespace before \"/>\"\n let insertPos = openingElement.end - 1;\n if (openingElement.selfClosing) {\n insertPos--;\n while (insertPos > openingElement.start && /\\s/.test(source[insertPos - 1]!)) {\n insertPos--;\n }\n }\n\n insertions.push({ position: insertPos, text: formatProps(props) });\n },\n });\n\n // Build result in a single pass using chunks (O(n) instead of O(n*m))\n insertions.sort((a, b) => a.position - b.position);\n\n const chunks: string[] = [];\n let lastPos = 0;\n for (const { position, text } of insertions) {\n chunks.push(source.slice(lastPos, position));\n chunks.push(text);\n lastPos = position;\n }\n chunks.push(source.slice(lastPos));\n\n return { annotatedSource: chunks.join(''), elementsAnnotated: insertions.length, parseResult };\n}\n","\n/**\n * Annotation Utilities\n *\n * Helper functions for working with oxc-parser AST nodes.\n */\n\nimport type { JSXElementName, JSXMemberExpression } from 'oxc-parser';\n\n/**\n * Extracts the tag name string from any JSXElementName variant.\n *\n * JSXElementName is a union of three types representing different JSX tag syntaxes:\n * - JSXIdentifier: `<button>` → \"button\", `<Button>` → \"Button\"\n * - JSXNamespacedName: `<svg:rect>` → \"svg:rect\" (rare, used in SVG/XML)\n * - JSXMemberExpression: `<Foo.Bar>` → \"Foo.Bar\", `<UI.Button.Primary>` → \"UI.Button.Primary\"\n */\nexport function getTagName(name: JSXElementName): string {\n switch (name.type) {\n case 'JSXIdentifier':\n return name.name;\n case 'JSXNamespacedName':\n return `${name.namespace.name}:${name.name.name}`;\n case 'JSXMemberExpression':\n return getJSXMemberExpressionName(name);\n }\n}\n\n/**\n * Recursively builds the dotted name string from a JSXMemberExpression.\n *\n * JSXMemberExpression represents dotted component names like `<Foo.Bar.Baz>`:\n * - object: either a JSXIdentifier or another JSXMemberExpression (for chaining)\n * - property: always a JSXIdentifier (the rightmost part)\n */\nexport function getJSXMemberExpressionName(node: JSXMemberExpression): string {\n const object = node.object.type === 'JSXIdentifier' ? node.object.name : getJSXMemberExpressionName(node.object);\n return `${object}.${node.property.name}`;\n}\n","/**\n * AST Walker\n *\n * Simple recursive walker for oxc-parser ASTs. Visits every node in the tree\n * and calls type-specific callbacks. Drop-in replacement for oxc-parser's\n * Visitor class, which has CJS/ESM interop issues in Electron.\n *\n * Once oxc-parser's Visitor works in Electron, this can be swapped back.\n */\n\n/**\n * Callbacks for specific AST node types.\n * Add more node types here as needed.\n */\nexport interface WalkCallbacks {\n JSXElement?: (node: any) => void;\n JSXFragment?: (node: any) => void;\n}\n\n/**\n * Recursively walks an oxc-parser AST, calling callbacks for matching node types.\n * Traverses all object properties and array elements depth-first.\n */\nexport function walk(node: unknown, callbacks: WalkCallbacks): void {\n if (node === null || node === undefined || typeof node !== \"object\") return;\n\n if (Array.isArray(node)) {\n for (const child of node) {\n walk(child, callbacks);\n }\n return;\n }\n\n const record = node as Record<string, unknown>;\n const type = record.type;\n\n if (typeof type === \"string\" && type in callbacks) {\n (callbacks as Record<string, (node: unknown) => void>)[type]!(node);\n }\n\n for (const value of Object.values(record)) {\n if (value !== null && typeof value === \"object\") {\n walk(value, callbacks);\n }\n }\n}\n","export type Range = {\n /** Start byte offset (inclusive). */\n start: number;\n /** End byte offset (exclusive). */\n end: number;\n};\n\nexport const ScopeType = {\n Program: 'program',\n Function: 'function',\n Block: 'block',\n Catch: 'catch',\n Class: 'class',\n ClassStaticBlock: 'class-static',\n For: 'for',\n Switch: 'switch',\n TsModule: 'ts-module',\n Enum: 'enum',\n Type: 'type',\n TsConditional: 'ts-conditional',\n} as const;\n\nexport type ScopeType = (typeof ScopeType)[keyof typeof ScopeType];\n\nexport const ScopeFlags = {\n Top: 1 << 0,\n Function: 1 << 1,\n Block: 1 << 2,\n Catch: 1 << 3,\n Class: 1 << 4,\n For: 1 << 5,\n Switch: 1 << 6,\n Module: 1 << 7,\n StrictMode: 1 << 8,\n ClassStaticBlock: 1 << 9,\n TsModuleBlock: 1 << 10,\n TsConditional: 1 << 11,\n Type: 1 << 12,\n Enum: 1 << 13,\n} as const;\n\nexport type ScopeFlags = number;\n\nexport const BindingKind = {\n Var: 'var',\n Let: 'let',\n Const: 'const',\n Function: 'function',\n Class: 'class',\n Param: 'param',\n Import: 'import',\n TypeImport: 'type-import',\n TypeAlias: 'type-alias',\n Interface: 'interface',\n Enum: 'enum',\n EnumMember: 'enum-member',\n TypeParam: 'type-param',\n Namespace: 'namespace',\n} as const;\n\nexport type BindingKind = (typeof BindingKind)[keyof typeof BindingKind];\n\nexport type Scope = {\n id: number;\n type: ScopeType;\n flags: ScopeFlags;\n start: number;\n end: number;\n parentId: number | null;\n childIds: number[];\n bindings: Map<string, number>;\n typeBindings: Map<string, number>;\n};\n\nexport type Binding = {\n id: number;\n name: string;\n kind: BindingKind;\n declStart: number;\n declEnd: number;\n scopeId: number;\n};\n\nexport type Reference = {\n id: number;\n name: string;\n start: number;\n end: number;\n scopeId: number;\n bindingId: number | null;\n};\n\nexport type ScopeAnalysis = {\n source: string;\n scopes: Scope[];\n bindings: Binding[];\n references: Reference[];\n};\n","import { parseSync, type ParserOptions } from 'oxc-parser';\n// oxc-parser's browser build (src-js/wasm.js) does not re-export `visitorKeys`.\n// Deep-import the generated keys table so this works in both Node and browser.\nimport visitorKeysDefault from 'oxc-parser/src-js/generated/visit/keys.js';\n\nconst visitorKeys = visitorKeysDefault as Record<string, readonly string[]>;\nimport {\n BindingKind,\n type Binding,\n type Range,\n type Reference,\n type Scope,\n type ScopeAnalysis,\n ScopeFlags,\n ScopeType,\n} from './types';\n\ntype AnyNode = {\n type: string;\n start?: number;\n end?: number;\n [key: string]: any;\n};\n\ntype AnalyzeOptions = {\n filename?: string;\n parserOptions?: ParserOptions;\n};\n\ntype ScopeStackItem = {\n scopeId: number;\n};\n\nconst ReferenceContext = {\n Value: 'value',\n Type: 'type',\n ValueAsType: 'value-as-type',\n} as const;\n\ntype ReferenceContext =\n (typeof ReferenceContext)[keyof typeof ReferenceContext];\n\nconst DEFAULT_FILENAME = 'file.tsx';\n\nexport function analyzeScopes(source: string, options: AnalyzeOptions = {}): ScopeAnalysis {\n const filename = options.filename ?? DEFAULT_FILENAME;\n const parseResult = parseSync(filename, source, options.parserOptions ?? undefined);\n const program = parseResult.program as AnyNode;\n\n const scopes: Scope[] = [];\n const bindings: Binding[] = [];\n const references: Reference[] = [];\n\n const scopeIdByNode = new WeakMap<object, number>();\n\n const rootScopeId = createScope({\n scopes,\n type: ScopeType.Program,\n start: 0,\n end: source.length,\n parentId: null,\n flags: getProgramFlags(program),\n });\n\n scopeIdByNode.set(program, rootScopeId);\n\n const bindingBuilder = new ScopeBuilder({\n source,\n scopes,\n bindings,\n scopeIdByNode,\n });\n\n bindingBuilder.walkBindings(program);\n\n const referenceBuilder = new ReferenceBuilder({\n scopes,\n bindings,\n references,\n scopeIdByNode,\n });\n\n referenceBuilder.walkReferences(program);\n\n return {\n source,\n scopes,\n bindings,\n references,\n };\n}\n\nexport function getReferenceAtPosition(\n analysis: ScopeAnalysis,\n position: number,\n): Reference | null {\n let best: Reference | null = null;\n for (const ref of analysis.references) {\n if (position >= ref.start && position < ref.end) {\n if (!best || (ref.end - ref.start) < (best.end - best.start)) {\n best = ref;\n }\n }\n }\n return best;\n}\n\nexport function getBindingForReference(\n analysis: ScopeAnalysis,\n reference: Reference,\n): Binding | null {\n if (reference.bindingId == null) {\n return null;\n }\n return analysis.bindings[reference.bindingId] ?? null;\n}\n\nexport function getValidRangesAtPosition(\n analysis: ScopeAnalysis,\n position: number,\n): Range[] {\n const ref = getReferenceAtPosition(analysis, position);\n if (!ref) return [];\n return getValidRangesForReference(analysis, ref);\n}\n\nexport function getValidRangesForReference(\n analysis: ScopeAnalysis,\n reference: Reference,\n): Range[] {\n const binding = getBindingForReference(analysis, reference);\n if (!binding) return [];\n const baseRange = getBindingVisibilityRange(analysis, binding);\n const shadowed = getShadowedRanges(analysis, binding, baseRange);\n return subtractRanges(baseRange, shadowed);\n}\n\nexport function getBindingVisibilityRange(\n analysis: ScopeAnalysis,\n binding: Binding,\n): Range {\n const scope = analysis.scopes[binding.scopeId];\n const start = isBlockScopedBindingKind(binding.kind)\n ? binding.declStart\n : scope.start;\n return { start, end: scope.end };\n}\n\nfunction getShadowedRanges(\n analysis: ScopeAnalysis,\n binding: Binding,\n baseRange: Range,\n): Range[] {\n const rootScope = analysis.scopes[binding.scopeId];\n const ranges: Range[] = [];\n const stack = [...rootScope.childIds];\n const useTypeBindings = usesTypeBindingsForShadowing(binding.kind);\n\n while (stack.length) {\n const scopeId = stack.pop() as number;\n const scope = analysis.scopes[scopeId];\n const shadowBindingId = useTypeBindings\n ? scope.typeBindings.get(binding.name)\n : scope.bindings.get(binding.name);\n\n if (shadowBindingId != null && shadowBindingId !== binding.id) {\n ranges.push({ start: scope.start, end: scope.end });\n continue;\n }\n\n stack.push(...scope.childIds);\n }\n\n return ranges\n .map((range) => clampRange(range, baseRange))\n .filter((range): range is Range => range !== null);\n}\n\nfunction clampRange(range: Range, base: Range): Range | null {\n const start = Math.max(range.start, base.start);\n const end = Math.min(range.end, base.end);\n if (start >= end) return null;\n return { start, end };\n}\n\nfunction subtractRanges(base: Range, exclusions: Range[]): Range[] {\n if (!exclusions.length) return [base];\n const normalized = normalizeRanges(exclusions);\n let current: Range[] = [base];\n\n for (const ex of normalized) {\n const next: Range[] = [];\n for (const range of current) {\n next.push(...subtractOne(range, ex));\n }\n current = next;\n if (!current.length) break;\n }\n\n return current;\n}\n\nfunction subtractOne(range: Range, exclude: Range): Range[] {\n if (exclude.end <= range.start || exclude.start >= range.end) {\n return [range];\n }\n\n const result: Range[] = [];\n if (exclude.start > range.start) {\n result.push({ start: range.start, end: Math.min(exclude.start, range.end) });\n }\n if (exclude.end < range.end) {\n result.push({ start: Math.max(exclude.end, range.start), end: range.end });\n }\n return result;\n}\n\nfunction normalizeRanges(ranges: Range[]): Range[] {\n const sorted = [...ranges].sort((a, b) => a.start - b.start);\n const result: Range[] = [];\n\n for (const range of sorted) {\n const last = result[result.length - 1];\n if (!last || range.start > last.end) {\n result.push({ ...range });\n } else {\n last.end = Math.max(last.end, range.end);\n }\n }\n\n return result;\n}\n\nfunction isNode(value: unknown): value is AnyNode {\n return Boolean(value && typeof value === 'object' && (value as AnyNode).type);\n}\n\nfunction getParamList(params: AnyNode | AnyNode[] | null | undefined): AnyNode[] {\n if (!params) return [];\n if (Array.isArray(params)) return params;\n if (Array.isArray(params.params)) return params.params;\n if (Array.isArray(params.items)) return params.items;\n return [];\n}\n\nfunction getProgramFlags(program: AnyNode): ScopeFlags {\n const sourceType = program.sourceType ?? program.source_type ?? 'module';\n let flags = ScopeFlags.Top;\n if (sourceType === 'module') {\n flags |= ScopeFlags.Module | ScopeFlags.StrictMode;\n }\n if (hasUseStrictDirective(program)) {\n flags |= ScopeFlags.StrictMode;\n }\n return flags;\n}\n\nfunction hasUseStrictDirective(container: AnyNode | null | undefined): boolean {\n if (!container) return false;\n const directives = container.directives;\n if (Array.isArray(directives)) {\n for (const directive of directives) {\n if (getDirectiveText(directive) === 'use strict') {\n return true;\n }\n }\n }\n\n const statements =\n container.body ??\n container.statements ??\n container.body?.body ??\n container.body?.statements;\n if (Array.isArray(statements)) {\n for (const stmt of statements) {\n if (!stmt) continue;\n const directiveText = getDirectiveText(stmt);\n if (directiveText === 'use strict') {\n return true;\n }\n if (directiveText == null) {\n break;\n }\n }\n }\n\n return false;\n}\n\nfunction getDirectiveText(node: AnyNode | null | undefined): string | null {\n if (!node) return null;\n if (typeof node.directive === 'string') {\n return node.directive;\n }\n const expr = node.expression ?? node;\n if (expr?.type === 'StringLiteral' || expr?.type === 'Literal') {\n const value = expr.value ?? expr.rawValue ?? expr.raw;\n if (typeof value === 'string') return value;\n }\n return null;\n}\n\nfunction isStrictScope(node: AnyNode, type: ScopeType): boolean {\n if (type === ScopeType.Class) return true;\n if (type === ScopeType.Function) {\n return hasUseStrictDirective(node.body);\n }\n if (type === ScopeType.TsModule) {\n return hasUseStrictDirective(node.body);\n }\n return false;\n}\n\nfunction shouldAddToValueBindings(kind: BindingKind): boolean {\n switch (kind) {\n case BindingKind.Var:\n case BindingKind.Let:\n case BindingKind.Const:\n case BindingKind.Function:\n case BindingKind.Class:\n case BindingKind.Param:\n case BindingKind.Import:\n case BindingKind.Enum:\n case BindingKind.EnumMember:\n case BindingKind.Namespace:\n return true;\n default:\n return false;\n }\n}\n\nfunction shouldAddToTypeBindings(kind: BindingKind): boolean {\n switch (kind) {\n case BindingKind.TypeImport:\n case BindingKind.TypeAlias:\n case BindingKind.Interface:\n case BindingKind.TypeParam:\n case BindingKind.Class:\n case BindingKind.Enum:\n case BindingKind.EnumMember:\n case BindingKind.Namespace:\n case BindingKind.Import:\n return true;\n default:\n return false;\n }\n}\n\nfunction isBlockScopedBindingKind(kind: BindingKind): boolean {\n return (\n kind === BindingKind.Let ||\n kind === BindingKind.Const ||\n kind === BindingKind.Class ||\n kind === BindingKind.EnumMember\n );\n}\n\nfunction usesTypeBindingsForShadowing(kind: BindingKind): boolean {\n return (\n kind === BindingKind.TypeImport ||\n kind === BindingKind.TypeAlias ||\n kind === BindingKind.Interface ||\n kind === BindingKind.TypeParam\n );\n}\n\nfunction canReferenceAsType(kind: BindingKind): boolean {\n return (\n kind === BindingKind.TypeImport ||\n kind === BindingKind.TypeAlias ||\n kind === BindingKind.Interface ||\n kind === BindingKind.TypeParam ||\n kind === BindingKind.Class ||\n kind === BindingKind.Enum ||\n kind === BindingKind.EnumMember ||\n kind === BindingKind.Namespace ||\n kind === BindingKind.Import\n );\n}\n\nfunction canReferenceAsValueAsType(kind: BindingKind): boolean {\n return kind === BindingKind.TypeImport || shouldAddToValueBindings(kind);\n}\n\nclass ScopeBuilder {\n private source: string;\n private scopes: Scope[];\n private bindings: Binding[];\n private scopeIdByNode: WeakMap<object, number>;\n private scopeStack: ScopeStackItem[] = [];\n\n constructor({\n source,\n scopes,\n bindings,\n scopeIdByNode,\n }: {\n source: string;\n scopes: Scope[];\n bindings: Binding[];\n scopeIdByNode: WeakMap<object, number>;\n }) {\n this.source = source;\n this.scopes = scopes;\n this.bindings = bindings;\n this.scopeIdByNode = scopeIdByNode;\n this.scopeStack.push({ scopeId: 0 });\n }\n\n walkBindings(node: AnyNode, ancestors: AnyNode[] = []): void {\n if (!node) return;\n switch (node.type) {\n case 'Program':\n this.registerScope(node, 0);\n this.walkChildren(node, ancestors);\n return;\n case 'BlockStatement':\n this.withScope(node, ScopeType.Block, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'FunctionDeclaration':\n case 'TSDeclareFunction':\n // `declare function f(...)` is a TSDeclareFunction — the same shape as\n // a FunctionDeclaration minus the body. Treating the two together\n // means ambient function declarations still bind their names at the\n // current scope and their parameters inside a function scope, so\n // downstream resolution behaves identically to the non-ambient form.\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Function, node.id);\n }\n this.withScope(node, ScopeType.Function, () => {\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'FunctionExpression':\n this.withScope(node, ScopeType.Function, () => {\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Function, node.id);\n }\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ArrowFunctionExpression':\n this.withScope(node, ScopeType.Function, () => {\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'VariableDeclaration':\n this.handleVariableDeclaration(node, ancestors);\n return;\n case 'ClassDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Class, node.id);\n }\n this.withScope(node, ScopeType.Class, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ClassExpression':\n this.withScope(node, ScopeType.Class, () => {\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Class, node.id);\n }\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'StaticBlock':\n this.withScope(node, ScopeType.ClassStaticBlock, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'CatchClause':\n this.withScope(node, ScopeType.Catch, () => {\n if (node.param) {\n this.declarePattern(node.param, BindingKind.Param);\n this.walkPatternExpressions(node.param, ancestors);\n }\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ForStatement':\n case 'ForInStatement':\n case 'ForOfStatement':\n this.withScope(node, ScopeType.For, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'SwitchStatement':\n this.withScope(node, ScopeType.Switch, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'ImportDeclaration':\n this.handleImportDeclaration(node);\n return;\n case 'TSImportEqualsDeclaration':\n this.handleImportEqualsDeclaration(node);\n return;\n case 'TSModuleDeclaration':\n this.handleTsModuleDeclaration(node, ancestors);\n return;\n case 'TSGlobalDeclaration':\n this.withScope(node, ScopeType.TsModule, () => {\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'TSTypeAliasDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.TypeAlias, node.id);\n }\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.typeAnnotation ?? node.type_annotation, ancestors);\n });\n return;\n case 'TSInterfaceDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Interface, node.id);\n }\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n if (node.extends) {\n for (const heritage of node.extends) {\n this.walkNode(heritage, ancestors);\n }\n }\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'TSEnumDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Enum, node.id);\n }\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n return;\n case 'TSEnumBody':\n this.withScope(node, ScopeType.Enum, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'TSEnumMember':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.EnumMember, node.id);\n }\n if (node.initializer) {\n this.walkNode(node.initializer, ancestors);\n }\n return;\n case 'TSTypeParameter':\n if (node.name?.name) {\n this.declareBinding(this.currentScopeId(), node.name.name, BindingKind.TypeParam, node.name);\n }\n if (node.constraint) {\n this.walkNode(node.constraint, ancestors);\n }\n if (node.default) {\n this.walkNode(node.default, ancestors);\n }\n return;\n case 'TSTypeParameterDeclaration':\n for (const param of node.params ?? []) {\n this.walkNode(param, ancestors);\n }\n return;\n case 'TSMappedType':\n this.withScope(node, ScopeType.Type, () => {\n if (node.key?.name) {\n this.declareBinding(this.currentScopeId(), node.key.name, BindingKind.TypeParam, node.key);\n }\n this.walkNode(node.constraint, ancestors);\n if (node.nameType ?? node.name_type) {\n this.walkNode(node.nameType ?? node.name_type, ancestors);\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkNode(node.typeAnnotation ?? node.type_annotation, ancestors);\n }\n });\n return;\n case 'TSConditionalType':\n if (node.checkType ?? node.check_type) {\n this.walkNode(node.checkType ?? node.check_type, ancestors);\n }\n this.withScope(node, ScopeType.TsConditional, () => {\n if (node.extendsType ?? node.extends_type) {\n this.walkNode(node.extendsType ?? node.extends_type, ancestors);\n }\n if (node.trueType ?? node.true_type) {\n this.walkNode(node.trueType ?? node.true_type, ancestors);\n }\n });\n if (node.falseType ?? node.false_type) {\n this.walkNode(node.falseType ?? node.false_type, ancestors);\n }\n return;\n case 'TSFunctionType':\n case 'TSConstructorType':\n case 'TSCallSignatureDeclaration':\n case 'TSMethodSignature':\n case 'TSConstructSignatureDeclaration':\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n const params = getParamList(node.params);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.returnType ?? node.return_type) {\n this.walkNode(node.returnType ?? node.return_type, ancestors);\n }\n });\n return;\n default:\n this.walkChildren(node, ancestors);\n }\n }\n\n private currentScopeId(): number {\n return this.scopeStack[this.scopeStack.length - 1]?.scopeId ?? 0;\n }\n\n private withScope(node: AnyNode, type: ScopeType, fn: () => void): void {\n const parentScopeId = this.currentScopeId();\n const parentScope = this.scopes[parentScopeId];\n let flags = getScopeFlags(type, parentScope.flags);\n if (isStrictScope(node, type)) {\n flags |= ScopeFlags.StrictMode;\n }\n flags = inheritStrictMode(flags, parentScope.flags);\n const start = getScopeStart(node, type, this.source);\n const end = getScopeEnd(node, type, this.source);\n const scopeId = createScope({\n scopes: this.scopes,\n type,\n start,\n end,\n parentId: parentScopeId,\n flags,\n });\n this.registerScope(node, scopeId);\n if (type === ScopeType.Block && parentScope.type === ScopeType.Catch) {\n this.moveBindingsToChild(parentScopeId, scopeId);\n }\n this.scopeStack.push({ scopeId });\n fn();\n this.scopeStack.pop();\n }\n\n private registerScope(node: AnyNode, scopeId: number): void {\n if (node && typeof node === 'object') {\n this.scopeIdByNode.set(node, scopeId);\n }\n }\n\n private moveBindingsToChild(parentScopeId: number, childScopeId: number): void {\n const parentScope = this.scopes[parentScopeId];\n if (!parentScope.bindings.size) return;\n const childScope = this.scopes[childScopeId];\n for (const [name, bindingId] of parentScope.bindings.entries()) {\n childScope.bindings.set(name, bindingId);\n const binding = this.bindings[bindingId];\n if (binding) {\n binding.scopeId = childScopeId;\n }\n }\n parentScope.bindings.clear();\n }\n\n private declareBinding(scopeId: number, name: string, kind: BindingKind, node: AnyNode): number {\n const scope = this.scopes[scopeId];\n const addValue = shouldAddToValueBindings(kind);\n const addType = shouldAddToTypeBindings(kind);\n if (addValue) {\n const existingValue = scope.bindings.get(name);\n if (existingValue != null) {\n if (kind === BindingKind.Var || kind === BindingKind.Function) {\n return existingValue;\n }\n return existingValue;\n }\n } else if (addType) {\n const existingType = scope.typeBindings.get(name);\n if (existingType != null) {\n return existingType;\n }\n }\n const binding: Binding = {\n id: this.bindings.length,\n name,\n kind,\n declStart: node.start ?? 0,\n declEnd: node.end ?? (node.start ?? 0),\n scopeId,\n };\n this.bindings.push(binding);\n if (addValue) {\n scope.bindings.set(name, binding.id);\n }\n if (addType && !scope.typeBindings.has(name)) {\n scope.typeBindings.set(name, binding.id);\n }\n return binding.id;\n }\n\n private declareParams(params: AnyNode[]): void {\n for (const param of params) {\n this.declarePattern(param, BindingKind.Param);\n }\n }\n\n private declareTypeParameters(typeParameters: AnyNode | null | undefined, ancestors: AnyNode[]): void {\n if (!typeParameters) return;\n const params = typeParameters.params ?? typeParameters.parameters;\n const list = Array.isArray(params)\n ? params\n : Array.isArray(typeParameters.items)\n ? typeParameters.items\n : Array.isArray(typeParameters)\n ? typeParameters\n : [];\n for (const param of list) {\n this.walkNode(param, ancestors);\n }\n }\n\n private declarePattern(pattern: AnyNode, kind: BindingKind): void {\n const identifiers: AnyNode[] = [];\n collectBindingIdentifiers(pattern, identifiers);\n for (const ident of identifiers) {\n if (ident?.name) {\n this.declareBinding(this.currentScopeId(), ident.name, kind, ident);\n }\n }\n }\n\n private handleVariableDeclaration(node: AnyNode, ancestors: AnyNode[]): void {\n const kind = node.kind;\n const bindingKind = kind === 'var' ? BindingKind.Var : kind === 'let' ? BindingKind.Let : BindingKind.Const;\n for (const decl of node.declarations ?? []) {\n if (!decl) continue;\n const scopeId =\n bindingKind === BindingKind.Var\n ? this.findVarScopeId()\n : this.currentScopeId();\n const identifiers: AnyNode[] = [];\n collectBindingIdentifiers(decl.id, identifiers);\n for (const ident of identifiers) {\n if (ident?.name) {\n this.declareBinding(scopeId, ident.name, bindingKind, ident);\n }\n }\n if (decl.id) {\n this.walkPatternExpressions(decl.id, ancestors);\n }\n if (decl.init) {\n this.walkNode(decl.init, ancestors);\n }\n }\n }\n\n private handleImportDeclaration(node: AnyNode): void {\n const rootScopeId = 0;\n const declarationKind =\n (node.importKind ?? node.import_kind) === 'type'\n ? BindingKind.TypeImport\n : BindingKind.Import;\n for (const spec of node.specifiers ?? []) {\n const local = spec?.local;\n if (!local?.name) continue;\n let kind = declarationKind;\n if (spec?.type === 'ImportSpecifier') {\n const specKind = spec.importKind ?? spec.import_kind;\n if (declarationKind === BindingKind.Import && specKind === 'type') {\n kind = BindingKind.TypeImport;\n }\n }\n this.declareBinding(rootScopeId, local.name, kind, local);\n }\n }\n\n private handleImportEqualsDeclaration(node: AnyNode): void {\n const kind =\n (node.importKind ?? node.import_kind) === 'type'\n ? BindingKind.TypeImport\n : BindingKind.Import;\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, kind, node.id);\n }\n }\n\n private handleTsModuleDeclaration(node: AnyNode, ancestors: AnyNode[]): void {\n const id = node.id;\n if (id?.type === 'Identifier' && id.name) {\n this.declareBinding(this.currentScopeId(), id.name, BindingKind.Namespace, id);\n }\n this.withScope(node, ScopeType.TsModule, () => {\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n }\n\n private walkParams(params: AnyNode[], ancestors: AnyNode[]): void {\n for (const param of params) {\n this.walkPatternExpressions(param, ancestors);\n }\n }\n\n private walkPatternExpressions(pattern: AnyNode, ancestors: AnyNode[]): void {\n if (!pattern) return;\n if (pattern.type === 'TSParameterProperty' && pattern.parameter) {\n this.walkPatternExpressions(pattern.parameter, ancestors.concat(pattern));\n return;\n }\n if (pattern.typeAnnotation) {\n this.walkNode(pattern.typeAnnotation, ancestors.concat(pattern));\n }\n switch (pattern.type) {\n case 'Identifier':\n return;\n case 'RestElement':\n this.walkPatternExpressions(pattern.argument, ancestors);\n return;\n case 'AssignmentPattern':\n this.walkPatternExpressions(pattern.left, ancestors);\n if (pattern.right) {\n this.walkNode(pattern.right, ancestors);\n }\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) {\n this.walkPatternExpressions(element, ancestors);\n }\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n if (prop.computed && prop.key) {\n this.walkNode(prop.key, ancestors);\n }\n if (prop.value) {\n this.walkPatternExpressions(prop.value, ancestors);\n }\n } else if (prop.type === 'RestElement') {\n this.walkPatternExpressions(prop.argument, ancestors);\n }\n }\n return;\n default:\n this.walkNode(pattern, ancestors);\n }\n }\n\n private findVarScopeId(): number {\n for (let i = this.scopeStack.length - 1; i >= 0; i -= 1) {\n const scope = this.scopes[this.scopeStack[i].scopeId];\n if (\n scope.type === ScopeType.Function ||\n scope.type === ScopeType.Program ||\n scope.type === ScopeType.ClassStaticBlock ||\n scope.type === ScopeType.TsModule\n ) {\n return scope.id;\n }\n }\n return 0;\n }\n\n private walkNode(node: AnyNode, ancestors: AnyNode[]): void {\n if (!node) return;\n this.walkBindings(node, ancestors.concat(node));\n }\n\n private walkChildren(node: AnyNode, ancestors: AnyNode[]): void {\n const keys = visitorKeys[node.type] ?? [];\n for (const key of keys) {\n const value = node[key];\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n this.walkBindings(child, ancestors.concat(node));\n }\n }\n } else if (isNode(value)) {\n this.walkBindings(value, ancestors.concat(node));\n }\n }\n }\n}\n\nclass ReferenceBuilder {\n private scopes: Scope[];\n private bindings: Binding[];\n private references: Reference[];\n private scopeIdByNode: WeakMap<object, number>;\n private scopeStack: ScopeStackItem[] = [];\n private contextStack: ReferenceContext[] = [ReferenceContext.Value];\n\n constructor({\n scopes,\n bindings,\n references,\n scopeIdByNode,\n }: {\n scopes: Scope[];\n bindings: Binding[];\n references: Reference[];\n scopeIdByNode: WeakMap<object, number>;\n }) {\n this.scopes = scopes;\n this.bindings = bindings;\n this.references = references;\n this.scopeIdByNode = scopeIdByNode;\n this.scopeStack.push({ scopeId: 0 });\n }\n\n walkReferences(node: AnyNode, ancestors: AnyNode[] = []): void {\n if (!node) return;\n switch (node.type) {\n case 'Program':\n case 'BlockStatement':\n case 'ForStatement':\n case 'ForInStatement':\n case 'ForOfStatement':\n case 'SwitchStatement':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'FunctionDeclaration':\n case 'FunctionExpression':\n case 'ArrowFunctionExpression':\n case 'TSDeclareFunction':\n case 'TSEmptyBodyFunctionExpression':\n // TSDeclareFunction covers `declare function f(...)` and function\n // overload signatures; TSEmptyBodyFunctionExpression is the body-less\n // signature used by abstract methods. Both share function-shaped\n // scoping of params and need references inside their type annotations\n // and predicates to resolve against the function's own scope.\n this.withScope(node, () => {\n const params = getParamList(node.params);\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'CatchClause':\n this.withScope(node, () => {\n if (node.param) {\n this.walkPatternReferences(node.param, ancestors.concat(node));\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'ClassDeclaration':\n case 'ClassExpression':\n // Decorators evaluate in the enclosing scope (they run at class-definition\n // time), so walk them before entering the class scope.\n this.walkDecorators(node, ancestors);\n this.withScope(node, () => {\n if (node.superClass) {\n this.walkReferences(node.superClass, ancestors.concat(node));\n }\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const superTypeArguments =\n node.superTypeArguments ??\n node.super_type_arguments ??\n node.superTypeParameters ??\n node.super_type_parameters;\n if (typeParameters) {\n this.withTypeContext(() => {\n this.walkReferences(typeParameters, ancestors.concat(node));\n });\n }\n if (superTypeArguments) {\n this.withTypeContext(() => {\n this.walkReferences(superTypeArguments, ancestors.concat(node));\n });\n }\n if (node.implements) {\n this.withTypeContext(() => {\n for (const impl of node.implements ?? []) {\n this.walkReferences(impl, ancestors.concat(node));\n }\n });\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'StaticBlock':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'VariableDeclarator':\n if (node.id) {\n this.walkPatternReferences(node.id, ancestors);\n }\n if (node.init) {\n this.walkReferences(node.init, ancestors.concat(node));\n }\n return;\n case 'ImportDeclaration':\n return;\n case 'ExportNamedDeclaration':\n // Walk the optional inline declaration (e.g. `export const x = 1`).\n // Specifiers come in two flavors:\n // - `export { foo }` / `export { foo as bar }` (no `source`) — the\n // `local` Identifier is a real reference to a local binding; the\n // `exported` alias is external-only and must NOT count as a\n // reference. In shorthand form the two point to the same node, so\n // walking only `local` also prevents double-counting.\n // - `export { foo } from 'm'` (with `source`) — neither side refers\n // to a local binding; they're names on the re-exported module.\n if (node.declaration) {\n this.walkReferences(node.declaration, ancestors.concat(node));\n }\n if (!node.source) {\n for (const spec of node.specifiers ?? []) {\n if (spec?.local) {\n this.walkReferences(spec.local, ancestors.concat(node, spec));\n }\n }\n }\n return;\n case 'ExportAllDeclaration':\n // `export * from 'm'` and `export * as ns from 'm'` never reference\n // local bindings — the alias in the latter is an external name only.\n return;\n case 'ExportDefaultDeclaration':\n if (node.declaration) {\n this.walkReferences(node.declaration, ancestors.concat(node));\n }\n return;\n case 'MetaProperty':\n // `import.meta` / `new.target` — both children are syntactic keyword\n // tokens, not user identifiers, so there are no references to emit.\n return;\n case 'TSImportEqualsDeclaration':\n if (node.moduleReference ?? node.module_reference) {\n this.walkReferences(node.moduleReference ?? node.module_reference, ancestors.concat(node));\n }\n return;\n case 'TSModuleDeclaration':\n case 'TSGlobalDeclaration':\n this.withScope(node, () => {\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'TSModuleBlock':\n this.walkChildren(node, ancestors);\n return;\n case 'TSTypeAliasDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const typeAnnotation = node.typeAnnotation ?? node.type_annotation;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (typeAnnotation) {\n this.walkReferences(typeAnnotation, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSInterfaceDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (node.extends) {\n for (const heritage of node.extends ?? []) {\n this.walkReferences(heritage, ancestors.concat(node));\n }\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSEnumDeclaration':\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n return;\n case 'TSEnumBody':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'TSEnumMember':\n if (node.initializer) {\n this.walkReferences(node.initializer, ancestors.concat(node));\n }\n return;\n case 'TSMappedType':\n this.withScope(node, () => {\n const nameType = node.nameType ?? node.name_type;\n const typeAnnotation = node.typeAnnotation ?? node.type_annotation;\n this.withTypeContext(() => {\n if (node.constraint) {\n this.walkReferences(node.constraint, ancestors.concat(node));\n }\n if (nameType) {\n this.walkReferences(nameType, ancestors.concat(node));\n }\n if (typeAnnotation) {\n this.walkReferences(typeAnnotation, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSConditionalType':\n this.withTypeContext(() => {\n const checkType = node.checkType ?? node.check_type;\n const extendsType = node.extendsType ?? node.extends_type;\n const trueType = node.trueType ?? node.true_type;\n const falseType = node.falseType ?? node.false_type;\n if (checkType) {\n this.walkReferences(checkType, ancestors.concat(node));\n }\n this.withScope(node, () => {\n if (extendsType) {\n this.walkReferences(extendsType, ancestors.concat(node));\n }\n if (trueType) {\n this.walkReferences(trueType, ancestors.concat(node));\n }\n });\n if (falseType) {\n this.walkReferences(falseType, ancestors.concat(node));\n }\n });\n return;\n case 'TSFunctionType':\n case 'TSConstructorType':\n case 'TSCallSignatureDeclaration':\n case 'TSConstructSignatureDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n const params = getParamList(node.params);\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSMethodSignature':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n const params = getParamList(node.params);\n this.withTypeContext(() => {\n if (node.key && node.computed) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.key, ancestors.concat(node));\n });\n }\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSPropertySignature':\n this.withTypeContext(() => {\n if (node.key && node.computed) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.key, ancestors.concat(node));\n });\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n }\n });\n return;\n case 'TSTypeQuery':\n if (node.exprName ?? node.expr_name) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.exprName ?? node.expr_name, ancestors.concat(node));\n });\n }\n if (node.typeArguments ?? node.type_arguments) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeArguments ?? node.type_arguments, ancestors.concat(node));\n });\n }\n return;\n case 'TSAsExpression':\n case 'TSSatisfiesExpression':\n case 'TSTypeAssertion':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n });\n }\n return;\n case 'TSInstantiationExpression':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n if (node.typeArguments ?? node.type_arguments) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeArguments ?? node.type_arguments, ancestors.concat(node));\n });\n }\n return;\n case 'TSNonNullExpression':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n return;\n case 'PropertyDefinition':\n case 'ClassProperty':\n case 'AccessorProperty':\n case 'TSAbstractPropertyDefinition':\n case 'TSAbstractAccessorProperty':\n this.walkDecorators(node, ancestors);\n if (node.computed && node.key) {\n this.walkReferences(node.key, ancestors.concat(node));\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n });\n }\n if (node.value) {\n this.walkReferences(node.value, ancestors.concat(node));\n }\n return;\n case 'TSAbstractMethodDefinition':\n // Abstract methods have no body; their `value` is an empty-body\n // function expression. Walk decorators, the computed key, and the\n // signature so any references inside still resolve.\n this.walkDecorators(node, ancestors);\n if (node.computed && node.key) {\n this.walkReferences(node.key, ancestors.concat(node));\n }\n if (node.value) {\n this.walkReferences(node.value, ancestors.concat(node));\n }\n return;\n case 'TSTypePredicate':\n // `x is T` / `asserts x is T`: the parameter name is a value-level\n // reference to the function's parameter, and the optional annotation\n // is a plain type. Use value-as-type for the param so a regular Param\n // binding (not a type binding) can resolve it.\n if (node.parameterName) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.parameterName, ancestors.concat(node));\n });\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n }\n return;\n default:\n break;\n }\n\n if (node.type === 'JSXIdentifier') {\n const parent = ancestors[ancestors.length - 1];\n const grandparent = ancestors[ancestors.length - 2];\n const parentKey = getParentKey(parent, node);\n if (isJsxIdentifierReference(node, parent, grandparent, parentKey)) {\n this.addReference(node);\n }\n return;\n }\n\n if (node.type === 'Identifier') {\n const parent = ancestors[ancestors.length - 1];\n const grandparent = ancestors[ancestors.length - 2];\n const parentKey = getParentKey(parent, node);\n if (isIdentifierReference(node, parent, grandparent, parentKey)) {\n this.addReference(node);\n }\n return;\n }\n\n this.walkChildren(node, ancestors);\n }\n\n private withScope(node: AnyNode, fn: () => void): void {\n const scopeId = this.scopeIdByNode.get(node);\n if (scopeId == null) {\n fn();\n return;\n }\n this.scopeStack.push({ scopeId });\n fn();\n this.scopeStack.pop();\n }\n\n private withContext(context: ReferenceContext, fn: () => void): void {\n this.contextStack.push(context);\n fn();\n this.contextStack.pop();\n }\n\n private withTypeContext(fn: () => void): void {\n this.withContext(ReferenceContext.Type, fn);\n }\n\n private withValueAsTypeContext(fn: () => void): void {\n this.withContext(ReferenceContext.ValueAsType, fn);\n }\n\n private currentContext(): ReferenceContext {\n return this.contextStack[this.contextStack.length - 1] ?? ReferenceContext.Value;\n }\n\n private addReference(node: AnyNode): void {\n const name = node.name;\n const scopeId = this.currentScopeId();\n const bindingId = this.resolveBinding(scopeId, name, this.currentContext());\n const ref: Reference = {\n id: this.references.length,\n name,\n start: node.start ?? 0,\n end: node.end ?? (node.start ?? 0),\n scopeId,\n bindingId,\n };\n this.references.push(ref);\n }\n\n private currentScopeId(): number {\n return this.scopeStack[this.scopeStack.length - 1]?.scopeId ?? 0;\n }\n\n private resolveBinding(\n scopeId: number,\n name: string,\n context: ReferenceContext,\n ): number | null {\n let currentScopeId: number | null = scopeId;\n while (currentScopeId != null) {\n const scope: Scope = this.scopes[currentScopeId]!;\n if (context === ReferenceContext.Type) {\n const typeBindingId = scope.typeBindings.get(name);\n if (typeBindingId != null) return typeBindingId;\n const valueBindingId = scope.bindings.get(name);\n if (valueBindingId != null) {\n const bindingKind = this.bindings[valueBindingId]?.kind;\n if (bindingKind && canReferenceAsType(bindingKind)) {\n return valueBindingId;\n }\n }\n } else if (context === ReferenceContext.ValueAsType) {\n const valueBindingId = scope.bindings.get(name);\n if (valueBindingId != null) return valueBindingId;\n const typeBindingId = scope.typeBindings.get(name);\n if (typeBindingId != null) {\n const bindingKind = this.bindings[typeBindingId]?.kind;\n if (bindingKind && canReferenceAsValueAsType(bindingKind)) {\n return typeBindingId;\n }\n }\n } else {\n const bindingId = scope.bindings.get(name);\n if (bindingId != null) return bindingId;\n }\n currentScopeId = scope.parentId;\n }\n return null;\n }\n\n private walkDecorators(node: AnyNode, ancestors: AnyNode[]): void {\n const decorators = node.decorators;\n if (!Array.isArray(decorators)) return;\n for (const decorator of decorators) {\n if (decorator) {\n this.walkReferences(decorator, ancestors.concat(node));\n }\n }\n }\n\n private walkPatternReferences(pattern: AnyNode, ancestors: AnyNode[]): void {\n if (!pattern) return;\n // Parameter decorators (e.g. `m(@dec x: number)`) attach to the pattern\n // itself and must resolve against the surrounding scope like any other\n // expression.\n this.walkDecorators(pattern, ancestors);\n if (pattern.type === 'TSParameterProperty' && pattern.parameter) {\n this.walkPatternReferences(pattern.parameter, ancestors.concat(pattern));\n return;\n }\n if (pattern.typeAnnotation) {\n this.withTypeContext(() => {\n this.walkReferences(pattern.typeAnnotation, ancestors.concat(pattern));\n });\n }\n switch (pattern.type) {\n case 'Identifier':\n return;\n case 'RestElement':\n this.walkPatternReferences(pattern.argument, ancestors.concat(pattern));\n return;\n case 'AssignmentPattern':\n this.walkPatternReferences(pattern.left, ancestors.concat(pattern));\n if (pattern.right) {\n this.walkReferences(pattern.right, ancestors.concat(pattern));\n }\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) {\n this.walkPatternReferences(element, ancestors.concat(pattern));\n }\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n if (prop.computed && prop.key) {\n this.walkReferences(prop.key, ancestors.concat(prop));\n }\n if (prop.value) {\n this.walkPatternReferences(prop.value, ancestors.concat(prop));\n }\n } else if (prop.type === 'RestElement') {\n this.walkPatternReferences(prop.argument, ancestors.concat(prop));\n }\n }\n return;\n default:\n this.walkReferences(pattern, ancestors.concat(pattern));\n }\n }\n\n private walkChildren(node: AnyNode, ancestors: AnyNode[]): void {\n const keys = visitorKeys[node.type] ?? [];\n for (const key of keys) {\n const value = node[key];\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n this.walkReferences(child, ancestors.concat(node));\n }\n }\n } else if (isNode(value)) {\n this.walkReferences(value, ancestors.concat(node));\n }\n }\n }\n}\n\nfunction createScope({\n scopes,\n type,\n start,\n end,\n parentId,\n flags,\n}: {\n scopes: Scope[];\n type: ScopeType;\n start: number;\n end: number;\n parentId: number | null;\n flags: ScopeFlags;\n}): number {\n const scopeId = scopes.length;\n const scope: Scope = {\n id: scopeId,\n type,\n flags,\n start,\n end,\n parentId,\n childIds: [],\n bindings: new Map(),\n typeBindings: new Map(),\n };\n scopes.push(scope);\n if (parentId != null) {\n scopes[parentId].childIds.push(scopeId);\n }\n return scopeId;\n}\n\nfunction inheritStrictMode(flags: ScopeFlags, parentFlags: ScopeFlags): ScopeFlags {\n if (parentFlags & ScopeFlags.StrictMode) {\n return flags | ScopeFlags.StrictMode;\n }\n return flags;\n}\n\nfunction getScopeFlags(type: ScopeType, parentFlags: ScopeFlags): ScopeFlags {\n switch (type) {\n case ScopeType.Program:\n return parentFlags;\n case ScopeType.Function:\n return ScopeFlags.Function;\n case ScopeType.Block:\n return ScopeFlags.Block;\n case ScopeType.Catch:\n return ScopeFlags.Catch | ScopeFlags.Block;\n case ScopeType.Class:\n return ScopeFlags.Class;\n case ScopeType.ClassStaticBlock:\n return ScopeFlags.ClassStaticBlock;\n case ScopeType.For:\n return ScopeFlags.For | ScopeFlags.Block;\n case ScopeType.Switch:\n return ScopeFlags.Switch | ScopeFlags.Block;\n case ScopeType.TsModule:\n return ScopeFlags.TsModuleBlock;\n case ScopeType.Enum:\n return ScopeFlags.Enum;\n case ScopeType.Type:\n return ScopeFlags.Type;\n case ScopeType.TsConditional:\n return ScopeFlags.TsConditional;\n default:\n return ScopeFlags.Block;\n }\n}\n\nfunction getScopeStart(node: AnyNode, type: ScopeType, source: string): number {\n if (type === ScopeType.Program) return 0;\n if (type === ScopeType.TsModule) {\n const body = node.body;\n if (body?.start != null) return body.start;\n }\n if (type === ScopeType.Function) {\n const body = node.body;\n if (body?.start != null) return body.start;\n }\n return node.start ?? 0;\n}\n\nfunction getScopeEnd(node: AnyNode, type: ScopeType, source: string): number {\n if (type === ScopeType.Program) return source.length;\n if (type === ScopeType.TsModule) {\n const body = node.body;\n if (body?.end != null) return body.end;\n }\n if (type === ScopeType.Function) {\n const body = node.body;\n if (body?.end != null) return body.end;\n }\n return node.end ?? source.length;\n}\n\nfunction collectBindingIdentifiers(pattern: AnyNode, out: AnyNode[]): void {\n if (!pattern) return;\n switch (pattern.type) {\n case 'Identifier':\n out.push(pattern);\n return;\n case 'TSParameterProperty':\n collectBindingIdentifiers(pattern.parameter, out);\n return;\n case 'RestElement':\n collectBindingIdentifiers(pattern.argument, out);\n return;\n case 'AssignmentPattern':\n collectBindingIdentifiers(pattern.left, out);\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) collectBindingIdentifiers(element, out);\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n collectBindingIdentifiers(prop.value, out);\n } else if (prop.type === 'RestElement') {\n collectBindingIdentifiers(prop.argument, out);\n }\n }\n return;\n default:\n return;\n }\n}\n\nfunction getParentKey(parent: AnyNode | undefined, node: AnyNode): string | null {\n if (!parent) return null;\n for (const key of Object.keys(parent)) {\n const value = parent[key];\n if (value === node) return key;\n if (Array.isArray(value)) {\n if (value.includes(node)) return key;\n }\n }\n return null;\n}\n\nfunction isIdentifierReference(\n node: AnyNode,\n parent?: AnyNode,\n grandparent?: AnyNode,\n parentKey?: string | null,\n): boolean {\n if (!parent) return true;\n\n if (\n parent.type === 'MemberExpression' &&\n parentKey === 'property' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'Property' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'MethodDefinition' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'PropertyDefinition' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n parent.type === 'ClassProperty' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n parent.type === 'AccessorProperty' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n (parent.type === 'TSAbstractMethodDefinition' ||\n parent.type === 'TSAbstractPropertyDefinition' ||\n parent.type === 'TSAbstractAccessorProperty') &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n (parent.type === 'TSPropertySignature' || parent.type === 'TSMethodSignature') &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n // Note: we don't add an ObjectPattern-specific exclusion. Declaration\n // contexts (VariableDeclarator, params, catch) route through\n // `walkPatternReferences` which never calls `isIdentifierReference`, so the\n // only time a `Property` inside an `ObjectPattern` reaches this check is\n // when the pattern is an *assignment target* — in which case the shorthand\n // value identifier genuinely is a reference. The general Property.key rule\n // above still excludes the non-computed key side.\n\n if (\n parent.type === 'VariableDeclarator' &&\n parentKey === 'id'\n ) {\n return false;\n }\n\n if (\n (parent.type === 'FunctionDeclaration' ||\n parent.type === 'FunctionExpression' ||\n parent.type === 'ArrowFunctionExpression') &&\n (parentKey === 'id' || parentKey === 'params')\n ) {\n return false;\n }\n\n if (\n (parent.type === 'ClassDeclaration' || parent.type === 'ClassExpression') &&\n parentKey === 'id'\n ) {\n return false;\n }\n if (\n (parent.type === 'TSTypeAliasDeclaration' ||\n parent.type === 'TSInterfaceDeclaration' ||\n parent.type === 'TSEnumDeclaration' ||\n parent.type === 'TSModuleDeclaration' ||\n parent.type === 'TSImportEqualsDeclaration') &&\n parentKey === 'id'\n ) {\n return false;\n }\n if (parent.type === 'TSEnumMember' && parentKey === 'id') {\n return false;\n }\n if (parent.type === 'TSTypeParameter' && parentKey === 'name') {\n return false;\n }\n if (parent.type === 'TSMappedType' && parentKey === 'key') {\n return false;\n }\n if (parent.type === 'TSIndexSignature' && parentKey === 'parameters') {\n return false;\n }\n if (\n (parent.type === 'TSQualifiedName' || parent.type === 'TSImportTypeQualifiedName') &&\n parentKey === 'right'\n ) {\n return false;\n }\n\n if (\n (parent.type === 'ImportSpecifier' ||\n parent.type === 'ImportDefaultSpecifier' ||\n parent.type === 'ImportNamespaceSpecifier') &&\n parentKey === 'local'\n ) {\n return false;\n }\n\n if (parent.type === 'CatchClause' && parentKey === 'param') {\n return false;\n }\n\n if (parent.type === 'LabeledStatement' && parentKey === 'label') {\n return false;\n }\n if (\n (parent.type === 'BreakStatement' || parent.type === 'ContinueStatement') &&\n parentKey === 'label'\n ) {\n return false;\n }\n\n return true;\n}\n\nfunction isJsxIdentifierReference(\n node: AnyNode,\n parent?: AnyNode,\n grandparent?: AnyNode,\n parentKey?: string | null,\n): boolean {\n if (!parent) return true;\n if (parent.type === 'JSXAttribute' && parentKey === 'name') {\n return false;\n }\n if (parent.type === 'JSXMemberExpression' && parentKey === 'property') {\n return false;\n }\n if (parent.type === 'JSXNamespacedName') {\n return false;\n }\n return true;\n}\n","/**\n * Canvas source-version identity.\n *\n * `sourceVersionHash` maps the exact text of a source file to a 16-hex-character\n * token identifying that content. It is the version stamp the canvas edit/\n * reconcile loop uses to answer \"has the host caught up to write W?\": the SDK\n * JSX transforms stamp `data-tempo-source-version` with the hash of the source\n * they annotate, and the write pipeline (`applyWrites` → `sourceVersionsByFile`)\n * reports the hash of the exact bytes it wrote. A captured element's stamp is\n * compared for EQUALITY against a write's version — never ordered, never\n * subtracted, never used as a high-water mark. Two identical contents MUST\n * produce the same token; two different contents MUST (for identity purposes)\n * produce different tokens.\n *\n * Because coverage is an equality test across independently-computed hashes,\n * every producer of a version — this function's callers in the vite/next/expo\n * transforms and in `applyWrites` — MUST route through THIS function so the\n * tokens are bit-identical. Changing the algorithm requires changing it for all\n * producers in lockstep, or old stamps and new write-versions stop matching.\n *\n * The token concatenates two independent 32-bit rolling hashes over the string's\n * UTF-16 code units — djb2 and sdbm — each rendered as unsigned 8-char hex. Two\n * independent hash families make an accidental collision between distinct source\n * contents vanishingly unlikely for version-identity use, while the function\n * stays dependency-free and single-pass (fast enough to run once per file per\n * transform on the devserver hot path).\n */\nexport function sourceVersionHash(content: string): string {\n let djb2 = 5381;\n let sdbm = 0;\n for (let i = 0; i < content.length; i++) {\n const c = content.charCodeAt(i);\n // djb2: hash * 33 ^ c. The trailing `^ c` keeps the value inside 32-bit\n // signed range every iteration, so no explicit coercion is needed.\n djb2 = ((djb2 << 5) + djb2) ^ c;\n // sdbm: c + hash*65599. The final term is an arithmetic subtraction, so\n // coerce back to a 32-bit int each step to prevent float drift.\n sdbm = (c + (sdbm << 6) + (sdbm << 16) - sdbm) | 0;\n }\n return toHex8(djb2) + toHex8(sdbm);\n}\n\n/** Render a 32-bit value as unsigned, zero-padded 8-char lowercase hex. */\nfunction toHex8(n: number): string {\n return (n >>> 0).toString(16).padStart(8, \"0\");\n}\n","import { realpathSync, statSync } from \"node:fs\";\nimport { relative } from \"node:path\";\n\nimport type {\n ElementInfo,\n PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\n\nexport const DEFAULT_EXCLUDE = [\"**/node_modules/**\"] as const;\n\n/**\n * Static per-component declaration of whether a custom component accepts\n * `children`. Supplied by callers that know this from a fixed table (e.g. the\n * Expo plugin's React Native host-component overrides). The Vite/Next.js\n * plugins supply no overrides — custom components are left without a\n * `supports-children` flag and consumers treat their support as unknown.\n */\nexport interface ElementTypeSupport {\n supportsChildren: boolean;\n}\n\n/** HTML void elements that cannot have children (self-closing only). */\nexport const HTML_VOID_ELEMENTS = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n) => Record<string, PropValue>;\n\nexport function cleanModuleId(id: string): string {\n return id.replace(/[?#].*$/, \"\");\n}\n\nexport function resolveCanonicalRoot(root: string): string {\n try {\n return realpathSync.native(root);\n } catch {\n return root;\n }\n}\n\nexport function isIntrinsicElement(tagName: string): boolean {\n return tagName.length > 0 && tagName[0] === tagName[0]!.toLowerCase();\n}\n\nexport function hasJsxAttribute(info: ElementInfo, attrName: string): boolean {\n for (const attr of info.element.openingElement.attributes) {\n const name = (attr as { name?: { name?: unknown } }).name;\n if (name?.name === attrName) return true;\n }\n return false;\n}\n\nexport function defaultComputeAnnotatedProps(\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n): Record<string, PropValue> {\n return {\n \"data-tempo-filepath\": filepath,\n \"data-tempo-position\": info.element.openingElement.start,\n \"data-tempo-modifiedts\": modifiedtsMs,\n // Content-hash identity of the file this element was annotated from. The\n // canvas reconcile loop equality-compares it against the write pipeline's\n // computed version to decide whether a capture reflects a given edit.\n \"data-tempo-source-version\": sourceVersion,\n };\n}\n\nexport function computeTempoAnnotatedProps(params: {\n info: ElementInfo;\n filepath: string;\n modifiedtsMs: number;\n sourceVersion: string;\n computeAnnotatedProps?: ComputeAnnotatedProps;\n elementSupportOverrides?: ReadonlyMap<string, ElementTypeSupport>;\n}): Record<string, PropValue> {\n const {\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps,\n elementSupportOverrides,\n } = params;\n\n const userProps = computeAnnotatedProps\n ? computeAnnotatedProps(info, filepath, modifiedtsMs, sourceVersion)\n : defaultComputeAnnotatedProps(info, filepath, modifiedtsMs, sourceVersion);\n\n if (isIntrinsicElement(info.tagName)) {\n return {\n ...userProps,\n \"data-tempo-supports-children\": hasJsxAttribute(\n info,\n \"data-tempo-supports-children\",\n )\n ? undefined\n : !HTML_VOID_ELEMENTS.has(info.tagName),\n };\n }\n\n const override = elementSupportOverrides?.get(info.tagName);\n if (override) {\n return {\n ...userProps,\n \"data-tempo-supports-children\": hasJsxAttribute(\n info,\n \"data-tempo-supports-children\",\n )\n ? undefined\n : override.supportsChildren,\n };\n }\n\n // Custom component with no static override: emit no `data-tempo-supports-*`\n // flags. Determining them required a per-file TypeScript program, which was\n // removed for being the dominant cost of devserver startup. Consumers treat\n // the absent flags as \"unknown\" and fall back to their own defaults.\n return userProps;\n}\n\nexport function getFileAnnotationContext(params: {\n source: string;\n filename: string;\n root: string;\n canonicalizeFilename?: boolean;\n}): {\n cleanFilename: string;\n filepath: string;\n modifiedtsMs: number;\n sourceVersion: string;\n} {\n const rawCleanFilename = cleanModuleId(params.filename);\n let cleanFilename = rawCleanFilename;\n if (params.canonicalizeFilename) {\n try {\n cleanFilename = realpathSync.native(rawCleanFilename);\n } catch {\n cleanFilename = rawCleanFilename;\n }\n }\n return {\n cleanFilename,\n filepath: relative(params.root, cleanFilename),\n modifiedtsMs: Math.trunc(statSync(cleanFilename).mtimeMs),\n // Hashed once per file per transform (the context is built once, reused\n // for every element) so the per-element funnel just forwards the token.\n sourceVersion: sourceVersionHash(params.source),\n };\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,eAAc,YAAAC,iBAAgB;AACvC,SAAS,YAAAC,iBAAgB;;;ACDzB,SAAS,aAAAC,kBAAoD;;;ACiBtD,SAAS,WAAW,MAA8B;AACvD,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,KAAK;AAAA,IACd,KAAK;AACH,aAAO,GAAG,KAAK,UAAU,IAAI,IAAI,KAAK,KAAK,IAAI;AAAA,IACjD,KAAK;AACH,aAAO,2BAA2B,IAAI;AAAA,EAC1C;AACF;AASO,SAAS,2BAA2B,MAAmC;AAC5E,QAAM,SAAS,KAAK,OAAO,SAAS,kBAAkB,KAAK,OAAO,OAAO,2BAA2B,KAAK,MAAM;AAC/G,SAAO,GAAG,MAAM,IAAI,KAAK,SAAS,IAAI;AACxC;;;ACfO,SAAS,KAAK,MAAe,WAAgC;AAClE,MAAI,SAAS,QAAQ,SAAS,UAAa,OAAO,SAAS,SAAU;AAErE,MAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,eAAW,SAAS,MAAM;AACxB,WAAK,OAAO,SAAS;AAAA,IACvB;AACA;AAAA,EACF;AAEA,QAAM,SAAS;AACf,QAAM,OAAO,OAAO;AAEpB,MAAI,OAAO,SAAS,YAAY,QAAQ,WAAW;AACjD,IAAC,UAAsD,IAAI,EAAG,IAAI;AAAA,EACpE;AAEA,aAAW,SAAS,OAAO,OAAO,MAAM,GAAG;AACzC,Q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AG;AACxB;AAAA,MACF;AAEA,aAAO;AAAA,QACL;AAAA,UACE,KAAK;AAAA,UACL,OAAO;AAAA,YACL,MAAM;AAAA,YACN,SAAS;AAAA,UACX;AAAA,UACA,UAAU;AAAA,QACZ;AAAA,MACF;AAAA,IACF;AAAA,IAEA,UAAU,QAAQ,IAAI;AACpB,UAAI,CAAC,WAAW,YAAY,SAAS;AACnC,eAAO;AAAA,MACT;AAEA,UAAI,GAAG,WAAW,IAAI,GAAG;AACvB,eAAO;AAAA,MACT;AAEA,YAAM,UAAU,cAAc,EAAE;AAChC,UAAI,CAAC,OAAO,OAAO,GAAG;AACpB,eAAO;AAAA,MACT;AAEA,UAAI;AACF,cAAM,WAAWC,UAAS,eAAe,OAAO;AAChD,cAAM,eAAe,KAAK,MAAMC,UAAS,OAAO,EAAE,OAAO;AAGzD,cAAM,gBAAgB,kBAAkB,MAAM;AAE9C,cAAM,SAAS;AAAA,UAAa;AAAA,UAAQ;AAAA,UAAS,CAAC,SAC5C,2BAA2B;AAAA,YACzB;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA,uBAAuB,QAAQ;AAAA,UACjC,CAAC;AAAA,QACH;AAEA,YAAI,OAAO,sBAAsB,GAAG;AAClC,iBAAO;AAAA,QACT;AAEA,eAAO;AAAA,UACL,MAAM,OAAO;AAAA,UACb,KAAK;AAAA,QACP;AAAA,MACF,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB;","names":["realpathSync","statSync","relative","parseSync","parseSync","realpathSync","relative","statSync"]}
1
+ {"version":3,"sources":["../index.ts","../../../modules/annotation/annotate-file.ts","../../../modules/file-parser/utils.ts","../../../modules/file-parser/walk.ts","../../../modules/file-parser/scope-analyzer/types.ts","../../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts","../../../modules/annotation/source-version.ts","../annotation-strategy.ts","../canvas-host-registration-contract.ts","../default-export-identity.ts","../hmr-generation-fence.ts","../missed-change-sweep.ts","../rapid-hot-update-replay.ts"],"sourcesContent":["import {\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, isAbsolute, join, relative, resolve } from \"node:path\";\nimport { createFilter, type FilterPattern } from \"@rollup/pluginutils\";\nimport type { Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport {\n annotateFile,\n type ElementInfo,\n type PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport { computeTempoAnnotatedProps } from \"./annotation-strategy.ts\";\nimport { TEMPO_INTERACT_FRAME_NAME } from \"./canvas/interact-frame.ts\";\nimport {\n CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER,\n CANVAS_HOST_REGISTRATION_ENDPOINT,\n normalizeCanvasRegistrationPath,\n} from \"./canvas-host-registration-contract.ts\";\nimport {\n type DefaultExportIdentity,\n isDefaultExportIdentityRewrite,\n readDefaultExportIdentity,\n} from \"./default-export-identity.ts\";\nimport { createHmrGenerationFence } from \"./hmr-generation-fence.ts\";\nimport {\n createMissedChangeSweep,\n type SweepModuleView,\n} from \"./missed-change-sweep.ts\";\nimport { createRapidHotUpdateReplay } from \"./rapid-hot-update-replay.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_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 window.__tempoInteractProjectionOwner = \"vite\";\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. */\nfunction fsPathFromModuleId(id: string): string {\n return cleanModuleId(id).replace(/^\\/@fs\\//, \"/\");\n}\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 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\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\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\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface TempoAnnotateOptions {\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// 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): 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 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 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\nconst CANVAS_HOST_WRAPPER_URL = \"/.tempo/tempo-host\";\n\nfunction 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<void> {\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 await retransformCanvasHostWrapper(\n server.environments?.client ?? server,\n canonicalWrapperPath,\n wrapperPath,\n );\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. */\ntype 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\n/**\n * Vite's official server contract stores transformed code in a module graph.\n * Reading the rewritten file is therefore only half a receipt: explicitly\n * invalidate every module node for that file, then await a fresh transform.\n */\nasync function retransformCanvasHostWrapper<TModule>(\n transformer: CanvasHostWrapperTransformer<TModule>,\n canonicalWrapperPath: string,\n wrapperPath: string,\n): Promise<void> {\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(CANVAS_HOST_WRAPPER_URL);\n if (!result) {\n throw new Error(\n `Vite did not transform ${CANVAS_HOST_WRAPPER_URL} after registration`,\n );\n }\n}\n\nfunction writeCanvasRegistrationResponseHeaders(res: ServerResponse): void {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER, \"1\");\n}\n\nfunction handleTempoMiddleware(\n errorServer: TempoErrorServer,\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 === 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;\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 { canvasPath?: unknown };\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 await synchronizeCanvasHostRegistrationTransform(\n viteServer,\n canvasPath,\n );\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ canvasPath }));\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;\n }\n\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;\n }\n\n if (url === \"/__tempo/report-clear\" && req.method === \"POST\") {\n errorServer.clearAll();\n res.statusCode = 200;\n res.end(\"ok\");\n return;\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;\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;\n }\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 = 3_000;\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/** Install the lost-watcher-event net on a dev server: every interval, stat\n * the served files and re-emit the watcher \"change\" for any whose fs mtime\n * advanced without Vite's watcher pipeline covering that revision (a\n * chokidar event lost under I/O pressure — the file is silently stale for\n * every consumer until someone re-delivers the event). Emitting the watcher\n * event makes Vite run its entire native pipeline; the sweep itself never\n * touches modules. Watcher-pipeline evidence and retry bounds live in\n * missed-change-sweep.ts.\n *\n * The compile-error recovery poll rides the same interval: both are periodic\n * recovery passes over the same cadence, and running them on one timer keeps\n * them from overlapping each other. */\nfunction installMissedChangeSweep(\n server: ViteDevServer,\n listErrorFiles: () => readonly string[],\n lastHotUpdateMtimeMs: (file: string) => number | undefined,\n pollCompileErrorRecovery: () => Promise<void>,\n): void {\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 const errorFiles = listErrorFiles();\n for (const errorFile of errorFiles) {\n const cleanFile = fsPathFromModuleId(errorFile);\n const file = isAbsolute(cleanFile)\n ? cleanFile\n : resolve(server.config.root, cleanFile);\n if (!files.has(file)) files.set(file, []);\n }\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,\n });\n let passRunning = false;\n const timer = setInterval(() => {\n if (passRunning) return;\n passRunning = true;\n void sweep\n .sweep()\n .then(() => pollCompileErrorRecovery())\n .catch(() => {})\n .finally(() => {\n passRunning = false;\n });\n }, MISSED_CHANGE_SWEEP_INTERVAL_MS);\n timer.unref?.();\n server.httpServer?.once(\"close\", () => clearInterval(timer));\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 = !!process.env.TEMPO;\n\n const include =\n options.include === undefined ? DEFAULT_INCLUDE : options.include;\n const exclude =\n options.exclude === undefined ? DEFAULT_EXCLUDE : options.exclude;\n const filter = createFilter(include, exclude);\n\n let canonicalRoot = process.cwd();\n let sourceIdentityRoot = canonicalRoot;\n let command: ResolvedConfig[\"command\"] = \"serve\";\n const errorServer = createErrorServer((file) =>\n 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 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 const rapidHotUpdateReplay = createRapidHotUpdateReplay();\n // Revision-specific evidence consumed by the missed-change sweep. This is\n // watcher-event coverage, not a claim that a browser visibly rendered the\n // revision; rapid client application races are repaired by the trailing\n // replay above.\n const hotUpdateMtimesMs = new Map<string, number>();\n const normalizedFileKey = (file: string): string => file.replace(/\\\\/g, \"/\");\n const recordHotUpdateCoverage = (file: string): void => {\n const cleanFile = fsPathFromModuleId(file);\n const key = normalizedFileKey(cleanFile);\n try {\n hotUpdateMtimesMs.set(key, statSync(cleanFile).mtimeMs);\n } catch {\n hotUpdateMtimesMs.delete(key);\n }\n };\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 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?: {\n transformRequest(id: string): Promise<unknown>;\n hot: HmrSendTarget;\n };\n };\n }\n ).environments?.client;\n try {\n const result = clientEnvironment\n ? await clientEnvironment.transformRequest(requestId)\n : await server.transformRequest(requestId);\n if (!result) 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 // Last default-export identity Vite served per file, keyed by canonical fs\n // path (module ids and watcher paths disagree on /@fs/ prefixes and\n // symlinks). Seeded by `transform`, advanced by every hot-update comparison.\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 // 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 re-seeds the identical identity.\n const repairDefaultExportIdentityRewrite = (file: string): boolean => {\n const key = canonicalIdentityKey(file);\n const before = defaultExportIdentityByFile.get(key);\n if (before === undefined) return false; // Never served — no stale client.\n let source: string;\n try {\n source = readFileSync(file, \"utf8\");\n } catch {\n return false;\n }\n const after = readDefaultExportIdentity(source);\n defaultExportIdentityByFile.set(key, after);\n if (!isDefaultExportIdentityRewrite(before, after)) return false;\n devServer?.ws.send({ type: \"full-reload\", path: \"*\" });\n return true;\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 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 resolveId: {\n order: \"pre\",\n async handler(id, importer, resolveOptions) {\n if (id === INTERACT_PROJECTION_CLIENT_PATH) {\n return INTERACT_PROJECTION_CLIENT_ID;\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 load(id) {\n if (id === INTERACT_PROJECTION_CLIENT_ID) {\n return `let stop;\nlet disposed = false;\nif (window.parent !== window && (window.name === ${JSON.stringify(TEMPO_INTERACT_FRAME_NAME)} || window.name.startsWith(${JSON.stringify(`${TEMPO_INTERACT_FRAME_NAME}:`)}))) {\n window.__tempoInteractProjectionOwner = \"vite\";\n void import(\"tempo-sdk/canvas/interact-projection\").then(({ installTempoInteractProjectionSource }) => {\n if (disposed) return;\n stop = installTempoInteractProjectionSource();\n });\n}\nif (import.meta.hot) import.meta.hot.dispose(() => {\n disposed = true;\n stop?.();\n});`;\n }\n return null;\n },\n\n // Expose error server for testing\n _tempoErrorServer: errorServer,\n // Test seam pinning the exact evidence the missed-change sweep reads.\n _tempoHotUpdateState: {\n lastHotUpdateMtimeMs(file: string) {\n return hotUpdateMtimesMs.get(normalizedFileKey(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 canonicalRoot = resolveCanonicalRoot(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 devServer = server;\n syncUnresolvedImportWatcher();\n server.watcher?.once?.(\"close\", closeUnresolvedImportWatchers);\n server.httpServer?.once(\"close\", closeUnresolvedImportWatchers);\n server.middlewares.use((req, res, next) => {\n handleTempoMiddleware(errorServer, server, req, res, next);\n });\n\n installMissedChangeSweep(\n server,\n () => errorServer.errorFiles,\n (file) => hotUpdateMtimesMs.get(normalizedFileKey(file)),\n () => pollCompileErrorRecovery(server),\n );\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 over the documented Environment API — never a\n // recovery action; the plugin must not reload modules or walk module\n // graphs.\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 === \"error\") {\n const err = typed.err;\n errorServer.setError({\n type: \"compile\",\n message: (err?.message as string) ?? \"Unknown error\",\n stack: err?.stack as string | undefined,\n file:\n (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 } 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 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 };\n },\n\n closeBundle() {\n devServer = undefined;\n rapidHotUpdateReplay.clear();\n hmrGenerationFence.clear();\n hotUpdateMtimesMs.clear();\n compileErrorPollSchedule.clear();\n closeUnresolvedImportWatchers();\n },\n\n hotUpdate: {\n order: \"post\",\n async handler(context) {\n if (!enabled || this.environment.config.consumer !== \"client\") return;\n recordHotUpdateCoverage(context.file);\n if (context.type === \"update\" && context.modules.length > 0) {\n rapidHotUpdateReplay.observe(context.file, () => {\n context.server.config.logger.info(\n `[tempo] replaying settled rapid watcher change: ${context.file}`,\n { timestamp: true },\n );\n context.server.watcher.emit(\"change\", context.file);\n });\n }\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 hasActiveCompileError(context.file) &&\n (await recoverActiveCompileError(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 defaultExportIdentityByFile.delete(\n canonicalIdentityKey(context.file),\n );\n return;\n }\n if (\n context.type === \"update\" &&\n repairDefaultExportIdentityRewrite(context.file)\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 },\n },\n\n // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.\n handleHotUpdate: {\n order: \"post\",\n async handler(context) {\n if (!enabled) return;\n recordHotUpdateCoverage(context.file);\n if (context.modules.length > 0) {\n rapidHotUpdateReplay.observe(context.file, () => {\n context.server.config.logger.info(\n `[tempo] replaying settled rapid watcher change: ${context.file}`,\n { timestamp: true },\n );\n context.server.watcher.emit(\"change\", context.file);\n });\n }\n forgetUnresolvedImportsFrom(context.file);\n if (\n hasActiveCompileError(context.file) &&\n (await recoverActiveCompileError(context.server, context.file))\n ) {\n return [];\n }\n if (repairDefaultExportIdentityRewrite(context.file)) {\n return [];\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 (!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 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 transform(source, id) {\n if (!enabled || command === \"build\") {\n return null;\n }\n\n if (id.startsWith(\"\\0\")) {\n return null;\n }\n\n const cleanId = cleanModuleId(id);\n if (!filter(cleanId)) {\n return null;\n }\n\n try {\n const filepath = relative(canonicalRoot, cleanId);\n const modifiedtsMs = Math.trunc(statSync(cleanId).mtimeMs);\n // Vite passes this hook the output of every earlier `enforce: \"pre\"`\n // transform. Content identity must instead describe the source file\n // itself: HMR origins and Tempo's write pipeline both hash those raw\n // bytes. Reading the same representation here prevents an upstream\n // source-mutating plugin from making annotations permanently disagree\n // with the edit that produced them.\n const rawSource = readFileSync(cleanId, \"utf8\");\n const sourceVersion = sourceVersionHash(rawSource);\n defaultExportIdentityByFile.set(\n canonicalIdentityKey(cleanId),\n readDefaultExportIdentity(rawSource),\n );\n\n const result = annotateFile(source, cleanId, (info) =>\n computeTempoAnnotatedProps({\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps: options.computeAnnotatedProps,\n }),\n );\n\n if (result.elementsAnnotated === 0) {\n return null;\n }\n\n return {\n code: result.annotatedSource,\n map: null,\n };\n } catch {\n return null;\n }\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 };\n\nexport type {\n StoryboardLayout,\n TempoCanvasConfig,\n TempoHtmlStoryboard,\n TempoPage,\n TempoRouteStoryboard,\n TempoStoryboard,\n} from \"./page.ts\";\n","import { parseSync, type JSXElement, type ParseResult } from 'oxc-parser';\nimport { getTagName, walk } from '@modules/file-parser';\n\nexport interface ElementInfo {\n element: JSXElement;\n /** e.g. \"div\", \"Button\", \"Foo.Bar\" */\n tagName: string;\n}\n\n/** Supported prop value types. `undefined` values are skipped. */\nexport type PropValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ((...args: unknown[]) => unknown)\n | object;\n\nfunction formatPropValue(value: PropValue): string | null {\n if (value === undefined) return null;\n if (typeof value === 'function') return value.toString();\n return JSON.stringify(value);\n}\n\nfunction formatProps(props: Record<string, PropValue>): string {\n return Object.entries(props)\n .map(([key, value]) => {\n const formatted = formatPropValue(value);\n if (formatted === null) return null;\n return ` ${key}={${formatted}}`;\n })\n .filter((s): s is string => s !== null)\n .join('');\n}\n\nfunction getExistingAttributeNames(element: JSXElement): Set<string> {\n const names = new Set<string>();\n\n for (const attr of element.openingElement.attributes ?? []) {\n if (attr.type !== 'JSXAttribute') continue;\n names.add(getTagName(attr.name));\n }\n\n return names;\n}\n\nfunction removeExistingProps(\n props: Record<string, PropValue>,\n existingNames: Set<string>\n): Record<string, PropValue> {\n return Object.fromEntries(\n Object.entries(props).filter(([key]) => !existingNames.has(key))\n );\n}\n\nexport interface AnnotateFileResult {\n annotatedSource: string;\n elementsAnnotated: number;\n /** The oxc-parser result. Check `parseResult.errors` for any parse errors. */\n parseResult: ParseResult;\n}\n\n/** Tag names that represent React fragments and should not be annotated */\nconst FRAGMENT_TAG_NAMES = new Set(['Fragment', 'React.Fragment']);\n\n/**\n * Annotates JSX elements in a source file by inserting additional props.\n *\n * Visits every JSXElement in source order and calls the handler to compute\n * props to insert. Props are inserted at the end of each opening tag.\n *\n * Fragments are skipped since they don't render DOM elements:\n * - JSX shorthand fragments (`<>...</>`) are a separate AST node type\n * - `React.Fragment` and `Fragment` are skipped by tag name\n */\nexport function annotateFile(\n source: string,\n filename: string,\n computeAnnotatedProps: (info: ElementInfo) => Record<string, PropValue>\n): AnnotateFileResult {\n const parseResult = parseSync(filename, source);\n const insertions: { position: number; text: string }[] = [];\n\n // Walk the AST to find all JSXElement nodes\n // Uses our own walker instead of oxc-parser's Visitor (CJS/ESM interop issue in Electron)\n walk(parseResult.program, {\n JSXElement(node: unknown) {\n const element = node as JSXElement;\n const tagName = getTagName(element.openingElement.name);\n if (FRAGMENT_TAG_NAMES.has(tagName)) return;\n\n const props = removeExistingProps(\n computeAnnotatedProps({ element, tagName }),\n getExistingAttributeNames(element)\n );\n if (Object.keys(props).length === 0) return;\n\n const openingElement = element.openingElement;\n\n // Insert before \">\" or \"/>\" at end of opening tag, skipping whitespace before \"/>\"\n let insertPos = openingElement.end - 1;\n if (openingElement.selfClosing) {\n insertPos--;\n while (insertPos > openingElement.start && /\\s/.test(source[insertPos - 1]!)) {\n insertPos--;\n }\n }\n\n insertions.push({ position: insertPos, text: formatProps(props) });\n },\n });\n\n // Build result in a single pass using chunks (O(n) instead of O(n*m))\n insertions.sort((a, b) => a.position - b.position);\n\n const chunks: string[] = [];\n let lastPos = 0;\n for (const { position, text } of insertions) {\n chunks.push(source.slice(lastPos, position));\n chunks.push(text);\n lastPos = position;\n }\n chunks.push(source.slice(lastPos));\n\n return { annotatedSource: chunks.join(''), elementsAnnotated: insertions.length, parseResult };\n}\n","\n/**\n * Annotation Utilities\n *\n * Helper functions for working with oxc-parser AST nodes.\n */\n\nimport type { JSXElementName, JSXMemberExpression } from 'oxc-parser';\n\n/**\n * Extracts the tag name string from any JSXElementName variant.\n *\n * JSXElementName is a union of three types representing different JSX tag syntaxes:\n * - JSXIdentifier: `<button>` → \"button\", `<Button>` → \"Button\"\n * - JSXNamespacedName: `<svg:rect>` → \"svg:rect\" (rare, used in SVG/XML)\n * - JSXMemberExpression: `<Foo.Bar>` → \"Foo.Bar\", `<UI.Button.Primary>` → \"UI.Button.Primary\"\n */\nexport function getTagName(name: JSXElementName): string {\n switch (name.type) {\n case 'JSXIdentifier':\n return name.name;\n case 'JSXNamespacedName':\n return `${name.namespace.name}:${name.name.name}`;\n case 'JSXMemberExpression':\n return getJSXMemberExpressionName(name);\n }\n}\n\n/**\n * Recursively builds the dotted name string from a JSXMemberExpression.\n *\n * JSXMemberExpression represents dotted component names like `<Foo.Bar.Baz>`:\n * - object: either a JSXIdentifier or another JSXMemberExpression (for chaining)\n * - property: always a JSXIdentifier (the rightmost part)\n */\nexport function getJSXMemberExpressionName(node: JSXMemberExpression): string {\n const object = node.object.type === 'JSXIdentifier' ? node.object.name : getJSXMemberExpressionName(node.object);\n return `${object}.${node.property.name}`;\n}\n","/**\n * AST Walker\n *\n * Simple recursive walker for oxc-parser ASTs. Visits every node in the tree\n * and calls type-specific callbacks. Drop-in replacement for oxc-parser's\n * Visitor class, which has CJS/ESM interop issues in Electron.\n *\n * Once oxc-parser's Visitor works in Electron, this can be swapped back.\n */\n\n/**\n * Callbacks for specific AST node types.\n * Add more node types here as needed.\n */\nexport interface WalkCallbacks {\n JSXElement?: (node: any) => void;\n JSXFragment?: (node: any) => void;\n}\n\n/**\n * Recursively walks an oxc-parser AST, calling callbacks for matching node types.\n * Traverses all object properties and array elements depth-first.\n */\nexport function walk(node: unknown, callbacks: WalkCallbacks): void {\n if (node === null || node === undefined || typeof node !== \"object\") return;\n\n if (Array.isArray(node)) {\n for (const child of node) {\n walk(child, callbacks);\n }\n return;\n }\n\n const record = node as Record<string, unknown>;\n const type = record.type;\n\n if (typeof type === \"string\" && type in callbacks) {\n (callbacks as Record<string, (node: unknown) => void>)[type]!(node);\n }\n\n for (const value of Object.values(record)) {\n if (value !== null && typeof value === \"object\") {\n walk(value, callbacks);\n }\n }\n}\n","export type Range = {\n /** Start byte offset (inclusive). */\n start: number;\n /** End byte offset (exclusive). */\n end: number;\n};\n\nexport const ScopeType = {\n Program: 'program',\n Function: 'function',\n Block: 'block',\n Catch: 'catch',\n Class: 'class',\n ClassStaticBlock: 'class-static',\n For: 'for',\n Switch: 'switch',\n TsModule: 'ts-module',\n Enum: 'enum',\n Type: 'type',\n TsConditional: 'ts-conditional',\n} as const;\n\nexport type ScopeType = (typeof ScopeType)[keyof typeof ScopeType];\n\nexport const ScopeFlags = {\n Top: 1 << 0,\n Function: 1 << 1,\n Block: 1 << 2,\n Catch: 1 << 3,\n Class: 1 << 4,\n For: 1 << 5,\n Switch: 1 << 6,\n Module: 1 << 7,\n StrictMode: 1 << 8,\n ClassStaticBlock: 1 << 9,\n TsModuleBlock: 1 << 10,\n TsConditional: 1 << 11,\n Type: 1 << 12,\n Enum: 1 << 13,\n} as const;\n\nexport type ScopeFlags = number;\n\nexport const BindingKind = {\n Var: 'var',\n Let: 'let',\n Const: 'const',\n Function: 'function',\n Class: 'class',\n Param: 'param',\n Import: 'import',\n TypeImport: 'type-import',\n TypeAlias: 'type-alias',\n Interface: 'interface',\n Enum: 'enum',\n EnumMember: 'enum-member',\n TypeParam: 'type-param',\n Namespace: 'namespace',\n} as const;\n\nexport type BindingKind = (typeof BindingKind)[keyof typeof BindingKind];\n\nexport type Scope = {\n id: number;\n type: ScopeType;\n flags: ScopeFlags;\n start: number;\n end: number;\n parentId: number | null;\n childIds: number[];\n bindings: Map<string, number>;\n typeBindings: Map<string, number>;\n};\n\nexport type Binding = {\n id: number;\n name: string;\n kind: BindingKind;\n declStart: number;\n declEnd: number;\n scopeId: number;\n};\n\nexport type Reference = {\n id: number;\n name: string;\n start: number;\n end: number;\n scopeId: number;\n bindingId: number | null;\n};\n\nexport type ScopeAnalysis = {\n source: string;\n scopes: Scope[];\n bindings: Binding[];\n references: Reference[];\n};\n","import { parseSync, type ParserOptions } from 'oxc-parser';\n// oxc-parser's browser build (src-js/wasm.js) does not re-export `visitorKeys`.\n// Deep-import the generated keys table so this works in both Node and browser.\nimport visitorKeysDefault from 'oxc-parser/src-js/generated/visit/keys.js';\n\nconst visitorKeys = visitorKeysDefault as Record<string, readonly string[]>;\nimport {\n BindingKind,\n type Binding,\n type Range,\n type Reference,\n type Scope,\n type ScopeAnalysis,\n ScopeFlags,\n ScopeType,\n} from './types';\n\ntype AnyNode = {\n type: string;\n start?: number;\n end?: number;\n [key: string]: any;\n};\n\ntype AnalyzeOptions = {\n filename?: string;\n parserOptions?: ParserOptions;\n};\n\ntype ScopeStackItem = {\n scopeId: number;\n};\n\nconst ReferenceContext = {\n Value: 'value',\n Type: 'type',\n ValueAsType: 'value-as-type',\n} as const;\n\ntype ReferenceContext =\n (typeof ReferenceContext)[keyof typeof ReferenceContext];\n\nconst DEFAULT_FILENAME = 'file.tsx';\n\nexport function analyzeScopes(source: string, options: AnalyzeOptions = {}): ScopeAnalysis {\n const filename = options.filename ?? DEFAULT_FILENAME;\n const parseResult = parseSync(filename, source, options.parserOptions ?? undefined);\n const program = parseResult.program as AnyNode;\n\n const scopes: Scope[] = [];\n const bindings: Binding[] = [];\n const references: Reference[] = [];\n\n const scopeIdByNode = new WeakMap<object, number>();\n\n const rootScopeId = createScope({\n scopes,\n type: ScopeType.Program,\n start: 0,\n end: source.length,\n parentId: null,\n flags: getProgramFlags(program),\n });\n\n scopeIdByNode.set(program, rootScopeId);\n\n const bindingBuilder = new ScopeBuilder({\n source,\n scopes,\n bindings,\n scopeIdByNode,\n });\n\n bindingBuilder.walkBindings(program);\n\n const referenceBuilder = new ReferenceBuilder({\n scopes,\n bindings,\n references,\n scopeIdByNode,\n });\n\n referenceBuilder.walkReferences(program);\n\n return {\n source,\n scopes,\n bindings,\n references,\n };\n}\n\nexport function getReferenceAtPosition(\n analysis: ScopeAnalysis,\n position: number,\n): Reference | null {\n let best: Reference | null = null;\n for (const ref of analysis.references) {\n if (position >= ref.start && position < ref.end) {\n if (!best || (ref.end - ref.start) < (best.end - best.start)) {\n best = ref;\n }\n }\n }\n return best;\n}\n\nexport function getBindingForReference(\n analysis: ScopeAnalysis,\n reference: Reference,\n): Binding | null {\n if (reference.bindingId == null) {\n return null;\n }\n return analysis.bindings[reference.bindingId] ?? null;\n}\n\nexport function getValidRangesAtPosition(\n analysis: ScopeAnalysis,\n position: number,\n): Range[] {\n const ref = getReferenceAtPosition(analysis, position);\n if (!ref) return [];\n return getValidRangesForReference(analysis, ref);\n}\n\nexport function getValidRangesForReference(\n analysis: ScopeAnalysis,\n reference: Reference,\n): Range[] {\n const binding = getBindingForReference(analysis, reference);\n if (!binding) return [];\n const baseRange = getBindingVisibilityRange(analysis, binding);\n const shadowed = getShadowedRanges(analysis, binding, baseRange);\n return subtractRanges(baseRange, shadowed);\n}\n\nexport function getBindingVisibilityRange(\n analysis: ScopeAnalysis,\n binding: Binding,\n): Range {\n const scope = analysis.scopes[binding.scopeId];\n const start = isBlockScopedBindingKind(binding.kind)\n ? binding.declStart\n : scope.start;\n return { start, end: scope.end };\n}\n\nfunction getShadowedRanges(\n analysis: ScopeAnalysis,\n binding: Binding,\n baseRange: Range,\n): Range[] {\n const rootScope = analysis.scopes[binding.scopeId];\n const ranges: Range[] = [];\n const stack = [...rootScope.childIds];\n const useTypeBindings = usesTypeBindingsForShadowing(binding.kind);\n\n while (stack.length) {\n const scopeId = stack.pop() as number;\n const scope = analysis.scopes[scopeId];\n const shadowBindingId = useTypeBindings\n ? scope.typeBindings.get(binding.name)\n : scope.bindings.get(binding.name);\n\n if (shadowBindingId != null && shadowBindingId !== binding.id) {\n ranges.push({ start: scope.start, end: scope.end });\n continue;\n }\n\n stack.push(...scope.childIds);\n }\n\n return ranges\n .map((range) => clampRange(range, baseRange))\n .filter((range): range is Range => range !== null);\n}\n\nfunction clampRange(range: Range, base: Range): Range | null {\n const start = Math.max(range.start, base.start);\n const end = Math.min(range.end, base.end);\n if (start >= end) return null;\n return { start, end };\n}\n\nfunction subtractRanges(base: Range, exclusions: Range[]): Range[] {\n if (!exclusions.length) return [base];\n const normalized = normalizeRanges(exclusions);\n let current: Range[] = [base];\n\n for (const ex of normalized) {\n const next: Range[] = [];\n for (const range of current) {\n next.push(...subtractOne(range, ex));\n }\n current = next;\n if (!current.length) break;\n }\n\n return current;\n}\n\nfunction subtractOne(range: Range, exclude: Range): Range[] {\n if (exclude.end <= range.start || exclude.start >= range.end) {\n return [range];\n }\n\n const result: Range[] = [];\n if (exclude.start > range.start) {\n result.push({ start: range.start, end: Math.min(exclude.start, range.end) });\n }\n if (exclude.end < range.end) {\n result.push({ start: Math.max(exclude.end, range.start), end: range.end });\n }\n return result;\n}\n\nfunction normalizeRanges(ranges: Range[]): Range[] {\n const sorted = [...ranges].sort((a, b) => a.start - b.start);\n const result: Range[] = [];\n\n for (const range of sorted) {\n const last = result[result.length - 1];\n if (!last || range.start > last.end) {\n result.push({ ...range });\n } else {\n last.end = Math.max(last.end, range.end);\n }\n }\n\n return result;\n}\n\nfunction isNode(value: unknown): value is AnyNode {\n return Boolean(value && typeof value === 'object' && (value as AnyNode).type);\n}\n\nfunction getParamList(params: AnyNode | AnyNode[] | null | undefined): AnyNode[] {\n if (!params) return [];\n if (Array.isArray(params)) return params;\n if (Array.isArray(params.params)) return params.params;\n if (Array.isArray(params.items)) return params.items;\n return [];\n}\n\nfunction getProgramFlags(program: AnyNode): ScopeFlags {\n const sourceType = program.sourceType ?? program.source_type ?? 'module';\n let flags = ScopeFlags.Top;\n if (sourceType === 'module') {\n flags |= ScopeFlags.Module | ScopeFlags.StrictMode;\n }\n if (hasUseStrictDirective(program)) {\n flags |= ScopeFlags.StrictMode;\n }\n return flags;\n}\n\nfunction hasUseStrictDirective(container: AnyNode | null | undefined): boolean {\n if (!container) return false;\n const directives = container.directives;\n if (Array.isArray(directives)) {\n for (const directive of directives) {\n if (getDirectiveText(directive) === 'use strict') {\n return true;\n }\n }\n }\n\n const statements =\n container.body ??\n container.statements ??\n container.body?.body ??\n container.body?.statements;\n if (Array.isArray(statements)) {\n for (const stmt of statements) {\n if (!stmt) continue;\n const directiveText = getDirectiveText(stmt);\n if (directiveText === 'use strict') {\n return true;\n }\n if (directiveText == null) {\n break;\n }\n }\n }\n\n return false;\n}\n\nfunction getDirectiveText(node: AnyNode | null | undefined): string | null {\n if (!node) return null;\n if (typeof node.directive === 'string') {\n return node.directive;\n }\n const expr = node.expression ?? node;\n if (expr?.type === 'StringLiteral' || expr?.type === 'Literal') {\n const value = expr.value ?? expr.rawValue ?? expr.raw;\n if (typeof value === 'string') return value;\n }\n return null;\n}\n\nfunction isStrictScope(node: AnyNode, type: ScopeType): boolean {\n if (type === ScopeType.Class) return true;\n if (type === ScopeType.Function) {\n return hasUseStrictDirective(node.body);\n }\n if (type === ScopeType.TsModule) {\n return hasUseStrictDirective(node.body);\n }\n return false;\n}\n\nfunction shouldAddToValueBindings(kind: BindingKind): boolean {\n switch (kind) {\n case BindingKind.Var:\n case BindingKind.Let:\n case BindingKind.Const:\n case BindingKind.Function:\n case BindingKind.Class:\n case BindingKind.Param:\n case BindingKind.Import:\n case BindingKind.Enum:\n case BindingKind.EnumMember:\n case BindingKind.Namespace:\n return true;\n default:\n return false;\n }\n}\n\nfunction shouldAddToTypeBindings(kind: BindingKind): boolean {\n switch (kind) {\n case BindingKind.TypeImport:\n case BindingKind.TypeAlias:\n case BindingKind.Interface:\n case BindingKind.TypeParam:\n case BindingKind.Class:\n case BindingKind.Enum:\n case BindingKind.EnumMember:\n case BindingKind.Namespace:\n case BindingKind.Import:\n return true;\n default:\n return false;\n }\n}\n\nfunction isBlockScopedBindingKind(kind: BindingKind): boolean {\n return (\n kind === BindingKind.Let ||\n kind === BindingKind.Const ||\n kind === BindingKind.Class ||\n kind === BindingKind.EnumMember\n );\n}\n\nfunction usesTypeBindingsForShadowing(kind: BindingKind): boolean {\n return (\n kind === BindingKind.TypeImport ||\n kind === BindingKind.TypeAlias ||\n kind === BindingKind.Interface ||\n kind === BindingKind.TypeParam\n );\n}\n\nfunction canReferenceAsType(kind: BindingKind): boolean {\n return (\n kind === BindingKind.TypeImport ||\n kind === BindingKind.TypeAlias ||\n kind === BindingKind.Interface ||\n kind === BindingKind.TypeParam ||\n kind === BindingKind.Class ||\n kind === BindingKind.Enum ||\n kind === BindingKind.EnumMember ||\n kind === BindingKind.Namespace ||\n kind === BindingKind.Import\n );\n}\n\nfunction canReferenceAsValueAsType(kind: BindingKind): boolean {\n return kind === BindingKind.TypeImport || shouldAddToValueBindings(kind);\n}\n\nclass ScopeBuilder {\n private source: string;\n private scopes: Scope[];\n private bindings: Binding[];\n private scopeIdByNode: WeakMap<object, number>;\n private scopeStack: ScopeStackItem[] = [];\n\n constructor({\n source,\n scopes,\n bindings,\n scopeIdByNode,\n }: {\n source: string;\n scopes: Scope[];\n bindings: Binding[];\n scopeIdByNode: WeakMap<object, number>;\n }) {\n this.source = source;\n this.scopes = scopes;\n this.bindings = bindings;\n this.scopeIdByNode = scopeIdByNode;\n this.scopeStack.push({ scopeId: 0 });\n }\n\n walkBindings(node: AnyNode, ancestors: AnyNode[] = []): void {\n if (!node) return;\n switch (node.type) {\n case 'Program':\n this.registerScope(node, 0);\n this.walkChildren(node, ancestors);\n return;\n case 'BlockStatement':\n this.withScope(node, ScopeType.Block, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'FunctionDeclaration':\n case 'TSDeclareFunction':\n // `declare function f(...)` is a TSDeclareFunction — the same shape as\n // a FunctionDeclaration minus the body. Treating the two together\n // means ambient function declarations still bind their names at the\n // current scope and their parameters inside a function scope, so\n // downstream resolution behaves identically to the non-ambient form.\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Function, node.id);\n }\n this.withScope(node, ScopeType.Function, () => {\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'FunctionExpression':\n this.withScope(node, ScopeType.Function, () => {\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Function, node.id);\n }\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ArrowFunctionExpression':\n this.withScope(node, ScopeType.Function, () => {\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'VariableDeclaration':\n this.handleVariableDeclaration(node, ancestors);\n return;\n case 'ClassDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Class, node.id);\n }\n this.withScope(node, ScopeType.Class, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ClassExpression':\n this.withScope(node, ScopeType.Class, () => {\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Class, node.id);\n }\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'StaticBlock':\n this.withScope(node, ScopeType.ClassStaticBlock, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'CatchClause':\n this.withScope(node, ScopeType.Catch, () => {\n if (node.param) {\n this.declarePattern(node.param, BindingKind.Param);\n this.walkPatternExpressions(node.param, ancestors);\n }\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ForStatement':\n case 'ForInStatement':\n case 'ForOfStatement':\n this.withScope(node, ScopeType.For, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'SwitchStatement':\n this.withScope(node, ScopeType.Switch, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'ImportDeclaration':\n this.handleImportDeclaration(node);\n return;\n case 'TSImportEqualsDeclaration':\n this.handleImportEqualsDeclaration(node);\n return;\n case 'TSModuleDeclaration':\n this.handleTsModuleDeclaration(node, ancestors);\n return;\n case 'TSGlobalDeclaration':\n this.withScope(node, ScopeType.TsModule, () => {\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'TSTypeAliasDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.TypeAlias, node.id);\n }\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.typeAnnotation ?? node.type_annotation, ancestors);\n });\n return;\n case 'TSInterfaceDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Interface, node.id);\n }\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n if (node.extends) {\n for (const heritage of node.extends) {\n this.walkNode(heritage, ancestors);\n }\n }\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'TSEnumDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Enum, node.id);\n }\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n return;\n case 'TSEnumBody':\n this.withScope(node, ScopeType.Enum, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'TSEnumMember':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.EnumMember, node.id);\n }\n if (node.initializer) {\n this.walkNode(node.initializer, ancestors);\n }\n return;\n case 'TSTypeParameter':\n if (node.name?.name) {\n this.declareBinding(this.currentScopeId(), node.name.name, BindingKind.TypeParam, node.name);\n }\n if (node.constraint) {\n this.walkNode(node.constraint, ancestors);\n }\n if (node.default) {\n this.walkNode(node.default, ancestors);\n }\n return;\n case 'TSTypeParameterDeclaration':\n for (const param of node.params ?? []) {\n this.walkNode(param, ancestors);\n }\n return;\n case 'TSMappedType':\n this.withScope(node, ScopeType.Type, () => {\n if (node.key?.name) {\n this.declareBinding(this.currentScopeId(), node.key.name, BindingKind.TypeParam, node.key);\n }\n this.walkNode(node.constraint, ancestors);\n if (node.nameType ?? node.name_type) {\n this.walkNode(node.nameType ?? node.name_type, ancestors);\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkNode(node.typeAnnotation ?? node.type_annotation, ancestors);\n }\n });\n return;\n case 'TSConditionalType':\n if (node.checkType ?? node.check_type) {\n this.walkNode(node.checkType ?? node.check_type, ancestors);\n }\n this.withScope(node, ScopeType.TsConditional, () => {\n if (node.extendsType ?? node.extends_type) {\n this.walkNode(node.extendsType ?? node.extends_type, ancestors);\n }\n if (node.trueType ?? node.true_type) {\n this.walkNode(node.trueType ?? node.true_type, ancestors);\n }\n });\n if (node.falseType ?? node.false_type) {\n this.walkNode(node.falseType ?? node.false_type, ancestors);\n }\n return;\n case 'TSFunctionType':\n case 'TSConstructorType':\n case 'TSCallSignatureDeclaration':\n case 'TSMethodSignature':\n case 'TSConstructSignatureDeclaration':\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n const params = getParamList(node.params);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.returnType ?? node.return_type) {\n this.walkNode(node.returnType ?? node.return_type, ancestors);\n }\n });\n return;\n default:\n this.walkChildren(node, ancestors);\n }\n }\n\n private currentScopeId(): number {\n return this.scopeStack[this.scopeStack.length - 1]?.scopeId ?? 0;\n }\n\n private withScope(node: AnyNode, type: ScopeType, fn: () => void): void {\n const parentScopeId = this.currentScopeId();\n const parentScope = this.scopes[parentScopeId];\n let flags = getScopeFlags(type, parentScope.flags);\n if (isStrictScope(node, type)) {\n flags |= ScopeFlags.StrictMode;\n }\n flags = inheritStrictMode(flags, parentScope.flags);\n const start = getScopeStart(node, type, this.source);\n const end = getScopeEnd(node, type, this.source);\n const scopeId = createScope({\n scopes: this.scopes,\n type,\n start,\n end,\n parentId: parentScopeId,\n flags,\n });\n this.registerScope(node, scopeId);\n if (type === ScopeType.Block && parentScope.type === ScopeType.Catch) {\n this.moveBindingsToChild(parentScopeId, scopeId);\n }\n this.scopeStack.push({ scopeId });\n fn();\n this.scopeStack.pop();\n }\n\n private registerScope(node: AnyNode, scopeId: number): void {\n if (node && typeof node === 'object') {\n this.scopeIdByNode.set(node, scopeId);\n }\n }\n\n private moveBindingsToChild(parentScopeId: number, childScopeId: number): void {\n const parentScope = this.scopes[parentScopeId];\n if (!parentScope.bindings.size) return;\n const childScope = this.scopes[childScopeId];\n for (const [name, bindingId] of parentScope.bindings.entries()) {\n childScope.bindings.set(name, bindingId);\n const binding = this.bindings[bindingId];\n if (binding) {\n binding.scopeId = childScopeId;\n }\n }\n parentScope.bindings.clear();\n }\n\n private declareBinding(scopeId: number, name: string, kind: BindingKind, node: AnyNode): number {\n const scope = this.scopes[scopeId];\n const addValue = shouldAddToValueBindings(kind);\n const addType = shouldAddToTypeBindings(kind);\n if (addValue) {\n const existingValue = scope.bindings.get(name);\n if (existingValue != null) {\n if (kind === BindingKind.Var || kind === BindingKind.Function) {\n return existingValue;\n }\n return existingValue;\n }\n } else if (addType) {\n const existingType = scope.typeBindings.get(name);\n if (existingType != null) {\n return existingType;\n }\n }\n const binding: Binding = {\n id: this.bindings.length,\n name,\n kind,\n declStart: node.start ?? 0,\n declEnd: node.end ?? (node.start ?? 0),\n scopeId,\n };\n this.bindings.push(binding);\n if (addValue) {\n scope.bindings.set(name, binding.id);\n }\n if (addType && !scope.typeBindings.has(name)) {\n scope.typeBindings.set(name, binding.id);\n }\n return binding.id;\n }\n\n private declareParams(params: AnyNode[]): void {\n for (const param of params) {\n this.declarePattern(param, BindingKind.Param);\n }\n }\n\n private declareTypeParameters(typeParameters: AnyNode | null | undefined, ancestors: AnyNode[]): void {\n if (!typeParameters) return;\n const params = typeParameters.params ?? typeParameters.parameters;\n const list = Array.isArray(params)\n ? params\n : Array.isArray(typeParameters.items)\n ? typeParameters.items\n : Array.isArray(typeParameters)\n ? typeParameters\n : [];\n for (const param of list) {\n this.walkNode(param, ancestors);\n }\n }\n\n private declarePattern(pattern: AnyNode, kind: BindingKind): void {\n const identifiers: AnyNode[] = [];\n collectBindingIdentifiers(pattern, identifiers);\n for (const ident of identifiers) {\n if (ident?.name) {\n this.declareBinding(this.currentScopeId(), ident.name, kind, ident);\n }\n }\n }\n\n private handleVariableDeclaration(node: AnyNode, ancestors: AnyNode[]): void {\n const kind = node.kind;\n const bindingKind = kind === 'var' ? BindingKind.Var : kind === 'let' ? BindingKind.Let : BindingKind.Const;\n for (const decl of node.declarations ?? []) {\n if (!decl) continue;\n const scopeId =\n bindingKind === BindingKind.Var\n ? this.findVarScopeId()\n : this.currentScopeId();\n const identifiers: AnyNode[] = [];\n collectBindingIdentifiers(decl.id, identifiers);\n for (const ident of identifiers) {\n if (ident?.name) {\n this.declareBinding(scopeId, ident.name, bindingKind, ident);\n }\n }\n if (decl.id) {\n this.walkPatternExpressions(decl.id, ancestors);\n }\n if (decl.init) {\n this.walkNode(decl.init, ancestors);\n }\n }\n }\n\n private handleImportDeclaration(node: AnyNode): void {\n const rootScopeId = 0;\n const declarationKind =\n (node.importKind ?? node.import_kind) === 'type'\n ? BindingKind.TypeImport\n : BindingKind.Import;\n for (const spec of node.specifiers ?? []) {\n const local = spec?.local;\n if (!local?.name) continue;\n let kind = declarationKind;\n if (spec?.type === 'ImportSpecifier') {\n const specKind = spec.importKind ?? spec.import_kind;\n if (declarationKind === BindingKind.Import && specKind === 'type') {\n kind = BindingKind.TypeImport;\n }\n }\n this.declareBinding(rootScopeId, local.name, kind, local);\n }\n }\n\n private handleImportEqualsDeclaration(node: AnyNode): void {\n const kind =\n (node.importKind ?? node.import_kind) === 'type'\n ? BindingKind.TypeImport\n : BindingKind.Import;\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, kind, node.id);\n }\n }\n\n private handleTsModuleDeclaration(node: AnyNode, ancestors: AnyNode[]): void {\n const id = node.id;\n if (id?.type === 'Identifier' && id.name) {\n this.declareBinding(this.currentScopeId(), id.name, BindingKind.Namespace, id);\n }\n this.withScope(node, ScopeType.TsModule, () => {\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n }\n\n private walkParams(params: AnyNode[], ancestors: AnyNode[]): void {\n for (const param of params) {\n this.walkPatternExpressions(param, ancestors);\n }\n }\n\n private walkPatternExpressions(pattern: AnyNode, ancestors: AnyNode[]): void {\n if (!pattern) return;\n if (pattern.type === 'TSParameterProperty' && pattern.parameter) {\n this.walkPatternExpressions(pattern.parameter, ancestors.concat(pattern));\n return;\n }\n if (pattern.typeAnnotation) {\n this.walkNode(pattern.typeAnnotation, ancestors.concat(pattern));\n }\n switch (pattern.type) {\n case 'Identifier':\n return;\n case 'RestElement':\n this.walkPatternExpressions(pattern.argument, ancestors);\n return;\n case 'AssignmentPattern':\n this.walkPatternExpressions(pattern.left, ancestors);\n if (pattern.right) {\n this.walkNode(pattern.right, ancestors);\n }\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) {\n this.walkPatternExpressions(element, ancestors);\n }\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n if (prop.computed && prop.key) {\n this.walkNode(prop.key, ancestors);\n }\n if (prop.value) {\n this.walkPatternExpressions(prop.value, ancestors);\n }\n } else if (prop.type === 'RestElement') {\n this.walkPatternExpressions(prop.argument, ancestors);\n }\n }\n return;\n default:\n this.walkNode(pattern, ancestors);\n }\n }\n\n private findVarScopeId(): number {\n for (let i = this.scopeStack.length - 1; i >= 0; i -= 1) {\n const scope = this.scopes[this.scopeStack[i].scopeId];\n if (\n scope.type === ScopeType.Function ||\n scope.type === ScopeType.Program ||\n scope.type === ScopeType.ClassStaticBlock ||\n scope.type === ScopeType.TsModule\n ) {\n return scope.id;\n }\n }\n return 0;\n }\n\n private walkNode(node: AnyNode, ancestors: AnyNode[]): void {\n if (!node) return;\n this.walkBindings(node, ancestors.concat(node));\n }\n\n private walkChildren(node: AnyNode, ancestors: AnyNode[]): void {\n const keys = visitorKeys[node.type] ?? [];\n for (const key of keys) {\n const value = node[key];\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n this.walkBindings(child, ancestors.concat(node));\n }\n }\n } else if (isNode(value)) {\n this.walkBindings(value, ancestors.concat(node));\n }\n }\n }\n}\n\nclass ReferenceBuilder {\n private scopes: Scope[];\n private bindings: Binding[];\n private references: Reference[];\n private scopeIdByNode: WeakMap<object, number>;\n private scopeStack: ScopeStackItem[] = [];\n private contextStack: ReferenceContext[] = [ReferenceContext.Value];\n\n constructor({\n scopes,\n bindings,\n references,\n scopeIdByNode,\n }: {\n scopes: Scope[];\n bindings: Binding[];\n references: Reference[];\n scopeIdByNode: WeakMap<object, number>;\n }) {\n this.scopes = scopes;\n this.bindings = bindings;\n this.references = references;\n this.scopeIdByNode = scopeIdByNode;\n this.scopeStack.push({ scopeId: 0 });\n }\n\n walkReferences(node: AnyNode, ancestors: AnyNode[] = []): void {\n if (!node) return;\n switch (node.type) {\n case 'Program':\n case 'BlockStatement':\n case 'ForStatement':\n case 'ForInStatement':\n case 'ForOfStatement':\n case 'SwitchStatement':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'FunctionDeclaration':\n case 'FunctionExpression':\n case 'ArrowFunctionExpression':\n case 'TSDeclareFunction':\n case 'TSEmptyBodyFunctionExpression':\n // TSDeclareFunction covers `declare function f(...)` and function\n // overload signatures; TSEmptyBodyFunctionExpression is the body-less\n // signature used by abstract methods. Both share function-shaped\n // scoping of params and need references inside their type annotations\n // and predicates to resolve against the function's own scope.\n this.withScope(node, () => {\n const params = getParamList(node.params);\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'CatchClause':\n this.withScope(node, () => {\n if (node.param) {\n this.walkPatternReferences(node.param, ancestors.concat(node));\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'ClassDeclaration':\n case 'ClassExpression':\n // Decorators evaluate in the enclosing scope (they run at class-definition\n // time), so walk them before entering the class scope.\n this.walkDecorators(node, ancestors);\n this.withScope(node, () => {\n if (node.superClass) {\n this.walkReferences(node.superClass, ancestors.concat(node));\n }\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const superTypeArguments =\n node.superTypeArguments ??\n node.super_type_arguments ??\n node.superTypeParameters ??\n node.super_type_parameters;\n if (typeParameters) {\n this.withTypeContext(() => {\n this.walkReferences(typeParameters, ancestors.concat(node));\n });\n }\n if (superTypeArguments) {\n this.withTypeContext(() => {\n this.walkReferences(superTypeArguments, ancestors.concat(node));\n });\n }\n if (node.implements) {\n this.withTypeContext(() => {\n for (const impl of node.implements ?? []) {\n this.walkReferences(impl, ancestors.concat(node));\n }\n });\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'StaticBlock':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'VariableDeclarator':\n if (node.id) {\n this.walkPatternReferences(node.id, ancestors);\n }\n if (node.init) {\n this.walkReferences(node.init, ancestors.concat(node));\n }\n return;\n case 'ImportDeclaration':\n return;\n case 'ExportNamedDeclaration':\n // Walk the optional inline declaration (e.g. `export const x = 1`).\n // Specifiers come in two flavors:\n // - `export { foo }` / `export { foo as bar }` (no `source`) — the\n // `local` Identifier is a real reference to a local binding; the\n // `exported` alias is external-only and must NOT count as a\n // reference. In shorthand form the two point to the same node, so\n // walking only `local` also prevents double-counting.\n // - `export { foo } from 'm'` (with `source`) — neither side refers\n // to a local binding; they're names on the re-exported module.\n if (node.declaration) {\n this.walkReferences(node.declaration, ancestors.concat(node));\n }\n if (!node.source) {\n for (const spec of node.specifiers ?? []) {\n if (spec?.local) {\n this.walkReferences(spec.local, ancestors.concat(node, spec));\n }\n }\n }\n return;\n case 'ExportAllDeclaration':\n // `export * from 'm'` and `export * as ns from 'm'` never reference\n // local bindings — the alias in the latter is an external name only.\n return;\n case 'ExportDefaultDeclaration':\n if (node.declaration) {\n this.walkReferences(node.declaration, ancestors.concat(node));\n }\n return;\n case 'MetaProperty':\n // `import.meta` / `new.target` — both children are syntactic keyword\n // tokens, not user identifiers, so there are no references to emit.\n return;\n case 'TSImportEqualsDeclaration':\n if (node.moduleReference ?? node.module_reference) {\n this.walkReferences(node.moduleReference ?? node.module_reference, ancestors.concat(node));\n }\n return;\n case 'TSModuleDeclaration':\n case 'TSGlobalDeclaration':\n this.withScope(node, () => {\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'TSModuleBlock':\n this.walkChildren(node, ancestors);\n return;\n case 'TSTypeAliasDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const typeAnnotation = node.typeAnnotation ?? node.type_annotation;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (typeAnnotation) {\n this.walkReferences(typeAnnotation, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSInterfaceDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (node.extends) {\n for (const heritage of node.extends ?? []) {\n this.walkReferences(heritage, ancestors.concat(node));\n }\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSEnumDeclaration':\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n return;\n case 'TSEnumBody':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'TSEnumMember':\n if (node.initializer) {\n this.walkReferences(node.initializer, ancestors.concat(node));\n }\n return;\n case 'TSMappedType':\n this.withScope(node, () => {\n const nameType = node.nameType ?? node.name_type;\n const typeAnnotation = node.typeAnnotation ?? node.type_annotation;\n this.withTypeContext(() => {\n if (node.constraint) {\n this.walkReferences(node.constraint, ancestors.concat(node));\n }\n if (nameType) {\n this.walkReferences(nameType, ancestors.concat(node));\n }\n if (typeAnnotation) {\n this.walkReferences(typeAnnotation, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSConditionalType':\n this.withTypeContext(() => {\n const checkType = node.checkType ?? node.check_type;\n const extendsType = node.extendsType ?? node.extends_type;\n const trueType = node.trueType ?? node.true_type;\n const falseType = node.falseType ?? node.false_type;\n if (checkType) {\n this.walkReferences(checkType, ancestors.concat(node));\n }\n this.withScope(node, () => {\n if (extendsType) {\n this.walkReferences(extendsType, ancestors.concat(node));\n }\n if (trueType) {\n this.walkReferences(trueType, ancestors.concat(node));\n }\n });\n if (falseType) {\n this.walkReferences(falseType, ancestors.concat(node));\n }\n });\n return;\n case 'TSFunctionType':\n case 'TSConstructorType':\n case 'TSCallSignatureDeclaration':\n case 'TSConstructSignatureDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n const params = getParamList(node.params);\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSMethodSignature':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n const params = getParamList(node.params);\n this.withTypeContext(() => {\n if (node.key && node.computed) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.key, ancestors.concat(node));\n });\n }\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSPropertySignature':\n this.withTypeContext(() => {\n if (node.key && node.computed) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.key, ancestors.concat(node));\n });\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n }\n });\n return;\n case 'TSTypeQuery':\n if (node.exprName ?? node.expr_name) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.exprName ?? node.expr_name, ancestors.concat(node));\n });\n }\n if (node.typeArguments ?? node.type_arguments) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeArguments ?? node.type_arguments, ancestors.concat(node));\n });\n }\n return;\n case 'TSAsExpression':\n case 'TSSatisfiesExpression':\n case 'TSTypeAssertion':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n });\n }\n return;\n case 'TSInstantiationExpression':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n if (node.typeArguments ?? node.type_arguments) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeArguments ?? node.type_arguments, ancestors.concat(node));\n });\n }\n return;\n case 'TSNonNullExpression':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n return;\n case 'PropertyDefinition':\n case 'ClassProperty':\n case 'AccessorProperty':\n case 'TSAbstractPropertyDefinition':\n case 'TSAbstractAccessorProperty':\n this.walkDecorators(node, ancestors);\n if (node.computed && node.key) {\n this.walkReferences(node.key, ancestors.concat(node));\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n });\n }\n if (node.value) {\n this.walkReferences(node.value, ancestors.concat(node));\n }\n return;\n case 'TSAbstractMethodDefinition':\n // Abstract methods have no body; their `value` is an empty-body\n // function expression. Walk decorators, the computed key, and the\n // signature so any references inside still resolve.\n this.walkDecorators(node, ancestors);\n if (node.computed && node.key) {\n this.walkReferences(node.key, ancestors.concat(node));\n }\n if (node.value) {\n this.walkReferences(node.value, ancestors.concat(node));\n }\n return;\n case 'TSTypePredicate':\n // `x is T` / `asserts x is T`: the parameter name is a value-level\n // reference to the function's parameter, and the optional annotation\n // is a plain type. Use value-as-type for the param so a regular Param\n // binding (not a type binding) can resolve it.\n if (node.parameterName) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.parameterName, ancestors.concat(node));\n });\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n }\n return;\n default:\n break;\n }\n\n if (node.type === 'JSXIdentifier') {\n const parent = ancestors[ancestors.length - 1];\n const grandparent = ancestors[ancestors.length - 2];\n const parentKey = getParentKey(parent, node);\n if (isJsxIdentifierReference(node, parent, grandparent, parentKey)) {\n this.addReference(node);\n }\n return;\n }\n\n if (node.type === 'Identifier') {\n const parent = ancestors[ancestors.length - 1];\n const grandparent = ancestors[ancestors.length - 2];\n const parentKey = getParentKey(parent, node);\n if (isIdentifierReference(node, parent, grandparent, parentKey)) {\n this.addReference(node);\n }\n return;\n }\n\n this.walkChildren(node, ancestors);\n }\n\n private withScope(node: AnyNode, fn: () => void): void {\n const scopeId = this.scopeIdByNode.get(node);\n if (scopeId == null) {\n fn();\n return;\n }\n this.scopeStack.push({ scopeId });\n fn();\n this.scopeStack.pop();\n }\n\n private withContext(context: ReferenceContext, fn: () => void): void {\n this.contextStack.push(context);\n fn();\n this.contextStack.pop();\n }\n\n private withTypeContext(fn: () => void): void {\n this.withContext(ReferenceContext.Type, fn);\n }\n\n private withValueAsTypeContext(fn: () => void): void {\n this.withContext(ReferenceContext.ValueAsType, fn);\n }\n\n private currentContext(): ReferenceContext {\n return this.contextStack[this.contextStack.length - 1] ?? ReferenceContext.Value;\n }\n\n private addReference(node: AnyNode): void {\n const name = node.name;\n const scopeId = this.currentScopeId();\n const bindingId = this.resolveBinding(scopeId, name, this.currentContext());\n const ref: Reference = {\n id: this.references.length,\n name,\n start: node.start ?? 0,\n end: node.end ?? (node.start ?? 0),\n scopeId,\n bindingId,\n };\n this.references.push(ref);\n }\n\n private currentScopeId(): number {\n return this.scopeStack[this.scopeStack.length - 1]?.scopeId ?? 0;\n }\n\n private resolveBinding(\n scopeId: number,\n name: string,\n context: ReferenceContext,\n ): number | null {\n let currentScopeId: number | null = scopeId;\n while (currentScopeId != null) {\n const scope: Scope = this.scopes[currentScopeId]!;\n if (context === ReferenceContext.Type) {\n const typeBindingId = scope.typeBindings.get(name);\n if (typeBindingId != null) return typeBindingId;\n const valueBindingId = scope.bindings.get(name);\n if (valueBindingId != null) {\n const bindingKind = this.bindings[valueBindingId]?.kind;\n if (bindingKind && canReferenceAsType(bindingKind)) {\n return valueBindingId;\n }\n }\n } else if (context === ReferenceContext.ValueAsType) {\n const valueBindingId = scope.bindings.get(name);\n if (valueBindingId != null) return valueBindingId;\n const typeBindingId = scope.typeBindings.get(name);\n if (typeBindingId != null) {\n const bindingKind = this.bindings[typeBindingId]?.kind;\n if (bindingKind && canReferenceAsValueAsType(bindingKind)) {\n return typeBindingId;\n }\n }\n } else {\n const bindingId = scope.bindings.get(name);\n if (bindingId != null) return bindingId;\n }\n currentScopeId = scope.parentId;\n }\n return null;\n }\n\n private walkDecorators(node: AnyNode, ancestors: AnyNode[]): void {\n const decorators = node.decorators;\n if (!Array.isArray(decorators)) return;\n for (const decorator of decorators) {\n if (decorator) {\n this.walkReferences(decorator, ancestors.concat(node));\n }\n }\n }\n\n private walkPatternReferences(pattern: AnyNode, ancestors: AnyNode[]): void {\n if (!pattern) return;\n // Parameter decorators (e.g. `m(@dec x: number)`) attach to the pattern\n // itself and must resolve against the surrounding scope like any other\n // expression.\n this.walkDecorators(pattern, ancestors);\n if (pattern.type === 'TSParameterProperty' && pattern.parameter) {\n this.walkPatternReferences(pattern.parameter, ancestors.concat(pattern));\n return;\n }\n if (pattern.typeAnnotation) {\n this.withTypeContext(() => {\n this.walkReferences(pattern.typeAnnotation, ancestors.concat(pattern));\n });\n }\n switch (pattern.type) {\n case 'Identifier':\n return;\n case 'RestElement':\n this.walkPatternReferences(pattern.argument, ancestors.concat(pattern));\n return;\n case 'AssignmentPattern':\n this.walkPatternReferences(pattern.left, ancestors.concat(pattern));\n if (pattern.right) {\n this.walkReferences(pattern.right, ancestors.concat(pattern));\n }\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) {\n this.walkPatternReferences(element, ancestors.concat(pattern));\n }\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n if (prop.computed && prop.key) {\n this.walkReferences(prop.key, ancestors.concat(prop));\n }\n if (prop.value) {\n this.walkPatternReferences(prop.value, ancestors.concat(prop));\n }\n } else if (prop.type === 'RestElement') {\n this.walkPatternReferences(prop.argument, ancestors.concat(prop));\n }\n }\n return;\n default:\n this.walkReferences(pattern, ancestors.concat(pattern));\n }\n }\n\n private walkChildren(node: AnyNode, ancestors: AnyNode[]): void {\n const keys = visitorKeys[node.type] ?? [];\n for (const key of keys) {\n const value = node[key];\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n this.walkReferences(child, ancestors.concat(node));\n }\n }\n } else if (isNode(value)) {\n this.walkReferences(value, ancestors.concat(node));\n }\n }\n }\n}\n\nfunction createScope({\n scopes,\n type,\n start,\n end,\n parentId,\n flags,\n}: {\n scopes: Scope[];\n type: ScopeType;\n start: number;\n end: number;\n parentId: number | null;\n flags: ScopeFlags;\n}): number {\n const scopeId = scopes.length;\n const scope: Scope = {\n id: scopeId,\n type,\n flags,\n start,\n end,\n parentId,\n childIds: [],\n bindings: new Map(),\n typeBindings: new Map(),\n };\n scopes.push(scope);\n if (parentId != null) {\n scopes[parentId].childIds.push(scopeId);\n }\n return scopeId;\n}\n\nfunction inheritStrictMode(flags: ScopeFlags, parentFlags: ScopeFlags): ScopeFlags {\n if (parentFlags & ScopeFlags.StrictMode) {\n return flags | ScopeFlags.StrictMode;\n }\n return flags;\n}\n\nfunction getScopeFlags(type: ScopeType, parentFlags: ScopeFlags): ScopeFlags {\n switch (type) {\n case ScopeType.Program:\n return parentFlags;\n case ScopeType.Function:\n return ScopeFlags.Function;\n case ScopeType.Block:\n return ScopeFlags.Block;\n case ScopeType.Catch:\n return ScopeFlags.Catch | ScopeFlags.Block;\n case ScopeType.Class:\n return ScopeFlags.Class;\n case ScopeType.ClassStaticBlock:\n return ScopeFlags.ClassStaticBlock;\n case ScopeType.For:\n return ScopeFlags.For | ScopeFlags.Block;\n case ScopeType.Switch:\n return ScopeFlags.Switch | ScopeFlags.Block;\n case ScopeType.TsModule:\n return ScopeFlags.TsModuleBlock;\n case ScopeType.Enum:\n return ScopeFlags.Enum;\n case ScopeType.Type:\n return ScopeFlags.Type;\n case ScopeType.TsConditional:\n return ScopeFlags.TsConditional;\n default:\n return ScopeFlags.Block;\n }\n}\n\nfunction getScopeStart(node: AnyNode, type: ScopeType, source: string): number {\n if (type === ScopeType.Program) return 0;\n if (type === ScopeType.TsModule) {\n const body = node.body;\n if (body?.start != null) return body.start;\n }\n if (type === ScopeType.Function) {\n const body = node.body;\n if (body?.start != null) return body.start;\n }\n return node.start ?? 0;\n}\n\nfunction getScopeEnd(node: AnyNode, type: ScopeType, source: string): number {\n if (type === ScopeType.Program) return source.length;\n if (type === ScopeType.TsModule) {\n const body = node.body;\n if (body?.end != null) return body.end;\n }\n if (type === ScopeType.Function) {\n const body = node.body;\n if (body?.end != null) return body.end;\n }\n return node.end ?? source.length;\n}\n\nfunction collectBindingIdentifiers(pattern: AnyNode, out: AnyNode[]): void {\n if (!pattern) return;\n switch (pattern.type) {\n case 'Identifier':\n out.push(pattern);\n return;\n case 'TSParameterProperty':\n collectBindingIdentifiers(pattern.parameter, out);\n return;\n case 'RestElement':\n collectBindingIdentifiers(pattern.argument, out);\n return;\n case 'AssignmentPattern':\n collectBindingIdentifiers(pattern.left, out);\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) collectBindingIdentifiers(element, out);\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n collectBindingIdentifiers(prop.value, out);\n } else if (prop.type === 'RestElement') {\n collectBindingIdentifiers(prop.argument, out);\n }\n }\n return;\n default:\n return;\n }\n}\n\nfunction getParentKey(parent: AnyNode | undefined, node: AnyNode): string | null {\n if (!parent) return null;\n for (const key of Object.keys(parent)) {\n const value = parent[key];\n if (value === node) return key;\n if (Array.isArray(value)) {\n if (value.includes(node)) return key;\n }\n }\n return null;\n}\n\nfunction isIdentifierReference(\n node: AnyNode,\n parent?: AnyNode,\n grandparent?: AnyNode,\n parentKey?: string | null,\n): boolean {\n if (!parent) return true;\n\n if (\n parent.type === 'MemberExpression' &&\n parentKey === 'property' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'Property' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'MethodDefinition' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'PropertyDefinition' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n parent.type === 'ClassProperty' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n parent.type === 'AccessorProperty' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n (parent.type === 'TSAbstractMethodDefinition' ||\n parent.type === 'TSAbstractPropertyDefinition' ||\n parent.type === 'TSAbstractAccessorProperty') &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n (parent.type === 'TSPropertySignature' || parent.type === 'TSMethodSignature') &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n // Note: we don't add an ObjectPattern-specific exclusion. Declaration\n // contexts (VariableDeclarator, params, catch) route through\n // `walkPatternReferences` which never calls `isIdentifierReference`, so the\n // only time a `Property` inside an `ObjectPattern` reaches this check is\n // when the pattern is an *assignment target* — in which case the shorthand\n // value identifier genuinely is a reference. The general Property.key rule\n // above still excludes the non-computed key side.\n\n if (\n parent.type === 'VariableDeclarator' &&\n parentKey === 'id'\n ) {\n return false;\n }\n\n if (\n (parent.type === 'FunctionDeclaration' ||\n parent.type === 'FunctionExpression' ||\n parent.type === 'ArrowFunctionExpression') &&\n (parentKey === 'id' || parentKey === 'params')\n ) {\n return false;\n }\n\n if (\n (parent.type === 'ClassDeclaration' || parent.type === 'ClassExpression') &&\n parentKey === 'id'\n ) {\n return false;\n }\n if (\n (parent.type === 'TSTypeAliasDeclaration' ||\n parent.type === 'TSInterfaceDeclaration' ||\n parent.type === 'TSEnumDeclaration' ||\n parent.type === 'TSModuleDeclaration' ||\n parent.type === 'TSImportEqualsDeclaration') &&\n parentKey === 'id'\n ) {\n return false;\n }\n if (parent.type === 'TSEnumMember' && parentKey === 'id') {\n return false;\n }\n if (parent.type === 'TSTypeParameter' && parentKey === 'name') {\n return false;\n }\n if (parent.type === 'TSMappedType' && parentKey === 'key') {\n return false;\n }\n if (parent.type === 'TSIndexSignature' && parentKey === 'parameters') {\n return false;\n }\n if (\n (parent.type === 'TSQualifiedName' || parent.type === 'TSImportTypeQualifiedName') &&\n parentKey === 'right'\n ) {\n return false;\n }\n\n if (\n (parent.type === 'ImportSpecifier' ||\n parent.type === 'ImportDefaultSpecifier' ||\n parent.type === 'ImportNamespaceSpecifier') &&\n parentKey === 'local'\n ) {\n return false;\n }\n\n if (parent.type === 'CatchClause' && parentKey === 'param') {\n return false;\n }\n\n if (parent.type === 'LabeledStatement' && parentKey === 'label') {\n return false;\n }\n if (\n (parent.type === 'BreakStatement' || parent.type === 'ContinueStatement') &&\n parentKey === 'label'\n ) {\n return false;\n }\n\n return true;\n}\n\nfunction isJsxIdentifierReference(\n node: AnyNode,\n parent?: AnyNode,\n grandparent?: AnyNode,\n parentKey?: string | null,\n): boolean {\n if (!parent) return true;\n if (parent.type === 'JSXAttribute' && parentKey === 'name') {\n return false;\n }\n if (parent.type === 'JSXMemberExpression' && parentKey === 'property') {\n return false;\n }\n if (parent.type === 'JSXNamespacedName') {\n return false;\n }\n return true;\n}\n","/**\n * Canvas source-version identity.\n *\n * `sourceVersionHash` maps the exact text of a source file to a 16-hex-character\n * token identifying that content. It is the version stamp the canvas edit/\n * reconcile loop uses to answer \"has the host caught up to write W?\": the SDK\n * JSX transforms stamp `data-tempo-source-version` with the hash of the source\n * they annotate, and the write pipeline (`applyWrites` → `sourceVersionsByFile`)\n * reports the hash of the exact bytes it wrote. A captured element's stamp is\n * compared for EQUALITY against a write's version — never ordered, never\n * subtracted, never used as a high-water mark. Two identical contents MUST\n * produce the same token; two different contents MUST (for identity purposes)\n * produce different tokens.\n *\n * Because coverage is an equality test across independently-computed hashes,\n * every producer of a version — this function's callers in the vite/next/expo\n * transforms and in `applyWrites` — MUST route through THIS function so the\n * tokens are bit-identical. Changing the algorithm requires changing it for all\n * producers in lockstep, or old stamps and new write-versions stop matching.\n *\n * The token concatenates two independent 32-bit rolling hashes over the string's\n * UTF-16 code units — djb2 and sdbm — each rendered as unsigned 8-char hex. Two\n * independent hash families make an accidental collision between distinct source\n * contents vanishingly unlikely for version-identity use, while the function\n * stays dependency-free and single-pass (fast enough to run once per file per\n * transform on the devserver hot path).\n */\nexport function sourceVersionHash(content: string): string {\n let djb2 = 5381;\n let sdbm = 0;\n for (let i = 0; i < content.length; i++) {\n const c = content.charCodeAt(i);\n // djb2: hash * 33 ^ c. The trailing `^ c` keeps the value inside 32-bit\n // signed range every iteration, so no explicit coercion is needed.\n djb2 = ((djb2 << 5) + djb2) ^ c;\n // sdbm: c + hash*65599. The final term is an arithmetic subtraction, so\n // coerce back to a 32-bit int each step to prevent float drift.\n sdbm = (c + (sdbm << 6) + (sdbm << 16) - sdbm) | 0;\n }\n return toHex8(djb2) + toHex8(sdbm);\n}\n\n/** Render a 32-bit value as unsigned, zero-padded 8-char lowercase hex. */\nfunction toHex8(n: number): string {\n return (n >>> 0).toString(16).padStart(8, \"0\");\n}\n","import { realpathSync, statSync } from \"node:fs\";\nimport { relative } from \"node:path\";\n\nimport type {\n ElementInfo,\n PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\n\nexport const DEFAULT_EXCLUDE = [\"**/node_modules/**\"] as const;\n\n/**\n * Static per-component declaration of whether a custom component accepts\n * `children`. Supplied by callers that know this from a fixed table (e.g. the\n * Expo plugin's React Native host-component overrides). The Vite/Next.js\n * plugins supply no overrides — custom components are left without a\n * `supports-children` flag and consumers treat their support as unknown.\n */\nexport interface ElementTypeSupport {\n supportsChildren: boolean;\n}\n\n/** HTML void elements that cannot have children (self-closing only). */\nexport const HTML_VOID_ELEMENTS = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n) => Record<string, PropValue>;\n\nexport function cleanModuleId(id: string): string {\n return id.replace(/[?#].*$/, \"\");\n}\n\nexport function resolveCanonicalRoot(root: string): string {\n try {\n return realpathSync.native(root);\n } catch {\n return root;\n }\n}\n\nexport function isIntrinsicElement(tagName: string): boolean {\n return tagName.length > 0 && tagName[0] === tagName[0]!.toLowerCase();\n}\n\nexport function hasJsxAttribute(info: ElementInfo, attrName: string): boolean {\n for (const attr of info.element.openingElement.attributes) {\n const name = (attr as { name?: { name?: unknown } }).name;\n if (name?.name === attrName) return true;\n }\n return false;\n}\n\nexport function defaultComputeAnnotatedProps(\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n): Record<string, PropValue> {\n return {\n \"data-tempo-filepath\": filepath,\n \"data-tempo-position\": info.element.openingElement.start,\n \"data-tempo-modifiedts\": modifiedtsMs,\n // Content-hash identity of the file this element was annotated from. The\n // canvas reconcile loop equality-compares it against the write pipeline's\n // computed version to decide whether a capture reflects a given edit.\n \"data-tempo-source-version\": sourceVersion,\n };\n}\n\nexport function computeTempoAnnotatedProps(params: {\n info: ElementInfo;\n filepath: string;\n modifiedtsMs: number;\n sourceVersion: string;\n computeAnnotatedProps?: ComputeAnnotatedProps;\n elementSupportOverrides?: ReadonlyMap<string, ElementTypeSupport>;\n}): Record<string, PropValue> {\n const {\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps,\n elementSupportOverrides,\n } = params;\n\n const userProps = computeAnnotatedProps\n ? computeAnnotatedProps(info, filepath, modifiedtsMs, sourceVersion)\n : defaultComputeAnnotatedProps(info, filepath, modifiedtsMs, sourceVersion);\n\n if (isIntrinsicElement(info.tagName)) {\n return {\n ...userProps,\n \"data-tempo-supports-children\": hasJsxAttribute(\n info,\n \"data-tempo-supports-children\",\n )\n ? undefined\n : !HTML_VOID_ELEMENTS.has(info.tagName),\n };\n }\n\n const override = elementSupportOverrides?.get(info.tagName);\n if (override) {\n return {\n ...userProps,\n \"data-tempo-supports-children\": hasJsxAttribute(\n info,\n \"data-tempo-supports-children\",\n )\n ? undefined\n : override.supportsChildren,\n };\n }\n\n // Custom component with no static override: emit no `data-tempo-supports-*`\n // flags. Determining them required a per-file TypeScript program, which was\n // removed for being the dominant cost of devserver startup. Consumers treat\n // the absent flags as \"unknown\" and fall back to their own defaults.\n return userProps;\n}\n\nexport function getFileAnnotationContext(params: {\n source: string;\n filename: string;\n root: string;\n canonicalizeFilename?: boolean;\n}): {\n cleanFilename: string;\n filepath: string;\n modifiedtsMs: number;\n sourceVersion: string;\n} {\n const rawCleanFilename = cleanModuleId(params.filename);\n let cleanFilename = rawCleanFilename;\n if (params.canonicalizeFilename) {\n try {\n cleanFilename = realpathSync.native(rawCleanFilename);\n } catch {\n cleanFilename = rawCleanFilename;\n }\n }\n return {\n cleanFilename,\n filepath: relative(params.root, cleanFilename),\n modifiedtsMs: Math.trunc(statSync(cleanFilename).mtimeMs),\n // Hashed once per file per transform (the context is built once, reused\n // for every element) so the per-element funnel just forwards the token.\n sourceVersion: sourceVersionHash(params.source),\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","/**\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","/**\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","/**\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 covered by every watcher\n * pipeline (`lastHotUpdateMtimeMs`) and schedules one ordinary trailing\n * replay after a rapid same-file burst. Normal updates remain immediate;\n * the replay makes the terminal disk revision apply after every overlapping\n * pipeline. 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 * the client-side failure is repaired at its cause by a terminal replay,\n * rather than papered over with a new client receipt protocol.\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 starts one asynchronous hot-update pipeline per watcher event. During\n * a rapid save burst those pipelines overlap, so the browser can permanently\n * apply the penultimate revision last. Normal updates must remain immediate:\n * delaying every update perturbs editor transactions that legitimately wait\n * for each HMR result. Instead, observing two or more same-file events inside\n * a quiet window schedules one ordinary watcher replay after the burst. That\n * last pipeline fetches the terminal disk revision after all earlier pipelines\n * have settled.\n *\n * The replay itself also arrives through the watcher. A one-event allowance\n * prevents that synthetic event from manufacturing another two-event burst\n * when it overlaps one late real event. Further real edits still re-arm the\n * mechanism. The mechanism is server-side, per-file, and uses Vite's public\n * watcher input; it adds no client receipt or importer traversal.\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 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 const bursts = new Map<\n string,\n { eventCount: number; timer?: Timer; replay: () => void }\n >();\n\n return {\n observe(file, replay) {\n const previous = bursts.get(file);\n if (previous?.timer) cancel(previous.timer);\n const burst: {\n eventCount: number;\n timer?: Timer;\n replay: () => void;\n } = {\n eventCount: (previous?.eventCount ?? 0) + 1,\n replay,\n };\n burst.timer = schedule(() => {\n if (bursts.get(file) !== burst) return;\n bursts.delete(file);\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: {\n eventCount: number;\n timer?: Timer;\n replay: () => void;\n } = { eventCount: -1, replay: burst.replay };\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 clear() {\n for (const burst of bursts.values()) {\n if (burst.timer) cancel(burst.timer);\n }\n bursts.clear();\n },\n };\n}\n"],"mappings":";;;;;AAAA;AAAA,EAEE;AAAA,EACA,gBAAAA;AAAA,EACA,YAAAC;AAAA,EACA,SAAS;AAAA,OACJ;AAEP,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY,MAAM,YAAAC,WAAU,eAAe;AAC7D,SAAS,oBAAwC;;;ACVjD,SAAS,aAAAC,kBAAoD;;;ACiBtD,SAAS,WAAW,MAA8B;AACvD,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,KAAK;AAAA,IACd,KAAK;AACH,aAAO,GAAG,KAAK,UAAU,IAAI,IAAI,KAAK,KAAK,IAAI;AAAA,IACjD,KAAK;AACH,aAAO,2BAA2B,IAAI;AAAA,EAC1C;AACF;AASO,SAAS,2BAA2B,MAAmC;AAC5E,QAAM,SAAS,KAAK,OAAO,SAAS,kBAAkB,KAAK,OAAO,OAAO,2BAA2B,KAAK,MAAM;AAC/G,SAAO,GAAG,MAAM,IAAI,KAAK,SAAS,IAAI;AACxC;;;ACfO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O;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAeF;AAGO,IAAM,gBAAgB;","names":["realpathSync","statSync","relative","parseSync","parseSync","realpathSync","resolve","statSync","options","relative"]}