import { lineStarts, toPosition } from '@internals/utils' import { ast, type FileNode, type InputNode, type OperationNode } from '@kubb/ast' import type { Adapter, Hookable, KubbHooks, Parser } from '@kubb/core' import type { CodeDeclaration, CodeIndex, InputOperation, InputPositions } from './protocol.ts' export type CodeIndexerOptions = { /** The hooks of the build to index. */ hooks: Hookable /** `false` when the written files will not match what Kubb printed, such as after a formatter. */ placeDeclarations: boolean /** Turns a written path into one relative to the project root. */ relativePath: (root: string, filePath: string) => string } /** Links the input of a build to the generated code, placing each declaration as Kubb writes its file. It keeps no file text. */ export class CodeIndexer { readonly #placeDeclarations: boolean readonly #relativePath: CodeIndexerOptions['relativePath'] readonly #declarations: Array = [] readonly #unhook: () => void #root = '.' #parsers = new Map() constructor({ hooks, placeDeclarations, relativePath }: CodeIndexerOptions) { this.#placeDeclarations = placeDeclarations this.#relativePath = relativePath this.#unhook = hooks.addHooks({ 'kubb:build:start': ({ config }) => { this.#root = config.root // The last parser that claims an extension wins, as in core. this.#parsers = new Map(config.parsers.flatMap((parser) => (parser.extNames ?? []).map((extname) => [extname, parser] as const))) }, 'kubb:file:processed': ({ file, source }) => this.#add(file, source), }) } /** Stops listening to the build. Safe to call twice. */ close(): void { this.#unhook() } /** The {@link CodeIndex} of the build. The adapter's `locate` places the keys in `inputFile`, the spec file. */ build({ input, inputFile }: { input: InputNode | null; inputFile?: { adapter: Adapter | undefined; text: string; path: string } }): CodeIndex { const { operations, refs } = indexInput(input) const pointers = [...new Set([...this.#declarations.map((item) => item.pointer), ...operations.map((operation) => operation.pointer)])] const inputPositions = inputFile && locate({ ...inputFile, pointers, kindOf: createKindOf(operations) }) return { declarations: this.#declarations, operations, refs, ...(inputPositions && { inputPositions }) } } /** One declaration per source of `file` that names an input key, placed where the file's parser finds its name. */ #add(file: FileNode, text: string): void { if (!file.sources.some((item) => item.pointer)) return const positionOf = findPositions(text, this.#placeDeclarations ? this.#parsers.get(file.extname) : undefined) const path = this.#relativePath(this.#root, file.path) for (const { name, pointer } of file.sources) { if (name && pointer) this.#declarations.push({ name, pointer, path, ...positionOf(name) }) } } } export function createCodeIndexer(options: CodeIndexerOptions): CodeIndexer { return new CodeIndexer(options) } /** For the adapter's `locate`: an operation when the pointer is one of the input's operations or sits under one; a schema otherwise. */ function createKindOf(operations: ReadonlyArray): (pointer: string) => 'schema' | 'operation' { const pointers = new Set(operations.map((operation) => operation.pointer)) return (pointer) => { for (let at = pointer; at.includes('/'); at = at.slice(0, at.lastIndexOf('/'))) { if (pointers.has(at)) return 'operation' } return 'schema' } } /** The operations of the input, and for each operation and named schema the schema pointers it references directly. */ function indexInput(input: InputNode | null): { operations: Array; refs: Record> } { if (!input) return { operations: [], refs: {} } const located = input.operations.filter((operation): operation is OperationNode & { pointer: string } => Boolean(operation.pointer)) const operations = located.map(({ pointer, operationId, method, path }) => ({ pointer, operationId: operationId || undefined, method, path })) const named = input.schemas.filter((schema) => schema.name && schema.pointer) const pointerByName = new Map(named.map((schema) => [schema.name!, schema.pointer!])) const toPointers = (names: Iterable) => [...names].flatMap((name) => pointerByName.get(name) ?? []) const refs: Record> = {} // Without the schema list the walk stops at the schemas an operation names itself. for (const operation of located) refs[operation.pointer] = toPointers(ast.graph.getUsedNames([operation], [])) for (const schema of named) refs[schema.pointer!] = toPointers(ast.graph.getRefNames(schema)) return { operations, refs } } /** Places each pointer in the input text with the adapter's `locate`. `undefined` when it places none. */ function locate({ adapter, text, path, pointers, kindOf, }: { adapter: Adapter | undefined text: string path: string pointers: ReadonlyArray kindOf: (pointer: string) => 'schema' | 'operation' }): InputPositions | undefined { if (!adapter?.locate) return undefined const starts = lineStarts(text) const positions: InputPositions['positions'] = {} try { for (const pointer of pointers) { const range = adapter.locate(text, { kind: kindOf(pointer), pointer }) if (range) positions[pointer] = toPosition(starts, range.start) } } catch { // A third-party adapter's `locate` must not fail a generation that already finished. return undefined } if (!Object.keys(positions).length) return undefined return { path, positions } } /** The position of each name that `parser` finds in `text`, as the storage writes it. */ function findPositions(text: string, parser: Parser | undefined): (name: string) => { line: number; column: number } | undefined { // The storage trims leading whitespace before it writes, so positions are counted in the trimmed text. const written = text.trimStart() const found = parser?.find?.(written) if (!found?.length) return () => undefined const offsets = new Map(found.toReversed().map((item) => [item.name, item.offset])) const starts = lineStarts(written) return (name) => { const offset = offsets.get(name) return offset === undefined ? undefined : toPosition(starts, offset) } }