ai-code-map 0.0.0-stage → 0.1.0-alpha.3
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/AGENTS.md +26 -0
- package/CHANGELOG.md +54 -0
- package/CONTRIBUTING.md +43 -0
- package/LICENSE +21 -0
- package/README.md +369 -2
- package/SECURITY.md +18 -0
- package/config.schema.json +130 -0
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +7690 -0
- package/dist/cli.js.map +1 -0
- package/dist/compiler-worker.d.ts +2 -0
- package/dist/compiler-worker.js +4395 -0
- package/dist/compiler-worker.js.map +1 -0
- package/dist/index.d.ts +1339 -0
- package/dist/index.js +7426 -0
- package/dist/index.js.map +1 -0
- package/docs/api.md +152 -0
- package/docs/architecture/ADR-0001-hybrid-syntax-and-semantics.md +140 -0
- package/docs/artifacts.md +156 -0
- package/docs/backlog.md +43 -0
- package/docs/limitations.md +82 -0
- package/docs/post-alpha-roadmap.md +341 -0
- package/docs/schema.md +133 -0
- package/examples/cli-workflow.sh +9 -0
- package/examples/programmatic-scan.ts +33 -0
- package/package.json +79 -3
- package/schemas/code-map.schema.json +1078 -0
- package/schemas/diagnostics.schema.json +60 -0
- package/schemas/file.schema.json +247 -0
- package/schemas/manifest.schema.json +307 -0
- package/schemas/project.schema.json +192 -0
- package/schemas/relation.schema.json +142 -0
- package/schemas/symbol.schema.json +165 -0
- package/skills/ai-code-map/SKILL.md +39 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/compiler-worker.ts","../src/analyze.ts","../src/constants.ts","../src/utils/path.ts","../src/errors.ts","../src/ids.ts","../src/schemas.ts","../src/utils/stable.ts","../src/utils/hash.ts","../src/analyzers/core.ts","../src/analyzers/helpers.ts","../src/analyzers/nestjs.ts","../src/analyzers/nextjs.ts","../src/analyzers/react.ts","../src/compiler-units.ts","../src/semantic.ts"],"sourcesContent":["import { Session } from \"node:inspector/promises\";\nimport { parentPort, workerData } from \"node:worker_threads\";\n\nimport { analyzeDefaultCompilerUnit } from \"./analyze.js\";\nimport type { CompilerWorkerInput } from \"./analyze.js\";\n\nif (!parentPort) throw new Error(\"Compiler worker requires a parent port.\");\nconst result = await analyzeDefaultCompilerUnit(workerData as CompilerWorkerInput);\n// Reclaim the unreachable compiler before cloning its normalized result into the parent heap.\n// This session is local to the worker; it does not open an inspector port.\nconst session = new Session();\nsession.connect();\ntry {\n await session.post(\"HeapProfiler.collectGarbage\");\n} finally {\n session.disconnect();\n}\nparentPort.postMessage(result);\nparentPort.close();\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nimport ts from \"typescript\";\n\nimport { ANALYZER_VERSION, SCHEMA_VERSION } from \"./constants.js\";\nimport { fileId, generatedCompilerUnitId } from \"./ids.js\";\nimport type {\n AnalysisContext,\n AnalysisContribution,\n CodeMap,\n CompilerUnitRecord,\n DiagnosticRecord,\n FileRecord,\n Framework,\n FrameworkAnalyzer,\n JsonValue,\n ProjectRecord,\n RelationRecord,\n SemanticResolver,\n SemanticInputObservation,\n SemanticInputRecord,\n SymbolRecord,\n SyntaxFact,\n SyntaxParserAdapter,\n SyntaxParseResult,\n} from \"./types.js\";\nimport {\n DiagnosticRecordSchema,\n FrameworkSchema,\n RelationRecordSchema,\n SymbolRecordSchema,\n} from \"./schemas.js\";\nimport { hashText } from \"./utils/hash.js\";\nimport {\n hasEmbeddedAbsolutePath,\n isAbsolutePath,\n looksLikeHostFilePath,\n normalizeStoredPath,\n redactAbsolutePathsInText,\n} from \"./utils/path.js\";\nimport { compareText, mapLimit } from \"./utils/stable.js\";\nimport { CoreAnalyzer, extractFileStructure } from \"./analyzers/core.js\";\nimport { trustedNestJsAnalyzerMethods } from \"./analyzers/nestjs.js\";\nimport { trustedNextJsAnalyzerMethods } from \"./analyzers/nextjs.js\";\nimport { ReactAnalyzer } from \"./analyzers/react.js\";\nimport type { ResolvedConfiguration } from \"./config.js\";\nimport { customProducerRecord, defaultProducerRecord, prepareSemanticInputs } from \"./freshness.js\";\nimport {\n FallbackParserAdapter,\n isBuiltInTypeScriptParserAdapter,\n TypeScriptParserAdapter,\n} from \"./parser.js\";\nimport {\n compilerDiagnostic,\n createBoundedModuleResolver,\n TypeScriptSemanticResolver,\n} from \"./semantic.js\";\nimport type { CompilerUnitPlan } from \"./compiler-units.js\";\nimport { runCompilerUnitWorker } from \"./compiler-worker-client.js\";\n\ninterface PreparedSource {\n absolutePath: string;\n relativePath: string;\n content: string;\n hash: string;\n file: FileRecord;\n syntax?: AnalysisContext[\"syntax\"];\n}\n\nexport interface AnalyzeProjectOptions {\n resolved: ResolvedConfiguration;\n analyzers?: FrameworkAnalyzer[];\n parser?: SyntaxParserAdapter;\n semanticResolver?: SemanticResolver;\n}\n\nexport async function analyzeProject(options: AnalyzeProjectOptions): Promise<CodeMap> {\n const { resolved } = options;\n const semanticInputs = await prepareSemanticInputs(resolved.root, resolved.config);\n const {\n packageMetadata,\n frameworks: selectedFrameworks,\n discovered,\n compilerGraph,\n configHash,\n } = semanticInputs;\n const parser =\n options.parser && !isBuiltInTypeScriptParserAdapter(options.parser)\n ? new FallbackParserAdapter(options.parser, new TypeScriptParserAdapter())\n : undefined;\n const prepared = await mapLimit(\n discovered,\n resolved.config.concurrency ?? 16,\n async (source): Promise<PreparedSource> => {\n const bytes = await fs.readFile(source.absolutePath);\n const content = bytes.toString(\"utf8\");\n const hash = hashText(bytes);\n const syntax = parser\n ? await parser.parse({\n path: source.relativePath,\n language: source.language,\n source: content,\n })\n : undefined;\n return {\n ...source,\n content,\n hash,\n ...(syntax ? { syntax } : {}),\n file: {\n schemaVersion: SCHEMA_VERSION,\n id: fileId(source.relativePath),\n path: source.relativePath,\n compilerUnit:\n compilerGraph.ownership.get(source.relativePath) ?? generatedCompilerUnitId(\"fallback\"),\n language: source.language,\n frameworks: [],\n hash,\n lines: lineCount(content),\n imports: [],\n exports: [],\n symbolIds: [],\n env: [],\n operations: [],\n syntax: {\n parser: sanitizePersistedText(\n syntax?.parser ?? \"typescript-compiler-syntax\",\n resolved.root,\n ),\n factCount: syntax?.facts.length ?? 0,\n hadErrors: syntax?.hadErrors ?? false,\n ...(syntax?.fallbackFrom\n ? { fallbackFrom: sanitizePersistedText(syntax.fallbackFrom, resolved.root) }\n : {}),\n },\n },\n };\n },\n );\n\n const semanticResolver = options.semanticResolver ?? new TypeScriptSemanticResolver();\n const diagnostics: DiagnosticRecord[] = [...compilerGraph.diagnostics];\n for (const source of prepared) {\n const syntax = source.syntax;\n if (!syntax?.fallbackFrom) continue;\n diagnostics.push({\n schemaVersion: SCHEMA_VERSION,\n code: \"parser-fallback\",\n severity: \"warning\",\n message:\n syntax.issues[0]?.message ??\n `Parser ${syntax.fallbackFrom} was unavailable; used ${syntax.parser}.`,\n file: source.relativePath,\n });\n }\n const symbols: SymbolRecord[] = [];\n const relations: RelationRecord[] = [];\n const internalPipeline = defaultAnalyzerPipeline();\n const internalAnalyzers = internalPipeline.analyzers;\n const analyzers = uniqueAnalyzers([...internalAnalyzers, ...(options.analyzers ?? [])]);\n const trustedInternalAnalyzers = internalPipeline.methods;\n const preparedByAbsolute = new Map(\n prepared.map((source) => [source.absolutePath, source] as const),\n );\n const indexedSourcePaths = new Set(prepared.map((source) => source.relativePath));\n const unitAliases = new Map<string, Record<string, string[]>>();\n const observedSemanticInputs: SemanticInputObservation[] = [];\n\n const builtInProducer =\n !options.semanticResolver &&\n !options.analyzers &&\n (!options.parser || isBuiltInTypeScriptParserAdapter(options.parser));\n\n // A completed worker releases its compiler heap before the next unit or serialization.\n for (const unit of compilerGraph.units) {\n if (unit.ownedFiles.length === 0) continue;\n const unitInput: CompilerWorkerInput = {\n unit,\n root: resolved.root,\n packageDependencies: packageMetadata.dependencies,\n includePrivateSymbols: resolved.config.includePrivateSymbols,\n selectedFrameworks,\n preparedByAbsolute: new Map(\n unit.ownedFiles.flatMap((absolute) => {\n const source = preparedByAbsolute.get(absolute);\n return source ? [[absolute, source] as const] : [];\n }),\n ),\n indexedSourcePaths,\n };\n let contribution: CompilerUnitContribution;\n if (builtInProducer) {\n const result = await runCompilerUnitWorker(unitInput);\n contribution = result.contribution;\n for (const file of result.files) {\n const source = preparedByAbsolute.get(path.resolve(resolved.root, file.path));\n if (source) source.file = file;\n }\n } else {\n contribution = await analyzeCompilerUnit({\n ...unitInput,\n analyzers,\n trustedInternalAnalyzers,\n semanticResolver,\n });\n }\n unitAliases.set(unit.record.id, contribution.pathAliases);\n diagnostics.push(...contribution.diagnostics);\n symbols.push(...contribution.symbols);\n relations.push(...contribution.relations);\n observedSemanticInputs.push(...contribution.semanticInputs);\n }\n\n const merged = mergeSpecializedSymbols(symbols, relations);\n addFileRelations(prepared, merged.symbols, merged.relations);\n const normalizedRelations = normalizeRelations(\n merged.relations,\n prepared.map((source) => source.file),\n merged.symbols,\n merged.replacements,\n resolved.root,\n );\n for (const source of prepared) {\n source.file.symbolIds = merged.symbols\n .filter((symbol) => symbol.file === source.relativePath)\n .map((symbol) => symbol.id)\n .sort(compareText);\n }\n\n const compilerUnits = compilerGraph.units.map((unit) => ({\n ...unit.record,\n pathAliases: unitAliases.get(unit.record.id) ?? unit.record.pathAliases,\n }));\n const pathAliases = compatibilityPathAliases(compilerUnits, compilerGraph.primaryConfig);\n const persistedSymbols = merged.symbols.map((symbol) =>\n sanitizePersistedSymbol(symbol, resolved.root),\n );\n const normalizedDiagnostics = normalizeDiagnostics(diagnostics, resolved.root);\n const manifestSemanticInputs = normalizeSemanticInputs(\n observedSemanticInputs,\n new Set(prepared.map((source) => source.relativePath)),\n );\n const producerComponents = {\n semanticResolver: {\n name: sanitizePersistedText(semanticResolver.name, resolved.root),\n version: sanitizePersistedText(semanticResolver.version ?? \"unversioned\", resolved.root),\n },\n syntaxParser:\n options.parser && !isBuiltInTypeScriptParserAdapter(options.parser)\n ? {\n name: sanitizePersistedText(options.parser.name, resolved.root),\n version: sanitizePersistedText(options.parser.version ?? \"unversioned\", resolved.root),\n }\n : { name: \"typescript-compiler-syntax\", version: ts.version },\n analyzers: analyzers\n .map((analyzer) => ({\n name: sanitizePersistedText(analyzer.name, resolved.root),\n version: sanitizePersistedText(analyzer.version ?? \"unversioned\", resolved.root),\n }))\n .sort((a, b) => compareText(a.name, b.name)),\n };\n const project: ProjectRecord = {\n schemaVersion: SCHEMA_VERSION,\n name: sanitizePersistedText(packageMetadata.name, resolved.root),\n ...(packageMetadata.packageManager\n ? { packageManager: sanitizePersistedText(packageMetadata.packageManager, resolved.root) }\n : {}),\n frameworks: selectedFrameworks,\n ...(compilerGraph.primaryConfig ? { tsconfig: compilerGraph.primaryConfig } : {}),\n pathAliases,\n compilerUnits,\n entryPoints: packageMetadata.entryPoints,\n workspaces: packageMetadata.workspaces.map((workspace) => ({\n ...workspace,\n name: sanitizePersistedText(workspace.name, resolved.root),\n })),\n counts: {\n files: prepared.length,\n symbols: persistedSymbols.length,\n relations: normalizedRelations.length,\n diagnostics: normalizedDiagnostics.length,\n },\n };\n return {\n manifest: {\n schemaVersion: SCHEMA_VERSION,\n analyzerVersion: ANALYZER_VERSION,\n producer: builtInProducer\n ? defaultProducerRecord()\n : customProducerRecord(producerComponents),\n semanticResolver: producerComponents.semanticResolver,\n syntaxParser: producerComponents.syntaxParser,\n analyzers: producerComponents.analyzers,\n configHash,\n sourceFiles: prepared\n .map((source) => ({\n path: source.relativePath,\n hash: source.hash,\n compilerUnit: source.file.compilerUnit,\n lines: source.file.lines,\n }))\n .sort((a, b) => compareText(a.path, b.path)),\n semanticInputs: manifestSemanticInputs,\n artifacts: [],\n integrityHash: \"0\".repeat(64),\n },\n project,\n files: prepared.map((source) => source.file).sort((a, b) => compareText(a.path, b.path)),\n symbols: persistedSymbols,\n relations: normalizedRelations,\n diagnostics: normalizedDiagnostics,\n };\n}\n\ninterface AnalyzeCompilerUnitOptions {\n unit: CompilerUnitPlan;\n root: string;\n packageDependencies: AnalysisContext[\"packageDependencies\"];\n includePrivateSymbols: boolean;\n selectedFrameworks: Framework[];\n preparedByAbsolute: Map<string, PreparedSource>;\n indexedSourcePaths: Set<string>;\n analyzers: FrameworkAnalyzer[];\n trustedInternalAnalyzers: ReadonlyMap<FrameworkAnalyzer, TrustedAnalyzerMethods>;\n semanticResolver: SemanticResolver;\n}\n\ninterface CompilerUnitContribution {\n pathAliases: Record<string, string[]>;\n diagnostics: DiagnosticRecord[];\n symbols: SymbolRecord[];\n relations: RelationRecord[];\n semanticInputs: SemanticInputObservation[];\n}\n\nexport type CompilerWorkerInput = Omit<\n AnalyzeCompilerUnitOptions,\n \"analyzers\" | \"trustedInternalAnalyzers\" | \"semanticResolver\"\n>;\n\nexport interface CompilerWorkerResult {\n contribution: CompilerUnitContribution;\n files: FileRecord[];\n}\n\nexport async function analyzeDefaultCompilerUnit(\n input: CompilerWorkerInput,\n): Promise<CompilerWorkerResult> {\n const pipeline = defaultAnalyzerPipeline();\n const contribution = await analyzeCompilerUnit({\n ...input,\n analyzers: pipeline.analyzers,\n trustedInternalAnalyzers: pipeline.methods,\n // We expose type facts and syntactic diagnostics, not TS JSDoc link diagnostics or prose.\n // This mode still parses all JavaScript JSDoc, which can define types.\n semanticResolver: new TypeScriptSemanticResolver(ts.JSDocParsingMode.ParseForTypeInfo),\n });\n return {\n contribution,\n files: [...input.preparedByAbsolute.values()].map((source) => source.file),\n };\n}\n\nasync function analyzeCompilerUnit(\n options: AnalyzeCompilerUnitOptions,\n): Promise<CompilerUnitContribution> {\n const { unit } = options;\n const semantic = await options.semanticResolver.resolve({\n root: options.root,\n sourceFiles: unit.sourceFiles,\n ...(unit.record.config ? { tsconfig: unit.record.config } : {}),\n compilerUnit: unit.record.id,\n });\n const { program, checker } = semantic;\n const resolveModule =\n semantic.resolveModule ??\n createBoundedModuleResolver(\n options.root,\n path.resolve(options.root, unit.record.root),\n program.getCompilerOptions(),\n );\n const diagnostics: DiagnosticRecord[] = [...semantic.diagnostics];\n const symbols: SymbolRecord[] = [];\n const relations: RelationRecord[] = [];\n\n for (const absolutePath of unit.ownedFiles) {\n const source = options.preparedByAbsolute.get(absolutePath);\n if (!source) continue;\n const sourceFile = program.getSourceFile(source.absolutePath);\n if (!sourceFile) {\n diagnostics.push({\n schemaVersion: SCHEMA_VERSION,\n code: \"analysis-error\",\n severity: \"error\",\n message:\n \"TypeScript did not include this selected source file in the owning compiler unit.\",\n file: source.relativePath,\n });\n continue;\n }\n const sourceDiagnostics = parseDiagnostics(program, sourceFile, options.root);\n diagnostics.push(...sourceDiagnostics);\n const syntax = source.syntax ?? syntaxFromProgram(sourceFile, sourceDiagnostics);\n source.file.syntax = {\n parser: sanitizePersistedText(syntax.parser, options.root),\n factCount: syntax.facts.length,\n hadErrors: syntax.hadErrors,\n ...(syntax.fallbackFrom\n ? { fallbackFrom: sanitizePersistedText(syntax.fallbackFrom, options.root) }\n : {}),\n };\n const context: AnalysisContext = {\n root: options.root,\n relativePath: source.relativePath,\n sourceFile,\n program,\n checker,\n sourceHash: source.hash,\n file: source.file,\n packageDependencies: options.packageDependencies,\n syntax,\n includePrivateSymbols: options.includePrivateSymbols,\n compilerUnit: unit.record,\n indexedSourcePaths: options.indexedSourcePaths,\n resolveModule,\n };\n\n const structure = extractFileStructure(context);\n source.file.imports = structure.imports;\n source.file.exports = structure.exports;\n source.file.env = structure.env;\n source.file.operations = structure.operations;\n diagnostics.push(...structure.diagnostics);\n relations.push(...structure.relations);\n\n for (const analyzer of options.analyzers) {\n const trustedSupport = trustedAnalyzerMethods(analyzer, options.trustedInternalAnalyzers);\n let supported = false;\n try {\n supported = trustedSupport\n ? trustedSupport.supports(context)\n : analyzer.supports(isolateCustomAnalyzerContext(context));\n } catch {\n diagnostics.push({\n schemaVersion: SCHEMA_VERSION,\n code: \"analysis-error\",\n severity: \"warning\",\n message: `Analyzer ${analyzer.name} failed during capability detection; its contribution was skipped.`,\n file: source.relativePath,\n });\n continue;\n }\n if (!supported || !analyzerEnabled(analyzer, options.selectedFrameworks)) continue;\n try {\n // Re-resolve trust immediately before invocation. A supplied analyzer is never allowed to\n // retain a cached trusted decision and then swap behavior between supports() and analyze().\n const trustedAnalysis = trustedAnalyzerMethods(analyzer, options.trustedInternalAnalyzers);\n const rawContribution = trustedAnalysis\n ? await trustedAnalysis.analyze(context)\n : await analyzer.analyze(isolateCustomAnalyzerContext(context));\n const contribution = trustedAnalysis\n ? rawContribution\n : sanitizeCustomContribution(\n rawContribution,\n options.root,\n analyzer.name,\n source,\n symbols,\n );\n symbols.push(...(contribution.symbols ?? []));\n relations.push(...(contribution.relations ?? []));\n diagnostics.push(...(contribution.diagnostics ?? []));\n source.file.frameworks.push(...(contribution.frameworks ?? []));\n } catch {\n diagnostics.push({\n schemaVersion: SCHEMA_VERSION,\n code: \"analysis-error\",\n severity: \"warning\",\n message: `Analyzer ${analyzer.name} failed; its contribution was skipped.`,\n file: source.relativePath,\n });\n }\n }\n source.file.frameworks = [...new Set(source.file.frameworks)].sort();\n }\n\n return {\n pathAliases: semantic.pathAliases,\n diagnostics,\n symbols,\n relations,\n semanticInputs: semantic.semanticInputs?.() ?? [],\n };\n}\n\nfunction isolateCustomAnalyzerContext(context: AnalysisContext): AnalysisContext {\n return {\n ...context,\n file: structuredClone(context.file),\n syntax: structuredClone(context.syntax),\n compilerUnit: structuredClone(context.compilerUnit),\n packageDependencies: new Set(context.packageDependencies),\n ...(context.indexedSourcePaths\n ? { indexedSourcePaths: new Set(context.indexedSourcePaths) }\n : {}),\n };\n}\n\nfunction sanitizeCustomContribution(\n contribution: AnalysisContribution,\n root: string,\n analyzerName: string,\n source: PreparedSource,\n knownSymbols: SymbolRecord[],\n): AnalysisContribution {\n const sourceFileId = fileId(source.relativePath);\n const localSymbolIds = new Set<string>(\n knownSymbols.filter((symbol) => symbol.file === source.relativePath).map((symbol) => symbol.id),\n );\n const localSymbols = new Map<string, SymbolRecord>(\n knownSymbols\n .filter((symbol) => symbol.file === source.relativePath)\n .map((symbol) => [symbol.id, symbol]),\n );\n\n const symbolIds = new Map<string, string>();\n const warnings: DiagnosticRecord[] = [];\n const pushWarning = (message: string) => {\n warnings.push({\n schemaVersion: SCHEMA_VERSION,\n code: \"analysis-error\",\n severity: \"warning\",\n message: sanitizePersistedText(message, root),\n file: source.relativePath,\n });\n };\n\n const rangeFitsSource = (range: SymbolRecord[\"range\"]): boolean =>\n range.startLine >= 1 &&\n range.endLine >= range.startLine &&\n range.endLine <= source.file.lines &&\n (range.endLine !== range.startLine || range.endColumn >= range.startColumn);\n const sanitizeEndpoint = (value: string): string =>\n symbolIds.get(value) ?? sanitizeCustomIdentifier(value, root);\n\n const symbols: SymbolRecord[] = [];\n for (const raw of contribution.symbols ?? []) {\n const sanitized = {\n ...raw,\n id: sanitizeCustomIdentifier(raw.id, root),\n name: sanitizePersistedText(raw.name, root),\n ...(raw.signature ? { signature: sanitizePersistedText(raw.signature, root) } : {}),\n ...(raw.documentation\n ? { documentation: sanitizePersistedText(raw.documentation, root) }\n : {}),\n facts: Object.fromEntries(\n Object.entries(raw.facts).map(([key, value]) => [\n sanitizePersistedText(key, root),\n sanitizeJsonValue(value, root),\n ]),\n ),\n };\n const parsed = SymbolRecordSchema.safeParse(sanitized);\n if (!parsed.success) {\n pushWarning(`Analyzer ${analyzerName} emitted an invalid custom symbol.`);\n continue;\n }\n if (parsed.data.file !== source.relativePath) {\n pushWarning(\n `Analyzer ${analyzerName} emitted a custom symbol for non-local file ${parsed.data.file}.`,\n );\n continue;\n }\n if (parsed.data.sourceHash !== source.hash) {\n pushWarning(\n `Analyzer ${analyzerName} emitted a custom symbol with a source hash mismatch for ${parsed.data.id}.`,\n );\n continue;\n }\n if (!rangeFitsSource(parsed.data.range)) {\n pushWarning(\n `Analyzer ${analyzerName} emitted a custom symbol with out-of-bounds source range for ${parsed.data.id}.`,\n );\n continue;\n }\n symbols.push(parsed.data);\n symbolIds.set(raw.id, parsed.data.id);\n localSymbolIds.add(parsed.data.id);\n localSymbols.set(parsed.data.id, parsed.data);\n }\n\n const relations: RelationRecord[] = [];\n for (const raw of contribution.relations ?? []) {\n const relation = {\n ...raw,\n from: sanitizeEndpoint(raw.from),\n to: sanitizeEndpoint(raw.to),\n origin: {\n ...raw.origin,\n explanation: sanitizePersistedText(raw.origin.explanation, root),\n analyzer: sanitizePersistedText(raw.origin.analyzer, root),\n },\n };\n const parsed = RelationRecordSchema.safeParse(relation);\n if (!parsed.success) {\n pushWarning(\n `Analyzer ${analyzerName} emitted an invalid custom relation from ${relation.from} to ${relation.to}.`,\n );\n continue;\n }\n if (\n parsed.data.origin.file !== source.relativePath ||\n parsed.data.origin.line !== parsed.data.origin.range.startLine ||\n parsed.data.origin.range.startLine < 1 ||\n parsed.data.origin.range.endLine > source.file.lines\n ) {\n pushWarning(\n `Analyzer ${analyzerName} emitted a custom relation with invalid evidence bounds for ${parsed.data.from} -> ${parsed.data.to}.`,\n );\n continue;\n }\n if (parsed.data.type === \"imports\") {\n pushWarning(\n `Analyzer ${analyzerName} emitted a custom imports relation; imports are core-owned and were skipped.`,\n );\n continue;\n } else if (parsed.data.type === \"contains\" || parsed.data.type === \"exports\") {\n const targetSymbol = localSymbols.get(parsed.data.to);\n if (!targetSymbol || !rangesEqual(parsed.data.origin.range, targetSymbol.range)) {\n pushWarning(\n `Analyzer ${analyzerName} emitted an invalid custom structural relation ${parsed.data.type} ${parsed.data.from} -> ${parsed.data.to}.`,\n );\n continue;\n }\n if (parsed.data.type === \"exports\") {\n if (parsed.data.from !== sourceFileId || !targetSymbol.exported) {\n pushWarning(\n `Analyzer ${analyzerName} emitted an invalid custom export relation ${parsed.data.from} -> ${parsed.data.to}.`,\n );\n continue;\n }\n } else if (parsed.data.from !== sourceFileId) {\n const parentSymbol = localSymbols.get(parsed.data.from);\n if (!parentSymbol || !rangeContains(parentSymbol.range, parsed.data.origin.range)) {\n pushWarning(\n `Analyzer ${analyzerName} emitted an invalid custom containment relation ${parsed.data.from} -> ${parsed.data.to}.`,\n );\n continue;\n }\n } else if (!localSymbolIds.has(parsed.data.to)) {\n pushWarning(\n `Analyzer ${analyzerName} emitted an invalid custom containment relation from file to non-local symbol ${parsed.data.to}.`,\n );\n continue;\n }\n }\n relations.push(parsed.data);\n }\n\n const diagnostics: DiagnosticRecord[] = [];\n for (const raw of contribution.diagnostics ?? []) {\n const diagnostic = {\n ...raw,\n message: sanitizePersistedText(raw.message, root),\n };\n const parsed = DiagnosticRecordSchema.safeParse(diagnostic);\n if (!parsed.success) {\n pushWarning(`Analyzer ${analyzerName} emitted an invalid custom diagnostic.`);\n continue;\n }\n if (parsed.data.file && parsed.data.file !== source.relativePath) {\n pushWarning(\n `Analyzer ${analyzerName} emitted a custom diagnostic for non-local file ${parsed.data.file}.`,\n );\n continue;\n }\n if (parsed.data.file && parsed.data.line && parsed.data.line > source.file.lines) {\n pushWarning(\n `Analyzer ${analyzerName} emitted a custom diagnostic with out-of-bounds line ${parsed.data.line}.`,\n );\n continue;\n }\n diagnostics.push(parsed.data);\n }\n\n const frameworks: Framework[] = [];\n for (const rawFramework of contribution.frameworks ?? []) {\n const parsed = FrameworkSchema.safeParse(rawFramework);\n if (!parsed.success) {\n pushWarning(`Analyzer ${analyzerName} emitted an invalid custom framework ${rawFramework}.`);\n continue;\n }\n frameworks.push(parsed.data);\n }\n return {\n ...(symbols.length ? { symbols } : {}),\n ...(relations.length ? { relations } : {}),\n ...(diagnostics.length || warnings.length\n ? {\n diagnostics: [...diagnostics, ...warnings],\n }\n : {}),\n ...(frameworks.length ? { frameworks } : {}),\n };\n}\n\nfunction sanitizeCustomIdentifier(value: string, root: string): string {\n if (value.startsWith(\"route:\")) {\n const route = value.slice(\"route:\".length);\n return looksLikeHostFilePath(route, root) ? \"route:<redacted>\" : value;\n }\n if (value.startsWith(\"external:\")) {\n const separator = value.lastIndexOf(\"#\");\n const moduleName = value.slice(\"external:\".length, separator > 0 ? separator : undefined);\n const exported = separator > 0 ? value.slice(separator + 1) : \"default\";\n const safeModule =\n isAbsolutePath(moduleName) || hasEmbeddedAbsolutePath(moduleName)\n ? \"<absolute-import>\"\n : sanitizePersistedText(moduleName, root);\n return `external:${safeModule}#${sanitizePersistedText(exported, root)}`;\n }\n const prefixEnd = value.indexOf(\":\");\n const nameStart = value.lastIndexOf(\"#\");\n if (prefixEnd >= 0) {\n const pathEnd = nameStart > prefixEnd ? nameStart : value.length;\n const candidatePath = value.slice(prefixEnd + 1, pathEnd);\n if (isAbsolutePath(candidatePath) || hasEmbeddedAbsolutePath(candidatePath)) {\n const safePath = sanitizePersistedText(candidatePath, root);\n const suffix = nameStart > prefixEnd ? value.slice(nameStart) : \"\";\n return `${value.slice(0, prefixEnd + 1)}${safePath}${sanitizePersistedText(suffix, root)}`;\n }\n }\n return sanitizePersistedText(value, root);\n}\n\nfunction rangesEqual(left: SymbolRecord[\"range\"], right: SymbolRecord[\"range\"]): boolean {\n return (\n left.startLine === right.startLine &&\n left.startColumn === right.startColumn &&\n left.endLine === right.endLine &&\n left.endColumn === right.endColumn\n );\n}\n\nfunction rangeContains(outer: SymbolRecord[\"range\"], inner: SymbolRecord[\"range\"]): boolean {\n if (\n outer.startLine > inner.startLine ||\n (outer.startLine === inner.startLine && outer.startColumn > inner.startColumn)\n )\n return false;\n if (\n outer.endLine < inner.endLine ||\n (outer.endLine === inner.endLine && outer.endColumn < inner.endColumn)\n )\n return false;\n return true;\n}\n\nfunction sanitizeJsonValue(value: JsonValue, root: string): JsonValue {\n if (typeof value === \"string\") return sanitizePersistedText(value, root);\n if (Array.isArray(value)) return value.map((item) => sanitizeJsonValue(item, root));\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [\n sanitizePersistedText(key, root),\n sanitizeJsonValue(item, root),\n ]),\n );\n }\n return value;\n}\n\nexport function defaultAnalyzers(): FrameworkAnalyzer[] {\n return [new CoreAnalyzer(), new ReactAnalyzer()];\n}\n\nconst canonicalCoreAnalyzerMethods: TrustedAnalyzerMethods = {\n supports: CoreAnalyzer.prototype.supports.bind(CoreAnalyzer.prototype),\n analyze: CoreAnalyzer.prototype.analyze.bind(CoreAnalyzer.prototype),\n};\nconst canonicalReactAnalyzerMethods: TrustedAnalyzerMethods = {\n supports: ReactAnalyzer.prototype.supports.bind(ReactAnalyzer.prototype),\n analyze: ReactAnalyzer.prototype.analyze.bind(ReactAnalyzer.prototype),\n};\n\nfunction defaultAnalyzerPipeline(): {\n analyzers: FrameworkAnalyzer[];\n methods: ReadonlyMap<FrameworkAnalyzer, TrustedAnalyzerMethods>;\n} {\n const core = new CoreAnalyzer();\n const react = new ReactAnalyzer();\n return {\n analyzers: [core, react],\n methods: new Map<FrameworkAnalyzer, TrustedAnalyzerMethods>([\n [core, canonicalCoreAnalyzerMethods],\n [react, canonicalReactAnalyzerMethods],\n ]),\n };\n}\n\nfunction uniqueAnalyzers(analyzers: FrameworkAnalyzer[]): FrameworkAnalyzer[] {\n const byName = new Map<string, FrameworkAnalyzer>();\n for (const analyzer of analyzers) byName.set(analyzer.name, analyzer);\n return [...byName.values()];\n}\n\nfunction analyzerEnabled(analyzer: FrameworkAnalyzer, frameworks: Framework[]): boolean {\n if (analyzer instanceof CoreAnalyzer) return true;\n const name = analyzer.name.toLowerCase();\n if (name.includes(\"react\")) return frameworks.includes(\"react\") || frameworks.includes(\"nextjs\");\n if (name.includes(\"next\")) return frameworks.includes(\"nextjs\");\n if (name.includes(\"nest\")) return frameworks.includes(\"nestjs\");\n return true;\n}\n\ninterface TrustedAnalyzerMethods {\n supports(context: AnalysisContext): boolean;\n analyze(context: AnalysisContext): AnalysisContribution | Promise<AnalysisContribution>;\n}\n\nfunction trustedAnalyzerMethods(\n analyzer: FrameworkAnalyzer,\n internal: ReadonlyMap<FrameworkAnalyzer, TrustedAnalyzerMethods>,\n): TrustedAnalyzerMethods | undefined {\n const internalMethods = internal.get(analyzer);\n if (internalMethods) return internalMethods;\n return trustedNextJsAnalyzerMethods(analyzer) ?? trustedNestJsAnalyzerMethods(analyzer);\n}\n\nfunction parseDiagnostics(\n program: ts.Program,\n sourceFile: ts.SourceFile,\n root: string,\n): DiagnosticRecord[] {\n return program\n .getSyntacticDiagnostics(sourceFile)\n .map((diagnostic) => compilerDiagnostic(diagnostic, root));\n}\n\nfunction syntaxFromProgram(\n sourceFile: ts.SourceFile,\n diagnostics: DiagnosticRecord[],\n): SyntaxParseResult {\n const parser = \"typescript-compiler-syntax\";\n const facts: SyntaxFact[] = [];\n for (const statement of sourceFile.statements) {\n const kind = ts.isImportDeclaration(statement)\n ? \"import\"\n : ts.isExportDeclaration(statement) || ts.isExportAssignment(statement)\n ? \"export\"\n : isTopLevelDeclaration(statement)\n ? \"declaration\"\n : undefined;\n if (!kind) continue;\n const name = syntaxStatementName(statement);\n facts.push({\n kind,\n nodeType: ts.SyntaxKind[statement.kind],\n ...(name ? { name } : {}),\n range: sourceRange(sourceFile, statement),\n evidence: { parser, exact: true },\n });\n }\n for (const diagnostic of diagnostics) {\n facts.push({\n kind: \"parse-error\",\n nodeType: \"typescript-diagnostic\",\n range: {\n startLine: diagnostic.line ?? 1,\n startColumn: diagnostic.column ?? 1,\n endLine: diagnostic.line ?? 1,\n endColumn: diagnostic.column ?? 1,\n },\n evidence: { parser, exact: true },\n });\n }\n return {\n parser,\n facts,\n issues: diagnostics.map((diagnostic) => ({ message: diagnostic.message })),\n hadErrors: diagnostics.length > 0,\n };\n}\n\nfunction isTopLevelDeclaration(statement: ts.Statement): boolean {\n return (\n ts.isFunctionDeclaration(statement) ||\n ts.isClassDeclaration(statement) ||\n ts.isInterfaceDeclaration(statement) ||\n ts.isTypeAliasDeclaration(statement) ||\n ts.isVariableStatement(statement)\n );\n}\n\nfunction syntaxStatementName(statement: ts.Statement): string | undefined {\n if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {\n return statement.moduleSpecifier.text;\n }\n if (ts.isExportAssignment(statement)) return \"default\";\n if (ts.isExportDeclaration(statement)) {\n return statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)\n ? statement.moduleSpecifier.text\n : \"export\";\n }\n if (ts.isVariableStatement(statement)) {\n return statement.declarationList.declarations\n .map((declaration) => (ts.isIdentifier(declaration.name) ? declaration.name.text : undefined))\n .filter((name): name is string => name !== undefined)\n .join(\",\");\n }\n const name = (statement as unknown as ts.NamedDeclaration).name;\n return name && ts.isIdentifier(name) ? name.text : undefined;\n}\n\nfunction sourceRange(sourceFile: ts.SourceFile, node: ts.Node): SymbolRecord[\"range\"] {\n const start = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile, false));\n const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n return {\n startLine: start.line + 1,\n startColumn: start.character + 1,\n endLine: end.line + 1,\n endColumn: end.character + 1,\n };\n}\n\ninterface MergedSymbols {\n symbols: SymbolRecord[];\n relations: RelationRecord[];\n replacements: Map<string, string>;\n}\n\nfunction mergeSpecializedSymbols(\n values: SymbolRecord[],\n relations: RelationRecord[],\n): MergedSymbols {\n const byLocation = new Map<string, SymbolRecord>();\n const replacements = new Map<string, string>();\n for (const value of values) {\n const key = `${value.file}:${value.range.startLine}:${value.range.startColumn}:${value.name}`;\n const existing = byLocation.get(key);\n if (!existing) {\n byLocation.set(key, value);\n continue;\n }\n const winner =\n specializationPriority(value.kind) >= specializationPriority(existing.kind)\n ? mergeSymbolFacts(value, existing)\n : mergeSymbolFacts(existing, value);\n const loser = winner.id === value.id ? existing : value;\n replacements.set(loser.id, winner.id);\n byLocation.set(key, winner);\n }\n return {\n symbols: [...byLocation.values()].sort((a, b) => compareText(a.id, b.id)),\n relations,\n replacements,\n };\n}\n\nfunction specializationPriority(kind: SymbolRecord[\"kind\"]): number {\n if (kind.startsWith(\"nest-\") || kind.startsWith(\"next-\") || kind === \"route\" || kind === \"dto\")\n return 3;\n if (kind.startsWith(\"react-\")) return 2;\n return 1;\n}\n\nfunction mergeSymbolFacts(primary: SymbolRecord, secondary: SymbolRecord): SymbolRecord {\n return {\n ...primary,\n exported: primary.exported || secondary.exported,\n ...(primary.defaultExport || secondary.defaultExport ? { defaultExport: true } : {}),\n ...((primary.signature ?? secondary.signature)\n ? { signature: primary.signature ?? secondary.signature }\n : {}),\n ...((primary.documentation ?? secondary.documentation)\n ? { documentation: primary.documentation ?? secondary.documentation }\n : {}),\n facts: { ...secondary.facts, ...primary.facts },\n };\n}\n\nfunction addFileRelations(\n prepared: PreparedSource[],\n symbols: SymbolRecord[],\n relations: RelationRecord[],\n): void {\n for (const symbol of symbols) {\n const source = prepared.find((candidate) => candidate.relativePath === symbol.file);\n if (!source) continue;\n relations.push({\n schemaVersion: SCHEMA_VERSION,\n from: fileId(symbol.file),\n type: \"contains\",\n to: symbol.id,\n confidence: 1,\n origin: {\n file: symbol.file,\n line: symbol.range.startLine,\n range: symbol.range,\n explanation: \"source containment\",\n classification: \"exact\",\n analyzer: \"typescript-node\",\n },\n });\n if (symbol.exported) {\n relations.push({\n schemaVersion: SCHEMA_VERSION,\n from: fileId(symbol.file),\n type: \"exports\",\n to: symbol.id,\n confidence: 1,\n origin: {\n file: symbol.file,\n line: symbol.range.startLine,\n range: symbol.range,\n explanation: \"export modifier\",\n classification: \"exact\",\n analyzer: \"typescript-node\",\n },\n });\n }\n }\n}\n\nfunction normalizeRelations(\n values: RelationRecord[],\n files: FileRecord[],\n symbols: SymbolRecord[],\n replacements: Map<string, string>,\n root: string,\n): RelationRecord[] {\n const knownFiles = new Set(files.map((file) => file.id));\n const byId = new Map(symbols.map((symbol) => [symbol.id, symbol]));\n const byFileAndName = new Map<string, SymbolRecord>();\n for (const symbol of symbols) byFileAndName.set(`${symbol.file}#${symbol.name}`, symbol);\n const resolveEndpoint = (id: string): string | undefined => {\n let resolved = id;\n const visited = new Set<string>();\n while (replacements.has(resolved) && !visited.has(resolved)) {\n visited.add(resolved);\n const replacement = replacements.get(resolved);\n if (!replacement) break;\n resolved = replacement;\n }\n if (\n knownFiles.has(resolved) ||\n byId.has(resolved) ||\n resolved.startsWith(\"external:\") ||\n resolved.startsWith(\"route:\")\n )\n return resolved;\n const parsed = /^(?:[^:]+):(.+)#([^#.]+)$/.exec(resolved);\n if (parsed) return byFileAndName.get(`${parsed[1]}#${parsed[2]}`)?.id;\n return undefined;\n };\n\n const all: RelationRecord[] = [];\n for (const value of values) {\n const from = resolveEndpoint(value.from);\n const to = resolveEndpoint(value.to);\n if (!from || !to || from === to) continue;\n all.push({\n ...value,\n from,\n to,\n confidence: clampConfidence(value.confidence),\n origin: {\n ...value.origin,\n explanation: sanitizePersistedText(value.origin.explanation, root),\n analyzer: sanitizePersistedText(value.origin.analyzer, root),\n },\n });\n }\n for (const value of [...all]) {\n if (!inverseEligible(value.type)) continue;\n all.push({\n ...value,\n from: value.to,\n type: \"used-by\",\n to: value.from,\n origin: {\n ...value.origin,\n explanation: `inverse of ${value.type}`,\n classification: \"derived\",\n analyzer: \"relation-normalizer\",\n },\n });\n }\n const map = new Map<string, RelationRecord>();\n for (const value of all) {\n const key = `${value.from}\\u0000${value.type}\\u0000${value.to}\\u0000${value.origin.file}\\u0000${value.origin.range.startLine}\\u0000${value.origin.range.startColumn}\\u0000${value.origin.range.endLine}\\u0000${value.origin.range.endColumn}`;\n const existing = map.get(key);\n if (!existing || relationWouldReplace(existing, value)) map.set(key, value);\n }\n return [...map.values()].sort((a, b) => compareText(relationKey(a), relationKey(b)));\n}\n\nfunction relationWouldReplace(existing: RelationRecord, candidate: RelationRecord): boolean {\n if (candidate.confidence > existing.confidence) return true;\n if (candidate.confidence < existing.confidence) return false;\n const candidateRank = relationDeterministicRank(candidate);\n const existingRank = relationDeterministicRank(existing);\n if (candidateRank !== existingRank) return candidateRank > existingRank;\n return compareText(relationKey(candidate), relationKey(existing)) < 0;\n}\n\nfunction relationDeterministicRank(relation: RelationRecord): number {\n switch (relation.origin.classification) {\n case \"exact\":\n return 2;\n case \"derived\":\n return 1;\n case \"framework-derived\":\n default:\n return 0;\n }\n}\n\nfunction inverseEligible(type: RelationRecord[\"type\"]): boolean {\n return [\"calls\", \"instantiates\", \"renders\", \"uses-hook\", \"depends-on\", \"injects\"].includes(type);\n}\n\nfunction clampConfidence(value: number): number {\n return Math.max(0, Math.min(1, Number.isFinite(value) ? value : 0));\n}\n\nfunction relationKey(value: RelationRecord): string {\n return [\n value.from,\n value.type,\n value.to,\n value.origin.file,\n String(value.origin.range.startLine).padStart(10, \"0\"),\n String(value.origin.range.startColumn).padStart(10, \"0\"),\n String(value.origin.range.endLine).padStart(10, \"0\"),\n String(value.origin.range.endColumn).padStart(10, \"0\"),\n value.origin.classification,\n value.origin.analyzer,\n value.origin.explanation,\n ].join(\"\\u0000\");\n}\n\nfunction normalizeDiagnostics(values: DiagnosticRecord[], root: string): DiagnosticRecord[] {\n const map = new Map<string, DiagnosticRecord>();\n for (const value of values) {\n const sanitized = { ...value, message: sanitizePersistedText(value.message, root) };\n const key = `${sanitized.file ?? \"\"}:${sanitized.line ?? 0}:${sanitized.column ?? 0}:${sanitized.code}:${sanitized.message}`;\n map.set(key, sanitized);\n }\n return [...map.values()].sort((a, b) => compareText(diagnosticKey(a), diagnosticKey(b)));\n}\n\nfunction sanitizePersistedSymbol(symbol: SymbolRecord, root: string): SymbolRecord {\n return {\n ...symbol,\n ...(symbol.signature ? { signature: sanitizePersistedText(symbol.signature, root) } : {}),\n ...(symbol.documentation\n ? { documentation: sanitizePersistedText(symbol.documentation, root) }\n : {}),\n };\n}\n\nfunction sanitizePersistedText(value: string, root: string): string {\n return redactAbsolutePathsInText(value, root) || \"<redacted>\";\n}\n\nfunction diagnosticKey(value: DiagnosticRecord): string {\n return `${value.file ?? \"\"}\\u0000${String(value.line ?? 0).padStart(10, \"0\")}\\u0000${value.code}\\u0000${value.message}`;\n}\n\nfunction lineCount(content: string): number {\n if (content.length === 0) return 0;\n return content.split(/\\r\\n|\\r|\\n/).length;\n}\n\nfunction normalizeSemanticInputs(\n values: SemanticInputObservation[],\n indexedSources: ReadonlySet<string>,\n): SemanticInputRecord[] {\n const byIdentity = new Map<string, SemanticInputRecord>();\n for (const value of values) {\n const normalized = normalizeStoredPath(value.path);\n if (!isSafeSemanticInputPath(normalized)) continue;\n if (value.kind === \"file\" && indexedSources.has(normalized)) continue;\n if (value.kind === \"symlink\") {\n const target = normalizeStoredPath(value.target);\n if (!isSafeSemanticInputPath(target)) continue;\n const record: SemanticInputRecord = {\n ...value,\n path: normalized,\n scope: value.scope ?? \"project\",\n target,\n };\n byIdentity.set(semanticInputIdentity(record), record);\n continue;\n }\n const record: SemanticInputRecord =\n value.kind === \"resolution-probe\" || value.kind === \"directory-listing\"\n ? { ...value, path: normalized, scope: value.scope ?? \"project\" }\n : { ...value, path: normalized };\n byIdentity.set(semanticInputIdentity(record), record);\n }\n for (const value of byIdentity.values()) {\n if (value.kind === \"file\") {\n byIdentity.delete(`resolution-probe\\u0000project\\u0000file\\u0000${value.path}`);\n byIdentity.delete(`resolution-probe\\u0000project\\u0000readable-file\\u0000${value.path}`);\n } else if (value.kind === \"toolchain-file\") {\n byIdentity.delete(`resolution-probe\\u0000toolchain\\u0000file\\u0000${value.path}`);\n byIdentity.delete(`resolution-probe\\u0000toolchain\\u0000readable-file\\u0000${value.path}`);\n } else if (value.kind === \"directory-listing\") {\n byIdentity.delete(`resolution-probe\\u0000${value.scope}\\u0000directory\\u0000${value.path}`);\n }\n }\n return [...byIdentity.values()].sort((a, b) =>\n compareText(semanticInputIdentity(a), semanticInputIdentity(b)),\n );\n}\n\nfunction semanticInputIdentity(value: SemanticInputRecord): string {\n return value.kind === \"resolution-probe\"\n ? `${value.kind}\\u0000${value.scope}\\u0000${value.targetKind}\\u0000${value.path}`\n : value.kind === \"directory-listing\" || value.kind === \"symlink\"\n ? `${value.kind}\\u0000${value.scope}\\u0000${value.path}`\n : `${value.kind}\\u0000${value.path}`;\n}\n\nfunction isSafeSemanticInputPath(value: string): boolean {\n return !isAbsolutePath(value) && value !== \"..\" && !value.startsWith(\"../\");\n}\n\nfunction compatibilityPathAliases(\n units: CompilerUnitRecord[],\n primaryConfig: string | undefined,\n): Record<string, string[]> {\n const primary = primaryConfig\n ? units.find((unit) => unit.config === primaryConfig)\n : units.find((unit) => unit.kind === \"configured\");\n return primary?.pathAliases ?? {};\n}\n","export const SCHEMA_VERSION = 4 as const;\nexport const CONFIG_VERSION = 1 as const;\nexport const ANALYZER_VERSION = \"0.4.0\";\nexport const DEFAULT_SYNTAX_PARSER = \"typescript-compiler-syntax\";\nexport const DEFAULT_SEMANTIC_RESOLVER = \"typescript-program\";\nexport const DEFAULT_ANALYZER_NAMES = [\"typescript-node\", \"react\"] as const;\nexport const DEFAULT_PRODUCER_ID = \"ai-code-map/default-pipeline\";\nexport const CUSTOM_PRODUCER_ID = \"ai-code-map/custom-pipeline\";\nexport const PRODUCER_CONTRACT_VERSION = 1 as const;\n\nexport const DEFAULT_OUTPUT = \".ai/code-map\";\nexport const DEFAULT_INCLUDE = [\n \"src/**/*\",\n \"app/**/*\",\n \"pages/**/*\",\n \"lib/**/*\",\n \"server/**/*\",\n \"*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}\",\n] as const;\nexport const DEFAULT_EXCLUDE = [\n \"**/node_modules/**\",\n \"**/.next/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/coverage/**\",\n \"**/.git/**\",\n \"**/.ai/**\",\n \"**/*.generated.*\",\n] as const;\n\nexport const MANAGED_ARTIFACTS = [\n \"overview.md\",\n \"manifest.json\",\n \"project.json\",\n \"files.jsonl\",\n \"symbols.jsonl\",\n \"relations.jsonl\",\n \"diagnostics.json\",\n] as const;\n\nexport const MAP_COMPANION_ARTIFACTS = [\n \"overview.md\",\n \"project.json\",\n \"files.jsonl\",\n \"symbols.jsonl\",\n \"relations.jsonl\",\n \"diagnostics.json\",\n] as const;\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { CodeMapError } from \"../errors.js\";\n\nexport function isAbsolutePath(value: string): boolean {\n const normalized = toPosixPath(value);\n return (\n path.posix.isAbsolute(normalized) ||\n /^[a-zA-Z]:[\\\\/]/.test(normalized) ||\n normalized.startsWith(\"//\")\n );\n}\n\nexport function isFileSystemUri(value: string): boolean {\n return /^file:(?:\\/\\/|\\/)/i.test(value.trim());\n}\n\nfunction hasEmbeddedDoubleSlashPath(value: string): boolean {\n const normalized = toPosixPath(value);\n let index = normalized.indexOf(\"//\");\n while (index >= 0) {\n const previous = index > 0 ? normalized[index - 1] : undefined;\n if (previous !== \":\") return true;\n index = normalized.indexOf(\"//\", index + 1);\n }\n return false;\n}\n\nexport function hasEmbeddedAbsolutePath(value: string): boolean {\n const normalized = toPosixPath(value);\n return (\n isAbsolutePath(normalized) ||\n isFileSystemUri(normalized) ||\n hasEmbeddedDoubleSlashPath(normalized) ||\n /(?:^|\\/)[A-Za-z]:(?:\\/|$)/.test(normalized) ||\n /(?:^|\\/)file:(?:\\/|$)/i.test(normalized)\n );\n}\n\nexport function isSafeRelativePathPattern(value: string): boolean {\n const normalized = toPosixPath(value);\n return (\n normalized.length > 0 &&\n !hasEmbeddedAbsolutePath(normalized) &&\n !normalized.split(\"/\").includes(\"..\")\n );\n}\n\n/** Distinguish recognizable host paths from ordinary web-route syntax. */\nexport function looksLikeHostFilePath(value: string, root?: string): boolean {\n const trimmed = value.trim();\n if (\n /file:(?:\\/\\/|\\/)/i.test(trimmed) ||\n /(?:^|[/])[A-Za-z]:[\\\\/]/.test(trimmed) ||\n /^\\\\\\\\/.test(trimmed) ||\n hasEmbeddedDoubleSlashPath(trimmed)\n ) {\n return true;\n }\n const normalized = toPosixPath(trimmed);\n if (root) {\n const normalizedRoot = toPosixPath(path.resolve(root));\n if (\n normalized === normalizedRoot ||\n normalized.startsWith(`${normalizedRoot}/`) ||\n normalized.includes(normalizedRoot)\n )\n return true;\n }\n return /^\\/(?:Users|home|root|private|tmp|var|etc|usr|opt|Volumes|mnt|proc|dev)(?:\\/|$)/.test(\n normalized,\n );\n}\n\nexport function toPosixPath(value: string): string {\n return value.replaceAll(\"\\\\\", \"/\");\n}\n\nexport function relativePosix(root: string, absolutePath: string): string {\n if (!isAbsolutePath(absolutePath)) {\n throw new CodeMapError(\n \"PATH_OUTSIDE_ROOT\",\n `Path ${absolutePath} is outside project root ${root}.`,\n );\n }\n const relative = path.relative(root, absolutePath);\n if (relative === \"\" || isRelativeInside(relative)) {\n return toPosixPath(relative || \".\");\n }\n throw new CodeMapError(\n \"PATH_OUTSIDE_ROOT\",\n `Path ${absolutePath} is outside project root ${root}.`,\n );\n}\n\nexport function isPathInside(root: string, candidate: string): boolean {\n if (isAbsolutePath(candidate) && !path.isAbsolute(candidate)) return false;\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === \"\" || isRelativeInside(relative);\n}\n\nexport async function isSafeRegularFile(root: string, candidate: string): Promise<boolean> {\n const absolute = path.resolve(candidate);\n if (!isPathInside(root, absolute)) return false;\n try {\n const stat = await fs.lstat(absolute);\n if (stat.isSymbolicLink() || !stat.isFile()) return false;\n const [realRoot, realFile] = await Promise.all([fs.realpath(root), fs.realpath(absolute)]);\n return isPathInside(realRoot, realFile);\n } catch {\n return false;\n }\n}\n\nexport async function readFileInsideRoot(root: string, candidate: string): Promise<Buffer> {\n const absolute = path.resolve(candidate);\n if (!(await isSafeRegularFile(root, absolute))) {\n throw new CodeMapError(\n \"PATH_OUTSIDE_ROOT\",\n `Refusing to read an unavailable, symbolic, or out-of-root file at ${absolute}.`,\n );\n }\n return fs.readFile(absolute);\n}\n\nfunction isRelativeInside(relative: string): boolean {\n const normalized = toPosixPath(relative);\n if (normalized === \"\" || normalized === \".\") return true;\n if (isAbsolutePath(normalized)) return false;\n return normalized !== \"..\" && !normalized.startsWith(\"../\") && !normalized.startsWith(\"..\\\\\");\n}\n\nexport function redactAbsolutePathsInText(message: string, root: string): string {\n const normalizedRoot = path.resolve(root);\n const redact = (candidate: string): string => {\n const trimmed = candidate.replace(/[)\\].,;:]+$/, \"\");\n if (!isAbsolutePath(trimmed) && !isFileSystemUri(trimmed)) return candidate;\n if (isFileSystemUri(trimmed)) return \"<outside-root>\";\n const foreignWindowsPath = path.win32.isAbsolute(trimmed) && !path.posix.isAbsolute(trimmed);\n if (foreignWindowsPath && path.posix.isAbsolute(normalizedRoot)) return \"<outside-root>\";\n try {\n if (isPathInside(normalizedRoot, trimmed)) {\n return relativePosix(normalizedRoot, trimmed);\n }\n } catch {\n // Fall back to opaque marker.\n }\n return \"<outside-root>\";\n };\n\n // Handle quoted paths and known roots first so spaces cannot split a machine path into\n // separately persisted fragments.\n let redacted = message.replace(\n /([\"'`])([^\"'`\\r\\n]+)\\1/g,\n (quoted: string, quote: string, contents: string) =>\n isAbsolutePath(contents) || isFileSystemUri(contents)\n ? `${quote}${redact(contents)}${quote}`\n : quoted,\n );\n for (const rootVariant of [normalizedRoot, toPosixPath(normalizedRoot)].sort(\n (a, b) => b.length - a.length,\n )) {\n if (rootVariant) redacted = redacted.replaceAll(rootVariant, \".\");\n }\n\n const chunks = redacted.split(\n /(\\s+(?:is|was|at|from|to|outside|inside|cannot|could|failed|for|and|or)\\s+)/gi,\n );\n return chunks\n .map((chunk) =>\n chunk.replace(\n /(?<![A-Za-z0-9_.-])[A-Za-z]:[\\\\/](?:[^\\\\/\\r\\n'\"`)\\],;:]+[\\\\/])*[^\\\\/\\s'\"`)\\],;:]+|(?<![A-Za-z0-9_.\\\\-])\\\\\\\\(?:[^\\\\\\r\\n'\"`)\\],;:]+\\\\)+[^\\\\\\s'\"`)\\],;:]+|(?<![A-Za-z0-9_.:/-])\\/\\/(?:[^/\\r\\n'\"`)\\],;:]+\\/)*[^/\\s'\"`)\\],;:]+|(?<![A-Za-z0-9_.:/-])\\/(?:[^/\\r\\n'\"`)\\],;:]+\\/)*[^/\\s'\"`)\\],;:]+/g,\n redact,\n ),\n )\n .join(\"\");\n}\n\nexport function normalizeStoredPath(value: string): string {\n const normalized = path.posix.normalize(toPosixPath(value));\n return normalized.startsWith(\"./\") ? normalized.slice(2) : normalized;\n}\n\n/** Keep user-authored module text useful without persisting host-specific absolute paths. */\nexport function sanitizeModuleSpecifier(value: string): string {\n return isAbsolutePath(value) || isFileSystemUri(value) || hasEmbeddedAbsolutePath(value)\n ? \"<absolute-import>\"\n : value;\n}\n","export class CodeMapError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"CodeMapError\";\n this.code = code;\n }\n}\n\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import type { SymbolKind } from \"./types.js\";\nimport { normalizeStoredPath, sanitizeModuleSpecifier } from \"./utils/path.js\";\n\nexport function fileId(filePath: string): string {\n return `file:${normalizeStoredPath(filePath)}`;\n}\n\nexport function symbolId(\n kind: SymbolKind,\n filePath: string,\n name: string,\n parent?: string,\n): string {\n const prefix = symbolPrefix(kind);\n const qualifiedName = parent ? `${parent}.${name}` : name;\n return `${prefix}:${normalizeStoredPath(filePath)}#${qualifiedName}`;\n}\n\nexport function externalId(moduleName: string, name = \"default\"): string {\n return `external:${sanitizeModuleSpecifier(moduleName)}#${name}`;\n}\n\nexport function configuredCompilerUnitId(configPath: string): string {\n return `compiler-unit:configured:${normalizeStoredPath(configPath)}`;\n}\n\nexport function generatedCompilerUnitId(name: string): string {\n return `compiler-unit:generated:${normalizeStoredPath(name)}`;\n}\n\nexport function routeId(method: string, route: string): string {\n return `route:${method.toUpperCase()}:${route || \"/\"}`;\n}\n\nfunction symbolPrefix(kind: SymbolKind): string {\n switch (kind) {\n case \"react-component\":\n return \"component\";\n case \"react-hook\":\n return \"hook\";\n case \"next-page\":\n case \"next-layout\":\n case \"next-route-handler\":\n case \"next-special-file\":\n return \"next\";\n case \"nest-module\":\n case \"nest-controller\":\n case \"nest-provider\":\n case \"nest-guard\":\n case \"nest-interceptor\":\n case \"nest-pipe\":\n case \"nest-filter\":\n case \"nest-gateway\":\n return \"nest\";\n case \"type-alias\":\n return \"type\";\n default:\n return kind;\n }\n}\n","import path from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport {\n CONFIG_VERSION,\n DEFAULT_EXCLUDE,\n DEFAULT_INCLUDE,\n DEFAULT_OUTPUT,\n MAP_COMPANION_ARTIFACTS,\n SCHEMA_VERSION,\n} from \"./constants.js\";\nimport {\n hasEmbeddedAbsolutePath,\n isAbsolutePath,\n normalizeStoredPath,\n toPosixPath,\n} from \"./utils/path.js\";\nimport { compareText, stableJson } from \"./utils/stable.js\";\n\nexport const JsonValueSchema = z.json();\nexport type JsonValue = z.infer<typeof JsonValueSchema>;\nexport type JsonPrimitive = Extract<JsonValue, string | number | boolean | null>;\n\nexport const LanguageSchema = z.enum([\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"cts\", \"mjs\", \"cjs\"]);\nexport type Language = z.infer<typeof LanguageSchema>;\n\nexport const FrameworkSchema = z.enum([\"typescript\", \"node\", \"react\", \"nextjs\", \"nestjs\"]);\nexport type Framework = z.infer<typeof FrameworkSchema>;\n\nexport const FrameworkSelectionSchema = z.union([FrameworkSchema, z.literal(\"auto\")]);\nexport type FrameworkSelection = z.infer<typeof FrameworkSelectionSchema>;\n\nexport const ConfigSchema = z\n .object({\n version: z.literal(CONFIG_VERSION).default(CONFIG_VERSION),\n root: z.string().min(1).default(\"../..\"),\n include: z\n .array(z.string().min(1))\n .min(1)\n .default([...DEFAULT_INCLUDE]),\n exclude: z.array(z.string().min(1)).default([...DEFAULT_EXCLUDE]),\n tsconfig: z.string().min(1).optional(),\n frameworks: z.array(FrameworkSelectionSchema).min(1).default([\"auto\"]),\n output: z.string().min(1).default(DEFAULT_OUTPUT),\n includePrivateSymbols: z.boolean().default(false),\n concurrency: z.number().int().min(1).max(64).optional(),\n })\n .strict()\n .superRefine((config, context) => {\n if (new Set(config.frameworks).size !== config.frameworks.length) {\n context.addIssue({\n code: \"custom\",\n path: [\"frameworks\"],\n message: \"framework selections must be unique\",\n });\n }\n if (config.frameworks.includes(\"auto\") && config.frameworks.length > 1) {\n context.addIssue({\n code: \"custom\",\n path: [\"frameworks\"],\n message: \"auto cannot be combined with explicit framework selections\",\n });\n }\n });\nexport type CodeMapConfig = z.infer<typeof ConfigSchema>;\n\nexport const SourceRangeSchema = z\n .object({\n startLine: z.number().int().positive(),\n startColumn: z.number().int().positive(),\n endLine: z.number().int().positive(),\n endColumn: z.number().int().positive(),\n })\n .strict()\n .superRefine((range, context) => {\n if (\n range.endLine < range.startLine ||\n (range.endLine === range.startLine && range.endColumn < range.startColumn)\n ) {\n context.addIssue({ code: \"custom\", message: \"range end must not precede its start\" });\n }\n });\nexport type SourceRange = z.infer<typeof SourceRangeSchema>;\n\nexport const StoredPathSchema = z\n .string()\n .min(1)\n .refine(\n (value) =>\n !value.includes(\"\\\\\") &&\n !value.startsWith(\"/\") &&\n !hasEmbeddedAbsolutePath(value) &&\n !value.split(\"/\").includes(\"..\"),\n \"must be a repository-relative POSIX path\",\n )\n .refine((value) => value === normalizeStoredPath(value), \"must be normalized\");\n\nconst StoredFilePathSchema = StoredPathSchema.refine(\n (value) => value !== \".\",\n \"must identify a file or non-root project path\",\n);\n\nconst StoredModuleAliasSchema = z\n .string()\n .min(1)\n .refine(\n (value) => !isAbsolutePath(value) && !toPosixPath(value).split(\"/\").includes(\"..\"),\n \"must not contain an absolute or parent-traversing path\",\n );\n\nexport const ImportSpecifierRecordSchema = z\n .object({\n imported: z.string(),\n local: z.string(),\n typeOnly: z.boolean().optional(),\n })\n .strict();\nexport type ImportSpecifierRecord = z.infer<typeof ImportSpecifierRecordSchema>;\n\nexport const ImportRecordSchema = z\n .object({\n source: z\n .string()\n .min(1)\n .refine((value) => !isAbsolutePath(value), \"must not expose an absolute module path\"),\n specifiers: z.array(ImportSpecifierRecordSchema),\n resolved: StoredFilePathSchema.optional(),\n external: z.boolean(),\n kind: z.enum([\"esm\", \"commonjs\"]),\n line: z.number().int().positive(),\n })\n .strict();\nexport type ImportRecord = z.infer<typeof ImportRecordSchema>;\n\nexport const ExportRecordSchema = z\n .object({\n name: z.string(),\n local: z.string().optional(),\n source: z\n .string()\n .refine((value) => !isAbsolutePath(value), \"must not expose an absolute module path\")\n .optional(),\n default: z.boolean(),\n typeOnly: z.boolean().optional(),\n line: z.number().int().positive(),\n })\n .strict();\nexport type ExportRecord = z.infer<typeof ExportRecordSchema>;\n\nexport const ExternalOperationKindSchema = z.enum([\"filesystem\", \"http\", \"database\", \"queue\"]);\nexport type ExternalOperationKind = z.infer<typeof ExternalOperationKindSchema>;\n\nexport const ExternalOperationSchema = z\n .object({\n kind: ExternalOperationKindSchema,\n api: z.string().min(1),\n line: z.number().int().positive(),\n })\n .strict();\nexport type ExternalOperation = z.infer<typeof ExternalOperationSchema>;\n\nexport const SyntaxSummarySchema = z\n .object({\n parser: z.string().min(1),\n factCount: z.number().int().nonnegative(),\n hadErrors: z.boolean(),\n fallbackFrom: z.string().min(1).optional(),\n })\n .strict();\nexport type SyntaxSummary = z.infer<typeof SyntaxSummarySchema>;\n\nexport const FileRecordSchema = z\n .object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n id: z.string().min(1),\n compilerUnit: z.string().min(1),\n path: StoredFilePathSchema,\n language: LanguageSchema,\n frameworks: z.array(FrameworkSchema),\n hash: z.string().regex(/^[a-f0-9]{64}$/),\n lines: z.number().int().nonnegative(),\n imports: z.array(ImportRecordSchema),\n exports: z.array(ExportRecordSchema),\n symbolIds: z.array(z.string().min(1)),\n env: z.array(z.string()),\n operations: z.array(ExternalOperationSchema),\n syntax: SyntaxSummarySchema,\n })\n .strict();\nexport type FileRecord = z.infer<typeof FileRecordSchema>;\n\nexport const CompilerUnitRecordSchema = z\n .object({\n id: z.string().min(1),\n kind: z.enum([\"configured\", \"fallback\"]),\n root: StoredPathSchema,\n config: StoredFilePathSchema.optional(),\n references: z.array(StoredFilePathSchema),\n extends: z.array(StoredFilePathSchema),\n pathAliases: z.record(StoredModuleAliasSchema, z.array(StoredPathSchema)),\n })\n .strict();\nexport type CompilerUnitRecord = z.infer<typeof CompilerUnitRecordSchema>;\n\nexport const SymbolKindSchema = z.enum([\n \"function\",\n \"class\",\n \"method\",\n \"interface\",\n \"type-alias\",\n \"variable\",\n \"react-component\",\n \"react-hook\",\n \"react-context\",\n \"next-page\",\n \"next-layout\",\n \"next-route-handler\",\n \"next-special-file\",\n \"nest-module\",\n \"nest-controller\",\n \"nest-provider\",\n \"nest-guard\",\n \"nest-interceptor\",\n \"nest-pipe\",\n \"nest-filter\",\n \"nest-gateway\",\n \"dto\",\n \"route\",\n]);\nexport type SymbolKind = z.infer<typeof SymbolKindSchema>;\n\nexport const SymbolRecordSchema = z\n .object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n id: z.string().min(1),\n name: z.string(),\n kind: SymbolKindSchema,\n file: StoredFilePathSchema,\n range: SourceRangeSchema,\n exported: z.boolean(),\n defaultExport: z.boolean().optional(),\n signature: z.string().optional(),\n documentation: z.string().optional(),\n facts: z.record(z.string(), JsonValueSchema),\n sourceHash: z.string().regex(/^[a-f0-9]{64}$/),\n })\n .strict();\nexport type SymbolRecord = z.infer<typeof SymbolRecordSchema>;\n\nexport const RelationTypeSchema = z.enum([\n \"imports\",\n \"exports\",\n \"reexports\",\n \"calls\",\n \"instantiates\",\n \"renders\",\n \"uses-hook\",\n \"reads-state\",\n \"depends-on\",\n \"used-by\",\n \"contains\",\n \"references\",\n \"injects\",\n \"handles-route\",\n \"consumes-dto\",\n \"belongs-to-module\",\n \"uses-layout\",\n]);\nexport type RelationType = z.infer<typeof RelationTypeSchema>;\n\nexport const RelationEvidenceClassificationSchema = z.enum([\n \"exact\",\n \"framework-derived\",\n \"heuristic\",\n \"derived\",\n]);\nexport type RelationEvidenceClassification = z.infer<typeof RelationEvidenceClassificationSchema>;\n\nexport const RelationOriginSchema = z\n .object({\n file: StoredFilePathSchema,\n line: z.number().int().positive(),\n range: SourceRangeSchema,\n explanation: z.string().min(1),\n classification: RelationEvidenceClassificationSchema,\n analyzer: z.string().min(1),\n })\n .strict();\nexport type RelationOrigin = z.infer<typeof RelationOriginSchema>;\n\nexport const RelationRecordSchema = z\n .object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n from: z.string().min(1),\n type: RelationTypeSchema,\n to: z.string().min(1),\n confidence: z.number().min(0).max(1),\n origin: RelationOriginSchema,\n })\n .strict();\nexport type RelationRecord = z.infer<typeof RelationRecordSchema>;\n\nexport const DiagnosticSeveritySchema = z.enum([\"info\", \"warning\", \"error\"]);\nexport type DiagnosticSeverity = z.infer<typeof DiagnosticSeveritySchema>;\n\nexport const DiagnosticCodeSchema = z.enum([\n \"parse-error\",\n \"unresolved-import\",\n \"invalid-config\",\n \"unsupported-file\",\n \"analysis-error\",\n \"parser-fallback\",\n \"compiler-config\",\n]);\nexport type DiagnosticCode = z.infer<typeof DiagnosticCodeSchema>;\n\nexport const DiagnosticRecordSchema = z\n .object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n code: DiagnosticCodeSchema,\n severity: DiagnosticSeveritySchema,\n message: z.string().min(1),\n file: StoredFilePathSchema.optional(),\n line: z.number().int().positive().optional(),\n column: z.number().int().positive().optional(),\n })\n .strict();\nexport type DiagnosticRecord = z.infer<typeof DiagnosticRecordSchema>;\n\nexport const WorkspacePackageSchema = z\n .object({\n name: z.string(),\n path: StoredFilePathSchema,\n entryPoints: z.array(StoredFilePathSchema),\n })\n .strict();\nexport type WorkspacePackage = z.infer<typeof WorkspacePackageSchema>;\n\nexport const MapCountsSchema = z\n .object({\n files: z.number().int().nonnegative(),\n symbols: z.number().int().nonnegative(),\n relations: z.number().int().nonnegative(),\n diagnostics: z.number().int().nonnegative(),\n })\n .strict();\nexport type MapCounts = z.infer<typeof MapCountsSchema>;\n\nexport const ProjectRecordSchema = z\n .object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n name: z.string(),\n packageManager: z.string().optional(),\n frameworks: z.array(FrameworkSchema),\n compilerUnits: z.array(CompilerUnitRecordSchema),\n tsconfig: StoredFilePathSchema.optional(),\n pathAliases: z.record(StoredModuleAliasSchema, z.array(StoredPathSchema)),\n entryPoints: z.array(StoredFilePathSchema),\n workspaces: z.array(WorkspacePackageSchema),\n counts: MapCountsSchema,\n })\n .strict();\nexport type ProjectRecord = z.infer<typeof ProjectRecordSchema>;\n\nexport const ManifestSourceFileSchema = z\n .object({\n path: StoredFilePathSchema,\n hash: z.string().regex(/^[a-f0-9]{64}$/),\n compilerUnit: z.string().min(1),\n lines: z.number().int().nonnegative(),\n })\n .strict();\nexport type ManifestSourceFile = z.infer<typeof ManifestSourceFileSchema>;\n\nconst SemanticFileInputRecordSchema = z\n .object({\n path: StoredPathSchema,\n kind: z.literal(\"file\"),\n hash: z.string().regex(/^[a-f0-9]{64}$/),\n })\n .strict();\nconst SemanticResolutionProbeRecordSchema = z\n .object({\n path: StoredPathSchema,\n kind: z.literal(\"resolution-probe\"),\n scope: z.enum([\"project\", \"toolchain\"]),\n targetKind: z.enum([\"file\", \"directory\", \"readable-file\"]),\n exists: z.boolean(),\n })\n .strict();\nconst SemanticDirectoryListingRecordSchema = z\n .object({\n path: StoredPathSchema,\n kind: z.literal(\"directory-listing\"),\n scope: z.enum([\"project\", \"toolchain\"]),\n hash: z.string().regex(/^[a-f0-9]{64}$/),\n })\n .strict();\nconst SemanticSymlinkRecordSchema = z\n .object({\n path: StoredPathSchema,\n kind: z.literal(\"symlink\"),\n scope: z.enum([\"project\", \"toolchain\"]),\n target: StoredPathSchema,\n })\n .strict();\nconst SemanticToolchainFileRecordSchema = z\n .object({\n path: StoredPathSchema,\n kind: z.literal(\"toolchain-file\"),\n hash: z.string().regex(/^[a-f0-9]{64}$/),\n })\n .strict();\nexport const SemanticInputRecordSchema = z.discriminatedUnion(\"kind\", [\n SemanticFileInputRecordSchema,\n SemanticResolutionProbeRecordSchema,\n SemanticDirectoryListingRecordSchema,\n SemanticSymlinkRecordSchema,\n SemanticToolchainFileRecordSchema,\n]);\nexport type SemanticInputRecord = z.infer<typeof SemanticInputRecordSchema>;\n\nexport const ArtifactIntegrityRecordSchema = z\n .object({\n path: z.enum(MAP_COMPANION_ARTIFACTS),\n hash: z.string().regex(/^[a-f0-9]{64}$/),\n })\n .strict();\nexport type ArtifactIntegrityRecord = z.infer<typeof ArtifactIntegrityRecordSchema>;\n\nexport const ProducerRecordSchema = z\n .object({\n id: z.string().min(1),\n kind: z.enum([\"built-in\", \"custom\"]),\n fingerprint: z.string().regex(/^[a-f0-9]{64}$/),\n })\n .strict();\nexport type ProducerRecord = z.infer<typeof ProducerRecordSchema>;\n\nconst VersionedToolSchema = z\n .object({\n name: z.string().min(1),\n version: z.string().min(1),\n })\n .strict();\n\nexport const ManifestRecordSchema = z\n .object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n analyzerVersion: z.string().min(1),\n producer: ProducerRecordSchema,\n semanticResolver: VersionedToolSchema,\n syntaxParser: VersionedToolSchema,\n analyzers: z.array(VersionedToolSchema),\n configHash: z.string().regex(/^[a-f0-9]{64}$/),\n sourceFiles: z.array(ManifestSourceFileSchema),\n semanticInputs: z.array(SemanticInputRecordSchema),\n artifacts: z.array(ArtifactIntegrityRecordSchema),\n integrityHash: z.string().regex(/^[a-f0-9]{64}$/),\n })\n .strict();\nexport type ManifestRecord = z.infer<typeof ManifestRecordSchema>;\n\nconst CodeMapShapeSchema = z\n .object({\n manifest: ManifestRecordSchema,\n project: ProjectRecordSchema,\n files: z.array(FileRecordSchema),\n symbols: z.array(SymbolRecordSchema),\n relations: z.array(RelationRecordSchema),\n diagnostics: z.array(DiagnosticRecordSchema),\n })\n .strict();\nexport const CodeMapSchema = CodeMapShapeSchema.superRefine((map, context) => {\n const fileByPath = new Map(map.files.map((file) => [file.path, file]));\n const fileIds = new Set<string>();\n const filePaths = new Set<string>();\n const compilerUnitsById = new Map(map.project.compilerUnits.map((unit) => [unit.id, unit]));\n const compilerUnitIds = new Set<string>();\n let fallbackCount = 0;\n for (const [index, file] of map.files.entries()) {\n addDuplicateIssue(context, fileIds, file.id, [\"files\", index, \"id\"]);\n addDuplicateIssue(context, filePaths, file.path, [\"files\", index, \"path\"]);\n if (file.id !== `file:${file.path}`) {\n context.addIssue({\n code: \"custom\",\n path: [\"files\", index, \"id\"],\n message: \"file ID must be derived from its path\",\n });\n }\n }\n\n for (const [index, unit] of map.project.compilerUnits.entries()) {\n addDuplicateIssue(context, compilerUnitIds, unit.id, [\"project\", \"compilerUnits\", index, \"id\"]);\n if (unit.kind === \"configured\" && !unit.config) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"compilerUnits\", index, \"config\"],\n message: \"configured compiler units require config\",\n });\n }\n if (unit.kind === \"fallback\" && unit.config) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"compilerUnits\", index, \"config\"],\n message: \"fallback compiler units must not have config\",\n });\n }\n if (unit.kind === \"fallback\") {\n fallbackCount += 1;\n if (\n unit.id !== \"compiler-unit:generated:fallback\" ||\n unit.root !== \".\" ||\n unit.references.length > 0 ||\n unit.extends.length > 0 ||\n Object.keys(unit.pathAliases).length > 0\n ) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"compilerUnits\", index],\n message: \"fallback compiler unit must use the canonical generated identity and shape\",\n });\n }\n }\n if (unit.kind === \"configured\" && unit.config) {\n if (unit.id !== `compiler-unit:configured:${unit.config}`) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"compilerUnits\", index, \"id\"],\n message: \"configured compiler-unit ID must be derived from its config path\",\n });\n }\n if (unit.root !== normalizeStoredPath(path.posix.dirname(unit.config))) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"compilerUnits\", index, \"root\"],\n message: \"configured compiler-unit root must match its config directory\",\n });\n }\n }\n }\n if (fallbackCount !== 1) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"compilerUnits\"],\n message: \"exactly one fallback compiler unit is required\",\n });\n }\n const configuredPaths = new Set(\n map.project.compilerUnits.flatMap((unit) =>\n unit.kind === \"configured\" && unit.config ? [unit.config] : [],\n ),\n );\n if (map.project.tsconfig && !configuredPaths.has(map.project.tsconfig)) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"tsconfig\"],\n message: \"project tsconfig must resolve to a configured compiler unit\",\n });\n }\n const compatibilityUnit = map.project.tsconfig\n ? map.project.compilerUnits.find((unit) => unit.config === map.project.tsconfig)\n : map.project.compilerUnits\n .filter((unit) => unit.kind === \"configured\")\n .sort((left, right) => compareText(left.id, right.id))[0];\n if (stableJson(map.project.pathAliases) !== stableJson(compatibilityUnit?.pathAliases ?? {})) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"pathAliases\"],\n message: \"project path aliases must match the compatibility compiler unit\",\n });\n }\n for (const [index, unit] of map.project.compilerUnits.entries()) {\n for (const reference of unit.references) {\n if (!configuredPaths.has(reference)) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"compilerUnits\", index, \"references\"],\n message: \"compiler-unit reference must resolve to a configured unit\",\n });\n }\n }\n }\n\n const symbolById = new Map<string, (typeof map.symbols)[number]>();\n for (const [index, symbol] of map.symbols.entries()) {\n if (symbolById.has(symbol.id)) {\n context.addIssue({\n code: \"custom\",\n path: [\"symbols\", index, \"id\"],\n message: `duplicate symbol ID ${symbol.id}`,\n });\n }\n symbolById.set(symbol.id, symbol);\n const owner = fileByPath.get(symbol.file);\n if (!owner) {\n context.addIssue({\n code: \"custom\",\n path: [\"symbols\", index, \"file\"],\n message: \"symbol references a missing file\",\n });\n } else if (owner.hash !== symbol.sourceHash) {\n context.addIssue({\n code: \"custom\",\n path: [\"symbols\", index, \"sourceHash\"],\n message: \"symbol source hash does not match its file\",\n });\n } else if (!rangeFitsFile(symbol.range, owner)) {\n context.addIssue({\n code: \"custom\",\n path: [\"symbols\", index, \"range\"],\n message: \"symbol range must fit within its source file\",\n });\n }\n }\n\n const importRelationKeys = new Set(\n map.relations\n .filter((relation) => relation.type === \"imports\")\n .map(\n (relation) =>\n `${relation.from}\\u0000${relation.to}\\u0000${relation.origin.file}\\u0000${relation.origin.line}`,\n ),\n );\n const expectedImportRelationKeys = new Set<string>();\n\n for (const [fileIndex, file] of map.files.entries()) {\n const unit = compilerUnitsById.get(file.compilerUnit);\n if (!unit) {\n context.addIssue({\n code: \"custom\",\n path: [\"files\", fileIndex, \"compilerUnit\"],\n message: \"file compiler unit must resolve to exactly one compiler unit\",\n });\n }\n\n const expected = map.symbols\n .filter((symbol) => symbol.file === file.path)\n .map((symbol) => symbol.id)\n .sort();\n const actual = [...file.symbolIds].sort();\n if (JSON.stringify(actual) !== JSON.stringify(expected)) {\n context.addIssue({\n code: \"custom\",\n path: [\"files\", fileIndex, \"symbolIds\"],\n message: \"file symbol IDs must exactly match symbols owned by the file\",\n });\n }\n\n for (const [importIndex, importRecord] of file.imports.entries()) {\n if (importRecord.line > file.lines) {\n context.addIssue({\n code: \"custom\",\n path: [\"files\", fileIndex, \"imports\", importIndex, \"line\"],\n message: \"import line must fit within its source file\",\n });\n }\n if (importRecord.external && importRecord.resolved) {\n context.addIssue({\n code: \"custom\",\n path: [\"files\", fileIndex, \"imports\", importIndex],\n message: \"external imports must not name an internal resolved path\",\n });\n }\n if (importRecord.resolved && !fileByPath.has(importRecord.resolved)) {\n context.addIssue({\n code: \"custom\",\n path: [\"files\", fileIndex, \"imports\", importIndex, \"resolved\"],\n message: \"resolved import must reference a persisted file\",\n });\n }\n const target = importRecord.resolved\n ? `file:${importRecord.resolved}`\n : `external:${importRecord.source}#default`;\n const key = `${file.id}\\u0000${target}\\u0000${file.path}\\u0000${importRecord.line}`;\n expectedImportRelationKeys.add(key);\n if (!importRelationKeys.has(key)) {\n context.addIssue({\n code: \"custom\",\n path: [\"files\", fileIndex, \"imports\", importIndex],\n message: \"import record must have matching relation evidence\",\n });\n }\n }\n for (const [exportIndex, exportRecord] of file.exports.entries()) {\n if (exportRecord.line > file.lines) {\n context.addIssue({\n code: \"custom\",\n path: [\"files\", fileIndex, \"exports\", exportIndex, \"line\"],\n message: \"export line must fit within its source file\",\n });\n }\n }\n for (const [operationIndex, operation] of file.operations.entries()) {\n if (operation.line > file.lines) {\n context.addIssue({\n code: \"custom\",\n path: [\"files\", fileIndex, \"operations\", operationIndex, \"line\"],\n message: \"operation line must fit within its source file\",\n });\n }\n }\n }\n\n const manifestPaths = new Set<string>();\n for (const [index, source] of map.manifest.sourceFiles.entries()) {\n addDuplicateIssue(context, manifestPaths, source.path, [\n \"manifest\",\n \"sourceFiles\",\n index,\n \"path\",\n ]);\n const file = fileByPath.get(source.path);\n if (!file || file.hash !== source.hash) {\n context.addIssue({\n code: \"custom\",\n path: [\"manifest\", \"sourceFiles\", index],\n message: \"manifest source must match a persisted file and hash\",\n });\n } else if (file.compilerUnit !== source.compilerUnit) {\n context.addIssue({\n code: \"custom\",\n path: [\"manifest\", \"sourceFiles\", index, \"compilerUnit\"],\n message: \"manifest source ownership must match the persisted file compiler unit\",\n });\n } else if (file.lines !== source.lines) {\n context.addIssue({\n code: \"custom\",\n path: [\"manifest\", \"sourceFiles\", index, \"lines\"],\n message: \"manifest source line count must match the persisted file\",\n });\n }\n }\n if (manifestPaths.size !== fileByPath.size) {\n context.addIssue({\n code: \"custom\",\n path: [\"manifest\", \"sourceFiles\"],\n message: \"manifest sources must exactly cover persisted files\",\n });\n }\n\n const semanticInputIdentities = new Set<string>();\n for (const [index, input] of map.manifest.semanticInputs.entries()) {\n addDuplicateIssue(context, semanticInputIdentities, semanticInputIdentity(input), [\n \"manifest\",\n \"semanticInputs\",\n index,\n ]);\n }\n\n const artifactPaths = new Set<string>();\n for (const [index, artifact] of map.manifest.artifacts.entries()) {\n addDuplicateIssue(context, artifactPaths, artifact.path, [\n \"manifest\",\n \"artifacts\",\n index,\n \"path\",\n ]);\n }\n const expectedArtifacts = [...MAP_COMPANION_ARTIFACTS].sort();\n if (JSON.stringify([...artifactPaths].sort()) !== JSON.stringify(expectedArtifacts)) {\n context.addIssue({\n code: \"custom\",\n path: [\"manifest\", \"artifacts\"],\n message: \"manifest artifact hashes must exactly cover every companion artifact\",\n });\n }\n\n const counts = {\n files: map.files.length,\n symbols: map.symbols.length,\n relations: map.relations.length,\n diagnostics: map.diagnostics.length,\n };\n for (const key of Object.keys(counts) as Array<keyof typeof counts>) {\n if (map.project.counts[key] !== counts[key]) {\n context.addIssue({\n code: \"custom\",\n path: [\"project\", \"counts\", key],\n message: `${key} count does not match persisted records`,\n });\n }\n }\n\n const validEndpoints = new Set([...fileIds, ...symbolById.keys()]);\n const relationIdentities = new Set<string>();\n for (const [index, relation] of map.relations.entries()) {\n addDuplicateIssue(context, relationIdentities, relationIdentity(relation), [\n \"relations\",\n index,\n ]);\n if (relation.type === \"imports\") {\n const key = `${relation.from}\\u0000${relation.to}\\u0000${relation.origin.file}\\u0000${relation.origin.line}`;\n if (!expectedImportRelationKeys.has(key)) {\n context.addIssue({\n code: \"custom\",\n path: [\"relations\", index],\n message: \"imports relation must have a matching file import record\",\n });\n }\n }\n for (const endpoint of [relation.from, relation.to]) {\n if (\n !validEndpoints.has(endpoint) &&\n !endpoint.startsWith(\"external:\") &&\n !endpoint.startsWith(\"route:\")\n ) {\n context.addIssue({\n code: \"custom\",\n path: [\"relations\", index],\n message: `relation references missing endpoint ${endpoint}`,\n });\n }\n }\n const originFile = fileByPath.get(relation.origin.file);\n if (!originFile) {\n context.addIssue({\n code: \"custom\",\n path: [\"relations\", index, \"origin\", \"file\"],\n message: \"relation evidence references a missing file\",\n });\n } else {\n if (relation.origin.line !== relation.origin.range.startLine) {\n context.addIssue({\n code: \"custom\",\n path: [\"relations\", index, \"origin\", \"line\"],\n message: \"relation origin line must match the start of its evidence range\",\n });\n }\n if (!rangeFitsFile(relation.origin.range, originFile)) {\n context.addIssue({\n code: \"custom\",\n path: [\"relations\", index, \"origin\", \"range\"],\n message: \"relation evidence range must fit within its source file\",\n });\n }\n if (relation.type === \"contains\" || relation.type === \"exports\") {\n const fromFile = endpointSourceFile(relation.from, fileByPath, symbolById);\n const toFile = endpointSourceFile(relation.to, fileByPath, symbolById);\n if (\n fromFile !== relation.origin.file ||\n (relation.type === \"exports\" && toFile !== relation.origin.file)\n ) {\n context.addIssue({\n code: \"custom\",\n path: [\"relations\", index],\n message:\n relation.type === \"exports\"\n ? \"exports endpoints and evidence must belong to the same file\"\n : \"contains evidence must belong to its source endpoint file\",\n });\n }\n\n const fromIsFile = relation.from.startsWith(\"file:\");\n const toSymbol = symbolById.get(relation.to);\n const fromSymbol = symbolById.get(relation.from);\n if (relation.type === \"contains\" && fromIsFile) {\n if (\n !toSymbol ||\n toSymbol.file !== relation.origin.file ||\n !rangesEqual(toSymbol.range, relation.origin.range)\n ) {\n context.addIssue({\n code: \"custom\",\n path: [\"relations\", index],\n message: \"file containment evidence must exactly identify a symbol owned by the file\",\n });\n }\n } else if (relation.type === \"contains\" && fromSymbol) {\n if (!toSymbol || !rangeContains(fromSymbol.range, relation.origin.range)) {\n context.addIssue({\n code: \"custom\",\n path: [\"relations\", index, \"origin\", \"range\"],\n message:\n \"symbol containment must target a symbol and its evidence must fall within the source symbol\",\n });\n }\n }\n if (\n relation.type === \"exports\" &&\n (!fromIsFile ||\n !toSymbol ||\n !toSymbol.exported ||\n !rangesEqual(toSymbol.range, relation.origin.range))\n ) {\n context.addIssue({\n code: \"custom\",\n path: [\"relations\", index],\n message: \"exports evidence must exactly identify an exported symbol owned by the file\",\n });\n }\n }\n }\n }\n\n for (const [index, diagnostic] of map.diagnostics.entries()) {\n const file = diagnostic.file ? fileByPath.get(diagnostic.file) : undefined;\n if (file && diagnostic.line && diagnostic.line > file.lines) {\n context.addIssue({\n code: \"custom\",\n path: [\"diagnostics\", index, \"line\"],\n message: \"diagnostic line must fit within its source file\",\n });\n }\n }\n});\nexport type CodeMap = z.infer<typeof CodeMapSchema>;\n\nfunction addDuplicateIssue(\n context: z.RefinementCtx,\n seen: Set<string>,\n value: string,\n path: PropertyKey[],\n): void {\n if (seen.has(value)) {\n context.addIssue({ code: \"custom\", path, message: `duplicate value ${value}` });\n }\n seen.add(value);\n}\n\nfunction relationIdentity(relation: RelationRecord): string {\n const range = relation.origin.range;\n return [\n relation.from,\n relation.type,\n relation.to,\n relation.origin.file,\n range.startLine,\n range.startColumn,\n range.endLine,\n range.endColumn,\n ].join(\"\\u0000\");\n}\n\nfunction semanticInputIdentity(input: SemanticInputRecord): string {\n return input.kind === \"resolution-probe\"\n ? `${input.scope}\\u0000${input.path}\\u0000${input.kind}\\u0000${input.targetKind}`\n : input.kind === \"directory-listing\" || input.kind === \"symlink\"\n ? `${input.scope}\\u0000${input.path}\\u0000${input.kind}`\n : `${input.path}\\u0000${input.kind}`;\n}\n\nfunction rangeFitsFile(range: SourceRange, file: FileRecord): boolean {\n return range.startLine <= file.lines && range.endLine <= file.lines;\n}\n\nfunction rangesEqual(left: SourceRange, right: SourceRange): boolean {\n return (\n left.startLine === right.startLine &&\n left.startColumn === right.startColumn &&\n left.endLine === right.endLine &&\n left.endColumn === right.endColumn\n );\n}\n\nfunction rangeContains(outer: SourceRange, inner: SourceRange): boolean {\n const startsAfter =\n inner.startLine > outer.startLine ||\n (inner.startLine === outer.startLine && inner.startColumn >= outer.startColumn);\n const endsBefore =\n inner.endLine < outer.endLine ||\n (inner.endLine === outer.endLine && inner.endColumn <= outer.endColumn);\n return startsAfter && endsBefore;\n}\n\nfunction endpointSourceFile(\n endpoint: string,\n files: ReadonlyMap<string, FileRecord>,\n symbols: ReadonlyMap<string, SymbolRecord>,\n): string | undefined {\n if (endpoint.startsWith(\"file:\")) return files.get(endpoint.slice(\"file:\".length))?.path;\n return symbols.get(endpoint)?.file;\n}\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { JsonValue } from \"../types.js\";\n\nexport function compareText(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction safeRecordEntry(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((entry) => safeRecordEntry(entry));\n }\n if (value !== null && typeof value === \"object\") {\n const record = value as Record<string, unknown>;\n const next: Record<string, unknown> = {};\n for (const key of Object.keys(record).sort(compareText)) {\n const child = record[key];\n if (child !== undefined) {\n next[key] = safeRecordEntry(child);\n }\n }\n return next;\n }\n return value;\n}\n\nexport function stableValue<T>(value: T): T {\n if (Array.isArray(value)) {\n return safeRecordEntry(value) as T;\n }\n if (value !== null && typeof value === \"object\") {\n return safeRecordEntry(value) as T;\n }\n return value;\n}\n\nexport function stableJson(value: unknown, pretty = false): string {\n return `${JSON.stringify(stableValue(value), null, pretty ? 2 : undefined)}\\n`;\n}\n\nexport function stableJsonLine(value: unknown): string {\n return JSON.stringify(stableValue(value));\n}\n\nexport async function atomicWriteIfChanged(filePath: string, content: string): Promise<boolean> {\n const canonicalBytes = Buffer.from(content, \"utf8\");\n try {\n if ((await fs.readFile(filePath)).equals(canonicalBytes)) return false;\n } catch (error) {\n // A managed artifact that exists but cannot be read is not a reusable commit. Writing the\n // replacement through the containing directory lets an ordinary scan repair mode corruption\n // on platforms where atomic rename-over-existing is supported.\n if (!isNotFound(error) && !isPermissionDenied(error)) throw error;\n }\n\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n const temporary = path.join(\n path.dirname(filePath),\n `.${path.basename(filePath)}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,\n );\n try {\n await fs.writeFile(temporary, canonicalBytes, { mode: 0o644 });\n await fs.rename(temporary, filePath);\n } catch (error) {\n await fs.rm(temporary, { force: true }).catch(() => undefined);\n throw error;\n }\n return true;\n}\n\nexport function asJsonValue(value: unknown): JsonValue {\n return stableValue(value) as JsonValue;\n}\n\nexport function isNotFound(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error && error.code === \"ENOENT\";\n}\n\nfunction isPermissionDenied(error: unknown): error is NodeJS.ErrnoException {\n return (\n error instanceof Error && \"code\" in error && (error.code === \"EACCES\" || error.code === \"EPERM\")\n );\n}\n\nexport async function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n}\n\nexport async function mapLimit<T, R>(\n values: readonly T[],\n limit: number,\n operation: (value: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(values.length);\n let cursor = 0;\n const workers = Array.from({ length: Math.min(Math.max(1, limit), values.length) }, async () => {\n while (cursor < values.length) {\n const index = cursor++;\n const value = values[index] as T;\n if (value === undefined) return;\n results[index] = await operation(value, index);\n }\n });\n await Promise.all(workers);\n return results;\n}\n","import { createHash } from \"node:crypto\";\n\nexport function hashText(value: string | Buffer): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function shortHash(value: string | Buffer, length = 12): string {\n return hashText(value).slice(0, length);\n}\n","import { isBuiltin } from \"node:module\";\nimport path from \"node:path\";\n\nimport ts from \"typescript\";\n\nimport { ANALYZER_VERSION, SCHEMA_VERSION } from \"../constants.js\";\nimport { externalId, fileId, symbolId } from \"../ids.js\";\nimport type {\n AnalysisContext,\n AnalysisContribution,\n DiagnosticRecord,\n ExportRecord,\n ExternalOperation,\n FileRecord,\n FrameworkAnalyzer,\n ImportRecord,\n RelationRecord,\n SymbolKind,\n SymbolRecord,\n} from \"../types.js\";\nimport { isPathInside, relativePosix, sanitizeModuleSpecifier } from \"../utils/path.js\";\nimport { compareText } from \"../utils/stable.js\";\nimport {\n getDeclarationName,\n hasDefaultModifier,\n hasExportModifier,\n hasModifier,\n makeSymbol,\n nodeLine,\n nodeRange,\n propertyNameText,\n visit,\n} from \"./helpers.js\";\n\nexport class CoreAnalyzer implements FrameworkAnalyzer {\n readonly name = \"typescript-node\";\n readonly version = ANALYZER_VERSION;\n\n supports(): boolean {\n return true;\n }\n\n analyze(context: AnalysisContext): AnalysisContribution {\n const symbols: SymbolRecord[] = [];\n const relations: RelationRecord[] = [];\n const seenSymbols = new Map<string, SymbolRecord>();\n\n for (const statement of context.sourceFile.statements) {\n extractTopLevelSymbol(context, statement, seenSymbols, relations);\n }\n symbols.push(...seenSymbols.values());\n\n const declarationIds = declarationIdMap(context, symbols);\n collectBehaviorRelations(context, declarationIds, relations);\n\n return {\n symbols: symbols.sort((a, b) => compareText(a.id, b.id)),\n relations,\n frameworks: [\"typescript\", \"node\"],\n };\n }\n}\n\nfunction extractTopLevelSymbol(\n context: AnalysisContext,\n statement: ts.Statement,\n output: Map<string, SymbolRecord>,\n relations: RelationRecord[],\n): void {\n if (ts.isFunctionDeclaration(statement)) {\n const name = statement.name?.text ?? \"default\";\n const record = makeSymbol(context, statement, \"function\", {\n name,\n exported: isNameExported(context, name, statement),\n facts: { async: hasModifier(statement, ts.SyntaxKind.AsyncKeyword) },\n });\n keepBestDeclaration(output, record, Boolean(statement.body));\n return;\n }\n if (ts.isClassDeclaration(statement)) {\n const className = statement.name?.text ?? \"default\";\n const classRecord = makeSymbol(context, statement, \"class\", {\n name: className,\n exported: isNameExported(context, className, statement),\n });\n keepBestDeclaration(output, classRecord, true);\n for (const member of statement.members) {\n if (!ts.isMethodDeclaration(member) && !ts.isConstructorDeclaration(member)) continue;\n if (hasModifier(member, ts.SyntaxKind.PrivateKeyword) && !isPrivateEnabled(context)) {\n continue;\n }\n const name = ts.isConstructorDeclaration(member)\n ? \"constructor\"\n : (propertyNameText(member.name) ?? \"anonymous\");\n const method = makeSymbol(context, member, \"method\", {\n name,\n parent: className,\n exported: classRecord.exported,\n facts: {\n async: ts.isMethodDeclaration(member)\n ? hasModifier(member, ts.SyntaxKind.AsyncKeyword)\n : false,\n },\n });\n keepBestDeclaration(output, method, Boolean(member.body));\n relations.push(\n relation(classRecord.id, \"contains\", method.id, context, member, 1, \"class member\"),\n );\n }\n return;\n }\n if (ts.isInterfaceDeclaration(statement)) {\n keepBestDeclaration(\n output,\n makeSymbol(context, statement, \"interface\", {\n exported: isNameExported(context, statement.name.text, statement),\n }),\n true,\n );\n return;\n }\n if (ts.isTypeAliasDeclaration(statement)) {\n keepBestDeclaration(\n output,\n makeSymbol(context, statement, \"type-alias\", {\n exported: isNameExported(context, statement.name.text, statement),\n }),\n true,\n );\n return;\n }\n if (ts.isVariableStatement(statement)) {\n const defaultExport = hasDefaultModifier(statement);\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name)) continue;\n const functionLike =\n declaration.initializer !== undefined &&\n (ts.isArrowFunction(declaration.initializer) ||\n ts.isFunctionExpression(declaration.initializer));\n const record = makeSymbol(context, declaration, functionLike ? \"function\" : \"variable\", {\n exported: isNameExported(context, declaration.name.text, statement),\n defaultExport,\n facts: functionLike\n ? { async: hasModifier(declaration.initializer, ts.SyntaxKind.AsyncKeyword) }\n : {},\n });\n keepBestDeclaration(output, record, true);\n }\n }\n}\n\nfunction isNameExported(context: AnalysisContext, name: string, node: ts.Node): boolean {\n if (hasExportModifier(node) || hasDefaultModifier(node)) return true;\n return context.file.exports.some(\n (entry) => !entry.source && (entry.local === name || (!entry.local && entry.name === name)),\n );\n}\n\nfunction isPrivateEnabled(context: AnalysisContext): boolean {\n return context.includePrivateSymbols;\n}\n\nfunction keepBestDeclaration(\n output: Map<string, SymbolRecord>,\n record: SymbolRecord,\n hasImplementation: boolean,\n): void {\n const existing = output.get(record.id);\n if (!existing || hasImplementation || !existing.signature) output.set(record.id, record);\n}\n\nfunction declarationIdMap(\n context: AnalysisContext,\n symbols: SymbolRecord[],\n): Map<ts.Declaration, string> {\n const byKey = new Map(symbols.map((symbol) => [`${symbol.kind}:${symbol.name}`, symbol.id]));\n const result = new Map<ts.Declaration, string>();\n for (const statement of context.sourceFile.statements) {\n if (ts.isFunctionDeclaration(statement)) {\n const name = statement.name?.text ?? \"default\";\n const id = byKey.get(`function:${name}`);\n if (id) result.set(statement, id);\n } else if (ts.isClassDeclaration(statement)) {\n const name = statement.name?.text ?? \"default\";\n const id = byKey.get(`class:${name}`);\n if (id) result.set(statement, id);\n for (const member of statement.members) {\n if (!ts.isMethodDeclaration(member) && !ts.isConstructorDeclaration(member)) continue;\n const memberName = ts.isConstructorDeclaration(member)\n ? \"constructor\"\n : (propertyNameText(member.name) ?? \"anonymous\");\n const memberId = symbolId(\"method\", context.relativePath, memberName, name);\n result.set(member, memberId);\n }\n } else if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name)) continue;\n const kind =\n declaration.initializer &&\n (ts.isArrowFunction(declaration.initializer) ||\n ts.isFunctionExpression(declaration.initializer))\n ? \"function\"\n : \"variable\";\n const id = byKey.get(`${kind}:${declaration.name.text}`);\n if (id) result.set(declaration, id);\n }\n } else if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) {\n const kind = ts.isInterfaceDeclaration(statement) ? \"interface\" : \"type-alias\";\n const id = byKey.get(`${kind}:${statement.name.text}`);\n if (id) result.set(statement, id);\n }\n }\n return result;\n}\n\nfunction collectBehaviorRelations(\n context: AnalysisContext,\n declarationIds: Map<ts.Declaration, string>,\n output: RelationRecord[],\n): void {\n let currentOwner = fileId(context.relativePath);\n const walk = (node: ts.Node): void => {\n const previousOwner = currentOwner;\n if (\n ts.isFunctionDeclaration(node) ||\n ts.isMethodDeclaration(node) ||\n ts.isConstructorDeclaration(node)\n ) {\n currentOwner = declarationIds.get(node) ?? currentOwner;\n } else if (\n (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) &&\n ts.isVariableDeclaration(node.parent)\n ) {\n currentOwner = declarationIds.get(node.parent) ?? currentOwner;\n } else if (ts.isClassDeclaration(node)) {\n currentOwner = declarationIds.get(node) ?? currentOwner;\n }\n\n if (ts.isCallExpression(node) && !isRequireCall(node)) {\n const target = resolveExpressionTarget(context, node.expression);\n if (target && target.id !== currentOwner) {\n output.push(\n relation(\n currentOwner,\n \"calls\",\n target.id,\n context,\n node,\n target.exact ? 1 : 0.35,\n target.exact ? \"TypeScript symbol resolution\" : \"unresolved call syntax\",\n ),\n );\n }\n } else if (ts.isNewExpression(node)) {\n const target = resolveExpressionTarget(context, node.expression);\n if (target && target.id !== currentOwner) {\n output.push(\n relation(\n currentOwner,\n \"instantiates\",\n target.id,\n context,\n node,\n target.exact ? 1 : 0.35,\n target.exact ? \"TypeScript constructor resolution\" : \"unresolved constructor syntax\",\n ),\n );\n }\n }\n\n if (ts.isIdentifier(node) && isReferenceIdentifier(node)) {\n const target = resolveExpressionTarget(context, node, false);\n if (target?.exact && target.id !== currentOwner && !target.id.startsWith(\"external:\")) {\n output.push(\n relation(\n currentOwner,\n \"references\",\n target.id,\n context,\n node,\n 1,\n \"TypeScript symbol reference\",\n ),\n );\n }\n }\n\n node.forEachChild(walk);\n currentOwner = previousOwner;\n };\n walk(context.sourceFile);\n\n for (const statement of context.sourceFile.statements) {\n if (!ts.isClassDeclaration(statement)) continue;\n const from = declarationIds.get(statement);\n if (!from) continue;\n for (const clause of statement.heritageClauses ?? []) {\n for (const type of clause.types) {\n const target = resolveExpressionTarget(context, type.expression);\n if (target) {\n output.push(\n relation(\n from,\n \"depends-on\",\n target.id,\n context,\n type,\n target.exact ? 1 : 0.35,\n target.exact ? \"TypeScript heritage resolution\" : \"unresolved heritage syntax\",\n ),\n );\n }\n }\n }\n }\n}\n\ninterface TargetResolution {\n id: string;\n exact: boolean;\n}\n\nfunction resolveExpressionTarget(\n context: AnalysisContext,\n expression: ts.Expression,\n allowFallback = true,\n): TargetResolution | undefined {\n let symbol = context.checker.getSymbolAtLocation(expression);\n if (!symbol && ts.isPropertyAccessExpression(expression)) {\n symbol = context.checker.getSymbolAtLocation(expression.name);\n }\n const externalBinding = importedExpressionBinding(context, expression);\n if (!symbol) {\n const imported = resolveImportedExpressionTarget(context, expression);\n if (imported) return { id: imported, exact: true };\n if (externalBinding) {\n return {\n id: externalId(externalBinding.module, externalBinding.exported),\n exact: true,\n };\n }\n const fallback = allowFallback ? expressionFallbackId(expression) : undefined;\n return fallback ? { id: fallback, exact: false } : undefined;\n }\n if (symbol.flags & ts.SymbolFlags.Alias) {\n try {\n symbol = context.checker.getAliasedSymbol(symbol);\n } catch {\n // An unresolved alias still gets an external fallback below.\n }\n }\n const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];\n if (!declaration) {\n const imported = resolveImportedExpressionTarget(context, expression);\n if (imported) return { id: imported, exact: true };\n if (externalBinding) {\n return {\n id: externalId(externalBinding.module, externalBinding.exported),\n exact: true,\n };\n }\n const fallback = allowFallback ? expressionFallbackId(expression) : undefined;\n return fallback ? { id: fallback, exact: false } : undefined;\n }\n const source = declaration.getSourceFile();\n if (!isPathInside(context.root, source.fileName)) {\n return externalBinding\n ? {\n id: externalId(externalBinding.module, externalBinding.exported),\n exact: true,\n }\n : allowFallback\n ? { id: externalId(\"unresolved\", symbol.getName()), exact: false }\n : undefined;\n }\n const relative = relativePosix(context.root, source.fileName);\n if (context.indexedSourcePaths && !context.indexedSourcePaths.has(relative)) {\n return externalBinding\n ? {\n id: externalId(externalBinding.module, externalBinding.exported),\n exact: true,\n }\n : allowFallback\n ? { id: externalId(\"unresolved\", symbol.getName()), exact: false }\n : undefined;\n }\n const id = declarationToId(declaration, relative);\n if (id) return { id, exact: true };\n if (externalBinding) {\n return {\n id: externalId(externalBinding.module, externalBinding.exported),\n exact: true,\n };\n }\n const fallback = allowFallback ? expressionFallbackId(expression) : undefined;\n return fallback ? { id: fallback, exact: false } : undefined;\n}\n\nfunction resolveImportedExpressionTarget(\n context: AnalysisContext,\n expression: ts.Expression,\n): string | undefined {\n const binding = importedExpressionBinding(context, expression, true);\n if (!binding?.resolved) return undefined;\n if (ts.isIdentifier(expression)) {\n const sourceFile = context.program.getSourceFile(path.resolve(context.root, binding.resolved));\n if (!sourceFile) return undefined;\n const declaration = findExportedDeclaration(sourceFile, binding.imported);\n return declaration ? declarationToId(declaration, binding.resolved) : undefined;\n }\n if (!ts.isPropertyAccessExpression(expression)) return undefined;\n const sourceFile = context.program.getSourceFile(path.resolve(context.root, binding.resolved));\n if (!sourceFile) return undefined;\n const declaration = findExportedDeclaration(sourceFile, expression.name.text);\n return declaration ? declarationToId(declaration, binding.resolved) : undefined;\n}\n\nfunction findExportedDeclaration(\n sourceFile: ts.SourceFile,\n exportedName: string,\n): ts.Declaration | undefined {\n for (const statement of sourceFile.statements) {\n if (\n (ts.isFunctionDeclaration(statement) ||\n ts.isClassDeclaration(statement) ||\n ts.isInterfaceDeclaration(statement) ||\n ts.isTypeAliasDeclaration(statement)) &&\n ((exportedName === \"default\" && hasDefaultModifier(statement)) ||\n statement.name?.text === exportedName)\n ) {\n return statement;\n }\n if (ts.isVariableStatement(statement)) {\n const declaration = statement.declarationList.declarations.find(\n (item) => ts.isIdentifier(item.name) && item.name.text === exportedName,\n );\n if (declaration) return declaration;\n }\n if (\n ts.isExportAssignment(statement) &&\n !statement.isExportEquals &&\n ts.isIdentifier(statement.expression)\n ) {\n if (exportedName === \"default\") {\n const declaration = findDeclarationByName(sourceFile, statement.expression.text);\n if (declaration) return declaration;\n }\n if (statement.expression.text === exportedName) {\n return findDeclarationByName(sourceFile, statement.expression.text);\n }\n }\n if (\n ts.isExportDeclaration(statement) &&\n statement.exportClause &&\n ts.isNamedExports(statement.exportClause)\n ) {\n const specifier = statement.exportClause.elements.find(\n (item) => item.name.text === exportedName,\n );\n if (specifier && !statement.moduleSpecifier) {\n return findExportedDeclaration(\n sourceFile,\n specifier.propertyName?.text ?? specifier.name.text,\n );\n }\n }\n }\n return undefined;\n}\n\nfunction findDeclarationByName(\n sourceFile: ts.SourceFile,\n name: string,\n): ts.Declaration | undefined {\n for (const statement of sourceFile.statements) {\n if (\n (ts.isFunctionDeclaration(statement) ||\n ts.isClassDeclaration(statement) ||\n ts.isInterfaceDeclaration(statement) ||\n ts.isTypeAliasDeclaration(statement)) &&\n statement.name?.text === name\n ) {\n return statement;\n }\n if (ts.isVariableStatement(statement)) {\n const declaration = statement.declarationList.declarations.find(\n (item) => ts.isIdentifier(item.name) && item.name.text === name,\n );\n if (declaration) return declaration;\n }\n }\n return undefined;\n}\n\ninterface ImportedExpressionBinding {\n module: string;\n exported: string;\n imported: string;\n resolved?: string;\n}\n\nfunction importedExpressionBinding(\n context: AnalysisContext,\n expression: ts.Expression,\n includeLocal = false,\n): ImportedExpressionBinding | undefined {\n const root = leftMostIdentifierNode(expression);\n if (!root) return undefined;\n const rootSymbol = context.checker.getSymbolAtLocation(root);\n if (!rootSymbol) return undefined;\n const declaration = rootSymbol.declarations?.find(isImportBindingDeclaration);\n if (!declaration) return undefined;\n const importDeclaration = enclosingImportDeclaration(declaration);\n if (!importDeclaration || !ts.isStringLiteral(importDeclaration.moduleSpecifier))\n return undefined;\n const source = sanitizeModuleSpecifier(importDeclaration.moduleSpecifier.text);\n const line = nodeLine(context.sourceFile, importDeclaration);\n const imported = context.file.imports.find(\n (record) =>\n record.kind === \"esm\" &&\n record.source === source &&\n record.line === line &&\n record.specifiers.some((specifier) => specifier.local === root.text),\n );\n if (!imported || (!includeLocal && !imported.external)) return undefined;\n const specifier = imported.specifiers.find((item) => item.local === root.text);\n if (!specifier) return undefined;\n return {\n module: imported.source,\n exported: ts.isPropertyAccessExpression(expression) ? expression.name.text : specifier.imported,\n imported: specifier.imported,\n ...(imported.resolved ? { resolved: imported.resolved } : {}),\n };\n}\n\nfunction isImportBindingDeclaration(declaration: ts.Declaration): boolean {\n return (\n ts.isImportSpecifier(declaration) ||\n ts.isImportClause(declaration) ||\n ts.isNamespaceImport(declaration)\n );\n}\n\nfunction enclosingImportDeclaration(declaration: ts.Declaration): ts.ImportDeclaration | undefined {\n let current: ts.Node = declaration;\n while (!ts.isSourceFile(current)) {\n if (ts.isImportDeclaration(current)) return current;\n current = current.parent;\n }\n return undefined;\n}\n\nfunction declarationToId(declaration: ts.Declaration, filePath: string): string | undefined {\n if (ts.isFunctionDeclaration(declaration)) {\n return symbolId(\"function\", filePath, declaration.name?.text ?? \"default\");\n }\n if (ts.isClassDeclaration(declaration)) {\n return symbolId(\"class\", filePath, declaration.name?.text ?? \"default\");\n }\n if (ts.isMethodDeclaration(declaration)) {\n const parent = declaration.parent;\n const parentName =\n ts.isClassDeclaration(parent) || ts.isInterfaceDeclaration(parent)\n ? (parent.name?.text ?? \"default\")\n : \"anonymous\";\n return symbolId(\n \"method\",\n filePath,\n propertyNameText(declaration.name) ?? \"anonymous\",\n parentName,\n );\n }\n if (ts.isVariableDeclaration(declaration)) {\n const name = getDeclarationName(declaration);\n const kind: SymbolKind =\n declaration.initializer &&\n (ts.isArrowFunction(declaration.initializer) ||\n ts.isFunctionExpression(declaration.initializer))\n ? \"function\"\n : \"variable\";\n return symbolId(kind, filePath, name);\n }\n if (ts.isInterfaceDeclaration(declaration))\n return symbolId(\"interface\", filePath, declaration.name.text);\n if (ts.isTypeAliasDeclaration(declaration))\n return symbolId(\"type-alias\", filePath, declaration.name.text);\n return undefined;\n}\n\nfunction isReferenceIdentifier(node: ts.Identifier): boolean {\n const parent = node.parent;\n if (\n (parent as ts.NamedDeclaration).name === node ||\n ts.isImportSpecifier(parent) ||\n ts.isImportClause(parent) ||\n ts.isNamespaceImport(parent) ||\n ts.isExportSpecifier(parent) ||\n ts.isBindingElement(parent) ||\n (ts.isPropertyAccessExpression(parent) && parent.name === node) ||\n (ts.isPropertyAssignment(parent) && parent.name === node) ||\n (ts.isPropertySignature(parent) && parent.name === node) ||\n (ts.isPropertyDeclaration(parent) && parent.name === node) ||\n (ts.isMethodDeclaration(parent) && parent.name === node)\n ) {\n return false;\n }\n return true;\n}\n\nfunction expressionFallbackId(expression: ts.Expression): string | undefined {\n if (ts.isIdentifier(expression)) return externalId(\"unresolved\", expression.text);\n if (ts.isPropertyAccessExpression(expression)) {\n return externalId(\"unresolved\", expression.name.text);\n }\n return undefined;\n}\n\nfunction leftMostIdentifierNode(expression: ts.Expression): ts.Identifier | undefined {\n let current = expression;\n while (ts.isPropertyAccessExpression(current)) current = current.expression;\n return ts.isIdentifier(current) ? current : undefined;\n}\n\nexport function extractFileStructure(context: AnalysisContext): Pick<\n FileRecord,\n \"imports\" | \"exports\" | \"env\" | \"operations\"\n> & {\n diagnostics: DiagnosticRecord[];\n relations: RelationRecord[];\n} {\n const imports: ImportRecord[] = [];\n const exports: ExportRecord[] = [];\n const env = new Set<string>();\n const operations: ExternalOperation[] = [];\n const diagnostics: DiagnosticRecord[] = [];\n const relations: RelationRecord[] = [];\n const importedModules = new Map<string, string>();\n\n for (const statement of context.sourceFile.statements) {\n if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {\n const rawSource = statement.moduleSpecifier.text;\n const source = sanitizeModuleSpecifier(rawSource);\n const specifiers = importSpecifiers(statement);\n for (const specifier of specifiers) importedModules.set(specifier.local, source);\n const resolved = resolveImport(context, rawSource);\n imports.push({\n source,\n specifiers,\n ...(resolved.path ? { resolved: resolved.path } : {}),\n external: resolved.external,\n kind: \"esm\",\n line: nodeLine(context.sourceFile, statement),\n });\n addImportRelation(context, relations, statement, source, resolved);\n if (!resolved.found && !isBuiltin(rawSource))\n diagnostics.push(unresolvedImport(context, statement, source));\n } else if (ts.isExportDeclaration(statement)) {\n extractExportDeclaration(context, statement, exports, relations);\n } else if (ts.isExportAssignment(statement)) {\n exports.push({\n name: \"default\",\n local: ts.isIdentifier(statement.expression) ? statement.expression.text : \"default\",\n default: true,\n line: nodeLine(context.sourceFile, statement),\n });\n }\n }\n\n visit(context.sourceFile, (node) => {\n if (ts.isCallExpression(node) && isRequireCall(node)) {\n const argument = node.arguments[0];\n if (!argument || !ts.isStringLiteral(argument)) return;\n const rawSource = argument.text;\n const source = sanitizeModuleSpecifier(rawSource);\n const resolved = resolveImport(context, rawSource);\n imports.push({\n source,\n specifiers: [],\n ...(resolved.path ? { resolved: resolved.path } : {}),\n external: resolved.external,\n kind: \"commonjs\",\n line: nodeLine(context.sourceFile, node),\n });\n addImportRelation(context, relations, node, source, resolved);\n if (!resolved.found && !isBuiltin(rawSource))\n diagnostics.push(unresolvedImport(context, node, source));\n }\n const envName = processEnvName(node);\n if (envName) env.add(envName);\n const operation = externalOperation(node, context.sourceFile, importedModules);\n if (operation) operations.push(operation);\n });\n\n extractCommonJsExports(context, exports);\n return {\n imports: dedupeImports(imports),\n exports: dedupeExports(exports),\n env: [...env].sort(compareText),\n operations: dedupeOperations(operations),\n diagnostics,\n relations,\n };\n}\n\nfunction importSpecifiers(statement: ts.ImportDeclaration): ImportRecord[\"specifiers\"] {\n const clause = statement.importClause;\n if (!clause) return [];\n const output: ImportRecord[\"specifiers\"] = [];\n const clauseTypeOnly = clause.phaseModifier === ts.SyntaxKind.TypeKeyword;\n if (clause.name) {\n output.push({\n imported: \"default\",\n local: clause.name.text,\n ...(clauseTypeOnly ? { typeOnly: true } : {}),\n });\n }\n const bindings = clause.namedBindings;\n if (bindings && ts.isNamespaceImport(bindings)) {\n output.push({\n imported: \"*\",\n local: bindings.name.text,\n ...(clauseTypeOnly ? { typeOnly: true } : {}),\n });\n } else if (bindings && ts.isNamedImports(bindings)) {\n for (const element of bindings.elements) {\n output.push({\n imported: element.propertyName?.text ?? element.name.text,\n local: element.name.text,\n ...(clauseTypeOnly || element.isTypeOnly ? { typeOnly: true } : {}),\n });\n }\n }\n return output.sort((a, b) => compareText(`${a.imported}:${a.local}`, `${b.imported}:${b.local}`));\n}\n\nfunction extractExportDeclaration(\n context: AnalysisContext,\n statement: ts.ExportDeclaration,\n exports: ExportRecord[],\n relations: RelationRecord[],\n): void {\n const rawSource =\n statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)\n ? statement.moduleSpecifier.text\n : undefined;\n const source = rawSource ? sanitizeModuleSpecifier(rawSource) : undefined;\n const line = nodeLine(context.sourceFile, statement);\n if (!statement.exportClause) {\n exports.push({ name: \"*\", ...(source ? { source } : {}), default: false, line });\n } else if (ts.isNamespaceExport(statement.exportClause)) {\n exports.push({\n name: statement.exportClause.name.text,\n ...(source ? { source } : {}),\n default: false,\n line,\n });\n } else {\n for (const element of statement.exportClause.elements) {\n exports.push({\n name: element.name.text,\n local: element.propertyName?.text ?? element.name.text,\n ...(source ? { source } : {}),\n default: element.name.text === \"default\",\n ...(statement.isTypeOnly || element.isTypeOnly ? { typeOnly: true } : {}),\n line,\n });\n }\n }\n if (rawSource && source) {\n const resolved = resolveImport(context, rawSource);\n relations.push(\n relation(\n fileId(context.relativePath),\n \"reexports\",\n resolved.path ? fileId(resolved.path) : externalId(source),\n context,\n statement,\n resolved.found ? 1 : 0.5,\n resolved.found ? \"resolved re-export\" : \"unresolved re-export\",\n ),\n );\n }\n}\n\nfunction extractCommonJsExports(context: AnalysisContext, exports: ExportRecord[]): void {\n visit(context.sourceFile, (node) => {\n if (!ts.isBinaryExpression(node) || node.operatorToken.kind !== ts.SyntaxKind.EqualsToken)\n return;\n const left = node.left;\n const line = nodeLine(context.sourceFile, node);\n if (\n ts.isPropertyAccessExpression(left) &&\n ts.isIdentifier(left.expression) &&\n left.expression.text === \"module\" &&\n left.name.text === \"exports\"\n ) {\n exports.push({\n name: \"default\",\n ...(ts.isIdentifier(node.right) ? { local: node.right.text } : {}),\n default: true,\n line,\n });\n } else if (\n ts.isPropertyAccessExpression(left) &&\n ((ts.isIdentifier(left.expression) && left.expression.text === \"exports\") ||\n (ts.isPropertyAccessExpression(left.expression) &&\n ts.isIdentifier(left.expression.expression) &&\n left.expression.expression.text === \"module\" &&\n left.expression.name.text === \"exports\"))\n ) {\n exports.push({\n name: left.name.text,\n local: ts.isIdentifier(node.right) ? node.right.text : left.name.text,\n default: false,\n line,\n });\n }\n });\n}\n\ninterface ImportResolution {\n found: boolean;\n external: boolean;\n path?: string;\n}\n\nfunction resolveImport(context: AnalysisContext, moduleName: string): ImportResolution {\n if (isBuiltin(moduleName) || moduleName.startsWith(\"node:\"))\n return { found: true, external: true };\n const resolution = context.resolveModule?.(moduleName, context.sourceFile.fileName);\n if (!resolution) return { found: false, external: !moduleName.startsWith(\".\") };\n if (resolution.isExternalLibraryImport) return { found: true, external: true };\n if (!isPathInside(context.root, resolution.resolvedFileName)) {\n return { found: true, external: true };\n }\n const relative = relativePosix(context.root, resolution.resolvedFileName);\n if (context.indexedSourcePaths && !context.indexedSourcePaths.has(relative)) {\n return { found: false, external: false };\n }\n return {\n found: true,\n external: false,\n path: relative,\n };\n}\n\nfunction addImportRelation(\n context: AnalysisContext,\n output: RelationRecord[],\n node: ts.Node,\n source: string,\n resolved: ImportResolution,\n): void {\n output.push(\n relation(\n fileId(context.relativePath),\n \"imports\",\n resolved.path ? fileId(resolved.path) : externalId(source),\n context,\n node,\n resolved.found ? 1 : 0.5,\n resolved.found ? \"module resolution\" : \"unresolved import text\",\n ),\n );\n}\n\nfunction unresolvedImport(\n context: AnalysisContext,\n node: ts.Node,\n source: string,\n): DiagnosticRecord {\n return {\n schemaVersion: SCHEMA_VERSION,\n code: \"unresolved-import\",\n severity: \"warning\",\n message: `Could not resolve import ${source}.`,\n file: context.relativePath,\n line: nodeLine(context.sourceFile, node),\n };\n}\n\nfunction processEnvName(node: ts.Node): string | undefined {\n if (\n ts.isPropertyAccessExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n ts.isIdentifier(node.expression.expression) &&\n node.expression.expression.text === \"process\" &&\n node.expression.name.text === \"env\"\n ) {\n return node.name.text;\n }\n if (\n ts.isElementAccessExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n ts.isIdentifier(node.expression.expression) &&\n node.expression.expression.text === \"process\" &&\n node.expression.name.text === \"env\" &&\n ts.isStringLiteral(node.argumentExpression)\n ) {\n return node.argumentExpression.text;\n }\n return undefined;\n}\n\nfunction externalOperation(\n node: ts.Node,\n sourceFile: ts.SourceFile,\n importedModules: Map<string, string>,\n): ExternalOperation | undefined {\n if (!ts.isCallExpression(node)) return undefined;\n let root: string | undefined;\n let api: string;\n if (ts.isIdentifier(node.expression)) {\n root = node.expression.text;\n api = root;\n } else if (ts.isPropertyAccessExpression(node.expression)) {\n root = leftMostIdentifierNode(node.expression)?.text;\n api = node.expression.getText(sourceFile);\n } else return undefined;\n const source = root ? importedModules.get(root) : undefined;\n let kind: ExternalOperation[\"kind\"] | undefined;\n if (\n root === \"fetch\" ||\n source === \"axios\" ||\n source === \"http\" ||\n source === \"https\" ||\n source?.startsWith(\"node:http\")\n )\n kind = \"http\";\n else if (source === \"fs\" || source === \"fs/promises\" || source?.startsWith(\"node:fs\"))\n kind = \"filesystem\";\n else if (source && /(?:prisma|typeorm|mongoose|sequelize|pg|mysql|database|redis)/i.test(source))\n kind = \"database\";\n else if (source && /(?:bull|queue|kafka|amqp|rabbit)/i.test(source)) kind = \"queue\";\n return kind ? { kind, api, line: nodeLine(sourceFile, node) } : undefined;\n}\n\nfunction isRequireCall(node: ts.CallExpression): boolean {\n return (\n ts.isIdentifier(node.expression) &&\n node.expression.text === \"require\" &&\n node.arguments.length > 0\n );\n}\n\nfunction dedupeImports(values: ImportRecord[]): ImportRecord[] {\n const map = new Map<string, ImportRecord>();\n for (const value of values) {\n map.set(`${value.kind}:${value.source}:${value.line}`, value);\n }\n return [...map.values()].sort((a, b) =>\n compareText(`${a.source}:${a.line}`, `${b.source}:${b.line}`),\n );\n}\n\nfunction dedupeExports(values: ExportRecord[]): ExportRecord[] {\n const map = new Map<string, ExportRecord>();\n for (const value of values) map.set(`${value.name}:${value.source ?? \"\"}:${value.line}`, value);\n return [...map.values()].sort((a, b) =>\n compareText(`${a.name}:${a.line}`, `${b.name}:${b.line}`),\n );\n}\n\nfunction dedupeOperations(values: ExternalOperation[]): ExternalOperation[] {\n const map = new Map<string, ExternalOperation>();\n for (const value of values) map.set(`${value.kind}:${value.api}:${value.line}`, value);\n return [...map.values()].sort((a, b) =>\n compareText(`${a.kind}:${a.line}:${a.api}`, `${b.kind}:${b.line}:${b.api}`),\n );\n}\n\nexport function relation(\n from: string,\n type: RelationRecord[\"type\"],\n to: string,\n context: AnalysisContext,\n node: ts.Node,\n confidence: number,\n explanation: string,\n): RelationRecord {\n return {\n schemaVersion: SCHEMA_VERSION,\n from,\n type,\n to,\n confidence,\n origin: {\n file: context.relativePath,\n line: nodeLine(context.sourceFile, node),\n range: nodeRange(context.sourceFile, node),\n explanation,\n classification: confidence === 1 ? \"exact\" : \"heuristic\",\n analyzer: \"typescript-node\",\n },\n };\n}\n","import ts from \"typescript\";\n\nimport { SCHEMA_VERSION } from \"../constants.js\";\nimport { symbolId } from \"../ids.js\";\nimport type {\n AnalysisContext,\n JsonValue,\n SourceRange,\n SymbolKind,\n SymbolRecord,\n} from \"../types.js\";\nimport { redactAbsolutePathsInText } from \"../utils/path.js\";\n\nexport function nodeRange(sourceFile: ts.SourceFile, node: ts.Node): SourceRange {\n const start = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile, false));\n const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n return {\n startLine: start.line + 1,\n startColumn: start.character + 1,\n endLine: end.line + 1,\n endColumn: end.character + 1,\n };\n}\n\nexport function nodeLine(sourceFile: ts.SourceFile, node: ts.Node): number {\n return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile, false)).line + 1;\n}\n\nexport function hasModifier(node: ts.Node, kind: ts.SyntaxKind): boolean {\n return Boolean(\n ts.canHaveModifiers(node) && ts.getModifiers(node)?.some((item) => item.kind === kind),\n );\n}\n\nexport function hasExportModifier(node: ts.Node): boolean {\n return hasModifier(node, ts.SyntaxKind.ExportKeyword);\n}\n\nexport function hasDefaultModifier(node: ts.Node): boolean {\n return hasModifier(node, ts.SyntaxKind.DefaultKeyword);\n}\n\nexport function getDeclarationName(node: ts.Declaration, fallback = \"default\"): string {\n const name = (node as ts.NamedDeclaration).name;\n if (name && ts.isIdentifier(name)) return name.text;\n if (name && (ts.isStringLiteral(name) || ts.isNumericLiteral(name))) return name.text;\n return fallback;\n}\n\nexport function getTopLevelDefaultExportDeclaration(\n sourceFile: ts.SourceFile,\n): ts.Declaration | undefined {\n for (const statement of sourceFile.statements) {\n if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) {\n const defaultName = statement.expression.text;\n const declaration = topLevelDeclarations(sourceFile).find(\n (item) => getDeclarationName(item, \"\") === defaultName,\n );\n if (declaration) return declaration;\n continue;\n }\n\n if (ts.isFunctionDeclaration(statement) && hasDefaultModifier(statement)) return statement;\n if (ts.isClassDeclaration(statement) && hasDefaultModifier(statement)) return statement;\n if (ts.isInterfaceDeclaration(statement) && hasDefaultModifier(statement)) return statement;\n if (ts.isTypeAliasDeclaration(statement) && hasDefaultModifier(statement)) return statement;\n if (ts.isEnumDeclaration(statement) && hasDefaultModifier(statement)) return statement;\n if (ts.isVariableStatement(statement) && hasDefaultModifier(statement)) {\n const declaration = statement.declarationList.declarations.find((item) =>\n ts.isIdentifier(item.name),\n );\n return declaration;\n }\n }\n return undefined;\n}\n\nexport function hasAnyTopLevelExport(sourceFile: ts.SourceFile): boolean {\n return sourceFile.statements.some(\n (statement) => ts.isExportAssignment(statement) || hasExportModifier(statement),\n );\n}\n\nfunction topLevelDeclarations(sourceFile: ts.SourceFile): ts.Declaration[] {\n return sourceFile.statements.flatMap((statement): ts.Declaration[] => {\n if (\n ts.isFunctionDeclaration(statement) ||\n ts.isClassDeclaration(statement) ||\n ts.isInterfaceDeclaration(statement) ||\n ts.isTypeAliasDeclaration(statement) ||\n ts.isEnumDeclaration(statement)\n ) {\n return [statement];\n }\n if (ts.isVariableStatement(statement)) return [...statement.declarationList.declarations];\n return [];\n });\n}\n\nexport function getSignature(context: AnalysisContext, node: ts.Node): string | undefined {\n const type = context.checker.getTypeAtLocation(node);\n const signatures = type.getCallSignatures();\n if (signatures.length > 0) {\n return [\n ...new Set(\n signatures.map((signature) =>\n context.checker.signatureToString(\n signature,\n node,\n ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,\n ),\n ),\n ),\n ]\n .map(redactStringLiterals)\n .join(\" | \");\n }\n if (ts.isClassDeclaration(node)) {\n return compactText(node.getText(context.sourceFile).split(/[\\r\\n{]/, 1)[0] ?? \"\");\n }\n if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) {\n return compactText(redactStringLiterals(node.getText(context.sourceFile)));\n }\n if (ts.isVariableDeclaration(node) && node.type) {\n return `${getDeclarationName(node)}: ${compactText(node.type.getText(context.sourceFile))}`;\n }\n return undefined;\n}\n\nexport function redactStringLiterals(value: string): string {\n return value.replace(/([\"'])(?:\\\\.|(?!\\1)[^\\\\\\r\\n])*\\1/g, '\"<literal>\"');\n}\n\nexport function makeSymbol(\n context: AnalysisContext,\n node: ts.Declaration | ts.SourceFile,\n kind: SymbolKind,\n options: {\n name?: string;\n parent?: string;\n exported?: boolean;\n defaultExport?: boolean;\n signature?: string;\n facts?: Record<string, JsonValue>;\n documentation?: string;\n } = {},\n): SymbolRecord {\n const name = options.name ?? (ts.isSourceFile(node) ? \"default\" : getDeclarationName(node));\n // Documentation is accepted only from an explicitly configured enricher. The base\n // scanner does not persist arbitrary JSDoc/source prose.\n const documentation = options.documentation;\n const signature =\n options.signature ?? (ts.isSourceFile(node) ? undefined : getSignature(context, node));\n const safeSignature = signature ? redactAbsolutePathsInText(signature, context.root) : undefined;\n const safeDocumentation = documentation\n ? redactAbsolutePathsInText(documentation, context.root)\n : undefined;\n return {\n schemaVersion: SCHEMA_VERSION,\n id: symbolId(kind, context.relativePath, name, options.parent),\n name,\n kind,\n file: context.relativePath,\n range: nodeRange(context.sourceFile, node),\n exported: options.exported ?? (!ts.isSourceFile(node) && hasExportModifier(node)),\n ...((options.defaultExport ?? (!ts.isSourceFile(node) && hasDefaultModifier(node)))\n ? { defaultExport: true }\n : {}),\n ...(safeSignature ? { signature: compactText(safeSignature) } : {}),\n ...(safeDocumentation ? { documentation: compactText(safeDocumentation) } : {}),\n facts: options.facts ?? {},\n sourceHash: context.sourceHash,\n };\n}\n\nexport function compactText(value: string, maxLength = 500): string {\n const compact = value.replace(/\\s+/g, \" \").trim();\n return compact.length > maxLength ? `${compact.slice(0, maxLength - 1)}…` : compact;\n}\n\nexport function visit(node: ts.Node, callback: (node: ts.Node) => void): void {\n callback(node);\n node.forEachChild((child) => visit(child, callback));\n}\n\nexport function decoratorName(decorator: ts.Decorator): string | undefined {\n const expression = decorator.expression;\n const target = ts.isCallExpression(expression) ? expression.expression : expression;\n return ts.isIdentifier(target) ? target.text : undefined;\n}\n\nexport function decoratorsOf(node: ts.Node): readonly ts.Decorator[] {\n return ts.canHaveDecorators(node) ? (ts.getDecorators(node) ?? []) : [];\n}\n\nexport function literalText(expression: ts.Expression | undefined): string | undefined {\n return expression &&\n (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression))\n ? expression.text\n : undefined;\n}\n\nexport function identifierText(expression: ts.Expression | undefined): string | undefined {\n return expression && ts.isIdentifier(expression) ? expression.text : undefined;\n}\n\nexport function propertyNameText(name: ts.PropertyName | undefined): string | undefined {\n if (!name) return undefined;\n if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name))\n return name.text;\n return undefined;\n}\n","import ts from \"typescript\";\n\nimport { SCHEMA_VERSION } from \"../constants.js\";\nimport { routeId, symbolId } from \"../ids.js\";\nimport type {\n AnalysisContribution,\n AnalysisContext,\n FrameworkAnalyzer,\n RelationRecord,\n} from \"../types.js\";\nimport {\n compactText,\n decoratorsOf,\n hasDefaultModifier,\n hasExportModifier,\n makeSymbol,\n nodeLine,\n nodeRange,\n} from \"./helpers.js\";\n\nconst METHOD_DECORATORS = new Set([\n \"Get\",\n \"Post\",\n \"Put\",\n \"Patch\",\n \"Delete\",\n \"Head\",\n \"Options\",\n \"All\",\n]);\nconst NEST_DECORATORS = new Set([\n \"Module\",\n \"Controller\",\n \"Injectable\",\n \"Guard\",\n \"UseGuards\",\n \"Body\",\n \"Param\",\n ...METHOD_DECORATORS,\n]);\n\ninterface ImportAliasMap {\n named: Record<string, string>;\n namespaces: Set<string>;\n}\n\ninterface ModuleMetadata {\n controllers: string[];\n providers: string[];\n imports: string[];\n exports: string[];\n}\n\nconst registeredNestJsAnalyzers = new WeakSet();\n\nexport class NestJsAnalyzer implements FrameworkAnalyzer {\n readonly name = \"nestjs\";\n readonly version = \"0.1.0-experimental\";\n\n constructor() {\n registeredNestJsAnalyzers.add(this);\n }\n\n supports(context: AnalysisContext): boolean {\n if (!context.relativePath.endsWith(\".ts\")) return false;\n return hasAnyNestImport(context.sourceFile) || containsReferencedBodyDto(context);\n }\n\n analyze(context: AnalysisContext): AnalysisContribution {\n const symbols: AnalysisContribution[\"symbols\"] = [];\n const relations: RelationRecord[] = [];\n const bodyDtoSymbolIds = collectBodyDtoSymbolIds(context);\n\n const aliases = collectImportAliases(context.sourceFile);\n const moduleMembership = collectModuleMembership(context);\n\n for (const statement of context.sourceFile.statements) {\n if (!ts.isClassDeclaration(statement) || !statement.name) continue;\n\n const className = statement.name.text;\n const decoratorNames = collectDecoratorNames(decoratorsOf(statement), aliases);\n const kind = classifyClass(\n className,\n decoratorNames,\n symbolId(\"dto\", context.relativePath, className),\n bodyDtoSymbolIds,\n );\n\n if (kind === \"dto\") {\n symbols.push(\n makeSymbol(context, statement, \"dto\", {\n name: className,\n exported: hasExportModifier(statement),\n defaultExport: hasDefaultModifier(statement),\n facts: {\n name: className.toLowerCase(),\n kind: \"dto\",\n },\n }),\n );\n continue;\n }\n\n if (!kind) continue;\n\n const symbol = makeSymbol(context, statement, kind, {\n name: className,\n exported: hasExportModifier(statement),\n defaultExport: hasDefaultModifier(statement),\n facts: {\n name: className.toLowerCase(),\n kind,\n },\n });\n symbols.push(symbol);\n\n if (kind === \"nest-module\") {\n const metadata = collectModuleMetadata(statement, aliases);\n if (metadata.controllers.length > 0) {\n symbol.facts.controllers = compactText(metadata.controllers.join(\",\"));\n for (const controller of metadata.controllers) {\n const controllerId = resolveLocalClassId(context, controller, \"nest-controller\");\n if (!controllerId) continue;\n relations.push(\n makeRelation(\n symbol.id,\n \"contains\",\n controllerId,\n context,\n statement,\n 1,\n \"module controller\",\n ),\n );\n }\n }\n if (metadata.providers.length > 0) {\n symbol.facts.providers = compactText(metadata.providers.join(\",\"));\n for (const provider of metadata.providers) {\n const providerId = resolveLocalClassId(context, provider, \"nest-provider\");\n if (!providerId) continue;\n relations.push(\n makeRelation(\n symbol.id,\n \"contains\",\n providerId,\n context,\n statement,\n 1,\n \"module provider\",\n ),\n );\n }\n }\n if (metadata.imports.length > 0) {\n symbol.facts.imports = compactText(metadata.imports.join(\",\"));\n }\n if (metadata.exports.length > 0) {\n symbol.facts.exports = compactText(metadata.exports.join(\",\"));\n }\n }\n\n if (kind === \"nest-controller\") {\n const baseRoute = collectControllerRoute(statement, aliases);\n symbol.facts.baseRoute = baseRoute;\n symbol.facts.kind = \"controller\";\n\n const controllerRoutes = collectControllerMethods(context, statement, className, aliases);\n relations.push(...controllerRoutes.relations);\n if (controllerRoutes.summary.length > 0) {\n symbol.facts.routes = compactText(controllerRoutes.summary.join(\",\"));\n }\n\n const guards = collectClassUseGuards(statement, aliases);\n if (guards.length > 0) {\n symbol.facts.guards = compactText(guards.join(\",\"));\n }\n }\n\n for (const injected of collectConstructorInjections(context, statement)) {\n relations.push(\n makeRelation(\n symbol.id,\n \"injects\",\n injected,\n context,\n statement,\n 1,\n \"constructor injection\",\n ),\n );\n }\n\n const moduleId = moduleMembership.get(className);\n if (moduleId) {\n relations.push(\n makeRelation(\n symbol.id,\n \"belongs-to-module\",\n moduleId,\n context,\n statement,\n 1,\n \"module membership\",\n ),\n );\n }\n }\n\n return { symbols, relations, frameworks: [\"nestjs\"] };\n }\n}\n\nconst nestJsSupports = NestJsAnalyzer.prototype.supports.bind(NestJsAnalyzer.prototype);\nconst nestJsAnalyze = NestJsAnalyzer.prototype.analyze.bind(NestJsAnalyzer.prototype);\n\n/** Return immutable canonical methods only for an unmodified, directly constructed instance. */\nexport function trustedNestJsAnalyzerMethods(analyzer: FrameworkAnalyzer):\n | {\n supports(context: AnalysisContext): boolean;\n analyze(context: AnalysisContext): AnalysisContribution | Promise<AnalysisContribution>;\n }\n | undefined {\n if (!registeredNestJsAnalyzers.has(analyzer)) return undefined;\n if (Object.getPrototypeOf(analyzer) !== NestJsAnalyzer.prototype) return undefined;\n if (Object.hasOwn(analyzer, \"supports\") || Object.hasOwn(analyzer, \"analyze\")) {\n return undefined;\n }\n const name = Object.getOwnPropertyDescriptor(analyzer, \"name\");\n const version = Object.getOwnPropertyDescriptor(analyzer, \"version\");\n if (name?.value !== \"nestjs\" || version?.value !== \"0.1.0-experimental\") return undefined;\n return {\n supports: (context) => nestJsSupports(context),\n analyze: (context) => nestJsAnalyze(context),\n };\n}\n\nexport default NestJsAnalyzer;\n\nfunction hasAnyNestImport(sourceFile: ts.SourceFile): boolean {\n return sourceFile.statements.some(\n (statement) =>\n ts.isImportDeclaration(statement) &&\n ts.isStringLiteral(statement.moduleSpecifier) &&\n statement.moduleSpecifier.text.startsWith(\"@nestjs/\"),\n );\n}\n\nfunction collectImportAliases(sourceFile: ts.SourceFile): ImportAliasMap {\n const aliases: ImportAliasMap = {\n named: {},\n namespaces: new Set<string>(),\n };\n for (const statement of sourceFile.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))\n continue;\n if (!statement.moduleSpecifier.text.startsWith(\"@nestjs/\")) continue;\n const clause = statement.importClause;\n if (!clause || !clause.namedBindings) continue;\n if (ts.isNamespaceImport(clause.namedBindings)) {\n aliases.namespaces.add(clause.namedBindings.name.text);\n continue;\n }\n if (!ts.isNamedImports(clause.namedBindings)) continue;\n for (const item of clause.namedBindings.elements) {\n aliases.named[item.name.text] = item.propertyName ? item.propertyName.text : item.name.text;\n }\n }\n return aliases;\n}\n\nfunction classifyClass(\n className: string,\n decorators: string[],\n symbolIdValue: string,\n dtoSymbolIds: Set<string>,\n):\n | \"nest-module\"\n | \"nest-controller\"\n | \"nest-provider\"\n | \"nest-guard\"\n | \"nest-interceptor\"\n | \"nest-pipe\"\n | \"nest-filter\"\n | \"nest-gateway\"\n | \"dto\"\n | undefined {\n if (dtoSymbolIds.has(symbolIdValue)) return \"dto\";\n if (decorators.includes(\"Module\")) return \"nest-module\";\n if (decorators.includes(\"Controller\")) return \"nest-controller\";\n if (!decorators.includes(\"Injectable\")) return undefined;\n if (className.endsWith(\"Guard\")) return \"nest-guard\";\n if (className.endsWith(\"Interceptor\")) return \"nest-interceptor\";\n if (className.endsWith(\"Pipe\")) return \"nest-pipe\";\n if (className.endsWith(\"Filter\")) return \"nest-filter\";\n if (className.endsWith(\"Gateway\")) return \"nest-gateway\";\n return \"nest-provider\";\n}\n\nfunction collectDecoratorNames(\n decorators: readonly ts.Decorator[],\n aliases: ImportAliasMap,\n): string[] {\n const names: string[] = [];\n for (const decorator of decorators) {\n const name = resolveDecoratorName(decorator.expression, aliases);\n if (name && NEST_DECORATORS.has(name)) {\n names.push(name);\n }\n }\n return names;\n}\n\nfunction resolveDecoratorName(\n expression: ts.Expression,\n aliases: ImportAliasMap,\n): string | undefined {\n const target = ts.isCallExpression(expression) ? expression.expression : expression;\n if (ts.isIdentifier(target)) {\n const resolved = aliases.named[target.text];\n if (resolved) return resolved;\n return undefined;\n }\n if (ts.isPropertyAccessExpression(target) && ts.isIdentifier(target.expression)) {\n if (aliases.namespaces.has(target.expression.text)) return target.name.text;\n }\n return undefined;\n}\n\nfunction collectControllerRoute(classNode: ts.ClassDeclaration, aliases: ImportAliasMap): string {\n for (const decorator of decoratorsOf(classNode)) {\n const expression = decorator.expression;\n const call = ts.isCallExpression(expression) ? expression : undefined;\n if (!call) continue;\n const name = resolveDecoratorName(expression, aliases);\n if (!name) continue;\n if (name !== \"Controller\") continue;\n const arg = call.arguments[0];\n if (!arg) return \"/\";\n if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {\n const value = arg.text.trim();\n return value.startsWith(\"/\") ? value : `/${value}`;\n }\n }\n return \"/\";\n}\n\nfunction collectControllerMethods(\n context: AnalysisContext,\n controller: ts.ClassDeclaration,\n className: string,\n aliases: ImportAliasMap,\n): { relations: RelationRecord[]; summary: string[] } {\n const relations: RelationRecord[] = [];\n const summary: string[] = [];\n const baseRoute = collectControllerRoute(controller, aliases);\n\n for (const member of controller.members) {\n if (!ts.isMethodDeclaration(member) || !ts.isIdentifier(member.name)) continue;\n\n const methodName = member.name.text;\n const methodDecorators = collectDecoratorNames(decoratorsOf(member), aliases);\n const methodVerbs = methodDecorators.filter((name) => METHOD_DECORATORS.has(name));\n if (methodVerbs.length === 0) continue;\n\n const methodRoute = collectMethodRoute(member, aliases);\n const fullRoute = combineRoutes(baseRoute, methodRoute);\n\n for (const verb of methodVerbs) {\n const lower = verb.toLowerCase();\n const methodId = symbolId(\"method\", context.relativePath, methodName, className);\n relations.push(\n makeRelation(\n methodId,\n \"handles-route\",\n routeId(lower, fullRoute),\n context,\n member,\n 1,\n \"http method route\",\n ),\n );\n summary.push(`${lower} ${fullRoute}`);\n\n const dto = collectBodyDto(member, aliases, context);\n if (dto) {\n relations.push(\n makeRelation(methodId, \"consumes-dto\", dto, context, member, 1, \"dto usage\"),\n );\n }\n }\n }\n\n return { relations, summary: dedupe(summary) };\n\n function collectMethodRoute(\n methodNode: ts.MethodDeclaration,\n aliasesMap: ImportAliasMap,\n ): string {\n for (const decorator of decoratorsOf(methodNode)) {\n const expression = decorator.expression;\n const call = ts.isCallExpression(expression) ? expression : undefined;\n if (!call) continue;\n const name = resolveDecoratorName(expression, aliasesMap);\n if (!name) continue;\n if (!METHOD_DECORATORS.has(name)) continue;\n const arg = call.arguments[0];\n if (!arg) return \"/\";\n if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {\n const route = arg.text.trim();\n return route.startsWith(\"/\") ? route : `/${route}`;\n }\n }\n return \"/\";\n }\n}\n\nfunction collectBodyDto(\n method: ts.MethodDeclaration,\n aliases: ImportAliasMap,\n context: AnalysisContext,\n): string | undefined {\n return collectBodyDtoFromMethod(method, aliases, context);\n}\n\nfunction collectBodyDtoSymbolIds(context: AnalysisContext): Set<string> {\n const ids = new Set<string>();\n for (const source of context.program\n .getSourceFiles()\n .filter((source) => !source.isDeclarationFile)) {\n if (!hasAnyNestImport(source)) continue;\n const sourceRelative = relativeFromAbsolute(context.root, source.fileName);\n if (!sourceRelative) continue;\n const aliases = collectImportAliases(source);\n for (const statement of source.statements) {\n if (!ts.isClassDeclaration(statement)) continue;\n for (const member of statement.members) {\n if (!ts.isMethodDeclaration(member)) continue;\n const dtoId = collectBodyDtoFromMethod(member, aliases, context);\n if (dtoId) ids.add(dtoId);\n }\n }\n }\n return ids;\n}\n\nfunction collectBodyDtoFromMethod(\n method: ts.MethodDeclaration,\n aliases: ImportAliasMap,\n context: AnalysisContext,\n): string | undefined {\n const param = method.parameters.find((item) => hasDecorator(item, \"Body\", aliases));\n if (!param?.type || !ts.isTypeReferenceNode(param.type) || !ts.isIdentifier(param.type.typeName))\n return undefined;\n\n const declaration = resolveIdentifierDeclaration(context, param.type.typeName);\n if (!declaration || !ts.isClassDeclaration(declaration) || !declaration.name) return undefined;\n const relative = relativeFromRoot(context, declaration.getSourceFile().fileName);\n if (!relative) return undefined;\n\n return symbolId(\"dto\", relative, declaration.name.text);\n}\n\nfunction containsReferencedBodyDto(context: AnalysisContext): boolean {\n const dtoIds = collectBodyDtoSymbolIds(context);\n return context.sourceFile.statements.some(\n (statement) =>\n ts.isClassDeclaration(statement) &&\n statement.name !== undefined &&\n dtoIds.has(symbolId(\"dto\", context.relativePath, statement.name.text)),\n );\n}\n\nfunction resolveIdentifierDeclaration(\n context: AnalysisContext,\n identifier: ts.Identifier,\n): ts.Declaration | undefined {\n let symbol = context.checker.getSymbolAtLocation(identifier);\n if (!symbol) return undefined;\n if ((symbol.flags & ts.SymbolFlags.Alias) !== 0) {\n symbol = context.checker.getAliasedSymbol(symbol);\n }\n return symbol.valueDeclaration ?? symbol.declarations?.[0];\n}\n\nfunction resolveLocalClassId(\n context: AnalysisContext,\n localName: string,\n kind: \"nest-controller\" | \"nest-provider\",\n): string | undefined {\n const identifier = findTopLevelIdentifier(context.sourceFile, localName);\n if (!identifier) return undefined;\n const declaration = resolveIdentifierDeclaration(context, identifier);\n if (!declaration || !ts.isClassDeclaration(declaration) || !declaration.name) return undefined;\n const relative = relativeFromRoot(context, declaration.getSourceFile().fileName);\n if (!relative) return undefined;\n return symbolId(kind, relative, declaration.name.text);\n}\n\nfunction findTopLevelIdentifier(\n sourceFile: ts.SourceFile,\n localName: string,\n): ts.Identifier | undefined {\n for (const statement of sourceFile.statements) {\n if (ts.isClassDeclaration(statement) && statement.name?.text === localName) {\n return statement.name;\n }\n if (!ts.isImportDeclaration(statement)) continue;\n const clause = statement.importClause;\n if (clause?.name?.text === localName) return clause.name;\n if (!clause?.namedBindings || !ts.isNamedImports(clause.namedBindings)) continue;\n const match = clause.namedBindings.elements.find((item) => item.name.text === localName);\n if (match) return match.name;\n }\n return undefined;\n}\n\nfunction relativeFromAbsolute(root: string, absolutePath: string): string | undefined {\n const normalized = absolutePath.replace(/\\\\/g, \"/\");\n const normalizedRoot = root.replace(/\\\\/g, \"/\");\n if (normalized !== normalizedRoot && !normalized.startsWith(`${normalizedRoot}/`))\n return undefined;\n const remainder = normalized.slice(normalizedRoot.length);\n return remainder.startsWith(\"/\") ? remainder.slice(1) : remainder;\n}\n\nfunction hasDecorator(\n parameter: ts.ParameterDeclaration,\n target: string,\n aliases: ImportAliasMap,\n): boolean {\n for (const decorator of decoratorsOf(parameter)) {\n const resolved = resolveDecoratorName(decorator.expression, aliases);\n if (resolved === target) return true;\n }\n return false;\n}\n\nfunction collectConstructorInjections(\n context: AnalysisContext,\n classNode: ts.ClassDeclaration,\n): string[] {\n const constructorNode = classNode.members.find(ts.isConstructorDeclaration);\n if (!constructorNode) return [];\n\n const dependencies: string[] = [];\n for (const parameter of constructorNode.parameters) {\n if (\n !parameter.type ||\n !ts.isTypeReferenceNode(parameter.type) ||\n !ts.isIdentifier(parameter.type.typeName)\n )\n continue;\n\n const declaration = resolveIdentifierDeclaration(context, parameter.type.typeName);\n if (!declaration) continue;\n const relative = relativeFromRoot(context, declaration.getSourceFile().fileName);\n if (!relative) continue;\n const targetName =\n ts.isClassDeclaration(declaration) && declaration.name\n ? declaration.name.text\n : parameter.type.typeName.text;\n dependencies.push(symbolId(\"nest-provider\", relative, targetName));\n }\n\n return dedupe(dependencies);\n}\n\nfunction collectModuleMetadata(\n classNode: ts.ClassDeclaration,\n aliases: ImportAliasMap,\n): ModuleMetadata {\n const defaults: ModuleMetadata = { controllers: [], providers: [], imports: [], exports: [] };\n for (const decorator of decoratorsOf(classNode)) {\n const expression = decorator.expression;\n const call = ts.isCallExpression(expression) ? expression : undefined;\n if (!call) continue;\n\n const name = resolveDecoratorName(expression, aliases);\n if (!name) continue;\n if (name !== \"Module\" || call.arguments.length === 0) continue;\n const arg = call.arguments[0];\n if (!arg || !ts.isObjectLiteralExpression(arg)) continue;\n\n for (const property of arg.properties) {\n if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property))\n continue;\n const propertyName = ts.isIdentifier(property.name)\n ? property.name.text\n : ts.isStringLiteral(property.name)\n ? property.name.text\n : undefined;\n if (!propertyName) continue;\n\n if (!(propertyName in defaults)) continue;\n const assigned = ts.isPropertyAssignment(property) ? property.initializer : property.name;\n if (propertyName === \"controllers\") {\n defaults.controllers.push(...collectIdentifiers(assigned));\n }\n if (propertyName === \"providers\") {\n defaults.providers.push(...collectIdentifiers(assigned));\n }\n if (propertyName === \"imports\") {\n defaults.imports.push(...collectIdentifiers(assigned));\n }\n if (propertyName === \"exports\") {\n defaults.exports.push(...collectIdentifiers(assigned));\n }\n }\n }\n\n return {\n controllers: dedupe(defaults.controllers),\n providers: dedupe(defaults.providers),\n imports: dedupe(defaults.imports),\n exports: dedupe(defaults.exports),\n };\n}\n\nfunction collectIdentifiers(node: ts.Expression | ts.BindingName): string[] {\n if (ts.isIdentifier(node)) return [node.text];\n if (ts.isPropertyAccessExpression(node)) return [node.name.text];\n if (ts.isArrayLiteralExpression(node)) {\n return node.elements\n .map((item) =>\n ts.isIdentifier(item)\n ? item.text\n : ts.isPropertyAccessExpression(item)\n ? item.name.text\n : undefined,\n )\n .filter((value): value is string => Boolean(value));\n }\n return [];\n}\n\nfunction collectModuleMembership(context: AnalysisContext): Map<string, string> {\n const mapping = new Map<string, string>();\n for (const source of context.program.getSourceFiles().filter((file) => !file.isDeclarationFile)) {\n const aliases = collectImportAliases(source);\n for (const statement of source.statements) {\n if (!ts.isClassDeclaration(statement) || !statement.name) continue;\n const decorators = collectDecoratorNames(decoratorsOf(statement), aliases);\n if (!decorators.includes(\"Module\")) continue;\n\n const metadata = collectModuleMetadata(statement, aliases);\n const moduleId = symbolId(\n \"nest-module\",\n relativeFromRoot(context, source.fileName) ?? context.relativePath,\n statement.name.text,\n );\n for (const child of [...metadata.controllers, ...metadata.providers]) {\n mapping.set(child, moduleId);\n }\n }\n }\n\n return mapping;\n}\n\nfunction collectClassUseGuards(classNode: ts.ClassDeclaration, aliases: ImportAliasMap): string[] {\n const names: string[] = [];\n for (const decorator of decoratorsOf(classNode)) {\n const expression = decorator.expression;\n const call = ts.isCallExpression(expression) ? expression : undefined;\n if (!call) continue;\n const name = resolveDecoratorName(expression, aliases);\n if (!name) continue;\n if (name !== \"UseGuards\") continue;\n for (const arg of call.arguments) {\n if (ts.isIdentifier(arg)) names.push(arg.text);\n }\n }\n return dedupe(names);\n}\n\nfunction dedupe(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction combineRoutes(base: string, child: string): string {\n const segments = [base, child].map((value) => value.replace(/^\\/+|\\/+$/g, \"\")).filter(Boolean);\n return segments.length > 0 ? `/${segments.join(\"/\")}` : \"/\";\n}\n\nfunction makeRelation(\n from: string,\n type: RelationRecord[\"type\"],\n to: string,\n context: AnalysisContext,\n node: ts.Node,\n confidence: number,\n explanation: string,\n): RelationRecord {\n return {\n schemaVersion: SCHEMA_VERSION,\n from,\n type,\n to,\n confidence,\n origin: {\n file: context.relativePath,\n line: nodeLine(context.sourceFile, node),\n range: nodeRange(context.sourceFile, node),\n explanation,\n classification: confidence === 1 ? \"framework-derived\" : \"heuristic\",\n analyzer: \"nestjs\",\n },\n };\n}\n\nfunction relativeFromRoot(context: AnalysisContext, absolutePath: string): string | undefined {\n const normalized = absolutePath.replace(/\\\\/g, \"/\");\n const root = context.root.replace(/\\\\/g, \"/\");\n if (normalized !== root && !normalized.startsWith(`${root}/`)) return undefined;\n const remainder = normalized.slice(root.length);\n return remainder.startsWith(\"/\") ? remainder.slice(1) : remainder;\n}\n","import path from \"node:path\";\n\nimport ts from \"typescript\";\n\nimport { SCHEMA_VERSION } from \"../constants.js\";\nimport { symbolId } from \"../ids.js\";\nimport type {\n AnalysisContribution,\n AnalysisContext,\n FrameworkAnalyzer,\n RelationRecord,\n} from \"../types.js\";\nimport {\n compactText,\n getDeclarationName,\n getTopLevelDefaultExportDeclaration,\n hasAnyTopLevelExport,\n makeSymbol,\n nodeLine,\n nodeRange,\n} from \"./helpers.js\";\n\nconst ROUTE_GROUP_SEGMENT = /^\\(.*\\)$/;\nconst ROUTE_METHODS = new Set([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\"]);\nconst APP_FILES_EXTENSIONS = new Set([\".ts\", \".tsx\", \".js\", \".jsx\"]);\n\ntype NextRouter = \"app\" | \"pages\";\ntype NextKind = \"page\" | \"layout\" | \"route\" | \"special\";\n\ninterface ParsedNextRoute {\n router: NextRouter;\n kind: NextKind;\n route: string;\n name: string;\n params: string[];\n}\n\nconst registeredNextJsAnalyzers = new WeakSet();\n\nexport class NextJsAnalyzer implements FrameworkAnalyzer {\n readonly name = \"nextjs\";\n readonly version = \"0.1.0-experimental\";\n\n constructor() {\n registeredNextJsAnalyzers.add(this);\n }\n\n supports(context: AnalysisContext): boolean {\n if (!APP_FILES_EXTENSIONS.has(path.extname(context.relativePath).toLowerCase())) return false;\n return (\n context.relativePath.startsWith(\"app/\") ||\n context.relativePath.startsWith(\"pages/\") ||\n context.relativePath === \"middleware.ts\"\n );\n }\n\n analyze(context: AnalysisContext): AnalysisContribution {\n const sourceFile = context.sourceFile;\n const route = parseNextRoute(context.relativePath);\n const defaultExportNode = getTopLevelDefaultExportDeclaration(sourceFile);\n const hasTopLevelExport = hasAnyTopLevelExport(sourceFile);\n const symbols: AnalysisContribution[\"symbols\"] = [];\n const relations: RelationRecord[] = [];\n\n if (!route) {\n return { symbols, relations, frameworks: [\"nextjs\"] };\n }\n\n if (route.kind === \"page\") {\n const pageFacts = pageFactsForRoute(context, route);\n const symbol = makeSymbol(context, defaultExportNode ?? sourceFile, \"next-page\", {\n name: defaultExportNode ? getDeclarationName(defaultExportNode, route.name) : route.name,\n defaultExport: Boolean(defaultExportNode),\n exported: hasTopLevelExport,\n facts: pageFacts,\n });\n symbols.push(symbol);\n\n if (route.router === \"app\") {\n for (const layout of collectContainingAppLayouts(context.relativePath, context)) {\n relations.push(\n makeRelation(\n symbol.id,\n \"uses-layout\",\n symbolId(\"next-layout\", layout, \"layout\"),\n context,\n sourceFile,\n 1,\n \"app route layout chain\",\n ),\n );\n }\n }\n return { symbols, relations, frameworks: [\"nextjs\"] };\n }\n\n if (route.kind === \"layout\") {\n symbols.push(\n makeSymbol(context, defaultExportNode ?? sourceFile, \"next-layout\", {\n exported: hasTopLevelExport,\n defaultExport: Boolean(defaultExportNode),\n name: \"layout\",\n facts: {\n router: route.router,\n route: route.route,\n runtime: runtimeFromSource(sourceFile),\n params: route.params.join(\",\"),\n metadata: compactText(collectMetadataMarkers(sourceFile).join(\",\")),\n },\n }),\n );\n return { symbols, relations, frameworks: [\"nextjs\"] };\n }\n\n if (route.kind === \"route\") {\n const methods = collectRouteMethods(sourceFile);\n symbols.push(\n makeSymbol(context, sourceFile, \"next-route-handler\", {\n exported: hasTopLevelExport,\n name: \"route-handler\",\n facts: {\n router: route.router,\n route: route.route,\n methods,\n runtime: runtimeFromSource(sourceFile),\n metadata: compactText(collectMetadataMarkers(sourceFile).join(\",\")),\n },\n }),\n );\n return { symbols, relations, frameworks: [\"nextjs\"] };\n }\n\n symbols.push(\n makeSymbol(context, sourceFile, \"next-special-file\", {\n exported: hasTopLevelExport,\n name: route.name,\n facts: {\n router: route.router,\n route: route.route,\n runtime: runtimeFromSource(sourceFile),\n },\n }),\n );\n\n return { symbols, relations, frameworks: [\"nextjs\"] };\n }\n}\n\nconst nextJsSupports = NextJsAnalyzer.prototype.supports.bind(NextJsAnalyzer.prototype);\nconst nextJsAnalyze = NextJsAnalyzer.prototype.analyze.bind(NextJsAnalyzer.prototype);\n\n/** Return immutable canonical methods only for an unmodified, directly constructed instance. */\nexport function trustedNextJsAnalyzerMethods(analyzer: FrameworkAnalyzer):\n | {\n supports(context: AnalysisContext): boolean;\n analyze(context: AnalysisContext): AnalysisContribution | Promise<AnalysisContribution>;\n }\n | undefined {\n if (!registeredNextJsAnalyzers.has(analyzer)) return undefined;\n if (Object.getPrototypeOf(analyzer) !== NextJsAnalyzer.prototype) return undefined;\n if (Object.hasOwn(analyzer, \"supports\") || Object.hasOwn(analyzer, \"analyze\")) {\n return undefined;\n }\n const name = Object.getOwnPropertyDescriptor(analyzer, \"name\");\n const version = Object.getOwnPropertyDescriptor(analyzer, \"version\");\n if (name?.value !== \"nextjs\" || version?.value !== \"0.1.0-experimental\") return undefined;\n return {\n supports: (context) => nextJsSupports(context),\n analyze: (context) => nextJsAnalyze(context),\n };\n}\n\nexport default NextJsAnalyzer;\n\nfunction parseNextRoute(relativePath: string): ParsedNextRoute | undefined {\n const normalized = relativePath.replace(/\\\\/g, \"/\");\n if (!normalized.startsWith(\"app/\") && !normalized.startsWith(\"pages/\")) return undefined;\n\n const router: NextRouter = normalized.startsWith(\"app/\") ? \"app\" : \"pages\";\n const segments = normalized.split(\"/\").filter(Boolean);\n const fileName = segments.at(-1);\n if (!fileName) return undefined;\n const fileBase = fileName.replace(/\\.(ts|tsx|js|jsx)$/, \"\");\n\n if (router === \"app\") {\n const routeSegments = segments.slice(1, -1);\n const baseRoute = buildRouteFromSegments(routeSegments);\n\n if (fileBase === \"layout\") {\n return {\n router,\n kind: \"layout\",\n route: baseRoute,\n name: \"layout\",\n params: dynamicSegmentNames(routeSegments),\n };\n }\n\n if (fileBase === \"page\") {\n return {\n router,\n kind: \"page\",\n route: baseRoute,\n name: baseRoute.split(\"/\")[baseRoute.split(\"/\").length - 1] || \"page\",\n params: dynamicSegmentNames(routeSegments),\n };\n }\n\n if (fileBase === \"route\") {\n return {\n router,\n kind: \"route\",\n route: baseRoute,\n name: \"route\",\n params: dynamicSegmentNames(routeSegments),\n };\n }\n\n if (fileBase.startsWith(\"_\")) {\n return {\n router,\n kind: \"special\",\n route: \"/_\" + fileBase.replace(/^_/, \"\"),\n name: fileName,\n params: [],\n };\n }\n\n return undefined;\n }\n\n const pageSegments = segments.slice(1);\n if (pageSegments.length === 0) return undefined;\n const isApi = pageSegments[0] === \"api\";\n const routeSegments = pageSegments.slice(0, pageSegments.length - 1);\n const route = `/${buildRouteFromSegments([...routeSegments, fileBase === \"index\" ? \"\" : fileBase].filter(Boolean)).replace(/^\\//, \"\")}`;\n\n return {\n router,\n kind: isApi ? \"route\" : \"page\",\n route,\n name: route.split(\"/\")[route.split(\"/\").length - 1] || \"page\",\n params: [...routeSegments, fileBase].filter(isDynamicSegment).map(stripDynamicMarkers),\n };\n}\n\nfunction pageFactsForRoute(\n context: AnalysisContext,\n route: ParsedNextRoute,\n): Record<string, string> {\n const markers = compactText(collectMetadataMarkers(context.sourceFile).join(\",\"));\n return {\n router: route.router,\n route: route.route,\n params: route.params.join(\",\"),\n runtime: runtimeFromSource(context.sourceFile),\n metadata: markers,\n };\n}\n\nfunction collectMetadataMarkers(sourceFile: ts.SourceFile): string[] {\n const facts: string[] = [];\n const addMarker = (name: string): void => {\n if (name === \"generateMetadata\") facts.push(\"generatemetadata\");\n if (name === \"getServerSideProps\") facts.push(\"getserversideprops\");\n if (name === \"getStaticProps\") facts.push(\"getstaticprops\");\n if (name === \"getStaticPaths\") facts.push(\"getstaticpaths\");\n };\n\n for (const statement of sourceFile.statements) {\n if (ts.isFunctionDeclaration(statement) && statement.name) {\n addMarker(statement.name.text);\n continue;\n }\n if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name)) addMarker(declaration.name.text);\n }\n }\n }\n return [...new Set(facts)];\n}\n\nfunction collectRouteMethods(sourceFile: ts.SourceFile): string {\n const methods = new Set<string>();\n\n const addFromDeclaration = (name: string | undefined): void => {\n if (!name) return;\n const normalized = name.toUpperCase();\n if (ROUTE_METHODS.has(normalized)) methods.add(normalized.toLowerCase());\n };\n\n for (const statement of sourceFile.statements) {\n if (ts.isFunctionDeclaration(statement) && statement.name) {\n addFromDeclaration(statement.name.text);\n continue;\n }\n\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name)) continue;\n if (isFunctionLikeExpression(declaration.initializer)) {\n addFromDeclaration(declaration.name.text);\n }\n }\n }\n\n return [...methods].join(\",\");\n}\n\nfunction isFunctionLikeExpression(\n node: ts.Expression | undefined,\n): node is ts.ArrowFunction | ts.FunctionExpression {\n return node !== undefined && (ts.isArrowFunction(node) || ts.isFunctionExpression(node));\n}\n\nfunction runtimeFromSource(sourceFile: ts.SourceFile): string {\n if (hasDirective(sourceFile, \"use client\")) return \"client\";\n if (hasDirective(sourceFile, \"use server\")) return \"server\";\n return \"server\";\n}\n\nfunction hasDirective(sourceFile: ts.SourceFile, directive: string): boolean {\n return sourceFile.statements\n .slice(0, 8)\n .some(\n (statement) =>\n ts.isExpressionStatement(statement) &&\n ts.isStringLiteral(statement.expression) &&\n statement.expression.text === directive,\n );\n}\n\nfunction collectContainingAppLayouts(relativePath: string, context: AnalysisContext): string[] {\n const fileSegments = relativePath.replace(/\\\\/g, \"/\").split(\"/\").filter(Boolean);\n if (fileSegments[0] !== \"app\") return [];\n\n const layoutSegments = fileSegments.slice(1, -1);\n const candidates: string[] = [];\n for (let index = 0; index <= layoutSegments.length; index += 1) {\n const prefix = layoutSegments.slice(0, index);\n const candidateWithoutExt = [\"app\", ...prefix, \"layout\"].join(\"/\");\n const tsx = `${candidateWithoutExt}.tsx`;\n const ts = `${candidateWithoutExt}.ts`;\n if (programContainsSourceFile(context, tsx)) candidates.push(tsx);\n if (programContainsSourceFile(context, ts)) candidates.push(ts);\n }\n return candidates;\n}\n\nfunction programContainsSourceFile(context: AnalysisContext, candidateRelative: string): boolean {\n const absolute = path.resolve(context.root, candidateRelative);\n return context.program\n .getSourceFiles()\n .some((source) => normalizeSourcePath(source.fileName) === normalizeSourcePath(absolute));\n}\n\nfunction normalizeSourcePath(value: string): string {\n return value.replace(/\\\\/g, \"/\");\n}\n\nfunction isDynamicSegment(segment: string): boolean {\n return /^\\[{1,2}\\.?.*\\]$/.test(segment);\n}\n\nfunction dynamicSegmentNames(segments: string[]): string[] {\n return segments.filter(isDynamicSegment).map(stripDynamicMarkers);\n}\n\nfunction stripDynamicMarkers(segment: string): string {\n return segment.replace(/^\\[\\[?\\.*/g, \"\").replace(/\\]$/g, \"\");\n}\n\nfunction buildRouteFromSegments(segments: string[]): string {\n const cleaned = segments\n .filter(Boolean)\n .filter((segment) => !ROUTE_GROUP_SEGMENT.test(segment))\n .map((segment) => segment);\n return `/${cleaned.length > 0 ? cleaned.join(\"/\") : \"\"}`;\n}\n\nfunction makeRelation(\n from: string,\n type: RelationRecord[\"type\"],\n to: string,\n context: AnalysisContext,\n node: ts.Node,\n confidence: number,\n explanation: string,\n): RelationRecord {\n return {\n schemaVersion: SCHEMA_VERSION,\n from,\n type,\n to,\n confidence,\n origin: {\n file: context.relativePath,\n line: nodeLine(context.sourceFile, node),\n range: nodeRange(context.sourceFile, node),\n explanation,\n classification: confidence === 1 ? \"framework-derived\" : \"heuristic\",\n analyzer: \"nextjs\",\n },\n };\n}\n","import path from \"node:path\";\n\nimport ts from \"typescript\";\n\nimport { ANALYZER_VERSION, SCHEMA_VERSION } from \"../constants.js\";\nimport { symbolId } from \"../ids.js\";\nimport type {\n AnalysisContribution,\n AnalysisContext,\n FrameworkAnalyzer,\n RelationRecord,\n} from \"../types.js\";\nimport { isPathInside, relativePosix } from \"../utils/path.js\";\nimport {\n compactText,\n hasDefaultModifier,\n hasExportModifier,\n makeSymbol,\n nodeLine,\n nodeRange,\n propertyNameText,\n redactStringLiterals,\n} from \"./helpers.js\";\n\nconst REACT_EXTENSIONS = new Set([\".ts\", \".tsx\", \".js\", \".jsx\"]);\nconst REACT_BUILTIN_HOOKS = new Set([\n \"useState\",\n \"useReducer\",\n \"useMemo\",\n \"useCallback\",\n \"useEffect\",\n \"useLayoutEffect\",\n \"useContext\",\n]);\nconst REACT_FACTORYS = new Set([\"memo\", \"forwardRef\"]);\n\ninterface ImportProfile {\n hookAliases: Map<string, string>;\n namespaceAliases: Set<string>;\n localImports: Map<string, { source: string; imported: string }>;\n}\n\ninterface ComponentDescriptor {\n name: string;\n id: string;\n body: ts.ConciseBody;\n}\n\ninterface NamedSyntaxCandidate {\n name: string;\n node: ts.Node;\n}\n\nexport class ReactAnalyzer implements FrameworkAnalyzer {\n readonly name = \"react\";\n readonly version = ANALYZER_VERSION;\n\n supports(context: AnalysisContext): boolean {\n const extension = path.extname(context.relativePath).toLowerCase();\n if (!REACT_EXTENSIONS.has(extension)) return false;\n return (\n hasDirective(context.sourceFile, \"use client\") ||\n hasDirective(context.sourceFile, \"use server\") ||\n hasReactImport(context.sourceFile) ||\n hasAnyJsx(context.sourceFile)\n );\n }\n\n analyze(context: AnalysisContext): AnalysisContribution {\n const profile = collectImportProfile(context.sourceFile);\n const symbols: AnalysisContribution[\"symbols\"] = [];\n const relations: RelationRecord[] = [];\n const componentIds = new Map<string, string>();\n const hookIds = new Map<string, string>();\n const components: ComponentDescriptor[] = [];\n\n for (const statement of context.sourceFile.statements) {\n if (ts.isFunctionDeclaration(statement) && statement.name) {\n const name = statement.name.text;\n if (isCustomHookName(name) && statement.body) {\n const symbol = makeSymbol(context, statement, \"react-hook\", {\n name,\n exported: isNameExported(context.sourceFile, statement),\n defaultExport: hasDefaultModifier(statement),\n facts: { runtime: inferRuntime(context.sourceFile) },\n });\n symbols.push(symbol);\n hookIds.set(name.toLowerCase(), symbol.id);\n continue;\n }\n if (statement.body && isComponentName(name, statement.body)) {\n const facts = collectComponentFacts(\n context,\n name,\n statement.parameters,\n statement.body,\n profile,\n );\n const symbol = makeSymbol(context, statement, \"react-component\", {\n name,\n exported: isNameExported(context.sourceFile, statement),\n defaultExport: hasDefaultModifier(statement),\n facts,\n });\n symbols.push(symbol);\n componentIds.set(name.toLowerCase(), symbol.id);\n components.push({ name, id: symbol.id, body: statement.body });\n continue;\n }\n }\n\n if (ts.isVariableStatement(statement)) {\n const exported = isNameExported(context.sourceFile, statement);\n const defaultExport = hasDefaultModifier(statement);\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const name = declaration.name.text;\n\n if (isContextFactory(declaration.initializer, profile)) {\n symbols.push(\n makeSymbol(context, declaration, \"react-context\", {\n name,\n exported,\n defaultExport,\n facts: { runtime: inferRuntime(context.sourceFile), type: \"react-context\" },\n }),\n );\n continue;\n }\n\n if (isCustomHookName(name) && isFunctionLikeExpression(declaration.initializer)) {\n const body = functionBody(declaration.initializer);\n if (body) {\n const symbol = makeSymbol(context, declaration, \"react-hook\", {\n name,\n exported,\n defaultExport,\n facts: { runtime: inferRuntime(context.sourceFile) },\n });\n symbols.push(symbol);\n hookIds.set(name.toLowerCase(), symbol.id);\n }\n continue;\n }\n\n const extracted = extractComponentFromExpression(declaration.initializer, name, profile);\n if (!extracted) continue;\n\n const facts = collectComponentFacts(\n context,\n name,\n extracted.parameters,\n extracted.body,\n profile,\n );\n const symbol = makeSymbol(context, declaration, \"react-component\", {\n name,\n exported,\n defaultExport,\n facts,\n });\n symbols.push(symbol);\n componentIds.set(name.toLowerCase(), symbol.id);\n components.push({ name, id: symbol.id, body: extracted.body });\n }\n }\n\n if (ts.isClassDeclaration(statement) && statement.name && isReactClassComponent(statement)) {\n const name = statement.name.text;\n const renderMethod = statement.members.find(\n (member): member is ts.MethodDeclaration =>\n ts.isMethodDeclaration(member) &&\n ts.isIdentifier(member.name) &&\n member.name.text === \"render\" &&\n Boolean(member.body),\n );\n if (!renderMethod?.body) continue;\n const symbol = makeSymbol(context, statement, \"react-component\", {\n name,\n exported: isNameExported(context.sourceFile, statement),\n defaultExport: hasDefaultModifier(statement),\n facts: { runtime: inferRuntime(context.sourceFile), class: true },\n });\n symbols.push(symbol);\n componentIds.set(name.toLowerCase(), symbol.id);\n components.push({ name, id: symbol.id, body: renderMethod.body });\n }\n }\n\n for (const component of components) {\n const rendered = collectRenderedComponents(component.body);\n for (const candidate of rendered) {\n const to =\n componentIds.get(candidate.name.toLowerCase()) ??\n resolveReactCandidateWithChecker(context, candidate, \"react-component\") ??\n resolveImportedReactComponent(context, profile, candidate.name) ??\n symbolId(\"react-component\", context.relativePath, candidate.name);\n relations.push(\n makeRelation(component.id, \"renders\", to, context, candidate.node, 0.95, \"JSX render\"),\n );\n }\n\n for (const candidate of collectCalledCustomHooks(component.body, profile)) {\n const to =\n hookIds.get(candidate.name.toLowerCase()) ??\n resolveReactCandidateWithChecker(context, candidate, \"react-hook\") ??\n resolveImportedReactSymbol(context, profile, candidate.name, \"react-hook\") ??\n symbolId(\"react-hook\", context.relativePath, candidate.name);\n relations.push(\n makeRelation(\n component.id,\n \"uses-hook\",\n to,\n context,\n candidate.node,\n 0.95,\n \"custom hook call\",\n ),\n );\n }\n }\n\n return { symbols, relations, frameworks: [\"react\"] };\n }\n}\n\nexport default ReactAnalyzer;\n\nfunction hasReactImport(sourceFile: ts.SourceFile): boolean {\n return sourceFile.statements.some(\n (statement) =>\n ts.isImportDeclaration(statement) &&\n ts.isStringLiteral(statement.moduleSpecifier) &&\n statement.moduleSpecifier.text === \"react\",\n );\n}\n\nfunction hasDirective(sourceFile: ts.SourceFile, value: string): boolean {\n return sourceFile.statements\n .slice(0, 8)\n .some(\n (statement) =>\n ts.isExpressionStatement(statement) &&\n ts.isStringLiteral(statement.expression) &&\n statement.expression.text === value,\n );\n}\n\nfunction hasAnyJsx(sourceFile: ts.SourceFile): boolean {\n let found = false;\n visit(sourceFile, (node) => {\n if (found) return;\n if (\n ts.isJsxElement(node) ||\n ts.isJsxSelfClosingElement(node) ||\n ts.isJsxOpeningElement(node) ||\n ts.isJsxFragment(node)\n ) {\n found = true;\n }\n });\n return found;\n}\n\nfunction inferRuntime(sourceFile: ts.SourceFile): string {\n if (hasDirective(sourceFile, \"use client\")) return \"client\";\n if (hasDirective(sourceFile, \"use server\")) return \"server\";\n return \"unclassified\";\n}\n\nfunction isNameExported(sourceFile: ts.SourceFile, node: ts.Node): boolean {\n return hasExportModifier(node);\n}\n\nfunction collectImportProfile(sourceFile: ts.SourceFile): ImportProfile {\n const hookAliases = new Map<string, string>();\n const namespaceAliases = new Set<string>();\n const localImports = new Map<string, { source: string; imported: string }>();\n\n for (const statement of sourceFile.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))\n continue;\n const source = statement.moduleSpecifier.text;\n const clause = statement.importClause;\n if (!clause) continue;\n\n if (source === \"react\") {\n if (clause.name) {\n hookAliases.set(clause.name.text, clause.name.text);\n localImports.set(clause.name.text, { source, imported: \"default\" });\n }\n if (!clause.namedBindings) continue;\n if (ts.isNamespaceImport(clause.namedBindings)) {\n namespaceAliases.add(clause.namedBindings.name.text);\n continue;\n }\n for (const item of clause.namedBindings.elements) {\n const local = item.name.text;\n const imported = item.propertyName?.text ?? item.name.text;\n hookAliases.set(local, imported);\n localImports.set(local, { source, imported });\n }\n continue;\n }\n\n if (clause.name) {\n localImports.set(clause.name.text, { source, imported: \"default\" });\n }\n if (!clause.namedBindings) continue;\n if (ts.isNamedImports(clause.namedBindings)) {\n for (const item of clause.namedBindings.elements) {\n localImports.set(item.name.text, {\n source,\n imported: item.propertyName?.text ?? item.name.text,\n });\n }\n } else if (ts.isNamespaceImport(clause.namedBindings)) {\n localImports.set(clause.namedBindings.name.text, {\n source,\n imported: \"*\",\n });\n }\n }\n\n return { hookAliases, namespaceAliases, localImports };\n}\n\nfunction isCustomHookName(name: string): boolean {\n return /^use[A-Z]/.test(name);\n}\n\nfunction isComponentName(name: string, body: ts.ConciseBody | undefined): boolean {\n return Boolean(body && isUpperCase(name) && !isCustomHookName(name) && containsJsx(body));\n}\n\nfunction isUpperCase(name: string): boolean {\n return /^[A-Z]/.test(name);\n}\n\nfunction isContextFactory(value: ts.Expression, profile: ImportProfile): boolean {\n return (\n ts.isCallExpression(value) && resolveCallName(value.expression, profile) === \"createContext\"\n );\n}\n\nfunction extractComponentFromExpression(\n value: ts.Expression,\n name: string,\n profile: ImportProfile,\n): { body: ts.ConciseBody; parameters: readonly ts.ParameterDeclaration[] } | undefined {\n if (!isUpperCase(name) || isCustomHookName(name)) return undefined;\n\n if (isFunctionLikeExpression(value)) {\n return { body: value.body, parameters: value.parameters };\n }\n\n if (ts.isClassExpression(value)) {\n const renderMethod = value.members.find(\n (member): member is ts.MethodDeclaration =>\n ts.isMethodDeclaration(member) &&\n ts.isIdentifier(member.name) &&\n member.name.text === \"render\" &&\n Boolean(member.body),\n );\n if (!renderMethod?.body) return undefined;\n return { body: renderMethod.body, parameters: renderMethod.parameters };\n }\n\n if (ts.isCallExpression(value)) {\n const calledName = resolveCallName(value.expression, profile);\n if (!calledName || !REACT_FACTORYS.has(calledName) || value.arguments.length === 0)\n return undefined;\n const first = value.arguments[0];\n if (!ts.isFunctionLike(first) || !containsJsx(first.body)) return undefined;\n return { body: first.body, parameters: first.parameters };\n }\n\n return undefined;\n}\n\nfunction isFunctionLikeExpression(\n expression: ts.Expression,\n): expression is ts.ArrowFunction | ts.FunctionExpression {\n return ts.isArrowFunction(expression) || ts.isFunctionExpression(expression);\n}\n\nfunction isReactClassComponent(statement: ts.ClassDeclaration): boolean {\n if (!statement.heritageClauses) return false;\n return statement.heritageClauses.some((clause) =>\n clause.types.some((item) => {\n const expr = item.expression;\n const typeName = ts.isIdentifier(expr)\n ? expr.text\n : ts.isPropertyAccessExpression(expr)\n ? expr.name.text\n : undefined;\n return typeName === \"Component\" || typeName === \"PureComponent\";\n }),\n );\n}\n\nfunction functionBody(expression: ts.Expression): ts.ConciseBody | undefined {\n return isFunctionLikeExpression(expression) ? expression.body : undefined;\n}\n\nfunction collectComponentFacts(\n context: AnalysisContext,\n name: string,\n parameters: readonly ts.ParameterDeclaration[],\n body: ts.ConciseBody,\n profile: ImportProfile,\n) {\n const facts: Record<string, string> = {\n runtime: inferRuntime(context.sourceFile),\n };\n\n const props = collectProps(context, parameters[0]);\n if (props.length > 0) {\n facts.props = `${name.toLowerCase()}props:${props.join(\",\")}`;\n }\n\n const behavior = collectComponentBehavior(context, body, profile);\n if (behavior.state.length > 0) facts.state = behavior.state.join(\",\");\n if (behavior.memo.length > 0) facts.memo = behavior.memo.join(\",\");\n if (behavior.effects.length > 0) facts.effects = behavior.effects.join(\",\");\n if (behavior.customHooks.length > 0) facts.hooks = behavior.customHooks.join(\",\");\n return facts;\n}\n\nfunction collectProps(context: AnalysisContext, parameter?: ts.ParameterDeclaration): string[] {\n if (!parameter) return [];\n const values: string[] = [];\n collectBindingNames(parameter.name, values);\n if (parameter.type) {\n values.push(...collectInterfaceMembers(parameter.type, context));\n }\n return dedupe(values);\n}\n\nfunction collectComponentBehavior(\n context: AnalysisContext,\n body: ts.ConciseBody,\n profile: ImportProfile,\n): { state: string[]; memo: string[]; effects: string[]; customHooks: string[] } {\n const state: string[] = [];\n const memo: string[] = [];\n const effects: string[] = [];\n const customHooks: string[] = [];\n\n visit(body, (node) => {\n if (!ts.isCallExpression(node)) return;\n const called = resolveCallName(node.expression, profile);\n if (!called) return;\n\n const declaration = variableDeclarationOfCall(node);\n if (called === \"useState\" || called === \"useReducer\") {\n if (declaration?.name) {\n const declaredNames: string[] = [];\n collectBindingNames(declaration.name, declaredNames);\n state.push(...declaredNames);\n }\n if (called === \"useReducer\") state.push(\"reducer\");\n return;\n }\n\n if (called === \"useMemo\" || called === \"useCallback\") {\n const target =\n declaration?.name && ts.isIdentifier(declaration.name) ? declaration.name.text : called;\n const dependencies = dependencyText(node.arguments[1], context.sourceFile);\n memo.push(`${called.toLowerCase()}:${target.toLowerCase()}<-${dependencies}`);\n return;\n }\n\n if (called === \"useEffect\" || called === \"useLayoutEffect\") {\n const deps = node.arguments[1]\n ? compactText(redactStringLiterals(node.arguments[1].getText(context.sourceFile)))\n : \"[]\";\n effects.push(`useeffect:${deps}`);\n return;\n }\n\n if (called.startsWith(\"use\") && !REACT_BUILTIN_HOOKS.has(called)) {\n customHooks.push(called.toLowerCase());\n }\n });\n\n return {\n state: dedupe(state),\n memo: dedupe(memo),\n effects: dedupe(effects),\n customHooks: dedupe(customHooks),\n };\n}\n\nfunction collectCalledCustomHooks(node: ts.Node, profile: ImportProfile): NamedSyntaxCandidate[] {\n const hooks: NamedSyntaxCandidate[] = [];\n visit(node, (current) => {\n if (!ts.isCallExpression(current)) return;\n const called = resolveCallName(current.expression, profile);\n if (called && called.startsWith(\"use\") && !REACT_BUILTIN_HOOKS.has(called)) {\n hooks.push({ name: called, node: current });\n }\n });\n return hooks;\n}\n\nfunction collectRenderedComponents(node: ts.Node): NamedSyntaxCandidate[] {\n const components: NamedSyntaxCandidate[] = [];\n visit(node, (current) => {\n if (!ts.isJsxElement(current) && !ts.isJsxSelfClosingElement(current)) return;\n const evidenceNode = ts.isJsxElement(current) ? current.openingElement : current;\n const tag = jsxTagName(evidenceNode.tagName);\n if (tag && isUpperCase(tag)) {\n components.push({ name: tag, node: evidenceNode });\n }\n });\n return components;\n}\n\nfunction resolveImportedReactComponent(\n context: AnalysisContext,\n profile: ImportProfile,\n renderedName: string,\n): string | undefined {\n return resolveImportedReactSymbol(context, profile, renderedName, \"react-component\");\n}\n\nfunction resolveReactCandidateWithChecker(\n context: AnalysisContext,\n candidate: NamedSyntaxCandidate,\n kind: \"react-component\" | \"react-hook\",\n): string | undefined {\n let location: ts.Node = candidate.node;\n if (ts.isJsxOpeningElement(candidate.node) || ts.isJsxSelfClosingElement(candidate.node)) {\n location = candidate.node.tagName;\n } else if (ts.isCallExpression(candidate.node)) {\n location = candidate.node.expression;\n }\n let symbol = context.checker.getSymbolAtLocation(location);\n if (!symbol && ts.isPropertyAccessExpression(location)) {\n symbol = context.checker.getSymbolAtLocation(location.name);\n }\n if (!symbol) return undefined;\n if (symbol.flags & ts.SymbolFlags.Alias) {\n try {\n symbol = context.checker.getAliasedSymbol(symbol);\n } catch {\n return undefined;\n }\n }\n const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];\n if (!declaration) return undefined;\n const sourceFile = declaration.getSourceFile();\n let relative: string;\n try {\n relative = path.relative(context.root, sourceFile.fileName).split(path.sep).join(\"/\");\n } catch {\n return undefined;\n }\n if (\n relative === \"\" ||\n relative === \"..\" ||\n relative.startsWith(\"../\") ||\n path.isAbsolute(relative) ||\n (context.indexedSourcePaths && !context.indexedSourcePaths.has(relative))\n ) {\n return undefined;\n }\n return symbolId(kind, relative, declarationToSymbolName(declaration) ?? symbol.getName());\n}\n\nfunction resolveImportedReactSymbol(\n context: AnalysisContext,\n profile: ImportProfile,\n importedName: string,\n kind: \"react-component\" | \"react-hook\",\n): string | undefined {\n const source = profile.localImports.get(importedName);\n if (!source) return undefined;\n if (!source.source.startsWith(\"./\") && !source.source.startsWith(\"../\")) {\n const resolved = context.resolveModule?.(source.source, context.sourceFile.fileName);\n if (!resolved) return undefined;\n if (!isPathInside(context.root, resolved.resolvedFileName)) return undefined;\n const relative = relativePosix(context.root, resolved.resolvedFileName);\n if (context.indexedSourcePaths && !context.indexedSourcePaths.has(relative)) return undefined;\n const sourceFile = context.program.getSourceFile(resolved.resolvedFileName);\n const declaration = sourceFile\n ? findExportedDeclaration(sourceFile, source.imported)\n : undefined;\n const actualName = declaration ? declarationToSymbolName(declaration) : undefined;\n if (actualName) return symbolId(kind, relative, actualName);\n return symbolId(kind, relative, source.imported);\n }\n const relative = path.posix.normalize(\n path.posix.join(path.posix.dirname(context.relativePath), source.source),\n );\n const candidates = [\n relative,\n `${relative}.ts`,\n `${relative}.tsx`,\n `${relative}.js`,\n `${relative}.jsx`,\n `${relative}.mjs`,\n `${relative}.cjs`,\n `${relative}/index.ts`,\n `${relative}/index.tsx`,\n `${relative}/index.jsx`,\n ];\n for (const candidate of candidates) {\n const absolute = path.resolve(context.root, candidate);\n const imported = context.program.getSourceFile(absolute);\n if (imported) {\n const declaration = findExportedDeclaration(imported, source.imported);\n if (declaration) {\n const symbolName = declarationToSymbolName(declaration);\n if (symbolName) return symbolId(kind, candidate, symbolName);\n }\n if (source.imported !== \"*\") return symbolId(kind, candidate, source.imported);\n }\n }\n const fallback = source.imported === \"*\" ? importedName : source.imported;\n return symbolId(kind, relative, fallback);\n}\n\nfunction declarationToSymbolName(declaration: ts.Declaration): string | undefined {\n if (ts.isFunctionDeclaration(declaration)) return declaration.name?.text ?? \"default\";\n if (ts.isClassDeclaration(declaration)) return declaration.name?.text ?? \"default\";\n if (ts.isInterfaceDeclaration(declaration) || ts.isTypeAliasDeclaration(declaration))\n return declaration.name.text;\n if (ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name))\n return declaration.name.text;\n return \"default\";\n}\n\nfunction findExportedDeclaration(\n sourceFile: ts.SourceFile,\n exportedName: string,\n): ts.Declaration | undefined {\n for (const statement of sourceFile.statements) {\n if (\n ts.isFunctionDeclaration(statement) &&\n ((exportedName === \"default\" && hasDefaultModifier(statement)) ||\n statement.name?.text === exportedName)\n )\n return statement;\n if (\n ts.isClassDeclaration(statement) &&\n ((exportedName === \"default\" && hasDefaultModifier(statement)) ||\n statement.name?.text === exportedName)\n )\n return statement;\n if (\n ts.isInterfaceDeclaration(statement) &&\n ((exportedName === \"default\" && hasDefaultModifier(statement)) ||\n statement.name.text === exportedName)\n )\n return statement;\n if (\n ts.isTypeAliasDeclaration(statement) &&\n ((exportedName === \"default\" && hasDefaultModifier(statement)) ||\n statement.name.text === exportedName)\n )\n return statement;\n if (ts.isVariableStatement(statement)) {\n const declaration =\n exportedName === \"default\"\n ? statement.declarationList.declarations.find(\n (item) => hasDefaultModifier(statement) && ts.isIdentifier(item.name),\n )\n : statement.declarationList.declarations.find(\n (item) => ts.isIdentifier(item.name) && item.name.text === exportedName,\n );\n if (declaration && ts.isIdentifier(declaration.name)) return declaration;\n }\n if (\n ts.isExportDeclaration(statement) &&\n statement.exportClause &&\n ts.isNamedExports(statement.exportClause)\n ) {\n const specifier = statement.exportClause.elements.find(\n (item) =>\n item.name.text === exportedName ||\n (item.name.text === \"default\" && item.propertyName?.text === exportedName),\n );\n if (!specifier) continue;\n return findExportedDeclaration(\n sourceFile,\n specifier.propertyName?.text ?? specifier.name.text,\n );\n }\n if (\n ts.isExportAssignment(statement) &&\n !statement.isExportEquals &&\n ts.isIdentifier(statement.expression)\n ) {\n return findDeclarationByName(sourceFile, statement.expression.text);\n }\n }\n return undefined;\n}\n\nfunction findDeclarationByName(\n sourceFile: ts.SourceFile,\n name: string,\n): ts.Declaration | undefined {\n for (const statement of sourceFile.statements) {\n if (\n ts.isFunctionDeclaration(statement) ||\n ts.isClassDeclaration(statement) ||\n ts.isInterfaceDeclaration(statement) ||\n ts.isTypeAliasDeclaration(statement)\n ) {\n if (statement.name?.text === name) return statement;\n }\n if (ts.isVariableStatement(statement)) {\n const declaration = statement.declarationList.declarations.find(\n (item) => ts.isIdentifier(item.name) && item.name.text === name,\n );\n if (declaration) return declaration;\n }\n }\n return undefined;\n}\n\nfunction dependencyText(expression: ts.Expression | undefined, sourceFile: ts.SourceFile): string {\n if (!expression || !ts.isArrayLiteralExpression(expression)) return \"[]\";\n return expression.elements\n .map((element) => compactText(redactStringLiterals(element.getText(sourceFile))))\n .join(\",\");\n}\n\nfunction resolveCallName(\n expression: ts.LeftHandSideExpression,\n profile: ImportProfile,\n): string | undefined {\n if (ts.isIdentifier(expression)) {\n return profile.hookAliases.get(expression.text) ?? expression.text;\n }\n if (\n ts.isPropertyAccessExpression(expression) &&\n ts.isIdentifier(expression.expression) &&\n profile.namespaceAliases.has(expression.expression.text)\n ) {\n return expression.name.text;\n }\n return undefined;\n}\n\nfunction variableDeclarationOfCall(node: ts.CallExpression): ts.VariableDeclaration | undefined {\n let current = node.parent as ts.Node | undefined;\n while (current) {\n if (ts.isVariableDeclaration(current)) return current;\n current = current.parent;\n }\n return undefined;\n}\n\nfunction collectBindingNames(name: ts.BindingName, values: string[]): void {\n if (ts.isIdentifier(name)) {\n values.push(name.text.toLowerCase());\n return;\n }\n if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) {\n for (const element of name.elements) {\n if (ts.isBindingElement(element)) collectBindingNames(element.name, values);\n }\n }\n}\n\nfunction collectInterfaceMembers(typeNode: ts.TypeNode, context: AnalysisContext): string[] {\n if (ts.isTypeLiteralNode(typeNode)) {\n return typeNode.members.flatMap((member) => {\n const name = propertyNameText(member.name);\n return name ? [name.toLowerCase()] : [];\n });\n }\n\n if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {\n const symbol = context.checker.getSymbolAtLocation(typeNode.typeName);\n const resolved =\n symbol && symbol.flags & ts.SymbolFlags.Alias\n ? context.checker.getAliasedSymbol(symbol)\n : symbol;\n const declaration = resolved?.declarations?.[0];\n if (declaration && ts.isInterfaceDeclaration(declaration)) {\n return declaration.members.flatMap((member) => {\n const name = propertyNameText(member.name);\n return name ? [name.toLowerCase()] : [];\n });\n }\n }\n\n return [];\n}\n\nfunction containsJsx(node: ts.Node): boolean {\n let found = false;\n visit(node, (current) => {\n if (\n ts.isJsxElement(current) ||\n ts.isJsxSelfClosingElement(current) ||\n ts.isJsxOpeningElement(current) ||\n ts.isJsxFragment(current)\n ) {\n found = true;\n }\n });\n return found;\n}\n\nfunction jsxTagName(tag: ts.JsxTagNameExpression): string | undefined {\n if (ts.isIdentifier(tag) || ts.isStringLiteral(tag)) return tag.text;\n if (ts.isPropertyAccessExpression(tag)) return tag.name.text;\n return undefined;\n}\n\nfunction visit(node: ts.Node, callback: (node: ts.Node) => void): void {\n callback(node);\n ts.forEachChild(node, (child) => visit(child, callback));\n}\n\nfunction dedupe(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction makeRelation(\n from: string,\n type: RelationRecord[\"type\"],\n to: string,\n context: AnalysisContext,\n node: ts.Node,\n confidence: number,\n explanation: string,\n): RelationRecord {\n return {\n schemaVersion: SCHEMA_VERSION,\n from,\n type,\n to,\n confidence,\n origin: {\n file: context.relativePath,\n line: nodeLine(context.sourceFile, node),\n range: nodeRange(context.sourceFile, node),\n explanation,\n classification: \"framework-derived\",\n analyzer: \"react\",\n },\n };\n}\n","import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport fg from \"fast-glob\";\nimport ts from \"typescript\";\n\nimport { SCHEMA_VERSION } from \"./constants.js\";\nimport type {\n CodeMapConfig,\n CompilerUnitRecord,\n DiagnosticRecord,\n SemanticInputObservation,\n WorkspacePackage,\n} from \"./types.js\";\nimport type { DiscoveredSource } from \"./discovery.js\";\nimport {\n isPathInside,\n isSafeRelativePathPattern,\n normalizeStoredPath,\n relativePosix,\n} from \"./utils/path.js\";\nimport { configuredCompilerUnitId, generatedCompilerUnitId } from \"./ids.js\";\nimport { hashText } from \"./utils/hash.js\";\nimport { compareText } from \"./utils/stable.js\";\n\nconst CONFIG_PATTERNS = [\"**/tsconfig.json\", \"**/jsconfig.json\", \"**/tsconfig.*.json\"];\nconst CONFIG_IGNORES = [\n \"**/node_modules/**\",\n \"**/.git/**\",\n \"**/.ai/**\",\n \"**/.next/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/out/**\",\n \"**/coverage/**\",\n];\nconst FALLBACK_UNIT_ID = generatedCompilerUnitId(\"fallback\");\n\nexport interface CompilerUnitPlan {\n record: CompilerUnitRecord;\n sourceFiles: string[];\n ownedFiles: string[];\n}\n\nexport interface CompilerUnitGraph {\n units: CompilerUnitPlan[];\n ownership: Map<string, string>;\n configInputs: string[];\n diagnostics: DiagnosticRecord[];\n primaryConfig?: string;\n}\n\ninterface ParsedConfigNode {\n absolutePath: string;\n relativePath: string;\n parsed: ts.ParsedCommandLine;\n source: ts.TsConfigSourceFile;\n sourceFiles: string[];\n sourceFileKeys: Set<string>;\n references: string[];\n extends: string[];\n pathAliases: Record<string, string[]>;\n hasOwnFileSelection: boolean;\n allowJs: boolean;\n valid: boolean;\n}\n\n/**\n * Build the bounded compiler configuration graph and assign every indexed source exactly once.\n * The returned plan contains normalized records only; compiler objects are intentionally omitted.\n */\nexport async function buildCompilerUnitGraph(\n root: string,\n config: CodeMapConfig,\n sources: readonly DiscoveredSource[],\n workspaces: readonly WorkspacePackage[],\n): Promise<CompilerUnitGraph> {\n const realRoot = realpathSync(root);\n const diagnostics: DiagnosticRecord[] = [];\n const fileSystem = new BoundedTypeScriptFileSystem(realRoot);\n const candidatePaths = await discoverConfigCandidates(realRoot, config, diagnostics);\n const parsedByPath = new Map<string, ParsedConfigNode>();\n const queue = [...candidatePaths];\n\n while (queue.length > 0) {\n const candidate = queue.shift();\n if (!candidate) continue;\n const logical = normalizeStoredPath(candidate);\n if (parsedByPath.has(logical)) continue;\n const absolute = path.resolve(realRoot, logical);\n const node = parseConfigNode(realRoot, absolute, fileSystem, diagnostics);\n if (!node) continue;\n parsedByPath.set(node.relativePath, node);\n for (const reference of node.references) {\n if (!parsedByPath.has(reference) && !queue.includes(reference)) queue.push(reference);\n }\n queue.sort(compareText);\n }\n\n const indexedKeys = new Set(sources.map((source) => canonicalPath(source.absolutePath)));\n const boundaryPaths = [\".\", ...workspaces.map((workspace) => workspace.path)].sort((a, b) =>\n compareText(a, b),\n );\n const seedPaths = new Set<string>();\n const configured = configuredTsconfigPath(realRoot, config.tsconfig, diagnostics);\n if (configured) seedPaths.add(configured);\n for (const conventional of [\"tsconfig.json\", \"jsconfig.json\"]) {\n if (parsedByPath.has(conventional)) seedPaths.add(conventional);\n }\n const extendedDependencies = new Set([...parsedByPath.values()].flatMap((node) => node.extends));\n const referenceTargets = new Set([...parsedByPath.values()].flatMap((node) => node.references));\n for (const node of parsedByPath.values()) {\n const directory = normalizeStoredPath(path.posix.dirname(node.relativePath));\n const atBoundary = boundaryPaths.includes(directory);\n const intersects = [...node.sourceFileKeys].some((file) => indexedKeys.has(file));\n const conventional = [\"tsconfig.json\", \"jsconfig.json\"].includes(\n path.posix.basename(node.relativePath),\n );\n const extendsOnlyBase =\n extendedDependencies.has(node.relativePath) &&\n !node.hasOwnFileSelection &&\n !conventional &&\n !referenceTargets.has(node.relativePath) &&\n configured !== node.relativePath;\n if (!extendsOnlyBase && (atBoundary || intersects)) seedPaths.add(node.relativePath);\n }\n\n // References from a retained solution/config node remain graph nodes even when they own no files.\n const retained = new Set<string>();\n const retainQueue = [...seedPaths].sort(compareText);\n while (retainQueue.length > 0) {\n const current = retainQueue.shift();\n if (!current || retained.has(current)) continue;\n const node = parsedByPath.get(current);\n if (!node) continue;\n retained.add(current);\n for (const reference of node.references) {\n if (!retained.has(reference)) retainQueue.push(reference);\n }\n retainQueue.sort(compareText);\n }\n\n const nodes = [...retained]\n .map((relative) => parsedByPath.get(relative))\n .filter((node): node is ParsedConfigNode => node !== undefined && node.valid)\n .sort((a, b) => compareText(a.relativePath, b.relativePath));\n const validNodePaths = new Set(nodes.map((node) => node.relativePath));\n const ownership = new Map<string, string>();\n const ownedByUnit = new Map<string, string[]>();\n const jsFallbackWarnings = new Set<string>();\n\n for (const source of [...sources].sort((a, b) => compareText(a.relativePath, b.relativePath))) {\n const sourceKey = canonicalPath(source.absolutePath);\n const selected = nodes.filter((node) => node.sourceFileKeys.has(sourceKey));\n const jsSource = isJavaScriptSourceFile(source.absolutePath);\n const eligible = jsSource ? selected.filter((node) => node.allowJs) : selected;\n const owner = chooseOwner(eligible, source.absolutePath, realRoot, boundaryPaths);\n if (jsSource && !owner && !jsFallbackWarnings.has(source.relativePath)) {\n jsFallbackWarnings.add(source.relativePath);\n const underDisallowingConfig = nodes.some(\n (node) =>\n !node.allowJs && isPathInside(path.dirname(node.absolutePath), source.absolutePath),\n );\n const underAllowingConfig = nodes.some(\n (node) =>\n node.allowJs && isPathInside(path.dirname(node.absolutePath), source.absolutePath),\n );\n const reason =\n selected.length > 0 || underDisallowingConfig\n ? \"the applicable configuration does not allow JavaScript\"\n : underAllowingConfig\n ? \"the nearby JavaScript-enabled configuration does not include the file\"\n : \"no eligible configuration includes the file\";\n diagnostics.push({\n ...graphDiagnostic(\n `A selected JavaScript source uses fallback compiler ownership because ${reason}.`,\n source.relativePath,\n ),\n severity: \"warning\",\n });\n }\n const ownerId = owner ? configuredCompilerUnitId(owner.relativePath) : FALLBACK_UNIT_ID;\n ownership.set(source.relativePath, ownerId);\n const owned = ownedByUnit.get(ownerId) ?? [];\n owned.push(source.absolutePath);\n ownedByUnit.set(ownerId, owned);\n }\n\n const units: CompilerUnitPlan[] = nodes.map((node) => {\n const rootPath = normalizeStoredPath(path.posix.dirname(node.relativePath));\n const id = configuredCompilerUnitId(node.relativePath);\n return {\n record: {\n id,\n kind: \"configured\",\n root: rootPath,\n config: node.relativePath,\n references: node.references.filter((reference) => validNodePaths.has(reference)),\n extends: node.extends,\n pathAliases: node.pathAliases,\n },\n sourceFiles: node.sourceFiles,\n ownedFiles: (ownedByUnit.get(id) ?? []).sort(compareText),\n };\n });\n\n units.push({\n record: {\n id: FALLBACK_UNIT_ID,\n kind: \"fallback\",\n root: \".\",\n references: [],\n extends: [],\n pathAliases: {},\n },\n sourceFiles: (ownedByUnit.get(FALLBACK_UNIT_ID) ?? []).sort(compareText),\n ownedFiles: (ownedByUnit.get(FALLBACK_UNIT_ID) ?? []).sort(compareText),\n });\n\n const configInputs = new Set<string>();\n for (const node of parsedByPath.values()) {\n configInputs.add(node.relativePath);\n for (const extended of node.extends) configInputs.add(extended);\n }\n\n const primaryConfig =\n configured && validNodePaths.has(configured)\n ? configured\n : [\"tsconfig.json\", \"jsconfig.json\"].find((candidate) => validNodePaths.has(candidate));\n return {\n units: units.sort((a, b) => compareText(a.record.id, b.record.id)),\n ownership,\n configInputs: [...configInputs].sort(compareText),\n diagnostics: normalizeGraphDiagnostics(diagnostics),\n ...(primaryConfig ? { primaryConfig } : {}),\n };\n}\n\nasync function discoverConfigCandidates(\n root: string,\n config: CodeMapConfig,\n diagnostics: DiagnosticRecord[],\n): Promise<string[]> {\n const matches = await fg(CONFIG_PATTERNS, {\n cwd: root,\n onlyFiles: true,\n unique: true,\n dot: false,\n followSymbolicLinks: false,\n ignore: [...CONFIG_IGNORES, ...config.exclude],\n });\n const candidates = new Set(matches.map(normalizeStoredPath));\n if (config.tsconfig) {\n const configured = configuredTsconfigPath(root, config.tsconfig, diagnostics);\n if (configured) candidates.add(configured);\n }\n return [...candidates]\n .filter((candidate) => safeRegularFile(root, path.resolve(root, candidate)))\n .sort(compareText);\n}\n\nfunction configuredTsconfigPath(\n root: string,\n configured: string | undefined,\n diagnostics: DiagnosticRecord[],\n): string | undefined {\n if (!configured) return undefined;\n const absolute = path.resolve(root, configured);\n if (!isPathInside(root, absolute) || !safeRegularFile(root, absolute)) {\n diagnostics.push(\n graphDiagnostic(\"The configured TypeScript project is unavailable or unsafe.\"),\n );\n return undefined;\n }\n return relativePosix(root, absolute);\n}\n\nfunction parseConfigNode(\n root: string,\n absolutePath: string,\n fileSystem: BoundedTypeScriptFileSystem,\n diagnostics: DiagnosticRecord[],\n): ParsedConfigNode | undefined {\n if (!safeRegularFile(root, absolutePath)) {\n diagnostics.push(graphDiagnostic(\"A TypeScript project reference was unavailable or unsafe.\"));\n return undefined;\n }\n const relativePath = relativePosix(root, absolutePath);\n let source: ts.TsConfigSourceFile;\n try {\n source = ts.readJsonConfigFile(absolutePath, fileSystem.readFile);\n } catch {\n diagnostics.push(\n graphDiagnostic(\"A TypeScript configuration could not be read.\", relativePath),\n );\n return undefined;\n }\n const host = fileSystem.parseHost(path.dirname(absolutePath));\n let parsed: ts.ParsedCommandLine;\n try {\n parsed = ts.parseJsonSourceFileConfigFileContent(\n source,\n host,\n path.dirname(absolutePath),\n undefined,\n absolutePath,\n undefined,\n undefined,\n fileSystem.extendedConfigCache,\n );\n } catch {\n diagnostics.push(\n graphDiagnostic(\"A TypeScript configuration could not be parsed.\", relativePath),\n );\n return undefined;\n }\n\n const optionSafety = sanitizeCompilerOptions(parsed.options, root, path.dirname(absolutePath));\n if (!optionSafety.valid) {\n diagnostics.push(\n graphDiagnostic(\"A TypeScript configuration option escaped the selected root.\", relativePath),\n );\n }\n const parsedSourceFiles = parsed.fileNames\n .filter((fileName) => safeRegularFile(root, fileName))\n .map((fileName) => realpathSync(fileName))\n .filter((fileName, index, values) => values.indexOf(fileName) === index)\n .sort(compareText);\n const sourceFiles = parsedSourceFiles\n .filter((fileName) => {\n if (parsed.options.allowJs === true) return true;\n return !isJavaScriptSourceFile(fileName);\n })\n .sort(compareText);\n const references: string[] = [];\n const safeReferences: ts.ProjectReference[] = [];\n for (const reference of parsed.projectReferences ?? []) {\n const target = ts.resolveProjectReferencePath(reference);\n if (!safeRegularFile(root, target)) {\n diagnostics.push(\n graphDiagnostic(\"A TypeScript project reference escaped the selected root.\", relativePath),\n );\n continue;\n }\n references.push(relativePosix(root, target));\n safeReferences.push(reference);\n }\n parsed.projectReferences = safeReferences.sort((a, b) =>\n compareText(ts.resolveProjectReferencePath(a), ts.resolveProjectReferencePath(b)),\n );\n\n const extended = (source.extendedSourceFiles ?? [])\n .filter((fileName) => safeRegularFile(root, fileName))\n .map((fileName) => relativePosix(root, realpathSync(fileName)))\n .filter((fileName, index, values) => values.indexOf(fileName) === index)\n .sort(compareText);\n if ((source.extendedSourceFiles ?? []).length !== extended.length) {\n diagnostics.push(\n graphDiagnostic(\"A TypeScript extends dependency escaped the selected root.\", relativePath),\n );\n }\n for (const error of parsed.errors) {\n if (error.category === ts.DiagnosticCategory.Error) {\n diagnostics.push(\n graphDiagnostic(\"TypeScript reported an invalid project configuration.\", relativePath),\n );\n break;\n }\n }\n const configText = fileSystem.readFile(absolutePath) ?? \"\";\n const rawConfig = ts.parseConfigFileTextToJson(absolutePath, configText).config as\n Record<string, unknown> | undefined;\n\n return {\n absolutePath,\n relativePath,\n parsed,\n source,\n sourceFiles,\n sourceFileKeys: new Set(parsedSourceFiles.map(canonicalPath)),\n references: [...new Set(references)].sort(compareText),\n extends: extended,\n pathAliases: normalizePathAliases(root, path.dirname(absolutePath), parsed.options),\n hasOwnFileSelection: Boolean(\n rawConfig &&\n (Object.prototype.hasOwnProperty.call(rawConfig, \"files\") ||\n Object.prototype.hasOwnProperty.call(rawConfig, \"include\")),\n ),\n allowJs: parsed.options.allowJs === true,\n valid: optionSafety.valid,\n };\n}\n\nfunction sanitizeCompilerOptions(\n options: ts.CompilerOptions,\n root: string,\n unitDirectory: string,\n): { valid: boolean } {\n let valid = true;\n const validatePath = (value: string | undefined): string | undefined => {\n if (!value) return value;\n const absolute = path.resolve(value);\n if (!isPathInside(root, absolute)) {\n valid = false;\n return undefined;\n }\n return absolute;\n };\n options.baseUrl = validatePath(options.baseUrl);\n options.rootDir = validatePath(options.rootDir);\n options.outDir = validatePath(options.outDir);\n options.declarationDir = validatePath(options.declarationDir);\n if (options.rootDirs) {\n const values = options.rootDirs\n .map((entry) => validatePath(entry))\n .filter((entry): entry is string => entry !== undefined);\n options.rootDirs = values;\n }\n if (options.typeRoots) {\n const values = options.typeRoots\n .map((entry) => validatePath(entry))\n .filter((entry): entry is string => entry !== undefined);\n options.typeRoots = values;\n } else {\n options.typeRoots = boundedTypeRoots(root, unitDirectory);\n }\n sanitizeCompilerPathAliases(options);\n options.configFilePath = options.configFilePath ?? path.join(unitDirectory, \"tsconfig.json\");\n return { valid };\n}\n\nexport function sanitizeCompilerPathAliases(options: ts.CompilerOptions): void {\n if (!options.paths) return;\n const sanitized: Record<string, string[]> = {};\n for (const [alias, targets] of Object.entries(options.paths).sort(([a], [b]) =>\n compareText(a, b),\n )) {\n if (!isSafeRelativePathPattern(alias)) continue;\n const safeTargets = targets.filter(isSafeRelativePathPattern);\n if (safeTargets.length > 0) sanitized[alias] = safeTargets;\n }\n options.paths = sanitized;\n}\n\nfunction boundedTypeRoots(root: string, start: string): string[] {\n const values: string[] = [];\n let current = path.resolve(start);\n while (isPathInside(root, current)) {\n values.push(path.join(current, \"node_modules\", \"@types\"));\n if (current === path.resolve(root)) break;\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return [...new Set(values)];\n}\n\nfunction normalizePathAliases(\n root: string,\n configDirectory: string,\n options: ts.CompilerOptions,\n): Record<string, string[]> {\n const base =\n options.baseUrl ??\n (options as ts.CompilerOptions & { pathsBasePath?: string }).pathsBasePath ??\n configDirectory;\n const output: Record<string, string[]> = {};\n const paths = (options.paths ?? {}) as Record<string, string[]>;\n for (const [alias, targets] of Object.entries(paths).sort(([a], [b]) => compareText(a, b))) {\n if (!isSafeRelativePathPattern(alias)) continue;\n const normalized: string[] = [];\n for (const target of targets) {\n if (!isSafeRelativePathPattern(target)) continue;\n const absolute = path.resolve(base, target);\n if (!isPathInside(root, absolute)) continue;\n normalized.push(relativePosix(root, absolute));\n }\n output[alias] = [...new Set(normalized)].sort(compareText);\n }\n return output;\n}\n\nfunction chooseOwner(\n eligible: ParsedConfigNode[],\n sourceFile: string,\n root: string,\n boundaries: string[],\n): ParsedConfigNode | undefined {\n return [...eligible].sort((a, b) => {\n const packageDepthA = deepestSharedBoundaryDepth(a.absolutePath, sourceFile, root, boundaries);\n const packageDepthB = deepestSharedBoundaryDepth(b.absolutePath, sourceFile, root, boundaries);\n if (packageDepthA !== packageDepthB) return packageDepthB - packageDepthA;\n const directoryDepthA = ancestorDepth(path.dirname(a.absolutePath), sourceFile, root);\n const directoryDepthB = ancestorDepth(path.dirname(b.absolutePath), sourceFile, root);\n if (directoryDepthA !== directoryDepthB) return directoryDepthB - directoryDepthA;\n return compareText(a.relativePath, b.relativePath);\n })[0];\n}\n\nfunction deepestSharedBoundaryDepth(\n configPath: string,\n sourcePath: string,\n root: string,\n boundaries: string[],\n): number {\n let depth = -1;\n for (const boundary of boundaries) {\n const absolute = path.resolve(root, boundary);\n if (isPathInside(absolute, configPath) && isPathInside(absolute, sourcePath)) {\n depth = Math.max(depth, pathDepth(relativePosix(root, absolute)));\n }\n }\n return depth;\n}\n\nfunction ancestorDepth(directory: string, sourcePath: string, root: string): number {\n return isPathInside(directory, sourcePath) ? pathDepth(relativePosix(root, directory)) : -1;\n}\n\nfunction pathDepth(value: string): number {\n return value === \".\" ? 0 : value.split(\"/\").length;\n}\n\nfunction isJavaScriptSourceFile(filePath: string): boolean {\n const extension = path.extname(filePath).toLowerCase();\n return (\n extension === \".js\" || extension === \".jsx\" || extension === \".mjs\" || extension === \".cjs\"\n );\n}\n\nfunction safeRegularFile(root: string, candidate: string): boolean {\n try {\n const absolute = path.resolve(candidate);\n if (!isPathInside(root, absolute)) return false;\n if (lstatSync(absolute).isSymbolicLink() || !statSync(absolute).isFile()) return false;\n return isPathInside(realpathSync(root), realpathSync(absolute));\n } catch {\n return false;\n }\n}\n\nfunction canonicalPath(fileName: string): string {\n try {\n const real = realpathSync(fileName);\n return ts.sys.useCaseSensitiveFileNames ? real : real.toLowerCase();\n } catch {\n const absolute = path.resolve(fileName);\n return ts.sys.useCaseSensitiveFileNames ? absolute : absolute.toLowerCase();\n }\n}\n\nfunction graphDiagnostic(message: string, file?: string): DiagnosticRecord {\n return {\n schemaVersion: SCHEMA_VERSION,\n code: \"compiler-config\",\n severity: \"warning\",\n message,\n ...(file ? { file } : {}),\n };\n}\n\nfunction normalizeGraphDiagnostics(values: DiagnosticRecord[]): DiagnosticRecord[] {\n const byKey = new Map<string, DiagnosticRecord>();\n for (const value of values) byKey.set(`${value.file ?? \"\"}\\u0000${value.message}`, value);\n return [...byKey.values()].sort((a, b) =>\n compareText(`${a.file ?? \"\"}\\u0000${a.message}`, `${b.file ?? \"\"}\\u0000${b.message}`),\n );\n}\n\n/** A synchronous, root-anchored host for TypeScript config parsing and Program construction. */\nexport class BoundedTypeScriptFileSystem {\n readonly extendedConfigCache = new Map<string, ts.ExtendedConfigCacheEntry>();\n private readonly root: string;\n private readonly typeScriptLib: string;\n private readonly observedInputs = new Map<string, SemanticInputObservation>();\n\n constructor(root: string) {\n this.root = realpathSync(root);\n this.typeScriptLib = realpathSync(path.dirname(ts.getDefaultLibFilePath({})));\n }\n\n readonly fileExists = (fileName: string): boolean => {\n const absolute = this.absolute(fileName);\n if (!this.isPermitted(absolute)) return false;\n try {\n const exists = statSync(absolute).isFile();\n this.recordProbe(absolute, \"file\", exists);\n return exists;\n } catch {\n this.recordProbe(absolute, \"file\", false);\n return false;\n }\n };\n\n readonly readFile = (fileName: string): string | undefined => {\n const absolute = this.absolute(fileName);\n if (!this.isPermitted(absolute)) return undefined;\n try {\n const contents = readFileSync(absolute);\n this.recordRead(absolute, contents);\n return contents.toString(\"utf8\");\n } catch {\n let exists = false;\n try {\n exists = statSync(absolute).isFile();\n } catch {\n // The file is absent or cannot be inspected.\n }\n this.recordProbe(absolute, \"file\", exists);\n this.recordProbe(absolute, \"readable-file\", false);\n return undefined;\n }\n };\n\n readonly directoryExists = (directory: string): boolean => {\n const absolute = this.absolute(directory);\n if (!this.isPermitted(absolute)) return false;\n try {\n const exists = statSync(absolute).isDirectory();\n this.recordProbe(absolute, \"directory\", exists);\n return exists;\n } catch {\n this.recordProbe(absolute, \"directory\", false);\n return false;\n }\n };\n\n readonly getDirectories = (directory: string): string[] => {\n const absolute = this.absolute(directory);\n if (!this.isPermitted(absolute)) return [];\n if (!this.directoryExists(absolute)) return [];\n const directories = ts.sys\n .getDirectories(absolute)\n .filter((entry) => this.isPermitted(path.resolve(absolute, entry)))\n .sort(compareText);\n this.recordDirectoryListing(absolute, directories);\n return directories;\n };\n\n readonly readDirectory: ts.ParseConfigHost[\"readDirectory\"] = (\n rootDir,\n extensions,\n excludes,\n includes,\n depth,\n ) => {\n const absolute = this.absolute(rootDir);\n if (!this.isPermitted(absolute)) return [];\n return ts.sys\n .readDirectory(absolute, extensions, excludes, includes, depth)\n .filter((entry) => this.isPermitted(path.resolve(absolute, entry)))\n .sort(compareText);\n };\n\n readonly realpath = (candidate: string): string => {\n const absolute = this.absolute(candidate);\n if (!this.isPermitted(absolute)) return absolute;\n try {\n const real = realpathSync(absolute);\n this.recordSymlink(absolute, real);\n return real;\n } catch {\n return absolute;\n }\n };\n\n parseHost(currentDirectory: string): ts.ParseConfigFileHost {\n return {\n useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,\n getCurrentDirectory: () => currentDirectory,\n fileExists: this.fileExists,\n readFile: this.readFile,\n readDirectory: this.readDirectory,\n directoryExists: this.directoryExists,\n getDirectories: this.getDirectories,\n realpath: this.realpath,\n onUnRecoverableConfigFileDiagnostic: () => undefined,\n };\n }\n\n semanticInputs(): SemanticInputObservation[] {\n return [...this.observedInputs.values()].sort((a, b) =>\n compareText(semanticObservationKey(a), semanticObservationKey(b)),\n );\n }\n\n private recordProbe(\n absolute: string,\n targetKind: \"file\" | \"directory\" | \"readable-file\",\n exists: boolean,\n ): void {\n const scoped = this.semanticScope(absolute);\n if (!scoped) return;\n const relative = relativePosix(scoped.root, absolute);\n const contentKey =\n targetKind === \"directory\"\n ? `directory-listing\\u0000${scoped.scope}\\u0000${relative}`\n : scoped.scope === \"toolchain\"\n ? `toolchain-file\\u0000${relative}`\n : `file\\u0000${relative}`;\n if (this.observedInputs.has(contentKey)) return;\n const observation: SemanticInputObservation = {\n path: relative,\n kind: \"resolution-probe\",\n scope: scoped.scope,\n targetKind,\n exists,\n };\n this.observedInputs.set(semanticObservationKey(observation), observation);\n }\n\n private recordRead(absolute: string, contents: Buffer): void {\n if (isPathInside(this.root, absolute)) {\n const relative = relativePosix(this.root, absolute);\n this.observedInputs.delete(`resolution-probe\\u0000project\\u0000file\\u0000${relative}`);\n this.observedInputs.delete(\n `resolution-probe\\u0000project\\u0000readable-file\\u0000${relative}`,\n );\n const observation: SemanticInputObservation = {\n path: relative,\n kind: \"file\",\n hash: hashText(contents),\n };\n this.observedInputs.set(semanticObservationKey(observation), observation);\n return;\n }\n if (isPathInside(this.typeScriptLib, absolute)) {\n const relative = relativePosix(this.typeScriptLib, absolute);\n this.observedInputs.delete(`resolution-probe\\u0000toolchain\\u0000file\\u0000${relative}`);\n this.observedInputs.delete(\n `resolution-probe\\u0000toolchain\\u0000readable-file\\u0000${relative}`,\n );\n const observation: SemanticInputObservation = {\n // Preserve the lexical file TypeScript opened. Hashing only a resolved target would miss\n // a same-version standard-library symlink being repointed to different bytes.\n path: relative,\n kind: \"toolchain-file\",\n hash: hashText(contents),\n };\n this.observedInputs.set(semanticObservationKey(observation), observation);\n }\n }\n\n private recordDirectoryListing(absolute: string, entries: string[]): void {\n const scoped = this.semanticScope(absolute);\n if (!scoped) return;\n const relative = relativePosix(scoped.root, absolute);\n this.observedInputs.delete(\n `resolution-probe\\u0000${scoped.scope}\\u0000directory\\u0000${relative}`,\n );\n const observation: SemanticInputObservation = {\n path: relative,\n kind: \"directory-listing\",\n scope: scoped.scope,\n hash: semanticDirectoryListingHash(absolute, entries),\n };\n this.observedInputs.set(semanticObservationKey(observation), observation);\n }\n\n private recordSymlink(absolute: string, real: string): void {\n const scoped = this.semanticScope(absolute);\n if (!scoped) return;\n const relative = relativePosix(scoped.root, absolute);\n const target = isPathInside(scoped.root, real)\n ? relativePosix(scoped.root, real)\n : \"<outside-root>\";\n if (relative === target) return;\n const observation: SemanticInputObservation = {\n path: relative,\n kind: \"symlink\",\n scope: scoped.scope,\n target,\n };\n this.observedInputs.set(semanticObservationKey(observation), observation);\n }\n\n private semanticScope(\n absolute: string,\n ): { scope: \"project\" | \"toolchain\"; root: string } | undefined {\n if (isPathInside(this.root, absolute)) return { scope: \"project\", root: this.root };\n if (isPathInside(this.typeScriptLib, absolute)) {\n return { scope: \"toolchain\", root: this.typeScriptLib };\n }\n return undefined;\n }\n\n private isPermitted(candidate: string): boolean {\n const absolute = this.absolute(candidate);\n const lexicalInRoot = isPathInside(this.root, absolute);\n const lexicalInToolchain = isPathInside(this.typeScriptLib, absolute);\n const lexicalAllowed = lexicalInRoot || lexicalInToolchain;\n if (!lexicalAllowed) return false;\n if (!existsSync(absolute)) return true;\n try {\n const real = realpathSync(absolute);\n this.recordSymlink(absolute, real);\n return (\n (lexicalInRoot && isPathInside(this.root, real)) ||\n (lexicalInToolchain && isPathInside(this.typeScriptLib, real))\n );\n } catch {\n return false;\n }\n }\n\n private absolute(candidate: string): string {\n return path.isAbsolute(candidate)\n ? path.resolve(candidate)\n : path.resolve(this.root, candidate);\n }\n}\n\nexport function semanticDirectoryListingHash(directory: string, entries: string[]): string {\n const normalized = entries\n .map((entry) => normalizeStoredPath(path.relative(directory, path.resolve(directory, entry))))\n .sort(compareText);\n return hashText(Buffer.from(normalized.join(\"\\u0000\"), \"utf8\"));\n}\n\nfunction semanticObservationKey(observation: SemanticInputObservation): string {\n return observation.kind === \"resolution-probe\"\n ? `${observation.kind}\\u0000${observation.scope ?? \"project\"}\\u0000${observation.targetKind}\\u0000${observation.path}`\n : observation.kind === \"directory-listing\" || observation.kind === \"symlink\"\n ? `${observation.kind}\\u0000${observation.scope ?? \"project\"}\\u0000${observation.path}`\n : `${observation.kind}\\u0000${observation.path}`;\n}\n\nexport function fallbackCompilerOptions(root: string): ts.CompilerOptions {\n return {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.NodeNext,\n moduleResolution: ts.ModuleResolutionKind.NodeNext,\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n jsx: ts.JsxEmit.Preserve,\n experimentalDecorators: true,\n configFilePath: path.join(root, \"tsconfig.fallback.json\"),\n typeRoots: boundedTypeRoots(root, root),\n };\n}\n","import path from \"node:path\";\n\nimport ts from \"typescript\";\n\nimport { SCHEMA_VERSION } from \"./constants.js\";\nimport {\n BoundedTypeScriptFileSystem,\n fallbackCompilerOptions,\n sanitizeCompilerPathAliases,\n} from \"./compiler-units.js\";\nimport type {\n DiagnosticRecord,\n SemanticResolution,\n SemanticResolveInput,\n SemanticResolver,\n} from \"./types.js\";\nimport {\n isPathInside,\n isSafeRelativePathPattern,\n normalizeStoredPath,\n relativePosix,\n redactAbsolutePathsInText,\n} from \"./utils/path.js\";\nimport { compareText } from \"./utils/stable.js\";\n\nexport const TYPESCRIPT_SEMANTIC_VERSION = `compiler-units-v4+typescript-${ts.version}`;\n\n/** TypeScript remains authoritative for all TypeScript/JavaScript semantic facts. */\nexport class TypeScriptSemanticResolver implements SemanticResolver {\n readonly name = \"typescript-program\";\n readonly version = TYPESCRIPT_SEMANTIC_VERSION;\n\n constructor(private readonly jsDocParsingMode = ts.JSDocParsingMode.ParseAll) {}\n\n resolve(input: SemanticResolveInput): SemanticResolution {\n const compiler = loadCompilerConfiguration(input.root, input.tsconfig);\n const currentDirectory = input.tsconfig\n ? path.dirname(path.resolve(input.root, input.tsconfig))\n : input.root;\n const fileSystem = compiler.fileSystem;\n const host = createBoundedCompilerHost(\n input.root,\n currentDirectory,\n compiler.options,\n fileSystem,\n compiler.parsedCommands,\n );\n // Built-in scans need type evidence; public/custom resolvers retain full JSDoc by default.\n host.jsDocParsingMode = this.jsDocParsingMode;\n const cache = ts.createModuleResolutionCache(\n currentDirectory,\n (fileName) => host.getCanonicalFileName(fileName),\n compiler.options,\n );\n const resolveProjectReferenceModule = createProjectReferenceModuleResolver(\n input.root,\n compiler.projectReferences ?? [],\n fileSystem,\n compiler.parsedCommands,\n );\n const resolveModule = (\n moduleName: string,\n containingFile: string,\n ): ts.ResolvedModuleFull | undefined => {\n const normal = ts.resolveModuleName(\n moduleName,\n containingFile,\n compiler.options,\n host,\n cache,\n ).resolvedModule;\n return resolveProjectReferenceModule(moduleName) ?? normal;\n };\n host.resolveModuleNameLiterals = (moduleLiterals, containingFile) =>\n moduleLiterals.map((literal) => {\n const resolvedModule = resolveModule(literal.text, containingFile);\n return { resolvedModule };\n });\n const rootNames = [...new Set(input.sourceFiles.map((file) => path.resolve(file)))].sort(\n compareText,\n );\n const program = ts.createProgram({\n rootNames,\n options: compiler.options,\n ...(compiler.projectReferences?.length\n ? { projectReferences: compiler.projectReferences }\n : {}),\n host,\n // Reference edges are parsed and fingerprinted by the compiler-unit graph. A read-only\n // scanner resolves their source imports directly so correctness never depends on prebuilt\n // declaration outputs being present beside a referenced project.\n configFileParsingDiagnostics: compiler.rawDiagnostics,\n });\n return {\n program,\n checker: program.getTypeChecker(),\n pathAliases: compiler.pathAliases,\n diagnostics: compiler.diagnostics,\n semanticInputs: () => fileSystem.semanticInputs(),\n resolveModule(moduleName, containingFile) {\n const resolved = resolveModule(moduleName, containingFile);\n return resolved\n ? {\n resolvedFileName: resolved.resolvedFileName,\n isExternalLibraryImport: Boolean(resolved.isExternalLibraryImport),\n }\n : undefined;\n },\n };\n }\n}\n\ninterface ReferencedPackage {\n name: string;\n root: string;\n manifest: Record<string, unknown>;\n parsed: ts.ParsedCommandLine;\n}\n\n/**\n * TypeScript normally resolves a referenced package through its emitted declaration entrypoint.\n * A scanner cannot require users to build first, so map a missing referenced-package output back\n * to a source owned by that referenced project. This is deliberately limited to direct, in-root\n * references and static package metadata.\n */\nfunction createProjectReferenceModuleResolver(\n root: string,\n references: readonly ts.ProjectReference[],\n fileSystem: BoundedTypeScriptFileSystem,\n parsedCommands: Map<string, ts.ParsedCommandLine>,\n): (moduleName: string) => ts.ResolvedModuleFull | undefined {\n const packages: ReferencedPackage[] = [];\n for (const reference of references) {\n const configPath = ts.resolveProjectReferencePath(reference);\n if (!isPathInside(root, configPath)) continue;\n const parsed = parseCommand(root, configPath, fileSystem, parsedCommands);\n if (!parsed) continue;\n const packageRoot = path.dirname(configPath);\n const packageJsonPath = path.join(packageRoot, \"package.json\");\n const raw = fileSystem.readFile(packageJsonPath);\n if (!raw) continue;\n try {\n const manifest = JSON.parse(raw) as Record<string, unknown>;\n if (typeof manifest.name !== \"string\" || manifest.name.length === 0) continue;\n packages.push({ name: manifest.name, root: packageRoot, manifest, parsed });\n } catch {\n // Invalid package metadata remains a normal unresolved import.\n }\n }\n packages.sort((a, b) => b.name.length - a.name.length || compareText(a.name, b.name));\n\n return (moduleName) => {\n const referenced = packages.find(\n (candidate) => moduleName === candidate.name || moduleName.startsWith(`${candidate.name}/`),\n );\n if (!referenced) return undefined;\n const subpath =\n moduleName === referenced.name ? \"\" : moduleName.slice(referenced.name.length + 1);\n const source = referencedPackageSource(referenced, subpath, fileSystem);\n if (!source) return undefined;\n return {\n resolvedFileName: source,\n extension: moduleExtension(source),\n isExternalLibraryImport: false,\n };\n };\n}\n\nfunction referencedPackageSource(\n referenced: ReferencedPackage,\n subpath: string,\n fileSystem: BoundedTypeScriptFileSystem,\n): string | undefined {\n const { parsed, root: packageRoot, manifest } = referenced;\n // Composite project references default rootDir to the configuration directory. Assuming a\n // conventional src/ directory breaks valid root-level packages and declaration redirects.\n const rootDir = parsed.options.rootDir ?? packageRoot;\n if (!isPathInside(packageRoot, rootDir)) return undefined;\n const owned = new Set(parsed.fileNames.map((fileName) => path.resolve(fileName)));\n const requestedTargets = packageEntryTargets(manifest, subpath);\n const bases: string[] = [];\n\n for (const target of requestedTargets) {\n const absoluteTarget = path.resolve(packageRoot, target);\n if (!isPathInside(packageRoot, absoluteTarget)) continue;\n const outDir = parsed.options.outDir;\n if (outDir && isPathInside(outDir, absoluteTarget)) {\n bases.push(path.resolve(rootDir, path.relative(outDir, absoluteTarget)));\n }\n bases.push(absoluteTarget);\n }\n bases.push(path.resolve(rootDir, subpath || \"index\"));\n\n for (const base of bases) {\n for (const candidate of sourceModuleCandidates(base)) {\n const absolute = path.resolve(candidate);\n if (\n isPathInside(packageRoot, absolute) &&\n owned.has(absolute) &&\n fileSystem.fileExists(absolute)\n ) {\n return fileSystem.realpath(absolute);\n }\n }\n }\n\n const expectedStem = normalizeModuleStem(subpath || \"index\");\n const matching = [...owned]\n .filter((fileName) => isPathInside(rootDir, fileName))\n .filter((fileName) => {\n const relative = normalizeModuleStem(relativePosix(rootDir, fileName));\n return relative === expectedStem || relative === `${expectedStem}/index`;\n })\n .sort(compareText);\n return matching[0];\n}\n\nfunction packageEntryTargets(manifest: Record<string, unknown>, subpath: string): string[] {\n const output: string[] = [];\n const exportKey = subpath ? `./${subpath}` : \".\";\n const exportsValue = manifest.exports;\n if (exportsValue && typeof exportsValue === \"object\" && !Array.isArray(exportsValue)) {\n const exportsRecord = exportsValue as Record<string, unknown>;\n const keyed = exportsRecord[exportKey];\n collectStaticPackageTargets(\n keyed ?? (!subpath && !(\".\" in exportsRecord) ? exportsValue : undefined),\n output,\n );\n } else if (!subpath) {\n collectStaticPackageTargets(exportsValue, output);\n }\n if (!subpath) {\n for (const field of [\"types\", \"typings\", \"source\", \"module\", \"main\"] as const) {\n const value = manifest[field];\n if (typeof value === \"string\") output.push(value);\n }\n }\n return [...new Set(output)];\n}\n\nfunction collectStaticPackageTargets(value: unknown, output: string[]): void {\n if (typeof value === \"string\") {\n output.push(value);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) collectStaticPackageTargets(item, output);\n return;\n }\n if (!value || typeof value !== \"object\") return;\n const record = value as Record<string, unknown>;\n for (const key of [\"types\", \"import\", \"default\", \"require\", \"node\"]) {\n if (key in record) collectStaticPackageTargets(record[key], output);\n }\n}\n\nfunction sourceModuleCandidates(value: string): string[] {\n const stem = value\n .replace(/\\.d\\.(?:ts|mts|cts)$/i, \"\")\n .replace(/\\.(?:tsx?|mts|cts|jsx?|mjs|cjs)$/i, \"\");\n const extensions = [\".ts\", \".tsx\", \".mts\", \".cts\", \".js\", \".jsx\", \".mjs\", \".cjs\"];\n return [\n value,\n ...extensions.map((extension) => `${stem}${extension}`),\n ...extensions.map((extension) => path.join(stem, `index${extension}`)),\n ];\n}\n\nfunction normalizeModuleStem(value: string): string {\n return normalizeStoredPath(value)\n .replace(/\\.d\\.(?:ts|mts|cts)$/i, \"\")\n .replace(/\\.(?:tsx?|mts|cts|jsx?|mjs|cjs)$/i, \"\");\n}\n\nfunction moduleExtension(fileName: string): ts.Extension {\n const lower = fileName.toLowerCase();\n if (lower.endsWith(\".tsx\")) return ts.Extension.Tsx;\n if (lower.endsWith(\".mts\")) return ts.Extension.Mts;\n if (lower.endsWith(\".cts\")) return ts.Extension.Cts;\n if (lower.endsWith(\".jsx\")) return ts.Extension.Jsx;\n if (lower.endsWith(\".mjs\")) return ts.Extension.Mjs;\n if (lower.endsWith(\".cjs\")) return ts.Extension.Cjs;\n if (lower.endsWith(\".js\")) return ts.Extension.Js;\n return ts.Extension.Ts;\n}\n\nexport function createTypeScriptSemanticResolver(): SemanticResolver {\n return new TypeScriptSemanticResolver();\n}\n\nexport function createBoundedModuleResolver(\n root: string,\n currentDirectory: string,\n options: ts.CompilerOptions,\n): NonNullable<SemanticResolution[\"resolveModule\"]> {\n const fileSystem = new BoundedTypeScriptFileSystem(root);\n const cache = ts.createModuleResolutionCache(\n currentDirectory,\n (fileName) => (ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase()),\n options,\n );\n const host: ts.ModuleResolutionHost = {\n fileExists: fileSystem.fileExists,\n readFile: fileSystem.readFile,\n directoryExists: fileSystem.directoryExists,\n getDirectories: fileSystem.getDirectories,\n realpath: fileSystem.realpath,\n getCurrentDirectory: () => currentDirectory,\n useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,\n };\n return (moduleName, containingFile) => {\n const resolved = ts.resolveModuleName(\n moduleName,\n containingFile,\n options,\n host,\n cache,\n ).resolvedModule;\n return resolved\n ? {\n resolvedFileName: resolved.resolvedFileName,\n isExternalLibraryImport: Boolean(resolved.isExternalLibraryImport),\n }\n : undefined;\n };\n}\n\ninterface CompilerConfiguration {\n options: ts.CompilerOptions;\n projectReferences?: readonly ts.ProjectReference[];\n pathAliases: Record<string, string[]>;\n diagnostics: DiagnosticRecord[];\n rawDiagnostics: readonly ts.Diagnostic[];\n fileSystem: BoundedTypeScriptFileSystem;\n parsedCommands: Map<string, ts.ParsedCommandLine>;\n}\n\nfunction loadCompilerConfiguration(root: string, tsconfig?: string): CompilerConfiguration {\n const fileSystem = new BoundedTypeScriptFileSystem(root);\n if (!tsconfig) {\n return {\n options: fallbackCompilerOptions(root),\n pathAliases: {},\n diagnostics: [],\n rawDiagnostics: [],\n fileSystem,\n parsedCommands: new Map(),\n };\n }\n\n const absolute = path.resolve(root, tsconfig);\n if (!isPathInside(root, absolute) || !fileSystem.fileExists(absolute)) {\n const diagnostic: DiagnosticRecord = {\n schemaVersion: SCHEMA_VERSION,\n code: \"compiler-config\",\n severity: \"warning\",\n message:\n \"The owning TypeScript configuration was unavailable or unsafe; fallback options were used.\",\n ...(isPathInside(root, absolute) ? { file: relativePosix(root, absolute) } : {}),\n };\n return {\n options: fallbackCompilerOptions(root),\n pathAliases: {},\n diagnostics: [diagnostic],\n rawDiagnostics: [],\n fileSystem,\n parsedCommands: new Map(),\n };\n }\n\n const parsedCommands = new Map<string, ts.ParsedCommandLine>();\n const parsed = parseCommand(root, absolute, fileSystem, parsedCommands);\n if (!parsed) {\n return {\n options: fallbackCompilerOptions(root),\n pathAliases: {},\n diagnostics: [\n {\n schemaVersion: SCHEMA_VERSION,\n code: \"compiler-config\",\n severity: \"warning\",\n message:\n \"The owning TypeScript configuration could not be parsed; fallback options were used.\",\n file: relativePosix(root, absolute),\n },\n ],\n rawDiagnostics: [],\n fileSystem,\n parsedCommands,\n };\n }\n const projectReferences = (parsed.projectReferences ?? []).filter((reference) => {\n const target = ts.resolveProjectReferencePath(reference);\n return isPathInside(root, target) && fileSystem.fileExists(target);\n });\n const options = parsed.options;\n anchorCompilerOptions(root, path.dirname(absolute), options);\n return {\n options,\n ...(projectReferences.length > 0 ? { projectReferences } : {}),\n pathAliases: pathAliases(root, path.dirname(absolute), options),\n diagnostics: parsed.errors.map((diagnostic) => compilerDiagnostic(diagnostic, root)),\n rawDiagnostics: parsed.errors,\n fileSystem,\n parsedCommands,\n };\n}\n\nfunction parseCommand(\n root: string,\n configPath: string,\n fileSystem: BoundedTypeScriptFileSystem,\n cache: Map<string, ts.ParsedCommandLine>,\n): ts.ParsedCommandLine | undefined {\n const absolute = path.resolve(configPath);\n const cached = cache.get(absolute);\n if (cached) return cached;\n if (!isPathInside(root, absolute) || !fileSystem.fileExists(absolute)) return undefined;\n try {\n const source = ts.readJsonConfigFile(absolute, fileSystem.readFile);\n const parsed = ts.parseJsonSourceFileConfigFileContent(\n source,\n fileSystem.parseHost(path.dirname(absolute)),\n path.dirname(absolute),\n undefined,\n absolute,\n undefined,\n undefined,\n fileSystem.extendedConfigCache,\n );\n parsed.projectReferences = (parsed.projectReferences ?? []).filter((reference) => {\n const target = ts.resolveProjectReferencePath(reference);\n return isPathInside(root, target) && fileSystem.fileExists(target);\n });\n anchorCompilerOptions(root, path.dirname(absolute), parsed.options);\n cache.set(absolute, parsed);\n return parsed;\n } catch {\n return undefined;\n }\n}\n\nfunction createBoundedCompilerHost(\n root: string,\n currentDirectory: string,\n options: ts.CompilerOptions,\n fileSystem: BoundedTypeScriptFileSystem,\n parsedCommands: Map<string, ts.ParsedCommandLine>,\n): ts.CompilerHost {\n const host = ts.createCompilerHost(options, true) as ts.CompilerHost & {\n useSourceOfProjectReferenceRedirect?: () => boolean;\n };\n host.getCurrentDirectory = () => currentDirectory;\n host.fileExists = fileSystem.fileExists;\n host.readFile = fileSystem.readFile;\n host.directoryExists = fileSystem.directoryExists;\n host.getDirectories = fileSystem.getDirectories;\n host.readDirectory = (rootDir, extensions, excludes, includes, depth) => [\n ...fileSystem.readDirectory(rootDir, extensions, excludes, includes, depth),\n ];\n host.realpath = fileSystem.realpath;\n host.getEnvironmentVariable = () => \"\";\n host.writeFile = () => undefined;\n host.getParsedCommandLine = (configFileName) =>\n parseCommand(root, configFileName, fileSystem, parsedCommands);\n host.useSourceOfProjectReferenceRedirect = () => true;\n return host;\n}\n\nfunction anchorCompilerOptions(\n root: string,\n unitDirectory: string,\n options: ts.CompilerOptions,\n): void {\n options.configFilePath = options.configFilePath ?? path.join(unitDirectory, \"tsconfig.json\");\n if (!options.typeRoots) options.typeRoots = boundedTypeRoots(root, unitDirectory);\n else options.typeRoots = options.typeRoots.filter((entry) => isPathInside(root, entry));\n if (options.baseUrl && !isPathInside(root, options.baseUrl)) options.baseUrl = undefined;\n if (options.rootDirs)\n options.rootDirs = options.rootDirs.filter((entry) => isPathInside(root, entry));\n sanitizeCompilerPathAliases(options);\n}\n\nfunction boundedTypeRoots(root: string, start: string): string[] {\n const values: string[] = [];\n let current = path.resolve(start);\n while (isPathInside(root, current)) {\n values.push(path.join(current, \"node_modules\", \"@types\"));\n if (current === path.resolve(root)) break;\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return [...new Set(values)];\n}\n\nfunction pathAliases(\n root: string,\n configDirectory: string,\n options: ts.CompilerOptions,\n): Record<string, string[]> {\n const base =\n options.baseUrl ??\n (options as ts.CompilerOptions & { pathsBasePath?: string }).pathsBasePath ??\n configDirectory;\n const paths = (options.paths ?? {}) as Record<string, string[]>;\n return Object.fromEntries(\n Object.entries(paths)\n .filter(([alias]) => isSafeRelativePathPattern(alias))\n .sort(([a], [b]) => compareText(a, b))\n .map(([alias, values]) => [\n alias,\n values\n .filter(isSafeRelativePathPattern)\n .map((value) => path.resolve(base, value))\n .filter((value) => isPathInside(root, value))\n .map((value) => normalizeStoredPath(relativePosix(root, value)))\n .filter((value, index, entries) => entries.indexOf(value) === index)\n .sort(compareText),\n ]),\n );\n}\n\nexport function compilerDiagnostic(diagnostic: ts.Diagnostic, root: string): DiagnosticRecord {\n const message = sanitizeCompilerMessage(\n ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\"),\n root,\n );\n const file = diagnostic.file;\n const start =\n file && diagnostic.start !== undefined\n ? file.getLineAndCharacterOfPosition(diagnostic.start)\n : undefined;\n let relativeFile: string | undefined;\n if (file) {\n try {\n relativeFile = relativePosix(root, file.fileName);\n } catch {\n // Never persist absolute or out-of-root compiler paths.\n }\n }\n return {\n schemaVersion: SCHEMA_VERSION,\n code: diagnostic.file ? \"parse-error\" : \"compiler-config\",\n severity:\n diagnostic.category === ts.DiagnosticCategory.Error\n ? \"error\"\n : diagnostic.category === ts.DiagnosticCategory.Warning\n ? \"warning\"\n : \"info\",\n message,\n ...(relativeFile ? { file: relativeFile } : {}),\n ...(start ? { line: start.line + 1, column: start.character + 1 } : {}),\n };\n}\n\nfunction sanitizeCompilerMessage(message: string, root: string): string {\n return redactAbsolutePathsInText(message, root) || \"TypeScript reported a compiler diagnostic.\";\n}\n"],"mappings":";AAAA,SAAS,eAAe;AACxB,SAAS,YAAY,kBAAkB;;;ACDvC,SAAS,YAAYA,WAAU;AAC/B,OAAOC,WAAU;AAEjB,OAAOC,SAAQ;;;ACHR,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,mBAA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;AAClE,SAAO,0BAA0B,OAAO,IAAI,KAAK;AACnD;;;ADvoCA,IAAI,CAAC,WAAY,OAAM,IAAI,MAAM,yCAAyC;AAC1E,IAAM,SAAS,MAAM,2BAA2B,UAAiC;AAGjF,IAAM,UAAU,IAAI,QAAQ;AAC5B,QAAQ,QAAQ;AAChB,IAAI;AACF,QAAM,QAAQ,KAAK,6BAA6B;AAClD,UAAE;AACA,UAAQ,WAAW;AACrB;AACA,WAAW,YAAY,MAAM;AAC7B,WAAW,MAAM;","names":["fs","path","ts","path","fs","path","path","relation","path","ts","ts","result","fallback","sourceFile","path","declaration","specifier","ts","ts","ts","source","path","ts","path","makeRelation","routeSegments","ts","path","makeRelation","path","ts","path","hasDirective","ts","isNameExported","isFunctionLikeExpression","symbol","makeRelation","ts","hasDirective","visit","isNameExported","isFunctionLikeExpression","dedupe","path","relative","findExportedDeclaration","findDeclarationByName","makeRelation","path","ts","path","path","ts","path","ts","ts","path","ts","path","boundedTypeRoots","ts","path","relation","rangesEqual","rangeContains","ts","name"]}
|