tempo-sdk 0.0.16 → 0.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/canvas/editor.d.ts +44 -9
- package/dist/canvas/editor.js +116 -416
- package/dist/canvas/editor.js.map +1 -1
- package/dist/canvas/index.d.ts +1 -0
- package/dist/canvas/index.js +152 -44
- package/dist/canvas/index.js.map +1 -1
- package/dist/canvas/parser.d.ts +1 -2
- package/dist/canvas/parser.js +1 -3
- package/dist/{chunk-ICP7LCPJ.js → chunk-6Q4I3RFN.js} +37 -9
- package/dist/chunk-6Q4I3RFN.js.map +1 -0
- package/dist/{chunk-77BNMPBS.js → chunk-CB5NJJJT.js} +31 -5
- package/dist/chunk-CB5NJJJT.js.map +1 -0
- package/dist/expo/plugin.cjs +30 -4
- package/dist/expo/plugin.cjs.map +1 -1
- package/dist/expo/plugin.js +1 -1
- package/dist/expo-babel-plugin.cjs +30 -4
- package/dist/expo-babel-plugin.cjs.map +1 -1
- package/dist/expo-babel-plugin.d.cts +1 -1
- package/dist/expo-babel-plugin.d.ts +1 -1
- package/dist/expo-babel-plugin.js +1 -1
- package/dist/index.js +26 -6
- package/dist/index.js.map +1 -1
- package/dist/nextjs-loader.cjs +29 -4
- package/dist/nextjs-loader.cjs.map +1 -1
- package/package.json +4 -3
- package/dist/annotation-strategy-DCJHc--2.d.cts +0 -13
- package/dist/annotation-strategy-DCJHc--2.d.ts +0 -13
- package/dist/chunk-2LP5G6CD.js +0 -748
- package/dist/chunk-2LP5G6CD.js.map +0 -1
- package/dist/chunk-77BNMPBS.js.map +0 -1
- package/dist/chunk-B3PHU7XX.js +0 -571
- package/dist/chunk-B3PHU7XX.js.map +0 -1
- package/dist/chunk-EJBWZCEE.js +0 -434
- package/dist/chunk-EJBWZCEE.js.map +0 -1
- package/dist/chunk-F64WRL4H.js +0 -884
- package/dist/chunk-F64WRL4H.js.map +0 -1
- package/dist/chunk-G7M57ARC.js +0 -902
- package/dist/chunk-G7M57ARC.js.map +0 -1
- package/dist/chunk-GHPL4LGE.js +0 -205
- package/dist/chunk-GHPL4LGE.js.map +0 -1
- package/dist/chunk-ICP7LCPJ.js.map +0 -1
- package/dist/chunk-IG3JZVZI.js +0 -846
- package/dist/chunk-IG3JZVZI.js.map +0 -1
- package/dist/chunk-MBTLXFNP.js +0 -605
- package/dist/chunk-MBTLXFNP.js.map +0 -1
- package/dist/chunk-MD3HJ7L3.js +0 -457
- package/dist/chunk-MD3HJ7L3.js.map +0 -1
- package/dist/chunk-O3HYJ6BU.js +0 -433
- package/dist/chunk-O3HYJ6BU.js.map +0 -1
- package/dist/chunk-WGGLHHC5.js +0 -337
- package/dist/chunk-WGGLHHC5.js.map +0 -1
- package/dist/chunk-X3K7Z2BH.js +0 -900
- package/dist/chunk-X3K7Z2BH.js.map +0 -1
- package/dist/chunk-ZHORRCQG.js +0 -756
- package/dist/chunk-ZHORRCQG.js.map +0 -1
- package/dist/index.cjs +0 -1170
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -99
- package/dist/page-BokkL6FZ.d.ts +0 -35
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../nextjs-loader.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","../annotation-strategy.ts"],"sourcesContent":["/**\n * Webpack-compatible loader that annotates JSX elements with Tempo's\n * `data-tempo-*` source-location metadata. Runs in both Webpack and Turbopack\n * via the rule registration done by `tempoNextjsPlugin` in `nextjs.ts`.\n *\n * Output parity with the Vite plugin (`./index.ts`) is exact — see SPEC_NEXTJS.md.\n */\n\nimport { realpathSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { sep, relative, resolve } from \"node:path\";\n\nimport {\n annotateFile,\n type ElementInfo,\n type PropValue,\n} from \"@modules/annotation\";\nimport { parseSync, type JSXElement } from \"oxc-parser\";\nimport { getTagName, walk } from \"@modules/file-parser\";\n\nimport { computeTempoAnnotatedProps } from \"./annotation-strategy.ts\";\n\nconst ROOT_META_NAME = \"tempo-project-root\";\n\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface NextjsLoaderOptions {\n /** Project-relative or absolute path to a module that default-exports a\n * ComputeAnnotatedProps function. Resolved against `rootContext` on first\n * invocation. */\n computeAnnotatedPropsModule?: string;\n /** Auto-inject `<meta name=\"tempo-project-root\">` into JSX `<head>`. Default: true. */\n autoInjectRootMeta?: boolean;\n}\n\n/**\n * The loader receives webpack-style `this` context. Both Webpack and Turbopack\n * implement this same shape via `loader-runner`.\n */\ninterface LoaderContext {\n resourcePath: string;\n rootContext: string;\n cacheable?: (flag?: boolean) => void;\n getOptions?: () => NextjsLoaderOptions;\n query?: NextjsLoaderOptions | string;\n}\n\n// ---------------------------------------------------------------------------\n// Module-level singletons. The loader file is required once per\n// loader-runner process; these survive across loader invocations on the same\n// worker.\n// ---------------------------------------------------------------------------\n\nlet cachedCanonicalRoot: string | null = null;\nlet cachedUserComputeProps: ComputeAnnotatedProps | null | undefined;\nlet cachedComputeModulePath: string | null = null;\n\n/** Reset cached singletons. Used by tests; never called in production. */\nexport function _resetLoaderState(): void {\n cachedCanonicalRoot = null;\n cachedUserComputeProps = undefined;\n cachedComputeModulePath = null;\n}\n\n// ---------------------------------------------------------------------------\n// Path utilities.\n// ---------------------------------------------------------------------------\n\nfunction stripQueryAndHash(path: string): string {\n const queryIdx = path.indexOf(\"?\");\n const hashIdx = path.indexOf(\"#\");\n let end = path.length;\n if (queryIdx !== -1) end = Math.min(end, queryIdx);\n if (hashIdx !== -1) end = Math.min(end, hashIdx);\n return path.slice(0, end);\n}\n\nfunction resolveCanonicalRoot(rootContext: string): string {\n try {\n return realpathSync.native(rootContext);\n } catch {\n return rootContext;\n }\n}\n\nfunction isInNodeModules(path: string): boolean {\n return path.includes(`${sep}node_modules${sep}`);\n}\n\n// ---------------------------------------------------------------------------\n// Root-meta injection. Splices a `<meta name=\"tempo-project-root\">` element\n// into the served document so consumers can reconstruct absolute paths from\n// the relative `data-tempo-filepath` values.\n//\n// Placement, in order of preference:\n// 1. As the first child of an existing JSX `<head>`.\n// 2. Wrapped in a fresh `<head>` spliced into the `<html>` element, for\n// layouts that have no `<head>` at all (e.g. App Router root layouts\n// that rely solely on the Metadata API). Next.js merges a manually\n// rendered `<head>` with its own metadata output, so this is safe.\n// 3. Nothing, for files that define neither `<head>` nor `<html>`.\n//\n// `<head />` / `<html />` may be authored self-closing; those are reopened\n// into `<tag>…</tag>` so the markup can live as a real child. Idempotent:\n// re-running on output finds the injected meta and no-ops.\n// ---------------------------------------------------------------------------\n\nfunction findFirstJSXElement(\n program: unknown,\n tagName: string,\n): JSXElement | null {\n let result: JSXElement | null = null;\n walk(program as Parameters<typeof walk>[0], {\n JSXElement(node: unknown) {\n if (result) return;\n const element = node as JSXElement;\n if (getTagName(element.openingElement.name) === tagName) {\n result = element;\n }\n },\n });\n return result;\n}\n\nfunction hasRootMetaChild(headElement: JSXElement): boolean {\n for (const child of headElement.children ?? []) {\n if (child.type !== \"JSXElement\") continue;\n const childTag = getTagName(child.openingElement.name);\n if (childTag !== \"meta\") continue;\n for (const attr of child.openingElement.attributes ?? []) {\n if (attr.type !== \"JSXAttribute\") continue;\n if (getTagName(attr.name) !== \"name\") continue;\n const value = attr.value;\n if (\n value &&\n value.type === \"Literal\" &&\n value.value === ROOT_META_NAME\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Splice `childMarkup` in as the first child of `element`. A normal element\n * takes the markup right after its opening tag's `>`; a self-closing element\n * (`<tag … />`) is first reopened into `<tag …></tag>` so the markup has a\n * place to live.\n */\nfunction injectFirstChildMarkup(\n source: string,\n element: JSXElement,\n childMarkup: string,\n): string {\n const opening = element.openingElement;\n if (!opening.selfClosing) {\n const insertPos = opening.end;\n return source.slice(0, insertPos) + childMarkup + source.slice(insertPos);\n }\n // `<tag … />` → `<tag …>childMarkup</tag>`: drop the trailing slash on the\n // opening tag, then add a matching close tag after the injected markup.\n const tagName = getTagName(opening.name);\n const reopened = source\n .slice(opening.start, opening.end)\n .replace(/\\s*\\/>$/, \">\");\n return (\n source.slice(0, opening.start) +\n `${reopened}${childMarkup}</${tagName}>` +\n source.slice(opening.end)\n );\n}\n\nexport function injectRootMetaIntoSource(\n source: string,\n filename: string,\n root: string,\n): string {\n let parseResult;\n try {\n parseResult = parseSync(filename, source);\n } catch {\n return source;\n }\n\n const metaTag = `<meta name=\"${ROOT_META_NAME}\" content={${JSON.stringify(root)}} />`;\n\n // Preferred: drop the meta directly inside an existing <head>.\n const headElement = findFirstJSXElement(parseResult.program, \"head\");\n if (headElement) {\n if (hasRootMetaChild(headElement)) return source;\n return injectFirstChildMarkup(source, headElement, metaTag);\n }\n\n // Fallback: no <head> — wrap the meta in one and splice it into <html>.\n const htmlElement = findFirstJSXElement(parseResult.program, \"html\");\n if (htmlElement) {\n return injectFirstChildMarkup(\n source,\n htmlElement,\n `<head>${metaTag}</head>`,\n );\n }\n\n // Neither <head> nor <html>: not a document-defining file — leave untouched.\n return source;\n}\n\n/**\n * Inject the project-root meta tag into the ALREADY-ANNOTATED source. The\n * annotated source is still a parseable JSX tree (annotateFile only added\n * attributes, never changed structure), so we can find the first `<head>`\n * the same way and splice in the meta tag right after its opening tag.\n *\n * The injected meta tag itself does NOT carry `data-tempo-*` attributes —\n * it's auto-generated, has no source location, and skipping annotation here\n * avoids the position-shift problem that pre-annotation splicing introduced.\n */\nexport function injectRootMetaIntoAnnotatedSource(\n annotatedSource: string,\n filename: string,\n root: string,\n): string {\n return injectRootMetaIntoSource(annotatedSource, filename, root);\n}\n\n// ---------------------------------------------------------------------------\n// User compute-props module resolution. Cached across calls.\n// ---------------------------------------------------------------------------\n\nfunction loadUserComputeProps(\n modulePath: string,\n canonicalRoot: string,\n): ComputeAnnotatedProps | null {\n // Resolve the user's module path against the project root. The user passes\n // a project-relative path (`./tempo-strategy.js`) or an absolute path; we\n // resolve relative to the canonical project root.\n const resolved = resolve(canonicalRoot, modulePath);\n const requireFromRoot = createRequire(`${canonicalRoot}/__tempo_loader__.js`);\n const mod = requireFromRoot(resolved);\n const fn = mod && (mod.default ?? mod);\n if (typeof fn !== \"function\") {\n return null;\n }\n return fn as ComputeAnnotatedProps;\n}\n\n// ---------------------------------------------------------------------------\n// Loader entry point. Webpack and Turbopack both call this with the source\n// as the first argument and `this` set to a LoaderContext.\n// ---------------------------------------------------------------------------\n\nfunction readOptions(this: LoaderContext): NextjsLoaderOptions {\n if (typeof this.getOptions === \"function\") {\n return this.getOptions() ?? {};\n }\n if (typeof this.query === \"string\") {\n return {};\n }\n return (this.query as NextjsLoaderOptions | undefined) ?? {};\n}\n\nexport function nextjsLoader(this: LoaderContext, source: string): string {\n this.cacheable?.(true);\n\n // Defensive env-var check (primary gate is at wrapper).\n if (!process.env.TEMPO) return source;\n\n const cleanPath = stripQueryAndHash(this.resourcePath ?? \"\");\n if (!/\\.(tsx|jsx)$/.test(cleanPath)) return source;\n if (isInNodeModules(cleanPath)) return source;\n\n const options = readOptions.call(this);\n\n try {\n // Lazy-init the canonical root once. Subsequent calls reuse the same value.\n if (cachedCanonicalRoot === null) {\n cachedCanonicalRoot = resolveCanonicalRoot(this.rootContext);\n }\n const canonicalRoot = cachedCanonicalRoot;\n\n // Lazy-resolve the user's strategy module on the first call that supplies one.\n // Re-resolve if the user's module path changes between rule registrations.\n const userModule = options.computeAnnotatedPropsModule;\n if (userModule && userModule !== cachedComputeModulePath) {\n try {\n cachedUserComputeProps = loadUserComputeProps(userModule, canonicalRoot);\n } catch {\n cachedUserComputeProps = null;\n }\n cachedComputeModulePath = userModule;\n } else if (cachedUserComputeProps === undefined) {\n cachedUserComputeProps = null;\n }\n const userComputeProps = cachedUserComputeProps;\n\n const filepath = relative(canonicalRoot, cleanPath);\n const modifiedtsMs = Math.trunc(statSync(cleanPath).mtimeMs);\n\n // Step 1: annotate every JSX element. The walker visits the ORIGINAL\n // source so every `data-tempo-position` is the byte offset of the JSX\n // `<` in the source file ON DISK. This keeps positions consistent with\n // what consumers (source-editor.ts, frame-preload.ts) read from disk\n // when navigating via filepath + position.\n const annotated = annotateFile(source, cleanPath, (info) =>\n computeTempoAnnotatedProps({\n info,\n filepath,\n modifiedtsMs,\n computeAnnotatedProps: userComputeProps ?? undefined,\n }),\n );\n\n // Step 2: optional auto-inject of root meta into JSX <head>. Run AFTER\n // annotation so injecting the meta does not shift any element's\n // recorded position. The injected meta tag itself does NOT get\n // `data-tempo-*` attributes (it's auto-generated, has no source\n // location, and consumers don't need to navigate to it).\n let finalSource = annotated.annotatedSource;\n if (options.autoInjectRootMeta !== false) {\n finalSource = injectRootMetaIntoAnnotatedSource(\n finalSource,\n cleanPath,\n canonicalRoot,\n );\n }\n\n if (finalSource === source) return source;\n return finalSource;\n } catch {\n return source;\n }\n}\n\nexport default nextjsLoader;\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","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\";\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) => 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): Record<string, PropValue> {\n return {\n \"data-tempo-filepath\": filepath,\n \"data-tempo-position\": info.element.openingElement.start,\n \"data-tempo-modifiedts\": modifiedtsMs,\n };\n}\n\nexport function computeTempoAnnotatedProps(params: {\n info: ElementInfo;\n filepath: string;\n modifiedtsMs: number;\n computeAnnotatedProps?: ComputeAnnotatedProps;\n elementSupportOverrides?: ReadonlyMap<string, ElementTypeSupport>;\n}): Record<string, PropValue> {\n const {\n info,\n filepath,\n modifiedtsMs,\n computeAnnotatedProps,\n elementSupportOverrides,\n } = params;\n\n const userProps = computeAnnotatedProps\n ? computeAnnotatedProps(info, filepath, modifiedtsMs)\n : defaultComputeAnnotatedProps(info, filepath, modifiedtsMs);\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} {\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 };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,IAAAA,kBAAuC;AACvC,yBAA8B;AAC9B,IAAAC,oBAAuC;;;ACVvC,IAAAC,qBAA6D;;;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,SAA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B,QAAW;AAC/C,+BAAyB;AAAA,IAC3B;AACA,UAAM,mBAAmB;AAEzB,UAAM,eAAW,4BAAS,eAAe,SAAS;AAClD,UAAM,eAAe,KAAK,UAAM,0BAAS,SAAS,EAAE,OAAO;AAO3D,UAAM,YAAY;AAAA,MAAa;AAAA,MAAQ;AAAA,MAAW,CAAC,SACjD,2BAA2B;AAAA,QACzB;AAAA,QACA;AAAA,QACA;AAAA,QACA,uBAAuB,oBAAoB;AAAA,MAC7C,CAAC;AAAA,IACH;AAOA,QAAI,cAAc,UAAU;AAC5B,QAAI,QAAQ,uBAAuB,OAAO;AACxC,oBAAc;AAAA,QACZ;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,QAAI,gBAAgB,OAAQ,QAAO;AACnC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,IAAO,wBAAQ;","names":["import_node_fs","import_node_path","import_oxc_parser","import_oxc_parser"]}
|
|
1
|
+
{"version":3,"sources":["../nextjs-loader.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":["/**\n * Webpack-compatible loader that annotates JSX elements with Tempo's\n * `data-tempo-*` source-location metadata. Runs in both Webpack and Turbopack\n * via the rule registration done by `tempoNextjsPlugin` in `nextjs.ts`.\n *\n * Output parity with the Vite plugin (`./index.ts`) is exact — see SPEC_NEXTJS.md.\n */\n\nimport { realpathSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { sep, relative, resolve } from \"node:path\";\n\nimport {\n annotateFile,\n sourceVersionHash,\n type ElementInfo,\n type PropValue,\n} from \"@modules/annotation\";\nimport { parseSync, type JSXElement } from \"oxc-parser\";\nimport { getTagName, walk } from \"@modules/file-parser\";\n\nimport { computeTempoAnnotatedProps } from \"./annotation-strategy.ts\";\n\nconst ROOT_META_NAME = \"tempo-project-root\";\n\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface NextjsLoaderOptions {\n /** Project-relative or absolute path to a module that default-exports a\n * ComputeAnnotatedProps function. Resolved against `rootContext` on first\n * invocation. */\n computeAnnotatedPropsModule?: string;\n /** Auto-inject `<meta name=\"tempo-project-root\">` into JSX `<head>`. Default: true. */\n autoInjectRootMeta?: boolean;\n}\n\n/**\n * The loader receives webpack-style `this` context. Both Webpack and Turbopack\n * implement this same shape via `loader-runner`.\n */\ninterface LoaderContext {\n resourcePath: string;\n rootContext: string;\n cacheable?: (flag?: boolean) => void;\n getOptions?: () => NextjsLoaderOptions;\n query?: NextjsLoaderOptions | string;\n}\n\n// ---------------------------------------------------------------------------\n// Module-level singletons. The loader file is required once per\n// loader-runner process; these survive across loader invocations on the same\n// worker.\n// ---------------------------------------------------------------------------\n\nlet cachedCanonicalRoot: string | null = null;\nlet cachedUserComputeProps: ComputeAnnotatedProps | null | undefined;\nlet cachedComputeModulePath: string | null = null;\n\n/** Reset cached singletons. Used by tests; never called in production. */\nexport function _resetLoaderState(): void {\n cachedCanonicalRoot = null;\n cachedUserComputeProps = undefined;\n cachedComputeModulePath = null;\n}\n\n// ---------------------------------------------------------------------------\n// Path utilities.\n// ---------------------------------------------------------------------------\n\nfunction stripQueryAndHash(path: string): string {\n const queryIdx = path.indexOf(\"?\");\n const hashIdx = path.indexOf(\"#\");\n let end = path.length;\n if (queryIdx !== -1) end = Math.min(end, queryIdx);\n if (hashIdx !== -1) end = Math.min(end, hashIdx);\n return path.slice(0, end);\n}\n\nfunction resolveCanonicalRoot(rootContext: string): string {\n try {\n return realpathSync.native(rootContext);\n } catch {\n return rootContext;\n }\n}\n\nfunction isInNodeModules(path: string): boolean {\n return path.includes(`${sep}node_modules${sep}`);\n}\n\n// ---------------------------------------------------------------------------\n// Root-meta injection. Splices a `<meta name=\"tempo-project-root\">` element\n// into the served document so consumers can reconstruct absolute paths from\n// the relative `data-tempo-filepath` values.\n//\n// Placement, in order of preference:\n// 1. As the first child of an existing JSX `<head>`.\n// 2. Wrapped in a fresh `<head>` spliced into the `<html>` element, for\n// layouts that have no `<head>` at all (e.g. App Router root layouts\n// that rely solely on the Metadata API). Next.js merges a manually\n// rendered `<head>` with its own metadata output, so this is safe.\n// 3. Nothing, for files that define neither `<head>` nor `<html>`.\n//\n// `<head />` / `<html />` may be authored self-closing; those are reopened\n// into `<tag>…</tag>` so the markup can live as a real child. Idempotent:\n// re-running on output finds the injected meta and no-ops.\n// ---------------------------------------------------------------------------\n\nfunction findFirstJSXElement(\n program: unknown,\n tagName: string,\n): JSXElement | null {\n let result: JSXElement | null = null;\n walk(program as Parameters<typeof walk>[0], {\n JSXElement(node: unknown) {\n if (result) return;\n const element = node as JSXElement;\n if (getTagName(element.openingElement.name) === tagName) {\n result = element;\n }\n },\n });\n return result;\n}\n\nfunction hasRootMetaChild(headElement: JSXElement): boolean {\n for (const child of headElement.children ?? []) {\n if (child.type !== \"JSXElement\") continue;\n const childTag = getTagName(child.openingElement.name);\n if (childTag !== \"meta\") continue;\n for (const attr of child.openingElement.attributes ?? []) {\n if (attr.type !== \"JSXAttribute\") continue;\n if (getTagName(attr.name) !== \"name\") continue;\n const value = attr.value;\n if (value && value.type === \"Literal\" && value.value === ROOT_META_NAME) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Splice `childMarkup` in as the first child of `element`. A normal element\n * takes the markup right after its opening tag's `>`; a self-closing element\n * (`<tag … />`) is first reopened into `<tag …></tag>` so the markup has a\n * place to live.\n */\nfunction injectFirstChildMarkup(\n source: string,\n element: JSXElement,\n childMarkup: string,\n): string {\n const opening = element.openingElement;\n if (!opening.selfClosing) {\n const insertPos = opening.end;\n return source.slice(0, insertPos) + childMarkup + source.slice(insertPos);\n }\n // `<tag … />` → `<tag …>childMarkup</tag>`: drop the trailing slash on the\n // opening tag, then add a matching close tag after the injected markup.\n const tagName = getTagName(opening.name);\n const reopened = source\n .slice(opening.start, opening.end)\n .replace(/\\s*\\/>$/, \">\");\n return (\n source.slice(0, opening.start) +\n `${reopened}${childMarkup}</${tagName}>` +\n source.slice(opening.end)\n );\n}\n\nexport function injectRootMetaIntoSource(\n source: string,\n filename: string,\n root: string,\n): string {\n let parseResult;\n try {\n parseResult = parseSync(filename, source);\n } catch {\n return source;\n }\n\n const metaTag = `<meta name=\"${ROOT_META_NAME}\" content={${JSON.stringify(root)}} />`;\n\n // Preferred: drop the meta directly inside an existing <head>.\n const headElement = findFirstJSXElement(parseResult.program, \"head\");\n if (headElement) {\n if (hasRootMetaChild(headElement)) return source;\n return injectFirstChildMarkup(source, headElement, metaTag);\n }\n\n // Fallback: no <head> — wrap the meta in one and splice it into <html>.\n const htmlElement = findFirstJSXElement(parseResult.program, \"html\");\n if (htmlElement) {\n return injectFirstChildMarkup(\n source,\n htmlElement,\n `<head>${metaTag}</head>`,\n );\n }\n\n // Neither <head> nor <html>: not a document-defining file — leave untouched.\n return source;\n}\n\n/**\n * Inject the project-root meta tag into the ALREADY-ANNOTATED source. The\n * annotated source is still a parseable JSX tree (annotateFile only added\n * attributes, never changed structure), so we can find the first `<head>`\n * the same way and splice in the meta tag right after its opening tag.\n *\n * The injected meta tag itself does NOT carry `data-tempo-*` attributes —\n * it's auto-generated, has no source location, and skipping annotation here\n * avoids the position-shift problem that pre-annotation splicing introduced.\n */\nexport function injectRootMetaIntoAnnotatedSource(\n annotatedSource: string,\n filename: string,\n root: string,\n): string {\n return injectRootMetaIntoSource(annotatedSource, filename, root);\n}\n\n// ---------------------------------------------------------------------------\n// User compute-props module resolution. Cached across calls.\n// ---------------------------------------------------------------------------\n\nfunction loadUserComputeProps(\n modulePath: string,\n canonicalRoot: string,\n): ComputeAnnotatedProps | null {\n // Resolve the user's module path against the project root. The user passes\n // a project-relative path (`./tempo-strategy.js`) or an absolute path; we\n // resolve relative to the canonical project root.\n const resolved = resolve(canonicalRoot, modulePath);\n const requireFromRoot = createRequire(`${canonicalRoot}/__tempo_loader__.js`);\n const mod = requireFromRoot(resolved);\n const fn = mod && (mod.default ?? mod);\n if (typeof fn !== \"function\") {\n return null;\n }\n return fn as ComputeAnnotatedProps;\n}\n\n// ---------------------------------------------------------------------------\n// Loader entry point. Webpack and Turbopack both call this with the source\n// as the first argument and `this` set to a LoaderContext.\n// ---------------------------------------------------------------------------\n\nfunction readOptions(this: LoaderContext): NextjsLoaderOptions {\n if (typeof this.getOptions === \"function\") {\n return this.getOptions() ?? {};\n }\n if (typeof this.query === \"string\") {\n return {};\n }\n return (this.query as NextjsLoaderOptions | undefined) ?? {};\n}\n\nexport function nextjsLoader(this: LoaderContext, source: string): string {\n this.cacheable?.(true);\n\n // Defensive env-var check (primary gate is at wrapper).\n if (!process.env.TEMPO) return source;\n\n const cleanPath = stripQueryAndHash(this.resourcePath ?? \"\");\n if (!/\\.(tsx|jsx)$/.test(cleanPath)) return source;\n if (isInNodeModules(cleanPath)) return source;\n\n const options = readOptions.call(this);\n\n try {\n // Lazy-init the canonical root once. Subsequent calls reuse the same value.\n if (cachedCanonicalRoot === null) {\n cachedCanonicalRoot = resolveCanonicalRoot(this.rootContext);\n }\n const canonicalRoot = cachedCanonicalRoot;\n\n // Lazy-resolve the user's strategy module on the first call that supplies one.\n // Re-resolve if the user's module path changes between rule registrations.\n const userModule = options.computeAnnotatedPropsModule;\n if (userModule && userModule !== cachedComputeModulePath) {\n try {\n cachedUserComputeProps = loadUserComputeProps(\n userModule,\n canonicalRoot,\n );\n } catch {\n cachedUserComputeProps = null;\n }\n cachedComputeModulePath = userModule;\n } else if (cachedUserComputeProps === undefined) {\n cachedUserComputeProps = null;\n }\n const userComputeProps = cachedUserComputeProps;\n\n const filepath = relative(canonicalRoot, cleanPath);\n const modifiedtsMs = Math.trunc(statSync(cleanPath).mtimeMs);\n // Hash the exact source string being transformed once per file; every\n // element in this file carries the same version token.\n const sourceVersion = sourceVersionHash(source);\n\n // Step 1: annotate every JSX element. The walker visits the ORIGINAL\n // source so every `data-tempo-position` is the byte offset of the JSX\n // `<` in the source file ON DISK. This keeps positions consistent with\n // what consumers (source-editor.ts, frame-preload.ts) read from disk\n // when navigating via filepath + position.\n const annotated = annotateFile(source, cleanPath, (info) =>\n computeTempoAnnotatedProps({\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps: userComputeProps ?? undefined,\n }),\n );\n\n // Step 2: optional auto-inject of root meta into JSX <head>. Run AFTER\n // annotation so injecting the meta does not shift any element's\n // recorded position. The injected meta tag itself does NOT get\n // `data-tempo-*` attributes (it's auto-generated, has no source\n // location, and consumers don't need to navigate to it).\n let finalSource = annotated.annotatedSource;\n if (options.autoInjectRootMeta !== false) {\n finalSource = injectRootMetaIntoAnnotatedSource(\n finalSource,\n cleanPath,\n canonicalRoot,\n );\n }\n\n if (finalSource === source) return source;\n return finalSource;\n } catch {\n return source;\n }\n}\n\nexport default nextjsLoader;\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,IAAAA,kBAAuC;AACvC,yBAA8B;AAC9B,IAAAC,oBAAuC;;;ACVvC,IAAAC,qBAA6D;;;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;AA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AO;AACnC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,IAAO,wBAAQ;","names":["import_node_fs","import_node_path","import_oxc_parser","import_oxc_parser"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tempo-sdk",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.18",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Tempo SDK — Vite, Next.js, and Expo plugins for JSX annotation and shared page/storyboard types",
|
|
6
6
|
"exports": {
|
|
@@ -82,8 +82,9 @@
|
|
|
82
82
|
"@modules/file-parser": "0.0.1"
|
|
83
83
|
},
|
|
84
84
|
"scripts": {
|
|
85
|
-
"
|
|
86
|
-
"build
|
|
85
|
+
"clean": "rm -rf dist",
|
|
86
|
+
"build": "pnpm run clean && tsup",
|
|
87
|
+
"build:if-missing": "test -f dist/index.js || pnpm run build",
|
|
87
88
|
"demo": "TEMPO=true pnpm --filter @tempo-modules/vite-annotate-plugin-demo dev",
|
|
88
89
|
"demo:nextjs": "TEMPO=true pnpm --filter @tempo-modules/tempo-sdk-nextjs-demo dev",
|
|
89
90
|
"test": "vitest run",
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { JSXElement } from 'oxc-parser';
|
|
2
|
-
|
|
3
|
-
interface ElementInfo {
|
|
4
|
-
element: JSXElement;
|
|
5
|
-
/** e.g. "div", "Button", "Foo.Bar" */
|
|
6
|
-
tagName: string;
|
|
7
|
-
}
|
|
8
|
-
/** Supported prop value types. `undefined` values are skipped. */
|
|
9
|
-
type PropValue = string | number | boolean | null | undefined | ((...args: unknown[]) => unknown) | object;
|
|
10
|
-
|
|
11
|
-
type ComputeAnnotatedProps = (info: ElementInfo, filepath: string, modifiedtsMs: number) => Record<string, PropValue>;
|
|
12
|
-
|
|
13
|
-
export type { ComputeAnnotatedProps as C, ElementInfo as E, PropValue as P };
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { JSXElement } from 'oxc-parser';
|
|
2
|
-
|
|
3
|
-
interface ElementInfo {
|
|
4
|
-
element: JSXElement;
|
|
5
|
-
/** e.g. "div", "Button", "Foo.Bar" */
|
|
6
|
-
tagName: string;
|
|
7
|
-
}
|
|
8
|
-
/** Supported prop value types. `undefined` values are skipped. */
|
|
9
|
-
type PropValue = string | number | boolean | null | undefined | ((...args: unknown[]) => unknown) | object;
|
|
10
|
-
|
|
11
|
-
type ComputeAnnotatedProps = (info: ElementInfo, filepath: string, modifiedtsMs: number) => Record<string, PropValue>;
|
|
12
|
-
|
|
13
|
-
export type { ComputeAnnotatedProps as C, ElementInfo as E, PropValue as P };
|