import type { ThymianFormat, ThymianHttpTransaction } from '@thymian/core'; import { nearestPathHints } from './nearest-paths.js'; import { canonicalPath, compareSelectors, encodePath, formatRequestSelector, parseSelector, type Selector, selectorForTransaction, type SelectorParts, } from './selector.js'; import { selectorCollisionError, unknownSelectorError, } from './selector-errors.js'; import { pathOf } from './transaction-filter.js'; const MAX_NEAR_MISSES = 5; export type TransactionCatalogEntry = readonly [ Selector, ThymianHttpTransaction, ]; /** * A bijection between the selectors of a loaded `ThymianFormat` and its * transactions. * * Built once per format load and thrown away with the format — it is cheap, and * caching it on `format.toHash()` would reintroduce exactly the staleness the * selector exists to remove. */ export class TransactionCatalog { private constructor( private readonly bySelector: Map, private readonly orderedEntries: readonly TransactionCatalogEntry[], private readonly selectorByTransactionId: ReadonlyMap, private readonly distinctPaths: readonly string[], private readonly byOperation: ReadonlyMap< string, readonly TransactionCatalogEntry[] >, ) {} /** * One pass over `format.getThymianHttpTransactions()`, then a sort. * * @throws `SelectorCollisionError` as soon as two transactions render the same * selector. That is the only hard error here. Rendering is total and * injective, so no description can make catalog construction impossible and no * two *distinct* transactions can collide by accident of encoding: a collision * means two sources describe the same method, path, status and media types, * and a selector is host-stripped, so nothing distinguishes them. Silently * picking one would make a hook target whichever load order won. */ static fromThymianFormat(format: ThymianFormat): TransactionCatalog { const bySelector = new Map(); for (const transaction of format.getThymianHttpTransactions()) { const selector = selectorForTransaction(transaction); const existing = bySelector.get(selector); if (existing) { throw selectorCollisionError(selector, existing, transaction); } bySelector.set(selector, transaction); } const orderedEntries: TransactionCatalogEntry[] = [...bySelector.entries()] .sort(([a], [b]) => compareSelectors(a, b)) .map(([selector, transaction]) => [selector, transaction] as const); const byOperation = new Map(); for (const entry of orderedEntries) { const operation = formatRequestSelector(entry[1].thymianReq); byOperation.set(operation, [ ...(byOperation.get(operation) ?? []), entry, ]); } return new TransactionCatalog( bySelector, orderedEntries, new Map( orderedEntries.map(([selector, transaction]) => [ transaction.transactionId, selector, ]), ), [ ...new Set( orderedEntries.map(([, transaction]) => pathOf(transaction)), ), ].sort(), byOperation, ); } get size(): number { return this.bySelector.size; } /** * Selectors sorted by selector. * * The order is a decision, not an accident: it is the order the generated type * surface is emitted in, so sorting is what makes reordering paths or schemas * in the source document a drift non-event. Correctness never depends on it. */ selectors(): readonly Selector[] { return this.orderedEntries.map(([selector]) => selector); } entries(): readonly TransactionCatalogEntry[] { return this.orderedEntries; } /** * Every distinct path the catalog holds, sorted — the universe a path glob is * matched against, and the set a vacuous glob fails against. * * Derived once at construction, like the selector index: both are read once * per hook that targets by filter, and the catalog is rebuilt per format load * anyway. */ paths(): readonly string[] { return this.distinctPaths; } /** * Every Transaction the same operation declares — the responses a call to * `transaction` may legitimately be answered with. * * Grouped by the **request half of the selector**, which is what the * generated `Responses` map is keyed by, so the union the types promise and * the set the runtime checks against are built by one rule. Two sources * describing the same operation contribute to one group; that is a superset, * and a superset is the safe direction — it never calls a declared response * undeclared. */ responsesOf( transaction: ThymianHttpTransaction, ): readonly TransactionCatalogEntry[] { return ( this.byOperation.get(formatRequestSelector(transaction.thymianReq)) ?? [] ); } /** The selector one transaction renders as, for a diagnostic that has the id. */ selectorFor(transactionId: string): Selector | undefined { return this.selectorByTransactionId.get(transactionId); } /** Every Transaction, in catalog order. */ transactions(): readonly ThymianHttpTransaction[] { return this.orderedEntries.map(([, transaction]) => transaction); } /** Never throws. Use where a miss is an expected outcome. */ tryResolve(selector: string): ThymianHttpTransaction | undefined { return this.bySelector.get(selector); } /** * A plain map lookup. Parsing happens only after a miss, to tell the caller * whether the selector was malformed or merely unknown — never on the happy * path. * * @throws `MalformedSelectorError` when the input is not a selector, * `UnknownSelectorError` when it is well-formed but names nothing loaded. */ resolve(selector: string): ThymianHttpTransaction { const transaction = this.bySelector.get(selector); if (transaction) { return transaction; } throw unknownSelectorError( selector, this.nearMissSuggestions(parseSelector(selector)), ); } /** * What to say to someone who named a selector nothing answers to. * * Public because the hook loader needs the same sentences without wanting the * throw: it has already missed through {@link tryResolve}, and asking for the * diagnostic by catching a second, deliberately failing lookup would make the * error channel do the work of a query. */ nearMissSuggestions(parts: SelectorParts): string[] { // An empty catalog is a state core explicitly warns about ("No nodes found // in Thymian format"). Sending the user after a path typo would be wrong // advice: no path would have resolved. if (this.size === 0) { return [ 'No transactions are loaded, so no selector can resolve. Check that your configured specifications were found and describe at least one operation.', ]; } const candidates = this.nearMisses(parts); if (candidates.length > 0) { return [ 'Did you mean one of these selectors?', ...candidates.map((candidate) => `"${candidate}"`), ]; } // No transaction shares this exact path under any method, so the typo is // most likely in the path itself. Falls back to the same prefix walk a // vacuous filter path value gets, so a path typo in a Selector is // diagnosed the same way one in a filter is — one near-miss story, not // two that could disagree. // `canonicalPath`, matching how `distinctPaths` is spelled (`pathOf`). // `encodePath` adds selector quoting for a path carrying whitespace or // `>`, and a quoted needle never prefix-matches an unquoted haystack — so // exactly the paths whose spelling is hardest to guess got no suggestion // and fell through to the bare "no path begins with" line. return nearestPathHints(canonicalPath(parts.path), this.distinctPaths); } /** * Deterministic rank buckets, in catalog order: same method and path first, * then the same path under another method. No fuzzy matching — it would add a * dependency and make the ordering unexplainable. */ private nearMisses(parts: SelectorParts): Selector[] { const sameMethod: Selector[] = []; const otherMethod: Selector[] = []; const path = encodePath(parts.path); for (const [selector, transaction] of this.orderedEntries) { if (encodePath(transaction.thymianReq.path) !== path) { continue; } if (transaction.thymianReq.method.toUpperCase() === parts.method) { sameMethod.push(selector); } else { otherMethod.push(selector); } } return [...sameMethod, ...otherMethod].slice(0, MAX_NEAR_MISSES); } }