@warlock.js/grimoire 5.63.1 → 5.65.0
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/CHANGELOG.md +61 -0
- package/esm/book/build.d.mts.map +1 -1
- package/esm/book/build.mjs +24 -2
- package/esm/book/build.mjs.map +1 -1
- package/esm/check/check-grimoire.d.mts.map +1 -1
- package/esm/check/check-grimoire.mjs +11 -1
- package/esm/check/check-grimoire.mjs.map +1 -1
- package/esm/check/rules/api-snapshot.mjs +39 -0
- package/esm/check/rules/api-snapshot.mjs.map +1 -0
- package/esm/check/rules/code-rules.mjs +45 -0
- package/esm/check/rules/code-rules.mjs.map +1 -0
- package/esm/check/rules/drift.mjs +54 -0
- package/esm/check/rules/drift.mjs.map +1 -0
- package/esm/check/rules/focused-tests.mjs +39 -0
- package/esm/check/rules/focused-tests.mjs.map +1 -0
- package/esm/check/rules/shows.mjs +52 -0
- package/esm/check/rules/shows.mjs.map +1 -0
- package/esm/codes/codes.d.mts +48 -0
- package/esm/codes/codes.d.mts.map +1 -1
- package/esm/codes/codes.mjs +26 -1
- package/esm/codes/codes.mjs.map +1 -1
- package/esm/contracts/adapter.d.mts +6 -0
- package/esm/contracts/adapter.d.mts.map +1 -1
- package/esm/contracts/guard.d.mts +104 -0
- package/esm/contracts/guard.d.mts.map +1 -0
- package/esm/contracts/index.mjs +5 -0
- package/esm/contracts/matrix.d.mts +75 -0
- package/esm/contracts/matrix.d.mts.map +1 -0
- package/esm/contracts/scry.d.mts +42 -0
- package/esm/contracts/scry.d.mts.map +1 -1
- package/esm/contracts/settings.d.mts +71 -0
- package/esm/contracts/settings.d.mts.map +1 -0
- package/esm/contracts/settings.mjs +67 -0
- package/esm/contracts/settings.mjs.map +1 -0
- package/esm/contracts/shots.d.mts +146 -0
- package/esm/contracts/shots.d.mts.map +1 -0
- package/esm/contracts/snapshot.d.mts +10 -0
- package/esm/contracts/snapshot.d.mts.map +1 -1
- package/esm/contracts/written.d.mts +13 -0
- package/esm/contracts/written.d.mts.map +1 -1
- package/esm/contracts/written.mjs +7 -1
- package/esm/contracts/written.mjs.map +1 -1
- package/esm/devtools/approvals.mjs +59 -0
- package/esm/devtools/approvals.mjs.map +1 -0
- package/esm/devtools/data.mjs +2 -0
- package/esm/devtools/data.mjs.map +1 -1
- package/esm/devtools/graphs.mjs +13 -3
- package/esm/devtools/graphs.mjs.map +1 -1
- package/esm/devtools/index.d.mts +7 -0
- package/esm/devtools/index.d.mts.map +1 -1
- package/esm/devtools/index.mjs +33 -3
- package/esm/devtools/index.mjs.map +1 -1
- package/esm/devtools/matrix.mjs +207 -0
- package/esm/devtools/matrix.mjs.map +1 -0
- package/esm/devtools/product-map.d.mts.map +1 -1
- package/esm/devtools/product-map.mjs +87 -1
- package/esm/devtools/product-map.mjs.map +1 -1
- package/esm/devtools/site.d.mts.map +1 -1
- package/esm/devtools/site.mjs +12 -3
- package/esm/devtools/site.mjs.map +1 -1
- package/esm/devtools/snapshot-source.mjs +13 -3
- package/esm/devtools/snapshot-source.mjs.map +1 -1
- package/esm/git/index.d.mts +20 -0
- package/esm/git/index.d.mts.map +1 -0
- package/esm/git/index.mjs +280 -0
- package/esm/git/index.mjs.map +1 -0
- package/esm/guard/api.mjs +70 -0
- package/esm/guard/api.mjs.map +1 -0
- package/esm/guard/assertions.mjs +18 -0
- package/esm/guard/assertions.mjs.map +1 -0
- package/esm/guard/collect.mjs +139 -0
- package/esm/guard/collect.mjs.map +1 -0
- package/esm/guard/format.mjs +27 -0
- package/esm/guard/format.mjs.map +1 -0
- package/esm/guard/glob.mjs +79 -0
- package/esm/guard/glob.mjs.map +1 -0
- package/esm/guard/index.mjs +9 -0
- package/esm/guard/rules.mjs +310 -0
- package/esm/guard/rules.mjs.map +1 -0
- package/esm/guard/scope.mjs +95 -0
- package/esm/guard/scope.mjs.map +1 -0
- package/esm/index.d.mts +10 -3
- package/esm/index.mjs +6 -2
- package/esm/paths/index.d.mts +15 -1
- package/esm/paths/index.d.mts.map +1 -1
- package/esm/paths/index.mjs +27 -3
- package/esm/paths/index.mjs.map +1 -1
- package/esm/proves/index.mjs +2 -1
- package/esm/proves/scan-proofs.mjs +1 -1
- package/esm/proves/scan-proofs.mjs.map +1 -1
- package/esm/proves/scan-shows.d.mts +21 -0
- package/esm/proves/scan-shows.d.mts.map +1 -0
- package/esm/proves/scan-shows.mjs +168 -0
- package/esm/proves/scan-shows.mjs.map +1 -0
- package/esm/releases/index.d.mts.map +1 -1
- package/esm/releases/index.mjs +5 -3
- package/esm/releases/index.mjs.map +1 -1
- package/esm/releases/stamp.mjs +121 -0
- package/esm/releases/stamp.mjs.map +1 -0
- package/esm/rules/focused.mjs +26 -0
- package/esm/rules/focused.mjs.map +1 -0
- package/esm/rules/index.mjs +88 -0
- package/esm/rules/index.mjs.map +1 -0
- package/esm/rules/logical-css.mjs +112 -0
- package/esm/rules/logical-css.mjs.map +1 -0
- package/esm/rules/no-js-imports.mjs +22 -0
- package/esm/rules/no-js-imports.mjs.map +1 -0
- package/esm/rules/scan.mjs +196 -0
- package/esm/rules/scan.mjs.map +1 -0
- package/esm/rules/specific-errors.mjs +51 -0
- package/esm/rules/specific-errors.mjs.map +1 -0
- package/esm/rules/type-discriminator.mjs +27 -0
- package/esm/rules/type-discriminator.mjs.map +1 -0
- package/esm/scry/also-changes.mjs +107 -0
- package/esm/scry/also-changes.mjs.map +1 -0
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +35 -0
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +40 -2
- package/esm/scry/query.mjs.map +1 -1
- package/esm/scry/search.d.mts.map +1 -1
- package/esm/scry/search.mjs +43 -11
- package/esm/scry/search.mjs.map +1 -1
- package/esm/shots/approve.mjs +195 -0
- package/esm/shots/approve.mjs.map +1 -0
- package/esm/shots/drift.mjs +174 -0
- package/esm/shots/drift.mjs.map +1 -0
- package/esm/shots/png.mjs +166 -0
- package/esm/shots/png.mjs.map +1 -0
- package/esm/shots/state.mjs +43 -0
- package/esm/shots/state.mjs.map +1 -0
- package/esm/shots/store.mjs +66 -0
- package/esm/shots/store.mjs.map +1 -0
- package/esm/shots/touched.mjs +38 -0
- package/esm/shots/touched.mjs.map +1 -0
- package/esm/warlock/adapter.d.mts.map +1 -1
- package/esm/warlock/adapter.mjs +22 -2
- package/esm/warlock/adapter.mjs.map +1 -1
- package/esm/warlock/api-command.mjs +41 -0
- package/esm/warlock/api-command.mjs.map +1 -0
- package/esm/warlock/approve-command.mjs +80 -0
- package/esm/warlock/approve-command.mjs.map +1 -0
- package/esm/warlock/collect-off-thread.mjs +66 -0
- package/esm/warlock/collect-off-thread.mjs.map +1 -0
- package/esm/warlock/commands.d.mts +1 -1
- package/esm/warlock/commands.d.mts.map +1 -1
- package/esm/warlock/commands.mjs +61 -8
- package/esm/warlock/commands.mjs.map +1 -1
- package/esm/warlock/guard-command.mjs +116 -0
- package/esm/warlock/guard-command.mjs.map +1 -0
- package/esm/warlock/index.d.mts +2 -1
- package/esm/warlock/index.mjs +2 -1
- package/esm/warlock/languages.mjs +75 -0
- package/esm/warlock/languages.mjs.map +1 -0
- package/esm/warlock/mcp-tools.mjs +2 -2
- package/esm/warlock/mcp-tools.mjs.map +1 -1
- package/esm/warlock/release-command.mjs +65 -0
- package/esm/warlock/release-command.mjs.map +1 -0
- package/esm/warlock/shows.d.mts +35 -0
- package/esm/warlock/shows.d.mts.map +1 -0
- package/esm/warlock/shows.mjs +195 -0
- package/esm/warlock/shows.mjs.map +1 -0
- package/esm/workspace/cache.mjs +4 -1
- package/esm/workspace/cache.mjs.map +1 -1
- package/esm/workspace/derived.mjs +11 -6
- package/esm/workspace/derived.mjs.map +1 -1
- package/esm/workspace/index.d.mts.map +1 -1
- package/esm/workspace/index.mjs +8 -1
- package/esm/workspace/index.mjs.map +1 -1
- package/esm/workspace/stored.mjs +4 -1
- package/esm/workspace/stored.mjs.map +1 -1
- package/esm/written/features.mjs +21 -5
- package/esm/written/features.mjs.map +1 -1
- package/esm/written/index.mjs +2 -1
- package/esm/written/parse-grimoire.d.mts.map +1 -1
- package/esm/written/parse-grimoire.mjs +16 -3
- package/esm/written/parse-grimoire.mjs.map +1 -1
- package/esm/written/settings.d.mts +11 -0
- package/esm/written/settings.d.mts.map +1 -0
- package/esm/written/settings.mjs +88 -0
- package/esm/written/settings.mjs.map +1 -0
- package/llms-full.txt +282 -39
- package/llms.txt +2 -0
- package/package.json +3 -3
- package/skills/backfill-a-grimoire/SKILL.md +4 -0
- package/skills/describe-an-app/SKILL.md +4 -1
- package/skills/guard-a-change/SKILL.md +85 -0
- package/skills/index.md +7 -3
- package/skills/record-a-change/SKILL.md +52 -16
- package/skills/review-a-change/SKILL.md +53 -0
- package/skills/use-the-grimoire/SKILL.md +27 -18
- package/skills/write-a-feature/SKILL.md +42 -1
- package/ui/grimoire-view.js +756 -40
- package/ui/grimoire.css +303 -28
- package/ui/product-map.css +43 -7
- package/ui/product-map.js +212 -37
package/esm/scry/query.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"sourcesContent":["/**\n * Answers one scry query from a snapshot. Pure: reads the snapshot only.\n */\nimport { packagesOf } from \"../book\";\nimport { normalizeRoutePath, routeMatches } from \"../bookmap\";\nimport { checkGrimoire } from \"../check\";\nimport { GrimoireError } from \"../codes\";\nimport type { BookFile, BookRoute } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookEntry } from \"../contracts/book\";\nimport type { FeatureBookmap, FlowBookmap } from \"../contracts/bookmap\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryImpactResult,\n ScryNotes,\n ScryPageRef,\n ScryQuery,\n ScryResult,\n ScryRoutePage,\n ScryRouteResult,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport { fileGraph, importClosure, importerClosure } from \"../graph\";\nimport { bookEntryPaths, projectPath, toPosixPath } from \"../paths\";\nimport { searchSnapshot, wordsOf } from \"./search\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\nconst sortedUnique = (items: Iterable<string>): string[] => [...new Set(items)].sort(byText);\n\n/** Route facts with routes but none that names its source file: only the core list was read, not the app's routes files. */\nconst INCOMPLETE_ROUTES = \"route facts look incomplete; run warlock grimoire build\";\n\nfunction routeFactsIncomplete(facts: GrimoireSnapshot[\"book\"][\"facts\"]): boolean {\n return (\n facts.routes !== null &&\n facts.routes.length > 0 &&\n facts.routes.every((route) => route.sourceFile === null)\n );\n}\n\n/** Notes every answer carries: whether the stored book is behind the files, and how fresh the route facts are. */\nfunction notesOf(snapshot: GrimoireSnapshot, needsRoutes: boolean): ScryNotes {\n const notes: string[] = [];\n\n if (snapshot.behind !== undefined) {\n const count = snapshot.behind.changed;\n\n notes.push(\n `book is stale (${count} ${count === 1 ? \"file\" : \"files\"} changed); run warlock grimoire build`,\n );\n }\n\n if (snapshot.routes === \"stale\") notes.push(\"route facts are stale; run warlock grimoire build\");\n if (snapshot.routes === \"missing\" && needsRoutes) {\n notes.push(\"route facts were never read; run warlock grimoire build\");\n }\n\n if (snapshot.book.routeNote !== undefined) notes.push(snapshot.book.routeNote);\n if (needsRoutes && routeFactsIncomplete(snapshot.book.facts)) notes.push(INCOMPLETE_ROUTES);\n\n return { routes: snapshot.routes, notes };\n}\n\n/** A project-relative POSIX path for what the caller typed (either separator, absolute or relative). */\nfunction fileOf(snapshot: GrimoireSnapshot, file: string): string {\n return projectPath(snapshot.root, toPosixPath(file.trim()));\n}\n\nfunction bookFile(snapshot: GrimoireSnapshot, file: string): BookFile {\n const found = snapshot.book.facts.files.find((item) => item.file === file);\n\n if (!found) {\n const roots = [\n ...new Set(snapshot.book.facts.files.map((item) => item.file.split(\"/\")[0] ?? \"\")),\n ]\n .filter((root) => root !== \"\")\n .sort(byText);\n\n throw new GrimoireError(\n \"GR9001\",\n `${file} is not in the book. Pass a code file under ${roots.join(\", \") || \"the source roots\"} as a project-relative path; if the file is new, run warlock grimoire build.`,\n );\n }\n\n return found;\n}\n\n/** The written app id that shows a site, or the site id when no written app matches it. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The project files a file imports only through type-only imports, sorted. */\nfunction typeOnlyImportsOf(file: BookFile): string[] {\n const value = new Set<string>();\n const typeOnly = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file === null) continue;\n\n (entry.typeOnly === true ? typeOnly : value).add(entry.file);\n }\n\n return sortedUnique([...typeOnly].filter((target) => !value.has(target)));\n}\n\n/** The book entry of one file, as the book writes it. */\nfunction entryOf(snapshot: GrimoireSnapshot, file: BookFile): BookEntry {\n const facts = snapshot.book.facts;\n const annotation = snapshot.annotations.files[file.file];\n const routeRef = (route: BookRoute) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n });\n const routes = facts.routes ?? [];\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation?.feature ?? null,\n borrowedBy: sortedUnique(annotation?.borrowedBy ?? []),\n flows: sortedUnique(annotation?.flows ?? []),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n // The same list the book entry holds (bare Node builtins such as `fs` left out too).\n packages: packagesOf(file),\n imports: sortedUnique(\n file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file])),\n ),\n // The same rule as the book entry: project files whose every import edge is type-only.\n typeOnlyImports: typeOnlyImportsOf(file),\n importedBy: sortedUnique(file.importedBy),\n routes: [\n ...routes\n .filter((route) => route.sourceFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"registers\" as const })),\n ...routes\n .filter((route) => route.handlerFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"handles\" as const })),\n ],\n pages: facts.pages\n .flatMap((page) => [\n ...(page.file === file.file\n ? [{ site: page.site, route: page.route, via: \"page\" as const }]\n : []),\n ...(page.setupFile === file.file\n ? [{ site: page.site, route: page.route, via: \"setup\" as const }]\n : []),\n ...(page.layouts.includes(file.file)\n ? [{ site: page.site, route: page.route, via: \"layout\" as const }]\n : []),\n ])\n .sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: facts.mobile\n .flatMap((app) =>\n app.screens.flatMap((screen) => [\n ...(screen.file === file.file\n ? [{ app: app.id, route: screen.route, via: \"screen\" as const }]\n : []),\n ...(screen.layouts.includes(file.file)\n ? [{ app: app.id, route: screen.route, via: \"layout\" as const }]\n : []),\n ]),\n )\n .sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n };\n}\n\n/** Where the book keeps the entry of `file`, or `null` when it has none. */\nfunction bookEntryOf(snapshot: GrimoireSnapshot, file: string): string | null {\n const facts = snapshot.book.facts;\n const roots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((item) => {\n const root = item.mobileApp === null ? undefined : roots.get(item.mobileApp);\n\n return {\n file: item.file,\n mobileApp:\n item.mobileApp === null || root === undefined ? null : { id: item.mobileApp, root },\n };\n }),\n );\n const entry = paths.get(file);\n\n return entry === undefined || entry.split(\"/\").includes(\"..\") ? null : entry;\n}\n\nfunction scryFile(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"file\" }>,\n): ScryFileResult {\n const file = bookFile(snapshot, fileOf(snapshot, query.file));\n\n return {\n type: \"file\",\n ...notesOf(snapshot, false),\n entry: entryOf(snapshot, file),\n bookEntry: bookEntryOf(snapshot, file.file),\n };\n}\n\nfunction flowBookmaps(snapshot: GrimoireSnapshot): FlowBookmap[] {\n return Object.values(snapshot.collected.flows).sort((left, right) => byText(left.ref, right.ref));\n}\n\nfunction scryImpact(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"impact\" }>,\n): ScryImpactResult {\n const facts = snapshot.book.facts;\n const target = bookFile(snapshot, fileOf(snapshot, query.file));\n const graph = fileGraph(facts.files);\n const reach = new Set(importerClosure(graph, [target.file]));\n const importers = [...reach].filter((file) => file !== target.file).sort(byText);\n const routes = (facts.routes ?? []).filter(\n (route) =>\n !route.isPage &&\n (route.handlerFile !== null\n ? reach.has(route.handlerFile)\n : route.sourceFile !== null && reach.has(route.sourceFile)),\n );\n const pages: ScryPageRef[] = [\n ...facts.pages\n .filter(\n (page) =>\n reach.has(page.file) ||\n (page.setupFile !== null && reach.has(page.setupFile)) ||\n page.layouts.some((layout) => reach.has(layout)),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n })),\n ...facts.mobile.flatMap((app) =>\n app.screens\n .filter(\n (screen) => reach.has(screen.file) || screen.layouts.some((layout) => reach.has(layout)),\n )\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n })),\n ),\n ];\n const flows = flowBookmaps(snapshot)\n .filter((bookmap) =>\n bookmap.steps.some(\n (step) => step.files.includes(target.file) || step.typeOnlyFiles.includes(target.file),\n ),\n )\n .map((bookmap) => bookmap.ref);\n const ownership = snapshot.ownership.files;\n const owner = ownership[target.file]?.owner ?? null;\n // Looked up once per importer: an app with thousands of files stays linear.\n const specFiles = new Set(\n facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const borrowers = sortedUnique([\n ...(ownership[target.file]?.borrowedBy ?? []),\n ...importers.flatMap((file) => {\n const ownerOf = ownership[file]?.owner;\n\n return ownerOf === undefined || ownerOf === null || specFiles.has(file) ? [] : [ownerOf];\n }),\n ]).filter((feature) => feature !== owner);\n const testFiles = new Set(facts.tests);\n const flowSet = new Set(flows);\n const tests = sortedUnique([\n ...importers.filter((file) => testFiles.has(file) || specFiles.has(file)),\n ...snapshot.proofs.filter((proof) => flowSet.has(proof.ref)).map((proof) => proof.at.file),\n ]);\n\n return {\n type: \"impact\",\n ...notesOf(snapshot, true),\n file: target.file,\n importers: { direct: sortedUnique(target.importedBy), all: importers },\n routes: routes.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n handlerFile: route.handlerFile,\n })),\n pages,\n flows,\n features: [\n ...(owner === null ? [] : [{ id: owner, via: \"owner\" as const }]),\n ...borrowers.map((id) => ({ id, via: \"borrower\" as const })),\n ],\n tests,\n };\n}\n\nfunction scryRoute(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"route\" }>,\n): ScryRouteResult {\n const facts = snapshot.book.facts;\n const method = query.method.toUpperCase();\n const asked = `${method} ${query.path}`;\n // Pages and screens come from the code scan, so a page URL is found with or without route facts.\n const pageMethod = method === \"GET\" || method === \"HEAD\";\n\n if (facts.routes === null) {\n const pages = pageMethod ? pagesAt(snapshot, query) : [];\n\n if (pages.length > 0) return pageRouteResult(snapshot, pages);\n\n throw new GrimoireError(\n \"GR9002\",\n `No route facts yet, so ${asked} cannot be looked up. Run warlock grimoire build (it boots the app once to read the routes), then ask again.`,\n );\n }\n\n const route = facts.routes.find((item) => routeMatches(item, method, query.path));\n\n if (!route) {\n const pages = pageMethod ? pagesAt(snapshot, query) : [];\n\n if (pages.length > 0) return pageRouteResult(snapshot, pages);\n\n const samePath = facts.routes\n .filter((item) => normalizeRoutePath(item.path) === normalizeRoutePath(query.path))\n .map((item) => `${item.method} ${item.path}`);\n\n if (routeFactsIncomplete(facts)) {\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}; ${INCOMPLETE_ROUTES}.`);\n }\n\n const pagePaths = pagesAt(snapshot, { path: query.path }).map(\n (page) => `${page.app} ${page.route}`,\n );\n const hint = [\n samePath.length > 0 ? ` Routes on that path: ${samePath.join(\", \")}.` : \"\",\n pagePaths.length > 0\n ? ` Pages on that path (GET or HEAD only${query.site === undefined ? \"\" : `, none on site ${query.site}`}): ${pagePaths.join(\", \")}.`\n : \"\",\n samePath.length === 0 && pagePaths.length === 0\n ? \" Run warlock routes to list them, or warlock grimoire build when the route is new.\"\n : \"\",\n ].join(\"\");\n\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}.${hint}`);\n }\n\n const graph = fileGraph(facts.files);\n const start = route.handlerFile ?? route.sourceFile;\n const files = start === null ? [] : importClosure(graph, [start]);\n const steps = snapshot.written.features.flatMap((feature) =>\n feature.flows.flatMap((flow) =>\n flow.steps\n .filter(\n (step) =>\n step.type === \"route\" &&\n step.route !== null &&\n routeMatches(route, step.route.method, step.route.path),\n )\n .map((step) => ({ flow: flow.ref, index: step.index })),\n ),\n );\n const page = route.isPage\n ? (facts.pages.find((item) => item.file === route.handlerFile) ??\n facts.pages.find(\n (item) => normalizeRoutePath(item.route) === normalizeRoutePath(route.path),\n ) ??\n null)\n : null;\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route,\n files,\n steps: steps.sort((left, right) => byText(left.flow, right.flow) || left.index - right.index),\n page,\n pages: [],\n };\n}\n\n/** Pages and mobile screens whose URL is the asked path, narrowed to `--site` when given. */\nfunction pagesAt(\n snapshot: GrimoireSnapshot,\n query: { path: string; site?: string | undefined },\n): ScryRoutePage[] {\n const facts = snapshot.book.facts;\n const graph = fileGraph(facts.files);\n const wanted = normalizeRoutePath(query.path);\n const site = query.site;\n const closure = (files: (string | null)[]): string[] =>\n importClosure(\n graph,\n files.filter((file): file is string => file !== null),\n );\n\n return [\n ...facts.pages\n .filter(\n (page) =>\n normalizeRoutePath(page.route) === wanted &&\n (site === undefined || page.site === site || siteApp(snapshot, page.site) === site),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n site: page.site,\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n setupFile: page.setupFile,\n layouts: page.layouts,\n files: closure([page.file, page.setupFile, ...page.layouts]),\n })),\n ...facts.mobile.flatMap((app) =>\n site !== undefined && app.id !== site && mobileApp(snapshot, app.id) !== site\n ? []\n : app.screens\n .filter((screen) => normalizeRoutePath(screen.route) === wanted)\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n site: app.id,\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n setupFile: null,\n layouts: screen.layouts,\n files: closure([screen.file, ...screen.layouts]),\n })),\n ),\n ].sort((left, right) => byText(left.app, right.app) || byText(left.file, right.file));\n}\n\n/** The answer for a URL that only pages or screens serve. */\nfunction pageRouteResult(snapshot: GrimoireSnapshot, pages: ScryRoutePage[]): ScryRouteResult {\n const first = pages[0];\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route: null,\n files: sortedUnique(pages.flatMap((page) => page.files)),\n steps: [],\n page:\n first === undefined\n ? null\n : (snapshot.book.facts.pages.find(\n (item) => item.file === first.file && item.site === first.site,\n ) ?? null),\n pages,\n };\n}\n\nfunction writtenFeature(snapshot: GrimoireSnapshot, id: string): WrittenFeature {\n const feature = snapshot.written.features.find((item) => item.id === id);\n\n if (!feature) {\n const known = snapshot.written.features.map((item) => item.id).sort(byText);\n const list =\n known.length > 0\n ? ` Features: ${known.join(\", \")}.`\n : \" The project has no grimoire/features/ folder yet.\";\n\n throw new GrimoireError(\"GR9003\", `No feature has the id ${JSON.stringify(id)}.${list}`);\n }\n\n return feature;\n}\n\nfunction findingsFor(\n snapshot: GrimoireSnapshot,\n match: (finding: GrimoireFinding) => boolean,\n): GrimoireFinding[] {\n return checkGrimoire(snapshot).findings.filter(match);\n}\n\nfunction emptyFeatureBookmap(feature: string): FeatureBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature,\n own: [],\n borrowed: [],\n routes: [],\n pages: {},\n unreached: [],\n };\n}\n\nfunction scryFeature(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"feature\" }>,\n): ScryFeatureResult {\n const feature = writtenFeature(snapshot, query.feature);\n\n if (feature.readme === null) {\n throw new GrimoireError(\n \"GR9003\",\n `grimoire/features/${feature.id} has no README.md, so the feature cannot be shown. Write the README (see warlock grimoire check), then ask again.`,\n );\n }\n\n const findings = findingsFor(\n snapshot,\n (finding) =>\n finding.subject.feature === feature.id ||\n (finding.subject.flow ?? \"\").startsWith(`${feature.id}/`),\n );\n\n return {\n type: \"feature\",\n ...notesOf(snapshot, false),\n readme: feature.readme,\n flows: [...feature.flows]\n .sort((left, right) => byText(left.id.value, right.id.value))\n .map((flow) => {\n const criteria = snapshot.collected.flows[flow.ref]?.criteria ?? [];\n\n return {\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n heading: flow.heading?.value ?? null,\n steps: flow.steps.length,\n cases: flow.cases.length,\n criteria: flow.criteria.length,\n tested: criteria.filter((criterion) => criterion.tests.length > 0).length,\n findings: findings.filter(\n (finding) => !finding.expected && finding.subject.flow === flow.ref,\n ).length,\n };\n }),\n bookmap: snapshot.collected.features[feature.id] ?? emptyFeatureBookmap(feature.id),\n changes: (feature.changelog?.entries ?? []).slice(0, 10),\n tasks: snapshot.collected.tasksIndex.open.filter((task) => task.feature === feature.id),\n findings,\n };\n}\n\nfunction scryFlow(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"flow\" }>,\n): ScryFlowResult {\n const feature = writtenFeature(snapshot, query.feature);\n const flow: WrittenFlow | undefined = feature.flows.find((item) => item.id.value === query.flow);\n\n if (!flow) {\n const known = feature.flows.map((item) => item.id.value).sort(byText);\n const list =\n known.length > 0\n ? ` Flows of ${feature.id}: ${known.join(\", \")}.`\n : ` ${feature.id} has no flows yet.`;\n\n throw new GrimoireError(\"GR9004\", `No flow ${feature.id}/${query.flow}.${list}`);\n }\n\n const bookmap =\n Object.values(snapshot.collected.flows).find(\n (item) => item.feature === feature.id && item.flow === flow.id.value,\n ) ?? snapshot.collected.flows[flow.ref];\n\n if (!bookmap) {\n throw new GrimoireError(\n \"GR9004\",\n `${flow.ref} has no book map yet. Run warlock grimoire build, then ask again.`,\n );\n }\n\n return {\n type: \"flow\",\n ...notesOf(snapshot, true),\n flow,\n bookmap,\n history: (feature.changelog?.entries ?? []).filter((entry) => entry.flow === flow.id.value),\n findings: findingsFor(snapshot, (finding) => finding.subject.flow === flow.ref),\n };\n}\n\n// ── Search ─────────────────────────────────────────────────────────────────\n\nfunction scrySearch(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): ScrySearchResult {\n if (wordsOf(query.text).length === 0) {\n throw new GrimoireError(\n \"GR9006\",\n `Search text ${JSON.stringify(query.text)} has no letters or digits; pass a word to look for.`,\n );\n }\n\n const { counts, hits } = searchSnapshot(snapshot, query);\n\n return { type: \"search\", ...notesOf(snapshot, false), text: query.text, counts, hits };\n}\n\n/**\n * Answer one query. Throws a `GrimoireError`: `GR9001` for a file not in the\n * book, `GR9002` no route, `GR9003` no feature, `GR9004` no flow, `GR9006`\n * a search with no words. Pure.\n */\nexport function scry(snapshot: GrimoireSnapshot, query: ScryQuery): ScryResult {\n switch (query.type) {\n case \"file\":\n return scryFile(snapshot, query);\n case \"impact\":\n return scryImpact(snapshot, query);\n case \"route\":\n return scryRoute(snapshot, query);\n case \"feature\":\n return scryFeature(snapshot, query);\n case \"flow\":\n return scryFlow(snapshot, query);\n case \"search\":\n return scrySearch(snapshot, query);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8BA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChG,MAAM,gBAAgB,UAAsC,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,MAAM;;AAG3F,MAAM,oBAA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,UACA,eAAe,KAAK,UAAU,MAAM,IAAI,EAAE,oDAC5C;CAGF,MAAM,EAAE,QAAQ,SAAS,eAAe,UAAU,KAAK;CAEvD,OAAO;EAAE,MAAM;EAAU,GAAG,QAAQ,UAAU,KAAK;EAAG,MAAM,MAAM;EAAM;EAAQ;CAAK;AACvF;;;;;;AAOA,SAAgB,KAAK,UAA4B,OAA8B;CAC7E,QAAQ,MAAM,MAAd;EACE,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;EACnC,KAAK,SACH,OAAO,UAAU,UAAU,KAAK;EAClC,KAAK,WACH,OAAO,YAAY,UAAU,KAAK;EACpC,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;CACrC;AACF"}
|
|
1
|
+
{"version":3,"file":"query.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"sourcesContent":["/**\n * Answers one scry query from a snapshot. Pure: reads the snapshot only.\n */\nimport { packagesOf } from \"../book\";\nimport { normalizeRoutePath, routeMatches } from \"../bookmap\";\nimport { checkGrimoire } from \"../check\";\nimport { GrimoireError } from \"../codes\";\nimport type { BookFile, BookRoute } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookEntry } from \"../contracts/book\";\nimport type { FeatureBookmap, FlowBookmap } from \"../contracts/bookmap\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryImpactResult,\n ScryNotes,\n ScryPageRef,\n ScryQuery,\n ScryResult,\n ScryRoutePage,\n ScryRouteResult,\n ScryHit,\n ScrySearchImpact,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport { fileGraph, importClosure, importerClosure } from \"../graph\";\nimport { bookEntryPaths, projectPath, toPosixPath } from \"../paths\";\nimport { alsoChangesOf } from \"./also-changes\";\nimport { searchSnapshot, wordsOf } from \"./search\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\nconst sortedUnique = (items: Iterable<string>): string[] => [...new Set(items)].sort(byText);\n\n/** Route facts with routes but none that names its source file: only the core list was read, not the app's routes files. */\nconst INCOMPLETE_ROUTES = \"route facts look incomplete; run warlock grimoire build\";\n\nfunction routeFactsIncomplete(facts: GrimoireSnapshot[\"book\"][\"facts\"]): boolean {\n return (\n facts.routes !== null &&\n facts.routes.length > 0 &&\n facts.routes.every((route) => route.sourceFile === null)\n );\n}\n\n/** Notes every answer carries: whether the stored book is behind the files, and how fresh the route facts are. */\nfunction notesOf(snapshot: GrimoireSnapshot, needsRoutes: boolean): ScryNotes {\n const notes: string[] = [];\n\n if (snapshot.behind !== undefined) {\n const count = snapshot.behind.changed;\n\n notes.push(\n `book is stale (${count} ${count === 1 ? \"file\" : \"files\"} changed); run warlock grimoire build`,\n );\n }\n\n if (snapshot.routes === \"stale\") notes.push(\"route facts are stale; run warlock grimoire build\");\n if (snapshot.routes === \"missing\" && needsRoutes) {\n notes.push(\"route facts were never read; run warlock grimoire build\");\n }\n\n if (snapshot.book.routeNote !== undefined) notes.push(snapshot.book.routeNote);\n if (needsRoutes && routeFactsIncomplete(snapshot.book.facts)) notes.push(INCOMPLETE_ROUTES);\n\n return { routes: snapshot.routes, notes };\n}\n\n/** A project-relative POSIX path for what the caller typed (either separator, absolute or relative). */\nfunction fileOf(snapshot: GrimoireSnapshot, file: string): string {\n return projectPath(snapshot.root, toPosixPath(file.trim()));\n}\n\nfunction bookFile(snapshot: GrimoireSnapshot, file: string): BookFile {\n const found = snapshot.book.facts.files.find((item) => item.file === file);\n\n if (!found) {\n const roots = [\n ...new Set(snapshot.book.facts.files.map((item) => item.file.split(\"/\")[0] ?? \"\")),\n ]\n .filter((root) => root !== \"\")\n .sort(byText);\n\n throw new GrimoireError(\n \"GR9001\",\n `${file} is not in the book. Pass a code file under ${roots.join(\", \") || \"the source roots\"} as a project-relative path; if the file is new, run warlock grimoire build.`,\n );\n }\n\n return found;\n}\n\n/** The written app id that shows a site, or the site id when no written app matches it. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The project files a file imports only through type-only imports, sorted. */\nfunction typeOnlyImportsOf(file: BookFile): string[] {\n const value = new Set<string>();\n const typeOnly = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file === null) continue;\n\n (entry.typeOnly === true ? typeOnly : value).add(entry.file);\n }\n\n return sortedUnique([...typeOnly].filter((target) => !value.has(target)));\n}\n\n/** The book entry of one file, as the book writes it. */\nfunction entryOf(snapshot: GrimoireSnapshot, file: BookFile): BookEntry {\n const facts = snapshot.book.facts;\n const annotation = snapshot.annotations.files[file.file];\n const routeRef = (route: BookRoute) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n });\n const routes = facts.routes ?? [];\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation?.feature ?? null,\n borrowedBy: sortedUnique(annotation?.borrowedBy ?? []),\n flows: sortedUnique(annotation?.flows ?? []),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n // The same list the book entry holds (bare Node builtins such as `fs` left out too).\n packages: packagesOf(file),\n imports: sortedUnique(\n file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file])),\n ),\n // The same rule as the book entry: project files whose every import edge is type-only.\n typeOnlyImports: typeOnlyImportsOf(file),\n importedBy: sortedUnique(file.importedBy),\n routes: [\n ...routes\n .filter((route) => route.sourceFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"registers\" as const })),\n ...routes\n .filter((route) => route.handlerFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"handles\" as const })),\n ],\n pages: facts.pages\n .flatMap((page) => [\n ...(page.file === file.file\n ? [{ site: page.site, route: page.route, via: \"page\" as const }]\n : []),\n ...(page.setupFile === file.file\n ? [{ site: page.site, route: page.route, via: \"setup\" as const }]\n : []),\n ...(page.layouts.includes(file.file)\n ? [{ site: page.site, route: page.route, via: \"layout\" as const }]\n : []),\n ])\n .sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: facts.mobile\n .flatMap((app) =>\n app.screens.flatMap((screen) => [\n ...(screen.file === file.file\n ? [{ app: app.id, route: screen.route, via: \"screen\" as const }]\n : []),\n ...(screen.layouts.includes(file.file)\n ? [{ app: app.id, route: screen.route, via: \"layout\" as const }]\n : []),\n ]),\n )\n .sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n };\n}\n\n/** Where the book keeps the entry of `file`, or `null` when it has none. */\nfunction bookEntryOf(snapshot: GrimoireSnapshot, file: string): string | null {\n const facts = snapshot.book.facts;\n const roots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((item) => {\n const root = item.mobileApp === null ? undefined : roots.get(item.mobileApp);\n\n return {\n file: item.file,\n mobileApp:\n item.mobileApp === null || root === undefined ? null : { id: item.mobileApp, root },\n };\n }),\n );\n const entry = paths.get(file);\n\n return entry === undefined || entry.split(\"/\").includes(\"..\") ? null : entry;\n}\n\nfunction scryFile(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"file\" }>,\n): ScryFileResult {\n const file = bookFile(snapshot, fileOf(snapshot, query.file));\n\n return {\n type: \"file\",\n ...notesOf(snapshot, false),\n entry: entryOf(snapshot, file),\n bookEntry: bookEntryOf(snapshot, file.file),\n };\n}\n\nfunction flowBookmaps(snapshot: GrimoireSnapshot): FlowBookmap[] {\n return Object.values(snapshot.collected.flows).sort((left, right) => byText(left.ref, right.ref));\n}\n\nfunction scryImpact(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"impact\" }>,\n): ScryImpactResult {\n const facts = snapshot.book.facts;\n const target = bookFile(snapshot, fileOf(snapshot, query.file));\n const graph = fileGraph(facts.files);\n const reach = new Set(importerClosure(graph, [target.file]));\n const importers = [...reach].filter((file) => file !== target.file).sort(byText);\n const routes = (facts.routes ?? []).filter(\n (route) =>\n !route.isPage &&\n (route.handlerFile !== null\n ? reach.has(route.handlerFile)\n : route.sourceFile !== null && reach.has(route.sourceFile)),\n );\n const pages: ScryPageRef[] = [\n ...facts.pages\n .filter(\n (page) =>\n reach.has(page.file) ||\n (page.setupFile !== null && reach.has(page.setupFile)) ||\n page.layouts.some((layout) => reach.has(layout)),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n })),\n ...facts.mobile.flatMap((app) =>\n app.screens\n .filter(\n (screen) => reach.has(screen.file) || screen.layouts.some((layout) => reach.has(layout)),\n )\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n })),\n ),\n ];\n const flows = flowBookmaps(snapshot)\n .filter((bookmap) =>\n bookmap.steps.some(\n (step) => step.files.includes(target.file) || step.typeOnlyFiles.includes(target.file),\n ),\n )\n .map((bookmap) => bookmap.ref);\n const ownership = snapshot.ownership.files;\n const owner = ownership[target.file]?.owner ?? null;\n // Looked up once per importer: an app with thousands of files stays linear.\n const specFiles = new Set(\n facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const borrowers = sortedUnique([\n ...(ownership[target.file]?.borrowedBy ?? []),\n ...importers.flatMap((file) => {\n const ownerOf = ownership[file]?.owner;\n\n return ownerOf === undefined || ownerOf === null || specFiles.has(file) ? [] : [ownerOf];\n }),\n ]).filter((feature) => feature !== owner);\n const testFiles = new Set(facts.tests);\n const flowSet = new Set(flows);\n const tests = sortedUnique([\n ...importers.filter((file) => testFiles.has(file) || specFiles.has(file)),\n ...snapshot.proofs.filter((proof) => flowSet.has(proof.ref)).map((proof) => proof.at.file),\n ]);\n\n return {\n type: \"impact\",\n ...notesOf(snapshot, true),\n file: target.file,\n importers: { direct: sortedUnique(target.importedBy), all: importers },\n routes: routes.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n handlerFile: route.handlerFile,\n })),\n pages,\n flows,\n features: [\n ...(owner === null ? [] : [{ id: owner, via: \"owner\" as const }]),\n ...borrowers.map((id) => ({ id, via: \"borrower\" as const })),\n ],\n tests,\n };\n}\n\nfunction scryRoute(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"route\" }>,\n): ScryRouteResult {\n const facts = snapshot.book.facts;\n const method = query.method.toUpperCase();\n const asked = `${method} ${query.path}`;\n // Pages and screens come from the code scan, so a page URL is found with or without route facts.\n const pageMethod = method === \"GET\" || method === \"HEAD\";\n\n if (facts.routes === null) {\n const pages = pageMethod ? pagesAt(snapshot, query) : [];\n\n if (pages.length > 0) return pageRouteResult(snapshot, pages);\n\n throw new GrimoireError(\n \"GR9002\",\n `No route facts yet, so ${asked} cannot be looked up. Run warlock grimoire build (it boots the app once to read the routes), then ask again.`,\n );\n }\n\n const route = facts.routes.find((item) => routeMatches(item, method, query.path));\n\n if (!route) {\n const pages = pageMethod ? pagesAt(snapshot, query) : [];\n\n if (pages.length > 0) return pageRouteResult(snapshot, pages);\n\n const samePath = facts.routes\n .filter((item) => normalizeRoutePath(item.path) === normalizeRoutePath(query.path))\n .map((item) => `${item.method} ${item.path}`);\n\n if (routeFactsIncomplete(facts)) {\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}; ${INCOMPLETE_ROUTES}.`);\n }\n\n const pagePaths = pagesAt(snapshot, { path: query.path }).map(\n (page) => `${page.app} ${page.route}`,\n );\n const hint = [\n samePath.length > 0 ? ` Routes on that path: ${samePath.join(\", \")}.` : \"\",\n pagePaths.length > 0\n ? ` Pages on that path (GET or HEAD only${query.site === undefined ? \"\" : `, none on site ${query.site}`}): ${pagePaths.join(\", \")}.`\n : \"\",\n samePath.length === 0 && pagePaths.length === 0\n ? \" Run warlock routes to list them, or warlock grimoire build when the route is new.\"\n : \"\",\n ].join(\"\");\n\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}.${hint}`);\n }\n\n const graph = fileGraph(facts.files);\n const start = route.handlerFile ?? route.sourceFile;\n const files = start === null ? [] : importClosure(graph, [start]);\n const steps = snapshot.written.features.flatMap((feature) =>\n feature.flows.flatMap((flow) =>\n flow.steps\n .filter(\n (step) =>\n step.type === \"route\" &&\n step.route !== null &&\n routeMatches(route, step.route.method, step.route.path),\n )\n .map((step) => ({ flow: flow.ref, index: step.index })),\n ),\n );\n const page = route.isPage\n ? (facts.pages.find((item) => item.file === route.handlerFile) ??\n facts.pages.find(\n (item) => normalizeRoutePath(item.route) === normalizeRoutePath(route.path),\n ) ??\n null)\n : null;\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route,\n files,\n steps: steps.sort((left, right) => byText(left.flow, right.flow) || left.index - right.index),\n page,\n pages: [],\n };\n}\n\n/** Pages and mobile screens whose URL is the asked path, narrowed to `--site` when given. */\nfunction pagesAt(\n snapshot: GrimoireSnapshot,\n query: { path: string; site?: string | undefined },\n): ScryRoutePage[] {\n const facts = snapshot.book.facts;\n const graph = fileGraph(facts.files);\n const wanted = normalizeRoutePath(query.path);\n const site = query.site;\n const closure = (files: (string | null)[]): string[] =>\n importClosure(\n graph,\n files.filter((file): file is string => file !== null),\n );\n\n return [\n ...facts.pages\n .filter(\n (page) =>\n normalizeRoutePath(page.route) === wanted &&\n (site === undefined || page.site === site || siteApp(snapshot, page.site) === site),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n site: page.site,\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n setupFile: page.setupFile,\n layouts: page.layouts,\n files: closure([page.file, page.setupFile, ...page.layouts]),\n })),\n ...facts.mobile.flatMap((app) =>\n site !== undefined && app.id !== site && mobileApp(snapshot, app.id) !== site\n ? []\n : app.screens\n .filter((screen) => normalizeRoutePath(screen.route) === wanted)\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n site: app.id,\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n setupFile: null,\n layouts: screen.layouts,\n files: closure([screen.file, ...screen.layouts]),\n })),\n ),\n ].sort((left, right) => byText(left.app, right.app) || byText(left.file, right.file));\n}\n\n/** The answer for a URL that only pages or screens serve. */\nfunction pageRouteResult(snapshot: GrimoireSnapshot, pages: ScryRoutePage[]): ScryRouteResult {\n const first = pages[0];\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route: null,\n files: sortedUnique(pages.flatMap((page) => page.files)),\n steps: [],\n page:\n first === undefined\n ? null\n : (snapshot.book.facts.pages.find(\n (item) => item.file === first.file && item.site === first.site,\n ) ?? null),\n pages,\n };\n}\n\nfunction writtenFeature(snapshot: GrimoireSnapshot, id: string): WrittenFeature {\n const feature = snapshot.written.features.find((item) => item.id === id);\n\n if (!feature) {\n const known = snapshot.written.features.map((item) => item.id).sort(byText);\n const list =\n known.length > 0\n ? ` Features: ${known.join(\", \")}.`\n : \" The project has no grimoire/features/ folder yet.\";\n\n throw new GrimoireError(\"GR9003\", `No feature has the id ${JSON.stringify(id)}.${list}`);\n }\n\n return feature;\n}\n\nfunction findingsFor(\n snapshot: GrimoireSnapshot,\n match: (finding: GrimoireFinding) => boolean,\n): GrimoireFinding[] {\n return checkGrimoire(snapshot).findings.filter(match);\n}\n\nfunction emptyFeatureBookmap(feature: string): FeatureBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature,\n own: [],\n borrowed: [],\n routes: [],\n pages: {},\n unreached: [],\n };\n}\n\nfunction scryFeature(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"feature\" }>,\n): ScryFeatureResult {\n const feature = writtenFeature(snapshot, query.feature);\n\n if (feature.readme === null) {\n throw new GrimoireError(\n \"GR9003\",\n `grimoire/features/${feature.id} has no README.md, so the feature cannot be shown. Write the README (see warlock grimoire check), then ask again.`,\n );\n }\n\n const findings = findingsFor(\n snapshot,\n (finding) =>\n finding.subject.feature === feature.id ||\n (finding.subject.flow ?? \"\").startsWith(`${feature.id}/`),\n );\n\n return {\n type: \"feature\",\n ...notesOf(snapshot, false),\n readme: feature.readme,\n flows: [...feature.flows]\n .sort((left, right) => byText(left.id.value, right.id.value))\n .map((flow) => {\n const criteria = snapshot.collected.flows[flow.ref]?.criteria ?? [];\n\n return {\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n heading: flow.heading?.value ?? null,\n steps: flow.steps.length,\n cases: flow.cases.length,\n criteria: flow.criteria.length,\n tested: criteria.filter((criterion) => criterion.tests.length > 0).length,\n findings: findings.filter(\n (finding) => !finding.expected && finding.subject.flow === flow.ref,\n ).length,\n };\n }),\n bookmap: snapshot.collected.features[feature.id] ?? emptyFeatureBookmap(feature.id),\n changes: (feature.changelog?.entries ?? []).slice(0, 10),\n tasks: snapshot.collected.tasksIndex.open.filter((task) => task.feature === feature.id),\n findings,\n };\n}\n\nfunction scryFlow(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"flow\" }>,\n): ScryFlowResult {\n const feature = writtenFeature(snapshot, query.feature);\n const flow: WrittenFlow | undefined = feature.flows.find((item) => item.id.value === query.flow);\n\n if (!flow) {\n const known = feature.flows.map((item) => item.id.value).sort(byText);\n const list =\n known.length > 0\n ? ` Flows of ${feature.id}: ${known.join(\", \")}.`\n : ` ${feature.id} has no flows yet.`;\n\n throw new GrimoireError(\"GR9004\", `No flow ${feature.id}/${query.flow}.${list}`);\n }\n\n const bookmap =\n Object.values(snapshot.collected.flows).find(\n (item) => item.feature === feature.id && item.flow === flow.id.value,\n ) ?? snapshot.collected.flows[flow.ref];\n\n if (!bookmap) {\n throw new GrimoireError(\n \"GR9004\",\n `${flow.ref} has no book map yet. Run warlock grimoire build, then ask again.`,\n );\n }\n\n return {\n type: \"flow\",\n ...notesOf(snapshot, true),\n flow,\n bookmap,\n history: (feature.changelog?.entries ?? []).filter((entry) => entry.flow === flow.id.value),\n findings: findingsFor(snapshot, (finding) => finding.subject.flow === flow.ref),\n };\n}\n\n// ── Search ─────────────────────────────────────────────────────────────────\n\n/** The most of each list a search answer carries from the top file's impact. */\nconst SEARCH_IMPACT_FILES = 8;\nconst SEARCH_IMPACT_OTHERS = 5;\n\n/** The top file's impact, shortened for a search answer; no file already listed twice. */\nfunction impactOfTop(\n snapshot: GrimoireSnapshot,\n file: string,\n hits: readonly ScryHit[],\n alsoChanges: readonly { file: string }[],\n): ScrySearchImpact | undefined {\n let full: ScryImpactResult;\n\n try {\n full = scryImpact(snapshot, { type: \"impact\", file });\n } catch {\n return undefined;\n }\n\n const listed = new Set([\n file,\n ...alsoChanges.map((change) => change.file),\n ...hits.filter((hit) => hit.type === \"file\").map((hit) => hit.id),\n ]);\n const specs = new Set(\n snapshot.book.facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const files = full.importers.all.filter((item) => !listed.has(item) && !specs.has(item));\n\n const impact: ScrySearchImpact = {\n file,\n files: files.slice(0, SEARCH_IMPACT_FILES),\n more: Math.max(0, files.length - SEARCH_IMPACT_FILES),\n routes: full.routes\n .slice(0, SEARCH_IMPACT_OTHERS)\n .map((route) => `${route.method} ${route.path}`),\n flows: full.flows.slice(0, SEARCH_IMPACT_OTHERS),\n tests: full.tests.filter((item) => !listed.has(item)).slice(0, SEARCH_IMPACT_OTHERS),\n };\n\n // Nothing beyond what the answer already lists: leave it out, so `next` stays the way to look further.\n return impact.files.length + impact.routes.length + impact.flows.length + impact.tests.length ===\n 0\n ? undefined\n : impact;\n}\n\nfunction scrySearch(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): ScrySearchResult {\n if (wordsOf(query.text).length === 0) {\n throw new GrimoireError(\n \"GR9006\",\n `Search text ${JSON.stringify(query.text)} has no letters or digits; pass a word to look for.`,\n );\n }\n\n const { counts, hits, weak } = searchSnapshot(snapshot, query);\n const { alsoChanges, next, topFile } = alsoChangesOf(snapshot, hits);\n const impact =\n topFile === undefined ? undefined : impactOfTop(snapshot, topFile, hits, alsoChanges);\n\n return {\n type: \"search\",\n ...notesOf(snapshot, false),\n text: query.text,\n counts,\n hits,\n alsoChanges,\n ...(impact === undefined ? {} : { impact }),\n weak,\n ...(next === undefined ? {} : { next }),\n };\n}\n\n/**\n * Answer one query. Throws a `GrimoireError`: `GR9001` for a file not in the\n * book, `GR9002` no route, `GR9003` no feature, `GR9004` no flow, `GR9006`\n * a search with no words. Pure.\n */\nexport function scry(snapshot: GrimoireSnapshot, query: ScryQuery): ScryResult {\n switch (query.type) {\n case \"file\":\n return scryFile(snapshot, query);\n case \"impact\":\n return scryImpact(snapshot, query);\n case \"route\":\n return scryRoute(snapshot, query);\n case \"feature\":\n return scryFeature(snapshot, query);\n case \"flow\":\n return scryFlow(snapshot, query);\n case \"search\":\n return scrySearch(snapshot, query);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiCA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChG,MAAM,gBAAgB,UAAsC,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,MAAM;;AAG3F,MAAM,oBAAoB;AAE1B,SAAS,qBAAqB,OAAmD;CAC/E,OACE,MAAM,WAAW,QACjB,MAAM,OAAO,SAAS,KACtB,MAAM,OAAO,OAAO,UAAU,MAAM,eAAe,IAAI;AAE3D;;AAGA,SAAS,QAAQ,UAA4B,aAAiC;CAC5E,MAAM,QAAkB,CAAC;CAEzB,IAAI,SAAS,WAAW,QAAW;EACjC,MAAM,QAAQ,SAAS,OAAO;EAE9B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AACF;;;;;;AAOA,SAAgB,KAAK,UAA4B,OAA8B;CAC7E,QAAQ,MAAM,MAAd;EACE,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;EACnC,KAAK,SACH,OAAO,UAAU,UAAU,KAAK;EAClC,KAAK,WACH,OAAO,YAAY,UAAU,KAAK;EACpC,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;CACrC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/search.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"search.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/search.ts"],"mappings":";;;;;qBA6Da,iBAAiB"}
|
package/esm/scry/search.mjs
CHANGED
|
@@ -1,9 +1,30 @@
|
|
|
1
1
|
//#region ../../packages/grimoire/src/scry/search.ts
|
|
2
|
+
/** An id such as `AC-5` is one word (`ac5`), so it never matches `ac` alone. */
|
|
3
|
+
const ID_PATTERN = /\b([a-z]{1,5})-(\d+)\b/gi;
|
|
4
|
+
/** Arabic words of five or more letters lose a leading article (`ال`, `وال`, `بال`, `لل`). */
|
|
5
|
+
const ARABIC_ARTICLE = /^(?:وال|بال|لل|ال)/u;
|
|
6
|
+
const ARABIC_WORD = /^\p{Script=Arabic}+$/u;
|
|
7
|
+
const ARTICLE_MIN_LENGTH = 5;
|
|
8
|
+
/**
|
|
9
|
+
* Letters without accents or marks, in one form: accents and Arabic vowel marks
|
|
10
|
+
* are dropped (which also unifies alef with hamza), tatweel is dropped, `ى` is
|
|
11
|
+
* `ي` and `ة` is `ه`, upper case is lower case.
|
|
12
|
+
*/
|
|
13
|
+
function foldText(text) {
|
|
14
|
+
return text.normalize("NFKD").replace(/[\p{M}\u0640]/gu, "").replace(/\u0649/g, "ي").replace(/\u0629/g, "ه");
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The words of a text, one tokeniser for the query and the index: `catalog/new-arrivals.service.ts` →
|
|
18
|
+
* `catalog new arrivals service ts`; `AC-5` → `ac5`; `café` → `cafe`; `الشحنة` → `شحنه`.
|
|
19
|
+
*/
|
|
20
|
+
function wordsOf(text) {
|
|
21
|
+
return foldText(text).replace(ID_PATTERN, "$1$2").replace(/([\p{Ll}\p{N}])(\p{Lu})/gu, "$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((word) => word !== "").map((word) => word.length >= ARTICLE_MIN_LENGTH && ARABIC_WORD.test(word) ? word.replace(ARABIC_ARTICLE, "") : word);
|
|
22
|
+
}
|
|
2
23
|
/**
|
|
3
24
|
* Words that carry no meaning in a sentence and are left out of the query and the
|
|
4
25
|
* index. The set is extendable: add words before the first search of a process.
|
|
5
26
|
*/
|
|
6
|
-
const SCRY_STOP_WORDS = new Set("the a an and or of to in on for with at by from is are was be been not no only its it their this that these those into through after before when then than so as has have had do does did can will should would via per if but also each any".split(" "));
|
|
27
|
+
const SCRY_STOP_WORDS = /* @__PURE__ */ new Set([..."the a an and or of to in on for with at by from is are was be been not no only its it their this that these those into through after before when then than so as has have had do does did can will should would via per if but also each any".split(" "), ...wordsOf("في من على إلى عن مع هذا هذه ذلك الذي التي أو و")]);
|
|
7
28
|
/** BM25 term saturation. */
|
|
8
29
|
const K1 = 1.2;
|
|
9
30
|
/** BM25 length normalisation. */
|
|
@@ -15,6 +36,13 @@ const WEIGHT = {
|
|
|
15
36
|
about: 1,
|
|
16
37
|
body: 1
|
|
17
38
|
};
|
|
39
|
+
/** File types that rank below code on an equal match, and by how much. */
|
|
40
|
+
const LOW_RANK_FILE_TYPES = /* @__PURE__ */ new Set([
|
|
41
|
+
"spec",
|
|
42
|
+
"locale",
|
|
43
|
+
"type"
|
|
44
|
+
]);
|
|
45
|
+
const LOW_RANK_FACTOR = .6;
|
|
18
46
|
/** Added to the name level of features and flows, so written content ranks above files of the same match. */
|
|
19
47
|
const WRITTEN_BOOST = 2;
|
|
20
48
|
const TYPE_ORDER = [
|
|
@@ -31,14 +59,9 @@ const TYPE_ORDER = [
|
|
|
31
59
|
"task"
|
|
32
60
|
];
|
|
33
61
|
const byText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
34
|
-
/** An id such as `AC-5` is one word (`ac5`), so it never matches `ac` alone. */
|
|
35
|
-
const ID_PATTERN = /\b([a-z]{1,5})-(\d+)\b/gi;
|
|
36
|
-
/** Lower-case words: `catalog/new-arrivals.service.ts` → `catalog new arrivals service ts`; `AC-5` → `ac5`. */
|
|
37
|
-
function wordsOf(text) {
|
|
38
|
-
return text.replace(ID_PATTERN, "$1$2").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().replace(/[^a-z0-9]+/g, " ").split(" ").filter((word) => word !== "");
|
|
39
|
-
}
|
|
40
62
|
/** Light stemming: `ies`, `ing`, `ed`, `es` and a plural `s` come off a longer word. */
|
|
41
63
|
function stem(word) {
|
|
64
|
+
if (!/^[a-z0-9]+$/.test(word)) return word;
|
|
42
65
|
if (word.length > 4 && word.endsWith("ies")) return `${word.slice(0, -3)}y`;
|
|
43
66
|
if (word.length > 5 && word.endsWith("ing")) return word.slice(0, -3);
|
|
44
67
|
if (word.length > 4 && word.endsWith("ed")) return word.slice(0, -2);
|
|
@@ -137,7 +160,8 @@ function candidates(snapshot) {
|
|
|
137
160
|
about: extra.about ?? hit.detail ?? "",
|
|
138
161
|
body: extra.body ?? [],
|
|
139
162
|
scored: extra.scored ?? true,
|
|
140
|
-
pageFile: extra.pageFile ?? false
|
|
163
|
+
pageFile: extra.pageFile ?? false,
|
|
164
|
+
factor: extra.factor ?? 1
|
|
141
165
|
});
|
|
142
166
|
};
|
|
143
167
|
for (const feature of snapshot.written.features) {
|
|
@@ -215,7 +239,8 @@ function candidates(snapshot) {
|
|
|
215
239
|
...app === void 0 ? {} : { app }
|
|
216
240
|
}, {
|
|
217
241
|
exportNames: file.exports.filter((entry) => entry.name !== "default" && entry.name !== "*").map((entry) => entry.name),
|
|
218
|
-
pageFile: pageFiles.has(file.file)
|
|
242
|
+
pageFile: pageFiles.has(file.file),
|
|
243
|
+
factor: LOW_RANK_FILE_TYPES.has(file.type) ? LOW_RANK_FACTOR : 1
|
|
219
244
|
});
|
|
220
245
|
for (const entry of file.exports) {
|
|
221
246
|
if (entry.name === "default" || entry.name === "*") continue;
|
|
@@ -258,6 +283,7 @@ function buildIndex(snapshot) {
|
|
|
258
283
|
nameWords,
|
|
259
284
|
titleText: titleWords.join(" "),
|
|
260
285
|
titleWords,
|
|
286
|
+
factor: candidate.factor,
|
|
261
287
|
boost: candidate.hit.type === "feature" || candidate.hit.type === "flow" ? WRITTEN_BOOST : 0,
|
|
262
288
|
length: 0,
|
|
263
289
|
bodyTokens
|
|
@@ -340,7 +366,8 @@ function searchSnapshot(snapshot, query) {
|
|
|
340
366
|
const tokens = [...new Set(tokensOf(query.text))];
|
|
341
367
|
const outcome = {
|
|
342
368
|
counts: {},
|
|
343
|
-
hits: []
|
|
369
|
+
hits: [],
|
|
370
|
+
weak: false
|
|
344
371
|
};
|
|
345
372
|
if (tokens.length === 0) return outcome;
|
|
346
373
|
const bm25 = /* @__PURE__ */ new Map();
|
|
@@ -350,7 +377,7 @@ function searchSnapshot(snapshot, query) {
|
|
|
350
377
|
if (list === void 0 || idf === void 0) continue;
|
|
351
378
|
for (const [position, weighted] of list) {
|
|
352
379
|
const length = index.docs[position]?.length ?? 0;
|
|
353
|
-
const part = idf * weighted * 2.2 / (weighted + K1 * (.25 + B * length / index.average));
|
|
380
|
+
const part = idf * weighted * 2.2 / (weighted + K1 * (.25 + B * length / index.average)) * (index.docs[position]?.factor ?? 1);
|
|
354
381
|
bm25.set(position, (bm25.get(position) ?? 0) + part);
|
|
355
382
|
}
|
|
356
383
|
}
|
|
@@ -381,6 +408,11 @@ function searchSnapshot(snapshot, query) {
|
|
|
381
408
|
});
|
|
382
409
|
}
|
|
383
410
|
ranked.sort((left, right) => right.score - left.score || Number(right.doc.boost > 0) - Number(left.doc.boost > 0) || Number(right.doc.candidate.pageFile) - Number(left.doc.candidate.pageFile) || TYPE_ORDER.indexOf(left.doc.candidate.hit.type) - TYPE_ORDER.indexOf(right.doc.candidate.hit.type) || byText(left.doc.candidate.hit.id, right.doc.candidate.hit.id));
|
|
411
|
+
const best = ranked[0];
|
|
412
|
+
if (best !== void 0 && !best.named) {
|
|
413
|
+
const position = index.docs.indexOf(best.doc);
|
|
414
|
+
outcome.weak = tokens.filter((token) => index.postings.get(token)?.some(([at]) => at === position)).length * 2 < tokens.length;
|
|
415
|
+
}
|
|
384
416
|
for (const { doc } of ranked) {
|
|
385
417
|
const type = doc.candidate.hit.type;
|
|
386
418
|
outcome.counts[type] = (outcome.counts[type] ?? 0) + 1;
|
package/esm/scry/search.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/search.ts"],"sourcesContent":["/**\n * `scry --search`: ranks the book's features, flows, blocks, pages, screens,\n * routes, mails, jobs, files, exports and tasks for a text, which may be a whole\n * sentence (a commit title, a bug report).\n *\n * Two tiers. Names come first: a candidate whose id or title is the whole query,\n * starts with it, or holds every query word as a whole word ranks above everything\n * else. Below them, a BM25F score ranks every candidate that shares words with the\n * query: whole words only, light stemming, no stop words, over four fields (id and\n * path words 3, export names 2, header sentence 1, written text 1).\n *\n * The index is built once per snapshot and kept in a `WeakMap`, so the MCP server\n * and the dev tab do not rebuild it for each query.\n */\nimport type { ScryHit, ScryHitType, ScryQuery } from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\n\n/**\n * Words that carry no meaning in a sentence and are left out of the query and the\n * index. The set is extendable: add words before the first search of a process.\n */\nexport const SCRY_STOP_WORDS: Set<string> = new Set(\n \"the a an and or of to in on for with at by from is are was be been not no only its it their this that these those into through after before when then than so as has have had do does did can will should would via per if but also each any\".split(\n \" \",\n ),\n);\n\n/** BM25 term saturation. */\nconst K1 = 1.2;\n\n/** BM25 length normalisation. */\nconst B = 0.75;\n\n/** Field weights of the BM25F score. */\nconst WEIGHT = { id: 3, exports: 2, about: 1, body: 1 } as const;\n\n/** Added to the name level of features and flows, so written content ranks above files of the same match. */\nconst WRITTEN_BOOST = 2;\n\nconst TYPE_ORDER: readonly ScryHitType[] = [\n \"feature\",\n \"flow\",\n \"block\",\n \"page\",\n \"screen\",\n \"route\",\n \"mail\",\n \"job\",\n \"file\",\n \"export\",\n \"task\",\n];\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\n\n/** One searchable piece of written text of a feature or flow (a summary, a story, a case, a criterion). */\ntype BodyPart = { label: string; text: string };\n\n/** What a candidate is before it is ranked: the hit without its score. */\ntype Candidate = {\n hit: Omit<ScryHit, \"score\" | \"matched\">;\n /** Name shown to the name tier (an export's own name, a block's `<app>/<page>`). */\n name: string;\n /** Text of the id field of the BM25F score. */\n idText: string;\n exportNames: string[];\n about: string;\n body: BodyPart[];\n /** Whether the BM25F score counts it (exports are found by name and through their file). */\n scored: boolean;\n /** A page or screen file: it outranks helper files on an equal score. */\n pageFile: boolean;\n};\n\ntype Doc = {\n candidate: Candidate;\n /** The name of the candidate as lower-case words, and its last segment, and its title. */\n nameText: string;\n lastText: string;\n nameWords: string[];\n titleText: string;\n titleWords: string[];\n boost: number;\n /** Length of the weighted token list (0 when the document is not scored). */\n length: number;\n /** Tokens of the written parts, per part, for the `matched` text. */\n bodyTokens: string[][];\n};\n\ntype SearchIndex = {\n docs: Doc[];\n postings: Map<string, [number, number][]>;\n idf: Map<string, number>;\n average: number;\n};\n\n/** An id such as `AC-5` is one word (`ac5`), so it never matches `ac` alone. */\nconst ID_PATTERN = /\\b([a-z]{1,5})-(\\d+)\\b/gi;\n\n/** Lower-case words: `catalog/new-arrivals.service.ts` → `catalog new arrivals service ts`; `AC-5` → `ac5`. */\nexport function wordsOf(text: string): string[] {\n return text\n .replace(ID_PATTERN, \"$1$2\")\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \" \")\n .split(\" \")\n .filter((word) => word !== \"\");\n}\n\n/** Light stemming: `ies`, `ing`, `ed`, `es` and a plural `s` come off a longer word. */\nfunction stem(word: string): string {\n if (word.length > 4 && word.endsWith(\"ies\")) return `${word.slice(0, -3)}y`;\n if (word.length > 5 && word.endsWith(\"ing\")) return word.slice(0, -3);\n if (word.length > 4 && word.endsWith(\"ed\")) return word.slice(0, -2);\n if (word.length > 4 && word.endsWith(\"es\")) return word.slice(0, -2);\n if (word.length > 3 && word.endsWith(\"s\") && !word.endsWith(\"ss\")) return word.slice(0, -1);\n\n return word;\n}\n\n/** The searchable tokens of a text: whole words without stop words, stemmed. */\nfunction tokensOf(text: string): string[] {\n return wordsOf(text)\n .filter((word) => !SCRY_STOP_WORDS.has(word))\n .map(stem);\n}\n\n/** The last segment of an id (`catalog/new-arrivals` → `new-arrivals`). */\nfunction lastSegment(id: string): string {\n const parts = id.split(/[\\s/#]+/).filter((part) => part !== \"\");\n\n return parts[parts.length - 1] ?? id;\n}\n\n/** The slug of a block name (`New arrivals` → `new-arrivals`). */\nfunction slug(text: string): string {\n return wordsOf(text).join(\"-\");\n}\n\nfunction flowBody(flow: WrittenFlow): BodyPart[] {\n return [\n ...(flow.summary === null ? [] : [{ label: \"summary\", text: flow.summary }]),\n { label: \"who\", text: flow.who.value },\n ...flow.story.map((step) => ({ label: `story ${step.index}`, text: step.text })),\n ...flow.cases.map((item) => ({\n label: `case ${item.question}`,\n text: `${item.question} ${item.answer} ${item.criteria.join(\" \")}`,\n })),\n ...flow.criteria.map((item) => ({ label: item.id, text: `${item.id} ${item.text}` })),\n ];\n}\n\nfunction featureBody(feature: WrittenFeature): BodyPart[] {\n const readme = feature.readme;\n\n if (readme === null) return [];\n\n return [\n ...(readme.summary === null ? [] : [{ label: \"summary\", text: readme.summary }]),\n ...(readme.why === null ? [] : [{ label: \"why\", text: readme.why }]),\n ...readme.audience.map((item) => ({ label: \"audience\", text: item.value })),\n ];\n}\n\n/** The written app id of a site, or its own id. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The app a file belongs to: the mobile app that owns it, else the site or mobile root that holds it. */\nfunction appOfFile(\n snapshot: GrimoireSnapshot,\n file: { file: string; mobileApp: string | null },\n): string | undefined {\n if (file.mobileApp !== null) return mobileApp(snapshot, file.mobileApp);\n\n let best: { app: string; length: number } | undefined;\n\n for (const match of Object.values(snapshot.apps)) {\n const root = match.site?.root ?? match.mobile?.root;\n\n if (root === undefined || root === \"\" || root === \".\") continue;\n if (file.file !== root && !file.file.startsWith(`${root}/`)) continue;\n if (best === undefined || root.length > best.length) {\n best = { app: match.app, length: root.length };\n }\n }\n\n return best?.app;\n}\n\nfunction candidates(snapshot: GrimoireSnapshot): Candidate[] {\n const facts = snapshot.book.facts;\n const list: Candidate[] = [];\n const pageFiles = new Set<string>([\n ...facts.pages.map((page) => page.file),\n ...facts.mobile.flatMap((app) => app.screens.map((screen) => screen.file)),\n ]);\n\n const add = (hit: Candidate[\"hit\"], extra: Partial<Omit<Candidate, \"hit\">> = {}): void => {\n list.push({\n hit,\n name: extra.name ?? hit.id,\n idText: extra.idText ?? hit.id,\n exportNames: extra.exportNames ?? [],\n about: extra.about ?? hit.detail ?? \"\",\n body: extra.body ?? [],\n scored: extra.scored ?? true,\n pageFile: extra.pageFile ?? false,\n });\n };\n\n for (const feature of snapshot.written.features) {\n add(\n { type: \"feature\", id: feature.id, detail: feature.readme?.title.value ?? null },\n { body: featureBody(feature) },\n );\n\n for (const flow of feature.flows) {\n add(\n { type: \"flow\", id: flow.ref, detail: flow.heading?.value ?? null },\n { body: flowBody(flow) },\n );\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n const rows = [\n ...app.layouts.flatMap((layout) => layout.blocks.map((row) => ({ page: layout.id, row }))),\n ...[...app.pages, ...app.screens].flatMap((page) =>\n page.blocks.map((row) => ({ page: page.id, row })),\n ),\n ];\n\n for (const { page, row } of rows) {\n // A block is found through its page and its text, never through the slug of its whole text.\n add(\n {\n type: \"block\",\n id: `${appId}/${page}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n app: appId,\n },\n { name: `${appId}/${page}`, idText: `${appId}/${page}`, about: row.block },\n );\n }\n }\n\n for (const page of facts.pages) {\n const app = siteApp(snapshot, page.site);\n\n add({ type: \"page\", id: `${app} ${page.route}`, detail: page.file, app });\n }\n\n for (const mobile of facts.mobile) {\n const app = mobileApp(snapshot, mobile.id);\n\n for (const screen of mobile.screens) {\n add({ type: \"screen\", id: `${app} ${screen.route}`, detail: screen.file, app });\n }\n }\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n add({ type: \"route\", id: `${route.method} ${route.path}`, detail: route.name });\n }\n\n for (const thing of facts.named) {\n if (thing.type !== \"mail\" && thing.type !== \"job\") continue;\n\n add({ type: thing.type, id: thing.name, detail: thing.file });\n }\n\n for (const file of facts.files) {\n const app = appOfFile(snapshot, file);\n\n add(\n {\n type: \"file\",\n id: file.file,\n detail: file.about,\n ...(app === undefined ? {} : { app }),\n },\n {\n exportNames: file.exports\n .filter((entry) => entry.name !== \"default\" && entry.name !== \"*\")\n .map((entry) => entry.name),\n pageFile: pageFiles.has(file.file),\n },\n );\n\n for (const entry of file.exports) {\n if (entry.name === \"default\" || entry.name === \"*\") continue;\n\n add(\n { type: \"export\", id: `${file.file}#${entry.name}`, detail: entry.about },\n { name: entry.name, scored: false },\n );\n }\n }\n\n for (const task of [\n ...snapshot.collected.tasksIndex.open,\n ...snapshot.collected.tasksIndex.done,\n ]) {\n add({ type: \"task\", id: task.id, detail: task.title });\n }\n\n // The first candidate of a type and id wins.\n const seen = new Set<string>();\n\n return list.filter((item) => {\n const key = `${item.hit.type} ${item.hit.id}`;\n\n if (seen.has(key)) return false;\n\n seen.add(key);\n\n return true;\n });\n}\n\nfunction buildIndex(snapshot: GrimoireSnapshot): SearchIndex {\n const docs: Doc[] = [];\n const postings = new Map<string, [number, number][]>();\n let scoredCount = 0;\n let totalLength = 0;\n\n for (const candidate of candidates(snapshot)) {\n const nameWords = wordsOf(candidate.name);\n const titleWords = wordsOf(candidate.hit.detail ?? \"\");\n const bodyTokens = candidate.body.map((part) => tokensOf(part.text));\n const doc: Doc = {\n candidate,\n nameText: nameWords.join(\" \"),\n lastText: wordsOf(lastSegment(candidate.name)).join(\" \"),\n nameWords,\n titleText: titleWords.join(\" \"),\n titleWords,\n boost: candidate.hit.type === \"feature\" || candidate.hit.type === \"flow\" ? WRITTEN_BOOST : 0,\n length: 0,\n bodyTokens,\n };\n\n if (candidate.scored) {\n const frequency = new Map<string, number>();\n const count = (tokens: string[], weight: number): void => {\n for (const token of tokens) {\n frequency.set(token, (frequency.get(token) ?? 0) + weight);\n doc.length += weight;\n }\n };\n\n count(tokensOf(candidate.idText), WEIGHT.id);\n count(tokensOf(candidate.exportNames.join(\" \")), WEIGHT.exports);\n count(tokensOf(candidate.about), WEIGHT.about);\n\n for (const tokens of bodyTokens) count(tokens, WEIGHT.body);\n\n for (const [token, weighted] of frequency) {\n const list = postings.get(token) ?? [];\n\n list.push([docs.length, weighted]);\n postings.set(token, list);\n }\n\n scoredCount++;\n totalLength += doc.length;\n }\n\n docs.push(doc);\n }\n\n const idf = new Map<string, number>();\n\n for (const [token, list] of postings) {\n idf.set(token, Math.log(1 + (scoredCount - list.length + 0.5) / (list.length + 0.5)));\n }\n\n return { docs, postings, idf, average: scoredCount === 0 ? 1 : totalLength / scoredCount };\n}\n\nconst indexes = new WeakMap<GrimoireSnapshot, SearchIndex>();\n\nfunction indexOf(snapshot: GrimoireSnapshot): SearchIndex {\n let index = indexes.get(snapshot);\n\n if (index === undefined) {\n index = buildIndex(snapshot);\n indexes.set(snapshot, index);\n }\n\n return index;\n}\n\n/**\n * The name level of a candidate for the query, or 0: the whole query is the name\n * or the title (7), starts it (6), every word is a whole word of the name or of the\n * title (5), or the words are spread over both (4).\n */\nfunction nameLevel(doc: Doc, query: string, words: readonly string[]): number {\n if (doc.nameText === query || doc.lastText === query || doc.titleText === query) return 7;\n if (\n doc.nameText.startsWith(query) ||\n doc.lastText.startsWith(query) ||\n doc.titleText.startsWith(query)\n ) {\n return 6;\n }\n\n if (\n words.every((word) => doc.nameWords.includes(word)) ||\n words.every((word) => doc.titleWords.includes(word))\n ) {\n return 5;\n }\n\n return words.every((word) => doc.nameWords.includes(word) || doc.titleWords.includes(word))\n ? 4\n : 0;\n}\n\n/** The written part that holds most of the query tokens, as `label: text`, or `undefined`. */\nfunction matchedPart(doc: Doc, tokens: readonly string[]): string | undefined {\n let best = 0;\n let found: BodyPart | undefined;\n\n doc.bodyTokens.forEach((partTokens, position) => {\n const count = tokens.filter((token) => partTokens.includes(token)).length;\n\n if (count > best) {\n best = count;\n found = doc.candidate.body[position];\n }\n });\n\n if (found === undefined) return undefined;\n\n const text = found.text.replace(/\\s+/g, \" \").trim();\n\n return `${found.label}: ${text.length > 90 ? `${text.slice(0, 89)}…` : text}`;\n}\n\nexport type SearchOutcome = {\n /** How many candidates matched, per type, before the limit cut the list. */\n counts: Partial<Record<ScryHitType, number>>;\n /** Best first. */\n hits: ScryHit[];\n};\n\n/**\n * Rank the book for a search query. A query of stop words only matches nothing.\n * Hits are in score order; on an equal score written content comes first, then a\n * page or screen file before helper files, then the type, then the id.\n */\nexport function searchSnapshot(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): SearchOutcome {\n const index = indexOf(snapshot);\n const words = wordsOf(query.text);\n const queryText = words.join(\" \");\n const tokens = [...new Set(tokensOf(query.text))];\n const outcome: SearchOutcome = { counts: {}, hits: [] };\n\n if (tokens.length === 0) return outcome;\n\n // BM25F over the terms of the query.\n const bm25 = new Map<number, number>();\n\n for (const token of tokens) {\n const list = index.postings.get(token);\n const idf = index.idf.get(token);\n\n if (list === undefined || idf === undefined) continue;\n\n for (const [position, weighted] of list) {\n const length = index.docs[position]?.length ?? 0;\n const part =\n (idf * weighted * (K1 + 1)) / (weighted + K1 * (1 - B + (B * length) / index.average));\n\n bm25.set(position, (bm25.get(position) ?? 0) + part);\n }\n }\n\n const levels = new Map<number, number>();\n\n index.docs.forEach((doc, position) => {\n const level = nameLevel(doc, queryText, words);\n\n if (level > 0) levels.set(position, level);\n });\n\n // Name matches score above every BM25F score; the BM25F score orders them inside a level.\n let highest = 0;\n\n for (const value of bm25.values()) highest = Math.max(highest, value);\n\n const offset = highest + 1;\n const matched = new Set([...bm25.keys(), ...levels.keys()]);\n const ranked: { doc: Doc; score: number; named: boolean }[] = [];\n\n for (const position of matched) {\n const doc = index.docs[position];\n\n if (doc === undefined) continue;\n if (query.app !== undefined && doc.candidate.hit.app !== query.app) continue;\n\n const level = levels.get(position);\n const score = bm25.get(position) ?? 0;\n\n ranked.push(\n level === undefined\n ? { doc, score, named: false }\n : { doc, score: offset + level + doc.boost + score / offset, named: true },\n );\n }\n\n ranked.sort(\n (left, right) =>\n right.score - left.score ||\n Number(right.doc.boost > 0) - Number(left.doc.boost > 0) ||\n Number(right.doc.candidate.pageFile) - Number(left.doc.candidate.pageFile) ||\n TYPE_ORDER.indexOf(left.doc.candidate.hit.type) -\n TYPE_ORDER.indexOf(right.doc.candidate.hit.type) ||\n byText(left.doc.candidate.hit.id, right.doc.candidate.hit.id),\n );\n\n for (const { doc } of ranked) {\n const type = doc.candidate.hit.type;\n\n outcome.counts[type] = (outcome.counts[type] ?? 0) + 1;\n }\n\n for (const { doc, score, named } of ranked.slice(0, query.limit ?? 20)) {\n // A feature or flow found by its written text shows the part that matched.\n const part = named || doc.boost === 0 ? undefined : matchedPart(doc, tokens);\n\n outcome.hits.push({\n ...doc.candidate.hit,\n score,\n ...(part === undefined ? {} : { matched: part }),\n });\n }\n\n return outcome;\n}\n"],"mappings":";;;;;AAsBA,MAAa,kBAA+B,IAAI,IAC9C,+OAA+O,MAC7O,GACF,CACF;;AAGA,MAAM,KAAK;;AAGX,MAAM,IAAI;;AAGV,MAAM,SAAS;CAAE,IAAI;CAAG,SAAS;CAAG,OAAO;CAAG,MAAM;AAAE;;AAGtD,MAAM,gBAAgB;AAEtB,MAAM,aAAqC;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;;AA4ChG,MAAM,aAAa;;AAGnB,SAAgB,QAAQ,MAAwB;CAC9C,OAAO,KACJ,QAAQ,YAAY,MAAM,CAAC,CAC3B,QAAQ,sBAAsB,OAAO,CAAC,CACtC,YAAY,CAAC,CACb,QAAQ,eAAe,GAAG,CAAC,CAC3B,MAAM,GAAG,CAAC,CACV,QAAQ,SAAS,SAAS,EAAE;AACjC;;AAGA,SAAS,KAAK,MAAsB;CAClC,IAAI,KAAK,SAAS,KAAK,KAAK,SAAS,KAAK,GAAG,OAAO,GAAG,KAAK,MAAM,GAAG,EAAE,EAAE;CACzE,IAAI,KAAK,SAAS,KAAK,KAAK,SAAS,KAAK,GAAG,OAAO,KAAK,MAAM,GAAG,EAAE;CACpE,IAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,GAAG,OAAO,KAAK,MAAM,GAAG,EAAE;CACnE,IAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,GAAG,OAAO,KAAK,MAAM,GAAG,EAAE;CACnE,IAAI,KAAK,SAAS,KAAK,KAAK,SAAS,GAAG,KAAK,CAAC,KAAK,SAAS,IAAI,GAAG,OAAO,KAAK,MAAM,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AAM,EAAE,SAAS,QAAQ;EAC5B,MAAM,OAAO,IAAI,UAAU,IAAI;EAE/B,QAAQ,OAAO,SAAS,QAAQ,OAAO,SAAS,KAAK;CACvD;CAEA,KAAK,MAAM,EAAE,KAAK,OAAO,WAAW,OAAO,MAAM,GAAG,MAAM,SAAS,EAAE,GAAG;EAEtE,MAAM,OAAO,SAAS,IAAI,UAAU,IAAI,SAAY,YAAY,KAAK,MAAM;EAE3E,QAAQ,KAAK,KAAK;GAChB,GAAG,IAAI,UAAU;GACjB;GACA,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,SAAS,KAAK;EAChD,CAAC;CACH;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"search.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/search.ts"],"sourcesContent":["/**\n * `scry --search`: ranks the book's features, flows, blocks, pages, screens,\n * routes, mails, jobs, files, exports and tasks for a text, which may be a whole\n * sentence (a commit title, a bug report).\n *\n * Two tiers. Names come first: a candidate whose id or title is the whole query,\n * starts with it, or holds every query word as a whole word ranks above everything\n * else. Below them, a BM25F score ranks every candidate that shares words with the\n * query: whole words only, light stemming, no stop words, over four fields (id and\n * path words 3, export names 2, header sentence 1, written text 1).\n *\n * The index is built once per snapshot and kept in a `WeakMap`, so the MCP server\n * and the dev tab do not rebuild it for each query.\n */\nimport type { ScryHit, ScryHitType, ScryQuery } from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\n\n/** An id such as `AC-5` is one word (`ac5`), so it never matches `ac` alone. */\nconst ID_PATTERN = /\\b([a-z]{1,5})-(\\d+)\\b/gi;\n\n/** Arabic words of five or more letters lose a leading article (`ال`, `وال`, `بال`, `لل`). */\nconst ARABIC_ARTICLE = /^(?:وال|بال|لل|ال)/u;\nconst ARABIC_WORD = /^\\p{Script=Arabic}+$/u;\nconst ARTICLE_MIN_LENGTH = 5;\n\n/**\n * Letters without accents or marks, in one form: accents and Arabic vowel marks\n * are dropped (which also unifies alef with hamza), tatweel is dropped, `ى` is\n * `ي` and `ة` is `ه`, upper case is lower case.\n */\nfunction foldText(text: string): string {\n return text\n .normalize(\"NFKD\")\n .replace(/[\\p{M}\\u0640]/gu, \"\")\n .replace(/\\u0649/g, \"\\u064A\")\n .replace(/\\u0629/g, \"\\u0647\");\n}\n\n/**\n * The words of a text, one tokeniser for the query and the index: `catalog/new-arrivals.service.ts` →\n * `catalog new arrivals service ts`; `AC-5` → `ac5`; `café` → `cafe`; `الشحنة` → `شحنه`.\n */\nexport function wordsOf(text: string): string[] {\n return foldText(text)\n .replace(ID_PATTERN, \"$1$2\")\n .replace(/([\\p{Ll}\\p{N}])(\\p{Lu})/gu, \"$1 $2\")\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter((word) => word !== \"\")\n .map((word) =>\n word.length >= ARTICLE_MIN_LENGTH && ARABIC_WORD.test(word)\n ? word.replace(ARABIC_ARTICLE, \"\")\n : word,\n );\n}\n\n/**\n * Words that carry no meaning in a sentence and are left out of the query and the\n * index. The set is extendable: add words before the first search of a process.\n */\nexport const SCRY_STOP_WORDS: Set<string> = new Set([\n ...\"the a an and or of to in on for with at by from is are was be been not no only its it their this that these those into through after before when then than so as has have had do does did can will should would via per if but also each any\".split(\n \" \",\n ),\n // Arabic: in, from, on, to, about, with, this (m, f), that, which (m, f), and, or.\n ...wordsOf(\"في من على إلى عن مع هذا هذه ذلك الذي التي أو و\"),\n]);\n\n/** BM25 term saturation. */\nconst K1 = 1.2;\n\n/** BM25 length normalisation. */\nconst B = 0.75;\n\n/** Field weights of the BM25F score. */\nconst WEIGHT = { id: 3, exports: 2, about: 1, body: 1 } as const;\n\n/** File types that rank below code on an equal match, and by how much. */\nconst LOW_RANK_FILE_TYPES: ReadonlySet<string> = new Set([\"spec\", \"locale\", \"type\"]);\nconst LOW_RANK_FACTOR = 0.6;\n\n/** Added to the name level of features and flows, so written content ranks above files of the same match. */\nconst WRITTEN_BOOST = 2;\n\nconst TYPE_ORDER: readonly ScryHitType[] = [\n \"feature\",\n \"flow\",\n \"block\",\n \"page\",\n \"screen\",\n \"route\",\n \"mail\",\n \"job\",\n \"file\",\n \"export\",\n \"task\",\n];\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\n\n/** One searchable piece of written text of a feature or flow (a summary, a story, a case, a criterion). */\ntype BodyPart = { label: string; text: string };\n\n/** What a candidate is before it is ranked: the hit without its score. */\ntype Candidate = {\n hit: Omit<ScryHit, \"score\" | \"matched\">;\n /** Name shown to the name tier (an export's own name, a block's `<app>/<page>`). */\n name: string;\n /** Text of the id field of the BM25F score. */\n idText: string;\n exportNames: string[];\n about: string;\n body: BodyPart[];\n /** Whether the BM25F score counts it (exports are found by name and through their file). */\n scored: boolean;\n /** A page or screen file: it outranks helper files on an equal score. */\n pageFile: boolean;\n /** Multiplies the BM25F score: specs, locale files and type files rank below code. */\n factor: number;\n};\n\ntype Doc = {\n candidate: Candidate;\n /** The name of the candidate as lower-case words, and its last segment, and its title. */\n nameText: string;\n lastText: string;\n nameWords: string[];\n titleText: string;\n titleWords: string[];\n boost: number;\n /** Rank factor of the candidate. */\n factor: number;\n /** Length of the weighted token list (0 when the document is not scored). */\n length: number;\n /** Tokens of the written parts, per part, for the `matched` text. */\n bodyTokens: string[][];\n};\n\ntype SearchIndex = {\n docs: Doc[];\n postings: Map<string, [number, number][]>;\n idf: Map<string, number>;\n average: number;\n};\n\n/** Light stemming: `ies`, `ing`, `ed`, `es` and a plural `s` come off a longer word. */\nfunction stem(word: string): string {\n // Stemming is Latin only.\n if (!/^[a-z0-9]+$/.test(word)) return word;\n\n if (word.length > 4 && word.endsWith(\"ies\")) return `${word.slice(0, -3)}y`;\n if (word.length > 5 && word.endsWith(\"ing\")) return word.slice(0, -3);\n if (word.length > 4 && word.endsWith(\"ed\")) return word.slice(0, -2);\n if (word.length > 4 && word.endsWith(\"es\")) return word.slice(0, -2);\n if (word.length > 3 && word.endsWith(\"s\") && !word.endsWith(\"ss\")) return word.slice(0, -1);\n\n return word;\n}\n\n/** The searchable tokens of a text: whole words without stop words, stemmed. */\nfunction tokensOf(text: string): string[] {\n return wordsOf(text)\n .filter((word) => !SCRY_STOP_WORDS.has(word))\n .map(stem);\n}\n\n/** The last segment of an id (`catalog/new-arrivals` → `new-arrivals`). */\nfunction lastSegment(id: string): string {\n const parts = id.split(/[\\s/#]+/).filter((part) => part !== \"\");\n\n return parts[parts.length - 1] ?? id;\n}\n\n/** The slug of a block name (`New arrivals` → `new-arrivals`). */\nfunction slug(text: string): string {\n return wordsOf(text).join(\"-\");\n}\n\nfunction flowBody(flow: WrittenFlow): BodyPart[] {\n return [\n ...(flow.summary === null ? [] : [{ label: \"summary\", text: flow.summary }]),\n { label: \"who\", text: flow.who.value },\n ...flow.story.map((step) => ({ label: `story ${step.index}`, text: step.text })),\n ...flow.cases.map((item) => ({\n label: `case ${item.question}`,\n text: `${item.question} ${item.answer} ${item.criteria.join(\" \")}`,\n })),\n ...flow.criteria.map((item) => ({ label: item.id, text: `${item.id} ${item.text}` })),\n ];\n}\n\nfunction featureBody(feature: WrittenFeature): BodyPart[] {\n const readme = feature.readme;\n\n if (readme === null) return [];\n\n return [\n ...(readme.summary === null ? [] : [{ label: \"summary\", text: readme.summary }]),\n ...(readme.why === null ? [] : [{ label: \"why\", text: readme.why }]),\n ...readme.audience.map((item) => ({ label: \"audience\", text: item.value })),\n ];\n}\n\n/** The written app id of a site, or its own id. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The app a file belongs to: the mobile app that owns it, else the site or mobile root that holds it. */\nfunction appOfFile(\n snapshot: GrimoireSnapshot,\n file: { file: string; mobileApp: string | null },\n): string | undefined {\n if (file.mobileApp !== null) return mobileApp(snapshot, file.mobileApp);\n\n let best: { app: string; length: number } | undefined;\n\n for (const match of Object.values(snapshot.apps)) {\n const root = match.site?.root ?? match.mobile?.root;\n\n if (root === undefined || root === \"\" || root === \".\") continue;\n if (file.file !== root && !file.file.startsWith(`${root}/`)) continue;\n if (best === undefined || root.length > best.length) {\n best = { app: match.app, length: root.length };\n }\n }\n\n return best?.app;\n}\n\nfunction candidates(snapshot: GrimoireSnapshot): Candidate[] {\n const facts = snapshot.book.facts;\n const list: Candidate[] = [];\n const pageFiles = new Set<string>([\n ...facts.pages.map((page) => page.file),\n ...facts.mobile.flatMap((app) => app.screens.map((screen) => screen.file)),\n ]);\n\n const add = (hit: Candidate[\"hit\"], extra: Partial<Omit<Candidate, \"hit\">> = {}): void => {\n list.push({\n hit,\n name: extra.name ?? hit.id,\n idText: extra.idText ?? hit.id,\n exportNames: extra.exportNames ?? [],\n about: extra.about ?? hit.detail ?? \"\",\n body: extra.body ?? [],\n scored: extra.scored ?? true,\n pageFile: extra.pageFile ?? false,\n factor: extra.factor ?? 1,\n });\n };\n\n for (const feature of snapshot.written.features) {\n add(\n { type: \"feature\", id: feature.id, detail: feature.readme?.title.value ?? null },\n { body: featureBody(feature) },\n );\n\n for (const flow of feature.flows) {\n add(\n { type: \"flow\", id: flow.ref, detail: flow.heading?.value ?? null },\n { body: flowBody(flow) },\n );\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n const rows = [\n ...app.layouts.flatMap((layout) => layout.blocks.map((row) => ({ page: layout.id, row }))),\n ...[...app.pages, ...app.screens].flatMap((page) =>\n page.blocks.map((row) => ({ page: page.id, row })),\n ),\n ];\n\n for (const { page, row } of rows) {\n // A block is found through its page and its text, never through the slug of its whole text.\n add(\n {\n type: \"block\",\n id: `${appId}/${page}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n app: appId,\n },\n { name: `${appId}/${page}`, idText: `${appId}/${page}`, about: row.block },\n );\n }\n }\n\n for (const page of facts.pages) {\n const app = siteApp(snapshot, page.site);\n\n add({ type: \"page\", id: `${app} ${page.route}`, detail: page.file, app });\n }\n\n for (const mobile of facts.mobile) {\n const app = mobileApp(snapshot, mobile.id);\n\n for (const screen of mobile.screens) {\n add({ type: \"screen\", id: `${app} ${screen.route}`, detail: screen.file, app });\n }\n }\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n add({ type: \"route\", id: `${route.method} ${route.path}`, detail: route.name });\n }\n\n for (const thing of facts.named) {\n if (thing.type !== \"mail\" && thing.type !== \"job\") continue;\n\n add({ type: thing.type, id: thing.name, detail: thing.file });\n }\n\n for (const file of facts.files) {\n const app = appOfFile(snapshot, file);\n\n add(\n {\n type: \"file\",\n id: file.file,\n detail: file.about,\n ...(app === undefined ? {} : { app }),\n },\n {\n exportNames: file.exports\n .filter((entry) => entry.name !== \"default\" && entry.name !== \"*\")\n .map((entry) => entry.name),\n pageFile: pageFiles.has(file.file),\n factor: LOW_RANK_FILE_TYPES.has(file.type) ? LOW_RANK_FACTOR : 1,\n },\n );\n\n for (const entry of file.exports) {\n if (entry.name === \"default\" || entry.name === \"*\") continue;\n\n add(\n { type: \"export\", id: `${file.file}#${entry.name}`, detail: entry.about },\n { name: entry.name, scored: false },\n );\n }\n }\n\n for (const task of [\n ...snapshot.collected.tasksIndex.open,\n ...snapshot.collected.tasksIndex.done,\n ]) {\n add({ type: \"task\", id: task.id, detail: task.title });\n }\n\n // The first candidate of a type and id wins.\n const seen = new Set<string>();\n\n return list.filter((item) => {\n const key = `${item.hit.type} ${item.hit.id}`;\n\n if (seen.has(key)) return false;\n\n seen.add(key);\n\n return true;\n });\n}\n\nfunction buildIndex(snapshot: GrimoireSnapshot): SearchIndex {\n const docs: Doc[] = [];\n const postings = new Map<string, [number, number][]>();\n let scoredCount = 0;\n let totalLength = 0;\n\n for (const candidate of candidates(snapshot)) {\n const nameWords = wordsOf(candidate.name);\n const titleWords = wordsOf(candidate.hit.detail ?? \"\");\n const bodyTokens = candidate.body.map((part) => tokensOf(part.text));\n const doc: Doc = {\n candidate,\n nameText: nameWords.join(\" \"),\n lastText: wordsOf(lastSegment(candidate.name)).join(\" \"),\n nameWords,\n titleText: titleWords.join(\" \"),\n titleWords,\n factor: candidate.factor,\n boost: candidate.hit.type === \"feature\" || candidate.hit.type === \"flow\" ? WRITTEN_BOOST : 0,\n length: 0,\n bodyTokens,\n };\n\n if (candidate.scored) {\n const frequency = new Map<string, number>();\n const count = (tokens: string[], weight: number): void => {\n for (const token of tokens) {\n frequency.set(token, (frequency.get(token) ?? 0) + weight);\n doc.length += weight;\n }\n };\n\n count(tokensOf(candidate.idText), WEIGHT.id);\n count(tokensOf(candidate.exportNames.join(\" \")), WEIGHT.exports);\n count(tokensOf(candidate.about), WEIGHT.about);\n\n for (const tokens of bodyTokens) count(tokens, WEIGHT.body);\n\n for (const [token, weighted] of frequency) {\n const list = postings.get(token) ?? [];\n\n list.push([docs.length, weighted]);\n postings.set(token, list);\n }\n\n scoredCount++;\n totalLength += doc.length;\n }\n\n docs.push(doc);\n }\n\n const idf = new Map<string, number>();\n\n for (const [token, list] of postings) {\n idf.set(token, Math.log(1 + (scoredCount - list.length + 0.5) / (list.length + 0.5)));\n }\n\n return { docs, postings, idf, average: scoredCount === 0 ? 1 : totalLength / scoredCount };\n}\n\nconst indexes = new WeakMap<GrimoireSnapshot, SearchIndex>();\n\nfunction indexOf(snapshot: GrimoireSnapshot): SearchIndex {\n let index = indexes.get(snapshot);\n\n if (index === undefined) {\n index = buildIndex(snapshot);\n indexes.set(snapshot, index);\n }\n\n return index;\n}\n\n/**\n * The name level of a candidate for the query, or 0: the whole query is the name\n * or the title (7), starts it (6), every word is a whole word of the name or of the\n * title (5), or the words are spread over both (4).\n */\nfunction nameLevel(doc: Doc, query: string, words: readonly string[]): number {\n if (doc.nameText === query || doc.lastText === query || doc.titleText === query) return 7;\n if (\n doc.nameText.startsWith(query) ||\n doc.lastText.startsWith(query) ||\n doc.titleText.startsWith(query)\n ) {\n return 6;\n }\n\n if (\n words.every((word) => doc.nameWords.includes(word)) ||\n words.every((word) => doc.titleWords.includes(word))\n ) {\n return 5;\n }\n\n return words.every((word) => doc.nameWords.includes(word) || doc.titleWords.includes(word))\n ? 4\n : 0;\n}\n\n/** The written part that holds most of the query tokens, as `label: text`, or `undefined`. */\nfunction matchedPart(doc: Doc, tokens: readonly string[]): string | undefined {\n let best = 0;\n let found: BodyPart | undefined;\n\n doc.bodyTokens.forEach((partTokens, position) => {\n const count = tokens.filter((token) => partTokens.includes(token)).length;\n\n if (count > best) {\n best = count;\n found = doc.candidate.body[position];\n }\n });\n\n if (found === undefined) return undefined;\n\n const text = found.text.replace(/\\s+/g, \" \").trim();\n\n return `${found.label}: ${text.length > 90 ? `${text.slice(0, 89)}…` : text}`;\n}\n\nexport type SearchOutcome = {\n /** How many candidates matched, per type, before the limit cut the list. */\n counts: Partial<Record<ScryHitType, number>>;\n /** Best first. */\n hits: ScryHit[];\n /** The best hit is not a name match and holds fewer than half of the query's distinct words. */\n weak: boolean;\n};\n\n/**\n * Rank the book for a search query. A query of stop words only matches nothing.\n * Hits are in score order; on an equal score written content comes first, then a\n * page or screen file before helper files, then the type, then the id.\n */\nexport function searchSnapshot(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): SearchOutcome {\n const index = indexOf(snapshot);\n const words = wordsOf(query.text);\n const queryText = words.join(\" \");\n const tokens = [...new Set(tokensOf(query.text))];\n const outcome: SearchOutcome = { counts: {}, hits: [], weak: false };\n\n if (tokens.length === 0) return outcome;\n\n // BM25F over the terms of the query.\n const bm25 = new Map<number, number>();\n\n for (const token of tokens) {\n const list = index.postings.get(token);\n const idf = index.idf.get(token);\n\n if (list === undefined || idf === undefined) continue;\n\n for (const [position, weighted] of list) {\n const length = index.docs[position]?.length ?? 0;\n const part =\n ((idf * weighted * (K1 + 1)) / (weighted + K1 * (1 - B + (B * length) / index.average))) *\n (index.docs[position]?.factor ?? 1);\n\n bm25.set(position, (bm25.get(position) ?? 0) + part);\n }\n }\n\n const levels = new Map<number, number>();\n\n index.docs.forEach((doc, position) => {\n const level = nameLevel(doc, queryText, words);\n\n if (level > 0) levels.set(position, level);\n });\n\n // Name matches score above every BM25F score; the BM25F score orders them inside a level.\n let highest = 0;\n\n for (const value of bm25.values()) highest = Math.max(highest, value);\n\n const offset = highest + 1;\n const matched = new Set([...bm25.keys(), ...levels.keys()]);\n const ranked: { doc: Doc; score: number; named: boolean }[] = [];\n\n for (const position of matched) {\n const doc = index.docs[position];\n\n if (doc === undefined) continue;\n if (query.app !== undefined && doc.candidate.hit.app !== query.app) continue;\n\n const level = levels.get(position);\n const score = bm25.get(position) ?? 0;\n\n ranked.push(\n level === undefined\n ? { doc, score, named: false }\n : { doc, score: offset + level + doc.boost + score / offset, named: true },\n );\n }\n\n ranked.sort(\n (left, right) =>\n right.score - left.score ||\n Number(right.doc.boost > 0) - Number(left.doc.boost > 0) ||\n Number(right.doc.candidate.pageFile) - Number(left.doc.candidate.pageFile) ||\n TYPE_ORDER.indexOf(left.doc.candidate.hit.type) -\n TYPE_ORDER.indexOf(right.doc.candidate.hit.type) ||\n byText(left.doc.candidate.hit.id, right.doc.candidate.hit.id),\n );\n\n const best = ranked[0];\n\n if (best !== undefined && !best.named) {\n const position = index.docs.indexOf(best.doc);\n const held = tokens.filter((token) =>\n index.postings.get(token)?.some(([at]) => at === position),\n ).length;\n\n outcome.weak = held * 2 < tokens.length;\n }\n\n for (const { doc } of ranked) {\n const type = doc.candidate.hit.type;\n\n outcome.counts[type] = (outcome.counts[type] ?? 0) + 1;\n }\n\n for (const { doc, score, named } of ranked.slice(0, query.limit ?? 20)) {\n // A feature or flow found by its written text shows the part that matched.\n const part = named || doc.boost === 0 ? undefined : matchedPart(doc, tokens);\n\n outcome.hits.push({\n ...doc.candidate.hit,\n score,\n ...(part === undefined ? {} : {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