@warlock.js/grimoire 5.63.1 → 5.64.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 +44 -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 +21 -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.map +1 -1
- package/esm/devtools/index.mjs +32 -2
- 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 +5 -1
- 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 +106 -0
- package/esm/scry/also-changes.mjs.map +1 -0
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +22 -0
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +7 -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 +15 -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/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 +276 -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 +21 -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/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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CAChE;CAEA,KAAK,MAAM,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,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A,OAAO;AACT"}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { GrimoireError } from "../codes/index.mjs";
|
|
2
|
+
import { GRIMOIRE_PATHS, criterionShotName } from "../paths/index.mjs";
|
|
3
|
+
import { currentFlows } from "./drift.mjs";
|
|
4
|
+
import { readBaseline, writeBaseline } from "./store.mjs";
|
|
5
|
+
import { optedOutFlows } from "./state.mjs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { copyFile, mkdir, readFile, rm } from "node:fs/promises";
|
|
9
|
+
|
|
10
|
+
//#region ../../packages/grimoire/src/shots/approve.ts
|
|
11
|
+
/**
|
|
12
|
+
* Approve and reject: the only code that writes `grimoire/approved/baseline.json`
|
|
13
|
+
* and the images under `grimoire/screenshots/approved/`.
|
|
14
|
+
*/
|
|
15
|
+
const FLOW_REF = /^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
16
|
+
/**
|
|
17
|
+
* A path under `grimoire/screenshots/`. The parts come from the baseline and
|
|
18
|
+
* the capture index (files in the project), so a part that is empty, `.` or
|
|
19
|
+
* `..`, or holds a separator, is refused: approving never reads, copies or
|
|
20
|
+
* deletes a file outside that folder.
|
|
21
|
+
*/
|
|
22
|
+
function shotsRoot(root, ...parts) {
|
|
23
|
+
for (const part of parts) if (part === "" || part === "." || part === ".." || /[\\/:]/.test(part)) throw new GrimoireError("GR9010", `The screenshot path ${JSON.stringify(parts.join("/"))} is not a path under ${GRIMOIRE_PATHS.screenshots}; correct ${GRIMOIRE_PATHS.baseline} or run the browser tests again.`);
|
|
24
|
+
return path.join(root, ...GRIMOIRE_PATHS.screenshots.split("/"), ...parts);
|
|
25
|
+
}
|
|
26
|
+
function sha256(bytes) {
|
|
27
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The drift items a request names. `GR9010` when a target matches nothing.
|
|
31
|
+
* `all` with a language keeps only that language's shot items.
|
|
32
|
+
*/
|
|
33
|
+
function selectDrift(snapshot, request) {
|
|
34
|
+
const drift = snapshot.shots?.drift ?? [];
|
|
35
|
+
const chosen = /* @__PURE__ */ new Map();
|
|
36
|
+
if (request.targets.length === 0) throw new GrimoireError("GR9010", "Name what to approve: a change id, a <feature>/<flow>, or --all.");
|
|
37
|
+
for (const target of request.targets) {
|
|
38
|
+
const matches = target === "all" ? drift : drift.filter((entry) => entry.id === target || FLOW_REF.test(target) && entry.ref === target);
|
|
39
|
+
const narrowed = request.language === void 0 ? matches : matches.filter((entry) => entry.language === request.language);
|
|
40
|
+
if (narrowed.length === 0 && target !== "all") throw new GrimoireError("GR9010", `Nothing to approve or reject matches ${JSON.stringify(target)}${request.language === void 0 ? "" : ` in ${request.language}`}. Pass a change id from the Bird view or the check, a <feature>/<flow>, or --all.`);
|
|
41
|
+
for (const entry of narrowed) chosen.set(entry.id, entry);
|
|
42
|
+
}
|
|
43
|
+
return [...chosen.values()];
|
|
44
|
+
}
|
|
45
|
+
/** The baseline of the current state: every flow, proving test and passing capture. */
|
|
46
|
+
async function baselineFromCurrent(root, snapshot, now) {
|
|
47
|
+
const baseline = {
|
|
48
|
+
schemaVersion: 1,
|
|
49
|
+
approvedAt: now,
|
|
50
|
+
flows: currentFlows(snapshot.written),
|
|
51
|
+
proofs: currentProofs(snapshot),
|
|
52
|
+
shots: [],
|
|
53
|
+
rejected: []
|
|
54
|
+
};
|
|
55
|
+
const shown = new Set((snapshot.shots?.shows ?? []).filter((line) => line.call !== null).map((line) => `${line.ref} ${line.criterion}`));
|
|
56
|
+
const optedOut = new Set(optedOutFlows(snapshot.written));
|
|
57
|
+
for (const capture of snapshot.shots?.captures?.captures ?? []) if (capture.outcome === "pass" && capture.file !== null && shown.has(`${capture.ref} ${capture.criterion}`) && !optedOut.has(capture.ref)) baseline.shots.push(await approveImage(root, capture.ref, capture.criterion, capture.language, capture.file, now));
|
|
58
|
+
return baseline;
|
|
59
|
+
}
|
|
60
|
+
function currentProofs(snapshot) {
|
|
61
|
+
const seen = /* @__PURE__ */ new Set();
|
|
62
|
+
const proofs = [];
|
|
63
|
+
for (const proof of snapshot.proofs) {
|
|
64
|
+
if (proof.test === null) continue;
|
|
65
|
+
const key = `${proof.ref} ${proof.criterion} ${proof.at.file}`;
|
|
66
|
+
if (seen.has(key)) continue;
|
|
67
|
+
seen.add(key);
|
|
68
|
+
proofs.push({
|
|
69
|
+
ref: proof.ref,
|
|
70
|
+
criterion: proof.criterion,
|
|
71
|
+
testFile: proof.at.file,
|
|
72
|
+
testName: proof.test.name
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return proofs;
|
|
76
|
+
}
|
|
77
|
+
/** Copy `captured/…` to `approved/…` and describe it. */
|
|
78
|
+
async function approveImage(root, ref, criterion, language, captured, now) {
|
|
79
|
+
const source = shotsRoot(root, ...captured.split("/"));
|
|
80
|
+
const file = `approved/${criterionShotName(ref, criterion, language)}`;
|
|
81
|
+
const target = shotsRoot(root, ...file.split("/"));
|
|
82
|
+
let bytes;
|
|
83
|
+
try {
|
|
84
|
+
bytes = await readFile(source);
|
|
85
|
+
} catch {
|
|
86
|
+
throw new GrimoireError("GR9010", `The capture ${GRIMOIRE_PATHS.screenshots}/${captured} is missing; run the browser tests again, then approve.`);
|
|
87
|
+
}
|
|
88
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
89
|
+
await copyFile(source, target);
|
|
90
|
+
return {
|
|
91
|
+
ref,
|
|
92
|
+
criterion,
|
|
93
|
+
language,
|
|
94
|
+
file,
|
|
95
|
+
sha256: sha256(bytes),
|
|
96
|
+
approvedAt: now
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function upsertFlow(baseline, flow) {
|
|
100
|
+
baseline.flows = [...baseline.flows.filter((entry) => entry.ref !== flow.ref), flow].sort((left, right) => left.ref.localeCompare(right.ref));
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Approve `items` (the baseline is created from the current state when there
|
|
104
|
+
* is none and `items` is empty with `createWhenMissing`). Returns the ids done.
|
|
105
|
+
*/
|
|
106
|
+
async function approveItems(snapshot, items, now = (/* @__PURE__ */ new Date()).toISOString(), options = {}) {
|
|
107
|
+
const root = snapshot.root;
|
|
108
|
+
const existing = await readBaseline(root) ?? snapshot.shots?.baseline ?? null;
|
|
109
|
+
if (existing === null) {
|
|
110
|
+
if (options.createWhenMissing !== true) throw new GrimoireError("GR9010", "Nothing is approved yet; approve everything first (--all).");
|
|
111
|
+
await writeBaseline(root, await baselineFromCurrent(root, snapshot, now));
|
|
112
|
+
return ["baseline"];
|
|
113
|
+
}
|
|
114
|
+
const baseline = structuredClone(existing);
|
|
115
|
+
const current = new Map(currentFlows(snapshot.written).map((flow) => [flow.ref, flow]));
|
|
116
|
+
const captures = new Map((snapshot.shots?.captures?.captures ?? []).map((capture) => [`${capture.ref} ${capture.criterion} ${capture.language}`, capture]));
|
|
117
|
+
const done = [];
|
|
118
|
+
const removedProofs = /* @__PURE__ */ new Set();
|
|
119
|
+
for (const item of items) {
|
|
120
|
+
const flow = current.get(item.ref);
|
|
121
|
+
const approvedFlow = baseline.flows.find((entry) => entry.ref === item.ref);
|
|
122
|
+
switch (item.type) {
|
|
123
|
+
case "shot-changed":
|
|
124
|
+
case "shot-added": {
|
|
125
|
+
const capture = captures.get(`${item.ref} ${item.criterion} ${item.language}`);
|
|
126
|
+
if (capture?.file == null) throw new GrimoireError("GR9010", `The capture for ${item.id} is missing; run the browser tests again.`);
|
|
127
|
+
const shot = await approveImage(root, item.ref, item.criterion ?? "", item.language ?? "", capture.file, now);
|
|
128
|
+
baseline.shots = [...baseline.shots.filter((entry) => !(entry.ref === shot.ref && entry.criterion === shot.criterion && entry.language === shot.language)), shot];
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
case "shot-removed":
|
|
132
|
+
if (item.approvedShot !== null) await rm(shotsRoot(root, ...item.approvedShot.split("/")), { force: true });
|
|
133
|
+
baseline.shots = baseline.shots.filter((entry) => !(entry.ref === item.ref && entry.criterion === item.criterion && entry.language === item.language));
|
|
134
|
+
break;
|
|
135
|
+
case "flow-added":
|
|
136
|
+
if (flow) upsertFlow(baseline, structuredClone(flow));
|
|
137
|
+
break;
|
|
138
|
+
case "flow-removed":
|
|
139
|
+
baseline.flows = baseline.flows.filter((entry) => entry.ref !== item.ref);
|
|
140
|
+
baseline.proofs = baseline.proofs.filter((entry) => entry.ref !== item.ref);
|
|
141
|
+
break;
|
|
142
|
+
case "criterion-added":
|
|
143
|
+
case "criterion-changed": {
|
|
144
|
+
const text = flow?.criteria.find((entry) => entry.id === item.criterion);
|
|
145
|
+
if (!flow || !text) break;
|
|
146
|
+
if (!approvedFlow) upsertFlow(baseline, structuredClone(flow));
|
|
147
|
+
else approvedFlow.criteria = [...approvedFlow.criteria.filter((entry) => entry.id !== item.criterion), { ...text }].sort((left, right) => left.id.localeCompare(right.id, "en", { numeric: true }));
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
case "criterion-removed":
|
|
151
|
+
if (approvedFlow) approvedFlow.criteria = approvedFlow.criteria.filter((entry) => entry.id !== item.criterion);
|
|
152
|
+
break;
|
|
153
|
+
case "case-added":
|
|
154
|
+
if (!flow) break;
|
|
155
|
+
if (!approvedFlow) upsertFlow(baseline, structuredClone(flow));
|
|
156
|
+
else if (item.case !== null && !approvedFlow.cases.includes(item.case)) approvedFlow.cases = [...approvedFlow.cases, item.case];
|
|
157
|
+
break;
|
|
158
|
+
case "case-removed":
|
|
159
|
+
if (approvedFlow) approvedFlow.cases = approvedFlow.cases.filter((entry) => entry !== item.case);
|
|
160
|
+
break;
|
|
161
|
+
case "proof-removed": removedProofs.add(`${item.ref} ${item.criterion}`);
|
|
162
|
+
}
|
|
163
|
+
done.push(item.id);
|
|
164
|
+
}
|
|
165
|
+
const proofs = currentProofs(snapshot);
|
|
166
|
+
const proven = new Set(proofs.map((proof) => `${proof.ref} ${proof.criterion}`));
|
|
167
|
+
baseline.proofs = [...proofs, ...baseline.proofs.filter((proof) => {
|
|
168
|
+
const key = `${proof.ref} ${proof.criterion}`;
|
|
169
|
+
return !proven.has(key) && !removedProofs.has(key);
|
|
170
|
+
})];
|
|
171
|
+
baseline.rejected = baseline.rejected.filter((entry) => !done.includes(entry.id));
|
|
172
|
+
baseline.approvedAt = now;
|
|
173
|
+
await writeBaseline(root, baseline);
|
|
174
|
+
return done;
|
|
175
|
+
}
|
|
176
|
+
/** Reject `items`: each stays an error (`GR4019`) while it is still there. Returns the ids done. */
|
|
177
|
+
async function rejectItems(snapshot, items, note, now = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
178
|
+
const existing = await readBaseline(snapshot.root) ?? snapshot.shots?.baseline ?? null;
|
|
179
|
+
if (existing === null) throw new GrimoireError("GR9010", "Nothing is approved yet, so there is no change to reject.");
|
|
180
|
+
const ids = items.map((item) => item.id);
|
|
181
|
+
const baseline = {
|
|
182
|
+
...structuredClone(existing),
|
|
183
|
+
rejected: [...existing.rejected.filter((entry) => !ids.includes(entry.id)), ...ids.map((id) => ({
|
|
184
|
+
id,
|
|
185
|
+
rejectedAt: now,
|
|
186
|
+
note
|
|
187
|
+
}))]
|
|
188
|
+
};
|
|
189
|
+
await writeBaseline(snapshot.root, baseline);
|
|
190
|
+
return ids;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
//#endregion
|
|
194
|
+
export { approveItems, rejectItems, selectDrift };
|
|
195
|
+
//# sourceMappingURL=approve.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"approve.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/shots/approve.ts"],"sourcesContent":["/**\n * Approve and reject: the only code that writes `grimoire/approved/baseline.json`\n * and the images under `grimoire/screenshots/approved/`.\n */\nimport { createHash } from \"node:crypto\";\nimport { copyFile, mkdir, readFile, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { GrimoireError } from \"../codes\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type {\n ApprovedBaseline,\n ApprovedFlow,\n ApprovedProof,\n ApprovedShot,\n DriftItem,\n} from \"../contracts/shots\";\nimport { criterionShotName, GRIMOIRE_PATHS } from \"../paths\";\nimport { currentFlows } from \"./drift\";\nimport { optedOutFlows } from \"./state\";\nimport { readBaseline, writeBaseline } from \"./store\";\n\n/** What to approve or reject. */\nexport type ApprovalRequest = {\n /** Drift ids, or `<feature>/<flow>` (every item of the flow), or `all`. */\n targets: string[];\n /** Keep only the shot items of this language. */\n language?: string;\n /** Why (reject only). */\n note?: string;\n};\n\nconst FLOW_REF = /^[a-z0-9]+(?:-[a-z0-9]+)*\\/[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * A path under `grimoire/screenshots/`. The parts come from the baseline and\n * the capture index (files in the project), so a part that is empty, `.` or\n * `..`, or holds a separator, is refused: approving never reads, copies or\n * deletes a file outside that folder.\n */\nfunction shotsRoot(root: string, ...parts: string[]): string {\n for (const part of parts) {\n if (part === \"\" || part === \".\" || part === \"..\" || /[\\\\/:]/.test(part)) {\n throw new GrimoireError(\n \"GR9010\",\n `The screenshot path ${JSON.stringify(parts.join(\"/\"))} is not a path under ${GRIMOIRE_PATHS.screenshots}; correct ${GRIMOIRE_PATHS.baseline} or run the browser tests again.`,\n );\n }\n }\n\n return path.join(root, ...GRIMOIRE_PATHS.screenshots.split(\"/\"), ...parts);\n}\n\nfunction sha256(bytes: Uint8Array): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\n/**\n * The drift items a request names. `GR9010` when a target matches nothing.\n * `all` with a language keeps only that language's shot items.\n */\nexport function selectDrift(snapshot: GrimoireSnapshot, request: ApprovalRequest): DriftItem[] {\n const drift = snapshot.shots?.drift ?? [];\n const chosen = new Map<string, DriftItem>();\n\n if (request.targets.length === 0) {\n throw new GrimoireError(\n \"GR9010\",\n \"Name what to approve: a change id, a <feature>/<flow>, or --all.\",\n );\n }\n\n for (const target of request.targets) {\n const matches =\n target === \"all\"\n ? drift\n : drift.filter(\n (entry) => entry.id === target || (FLOW_REF.test(target) && entry.ref === target),\n );\n const narrowed =\n request.language === undefined\n ? matches\n : matches.filter((entry) => entry.language === request.language);\n\n if (narrowed.length === 0 && target !== \"all\") {\n throw new GrimoireError(\n \"GR9010\",\n `Nothing to approve or reject matches ${JSON.stringify(target)}${request.language === undefined ? \"\" : ` in ${request.language}`}. Pass a change id from the Bird view or the check, a <feature>/<flow>, or --all.`,\n );\n }\n\n for (const entry of narrowed) chosen.set(entry.id, entry);\n }\n\n return [...chosen.values()];\n}\n\n/** The baseline of the current state: every flow, proving test and passing capture. */\nasync function baselineFromCurrent(\n root: string,\n snapshot: GrimoireSnapshot,\n now: string,\n): Promise<ApprovedBaseline> {\n const baseline: ApprovedBaseline = {\n schemaVersion: 1,\n approvedAt: now,\n flows: currentFlows(snapshot.written),\n proofs: currentProofs(snapshot),\n shots: [],\n rejected: [],\n };\n const shown = new Set(\n (snapshot.shots?.shows ?? [])\n .filter((line) => line.call !== null)\n .map((line) => `${line.ref} ${line.criterion}`),\n );\n const optedOut = new Set(optedOutFlows(snapshot.written));\n\n for (const capture of snapshot.shots?.captures?.captures ?? []) {\n if (\n capture.outcome === \"pass\" &&\n capture.file !== null &&\n shown.has(`${capture.ref} ${capture.criterion}`) &&\n !optedOut.has(capture.ref)\n ) {\n baseline.shots.push(\n await approveImage(\n root,\n capture.ref,\n capture.criterion,\n capture.language,\n capture.file,\n now,\n ),\n );\n }\n }\n\n return baseline;\n}\n\nfunction currentProofs(snapshot: GrimoireSnapshot): ApprovedProof[] {\n const seen = new Set<string>();\n const proofs: ApprovedProof[] = [];\n\n for (const proof of snapshot.proofs) {\n if (proof.test === null) continue;\n\n const key = `${proof.ref} ${proof.criterion} ${proof.at.file}`;\n\n if (seen.has(key)) continue;\n\n seen.add(key);\n proofs.push({\n ref: proof.ref,\n criterion: proof.criterion,\n testFile: proof.at.file,\n testName: proof.test.name,\n });\n }\n\n return proofs;\n}\n\n/** Copy `captured/…` to `approved/…` and describe it. */\nasync function approveImage(\n root: string,\n ref: string,\n criterion: string,\n language: string,\n captured: string,\n now: string,\n): Promise<ApprovedShot> {\n const source = shotsRoot(root, ...captured.split(\"/\"));\n const file = `approved/${criterionShotName(ref, criterion, language)}`;\n const target = shotsRoot(root, ...file.split(\"/\"));\n let bytes: Buffer;\n\n try {\n bytes = await readFile(source);\n } catch {\n throw new GrimoireError(\n \"GR9010\",\n `The capture ${GRIMOIRE_PATHS.screenshots}/${captured} is missing; run the browser tests again, then approve.`,\n );\n }\n\n await mkdir(path.dirname(target), { recursive: true });\n await copyFile(source, target);\n\n return { ref, criterion, language, file, sha256: sha256(bytes), approvedAt: now };\n}\n\nfunction upsertFlow(baseline: ApprovedBaseline, flow: ApprovedFlow): void {\n baseline.flows = [...baseline.flows.filter((entry) => entry.ref !== flow.ref), flow].sort(\n (left, right) => left.ref.localeCompare(right.ref),\n );\n}\n\n/**\n * Approve `items` (the baseline is created from the current state when there\n * is none and `items` is empty with `createWhenMissing`). Returns the ids done.\n */\nexport async function approveItems(\n snapshot: GrimoireSnapshot,\n items: readonly DriftItem[],\n now = new Date().toISOString(),\n options: { createWhenMissing?: boolean } = {},\n): Promise<string[]> {\n const root = snapshot.root;\n // Read from disk: the panel's snapshot may be a moment old, and an approval made since must not be lost.\n const existing = (await readBaseline(root)) ?? snapshot.shots?.baseline ?? null;\n\n if (existing === null) {\n if (options.createWhenMissing !== true) {\n throw new GrimoireError(\n \"GR9010\",\n \"Nothing is approved yet; approve everything first (--all).\",\n );\n }\n\n await writeBaseline(root, await baselineFromCurrent(root, snapshot, now));\n\n return [\"baseline\"];\n }\n\n const baseline: ApprovedBaseline = structuredClone(existing);\n const current = new Map(currentFlows(snapshot.written).map((flow) => [flow.ref, flow]));\n const captures = new Map(\n (snapshot.shots?.captures?.captures ?? []).map((capture) => [\n `${capture.ref} ${capture.criterion} ${capture.language}`,\n capture,\n ]),\n );\n const done: string[] = [];\n const removedProofs = new Set<string>();\n\n for (const item of items) {\n const flow = current.get(item.ref);\n const approvedFlow = baseline.flows.find((entry) => entry.ref === item.ref);\n\n switch (item.type) {\n case \"shot-changed\":\n case \"shot-added\": {\n const capture = captures.get(`${item.ref} ${item.criterion} ${item.language}`);\n\n if (capture?.file == null) {\n throw new GrimoireError(\n \"GR9010\",\n `The capture for ${item.id} is missing; run the browser tests again.`,\n );\n }\n\n const shot = await approveImage(\n root,\n item.ref,\n item.criterion ?? \"\",\n item.language ?? \"\",\n capture.file,\n now,\n );\n\n baseline.shots = [\n ...baseline.shots.filter(\n (entry) =>\n !(\n entry.ref === shot.ref &&\n entry.criterion === shot.criterion &&\n entry.language === shot.language\n ),\n ),\n shot,\n ];\n break;\n }\n case \"shot-removed\":\n if (item.approvedShot !== null) {\n await rm(shotsRoot(root, ...item.approvedShot.split(\"/\")), { force: true });\n }\n\n baseline.shots = baseline.shots.filter(\n (entry) =>\n !(\n entry.ref === item.ref &&\n entry.criterion === item.criterion &&\n entry.language === item.language\n ),\n );\n break;\n case \"flow-added\":\n if (flow) upsertFlow(baseline, structuredClone(flow));\n break;\n case \"flow-removed\":\n baseline.flows = baseline.flows.filter((entry) => entry.ref !== item.ref);\n baseline.proofs = baseline.proofs.filter((entry) => entry.ref !== item.ref);\n break;\n case \"criterion-added\":\n case \"criterion-changed\": {\n const text = flow?.criteria.find((entry) => entry.id === item.criterion);\n\n if (!flow || !text) break;\n\n if (!approvedFlow) upsertFlow(baseline, structuredClone(flow));\n else {\n approvedFlow.criteria = [\n ...approvedFlow.criteria.filter((entry) => entry.id !== item.criterion),\n { ...text },\n ].sort((left, right) => left.id.localeCompare(right.id, \"en\", { numeric: true }));\n }\n break;\n }\n case \"criterion-removed\":\n if (approvedFlow) {\n approvedFlow.criteria = approvedFlow.criteria.filter(\n (entry) => entry.id !== item.criterion,\n );\n }\n break;\n case \"case-added\":\n if (!flow) break;\n\n if (!approvedFlow) upsertFlow(baseline, structuredClone(flow));\n else if (item.case !== null && !approvedFlow.cases.includes(item.case)) {\n approvedFlow.cases = [...approvedFlow.cases, item.case];\n }\n break;\n case \"case-removed\":\n if (approvedFlow)\n approvedFlow.cases = approvedFlow.cases.filter((entry) => entry !== item.case);\n break;\n case \"proof-removed\":\n removedProofs.add(`${item.ref} ${item.criterion}`);\n break;\n }\n\n done.push(item.id);\n }\n\n // New proving tests are never drift; they join the baseline with the next approval.\n const proofs = currentProofs(snapshot);\n const proven = new Set(proofs.map((proof) => `${proof.ref} ${proof.criterion}`));\n\n baseline.proofs = [\n ...proofs,\n ...baseline.proofs.filter((proof) => {\n const key = `${proof.ref} ${proof.criterion}`;\n\n return !proven.has(key) && !removedProofs.has(key);\n }),\n ];\n baseline.rejected = baseline.rejected.filter((entry) => !done.includes(entry.id));\n baseline.approvedAt = now;\n\n await writeBaseline(root, baseline);\n\n return done;\n}\n\n/** Reject `items`: each stays an error (`GR4019`) while it is still there. Returns the ids done. */\nexport async function rejectItems(\n snapshot: GrimoireSnapshot,\n items: readonly DriftItem[],\n note: string | null,\n now = new Date().toISOString(),\n): Promise<string[]> {\n const existing = (await readBaseline(snapshot.root)) ?? snapshot.shots?.baseline ?? null;\n\n if (existing === null) {\n throw new GrimoireError(\"GR9010\", \"Nothing is approved yet, so there is no change to reject.\");\n }\n\n const ids = items.map((item) => item.id);\n const baseline: ApprovedBaseline = {\n ...structuredClone(existing),\n rejected: [\n ...existing.rejected.filter((entry) => !ids.includes(entry.id)),\n ...ids.map((id) => ({ id, rejectedAt: now, note })),\n ],\n };\n\n await writeBaseline(snapshot.root, baseline);\n\n return ids;\n}\n"],"mappings":";;;;;;;;;;;;;;AA+BA,MAAM,WAAW;;;;;;;AAQjB,SAAS,UAAU,MAAc,GAAG,OAAyB;CAC3D,KAAK,MAAM,QAAQ,OACjB,IAAI,SAAS,MAAM,SAAS,OAAO,SAAS,QAAQ,SAAS,KAAK,IAAI,GACpE,MAAM,IAAI,cACR,UACA,uBAAuB,KAAK,UAAU,MAAM,KAAK,GA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;CAEpF,IAAI,aAAa,MACf,MAAM,IAAI,cAAc,UAAU,2DAA2D;CAG/F,MAAM,MAAM,MAAM,KAAK,SAAS,KAAK,EAAE;CACvC,MAAM,WAA6B;EACjC,GAAG,gBAAgB,QAAQ;EAC3B,UAAU,CACR,GAAG,SAAS,SAAS,QAAQ,UAAU,CAAC,IAAI,SAAS,MAAM,EAAE,CAAC,GAC9D,GAAG,IAAI,KAAK,QAAQ;GAAE;GAAI,YAAY;GAAK;EAAK,EAAE,CACpD;CACF;CAEA,MAAM,cAAc,SAAS,MAAM,QAAQ;CAE3C,OAAO;AACT"}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { GRIMOIRE_PATHS } from "../paths/index.mjs";
|
|
2
|
+
import { comparePng } from "./png.mjs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
|
|
6
|
+
//#region ../../packages/grimoire/src/shots/drift.ts
|
|
7
|
+
/**
|
|
8
|
+
* Drift: the current state of the flows, proving tests and captures against
|
|
9
|
+
* the approved baseline. Ids are `<type>:<feature>/<flow>[:<AC-n>][:<language>|:<case>]`.
|
|
10
|
+
*/
|
|
11
|
+
/** The flows of a written grimoire in the shape the baseline stores. */
|
|
12
|
+
function currentFlows(written) {
|
|
13
|
+
return written.features.flatMap((feature) => feature.flows).map((flow) => ({
|
|
14
|
+
ref: flow.ref,
|
|
15
|
+
criteria: flow.criteria.map((criterion) => ({
|
|
16
|
+
id: criterion.id,
|
|
17
|
+
text: criterion.text
|
|
18
|
+
})),
|
|
19
|
+
cases: [...new Set(flow.cases.map((entry) => entry.question))]
|
|
20
|
+
})).sort((left, right) => left.ref.localeCompare(right.ref));
|
|
21
|
+
}
|
|
22
|
+
/** The id of a drift item. */
|
|
23
|
+
function driftId(type, ref, criterion, extra) {
|
|
24
|
+
return [
|
|
25
|
+
type,
|
|
26
|
+
ref,
|
|
27
|
+
criterion,
|
|
28
|
+
extra === "" ? null : extra
|
|
29
|
+
].filter((part) => part !== null).join(":");
|
|
30
|
+
}
|
|
31
|
+
function item(baseline, fields) {
|
|
32
|
+
const criterion = fields.criterion ?? null;
|
|
33
|
+
const extra = fields.language ?? fields.case ?? null;
|
|
34
|
+
const id = driftId(fields.type, fields.ref, criterion, extra);
|
|
35
|
+
return {
|
|
36
|
+
id,
|
|
37
|
+
type: fields.type,
|
|
38
|
+
ref: fields.ref,
|
|
39
|
+
criterion,
|
|
40
|
+
language: fields.language ?? null,
|
|
41
|
+
case: fields.case ?? null,
|
|
42
|
+
before: fields.before ?? null,
|
|
43
|
+
after: fields.after ?? null,
|
|
44
|
+
approvedShot: fields.approvedShot ?? null,
|
|
45
|
+
capturedShot: fields.capturedShot ?? null,
|
|
46
|
+
rejected: baseline.rejected.find((entry) => entry.id === id) ?? null
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
async function readImage(root, file) {
|
|
50
|
+
try {
|
|
51
|
+
return await readFile(path.join(root, ...GRIMOIRE_PATHS.screenshots.split("/"), ...file.split("/")));
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** The differences of the current state from the approved baseline, in a stable order. */
|
|
57
|
+
async function computeDrift(input) {
|
|
58
|
+
const { baseline } = input;
|
|
59
|
+
const items = [];
|
|
60
|
+
const now = new Map(currentFlows(input.written).map((flow) => [flow.ref, flow]));
|
|
61
|
+
const approved = new Map(baseline.flows.map((flow) => [flow.ref, flow]));
|
|
62
|
+
for (const [ref, flow] of now) {
|
|
63
|
+
const before = approved.get(ref);
|
|
64
|
+
if (before === void 0) {
|
|
65
|
+
items.push(item(baseline, {
|
|
66
|
+
type: "flow-added",
|
|
67
|
+
ref
|
|
68
|
+
}));
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const beforeCriteria = new Map(before.criteria.map((criterion) => [criterion.id, criterion.text]));
|
|
72
|
+
const nowCriteria = new Map(flow.criteria.map((criterion) => [criterion.id, criterion.text]));
|
|
73
|
+
for (const [id, text] of nowCriteria) {
|
|
74
|
+
const old = beforeCriteria.get(id);
|
|
75
|
+
if (old === void 0) items.push(item(baseline, {
|
|
76
|
+
type: "criterion-added",
|
|
77
|
+
ref,
|
|
78
|
+
criterion: id,
|
|
79
|
+
after: text
|
|
80
|
+
}));
|
|
81
|
+
else if (old !== text) items.push(item(baseline, {
|
|
82
|
+
type: "criterion-changed",
|
|
83
|
+
ref,
|
|
84
|
+
criterion: id,
|
|
85
|
+
before: old,
|
|
86
|
+
after: text
|
|
87
|
+
}));
|
|
88
|
+
}
|
|
89
|
+
for (const [id, text] of beforeCriteria) if (!nowCriteria.has(id)) items.push(item(baseline, {
|
|
90
|
+
type: "criterion-removed",
|
|
91
|
+
ref,
|
|
92
|
+
criterion: id,
|
|
93
|
+
before: text
|
|
94
|
+
}));
|
|
95
|
+
for (const question of flow.cases) if (!before.cases.includes(question)) items.push(item(baseline, {
|
|
96
|
+
type: "case-added",
|
|
97
|
+
ref,
|
|
98
|
+
case: question,
|
|
99
|
+
after: question
|
|
100
|
+
}));
|
|
101
|
+
for (const question of before.cases) if (!flow.cases.includes(question)) items.push(item(baseline, {
|
|
102
|
+
type: "case-removed",
|
|
103
|
+
ref,
|
|
104
|
+
case: question,
|
|
105
|
+
before: question
|
|
106
|
+
}));
|
|
107
|
+
}
|
|
108
|
+
for (const ref of approved.keys()) if (!now.has(ref)) items.push(item(baseline, {
|
|
109
|
+
type: "flow-removed",
|
|
110
|
+
ref
|
|
111
|
+
}));
|
|
112
|
+
const proven = new Set(input.proofs.map((proof) => `${proof.ref} ${proof.criterion}`));
|
|
113
|
+
const seenProofs = /* @__PURE__ */ new Set();
|
|
114
|
+
for (const proof of baseline.proofs) {
|
|
115
|
+
const key = `${proof.ref} ${proof.criterion}`;
|
|
116
|
+
if (proven.has(key) || seenProofs.has(key)) continue;
|
|
117
|
+
seenProofs.add(key);
|
|
118
|
+
if (!now.get(proof.ref)?.criteria.some((criterion) => criterion.id === proof.criterion)) continue;
|
|
119
|
+
items.push(item(baseline, {
|
|
120
|
+
type: "proof-removed",
|
|
121
|
+
ref: proof.ref,
|
|
122
|
+
criterion: proof.criterion,
|
|
123
|
+
before: proof.testName ?? proof.testFile
|
|
124
|
+
}));
|
|
125
|
+
}
|
|
126
|
+
items.push(...await shotDrift(input));
|
|
127
|
+
return items.sort((left, right) => left.ref.localeCompare(right.ref) || (left.criterion ?? "").localeCompare(right.criterion ?? "", "en", { numeric: true }) || left.id.localeCompare(right.id));
|
|
128
|
+
}
|
|
129
|
+
async function shotDrift(input) {
|
|
130
|
+
const { baseline } = input;
|
|
131
|
+
const items = [];
|
|
132
|
+
const shown = new Set(input.shows.filter((line) => line.call !== null).map((line) => `${line.ref} ${line.criterion}`));
|
|
133
|
+
const expected = input.languages.length > 0 ? input.languages : [""];
|
|
134
|
+
const approved = new Map(baseline.shots.map((shot) => [`${shot.ref} ${shot.criterion} ${shot.language}`, shot]));
|
|
135
|
+
const captured = new Map((input.captures?.captures ?? []).filter((capture) => capture.outcome === "pass" && capture.file !== null).map((capture) => [`${capture.ref} ${capture.criterion} ${capture.language}`, capture]));
|
|
136
|
+
for (const [key, capture] of captured) {
|
|
137
|
+
if (!shown.has(`${capture.ref} ${capture.criterion}`) || input.optedOut.includes(capture.ref)) continue;
|
|
138
|
+
const shot = approved.get(key);
|
|
139
|
+
const base = {
|
|
140
|
+
ref: capture.ref,
|
|
141
|
+
criterion: capture.criterion,
|
|
142
|
+
language: capture.language
|
|
143
|
+
};
|
|
144
|
+
if (shot === void 0) {
|
|
145
|
+
items.push(item(baseline, {
|
|
146
|
+
type: "shot-added",
|
|
147
|
+
...base,
|
|
148
|
+
capturedShot: capture.file
|
|
149
|
+
}));
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (capture.sha256 === shot.sha256) continue;
|
|
153
|
+
const [before, after] = await Promise.all([readImage(input.root, shot.file), readImage(input.root, capture.file ?? "")]);
|
|
154
|
+
if (after === null) continue;
|
|
155
|
+
if (before === null || comparePng(before, after).changed) items.push(item(baseline, {
|
|
156
|
+
type: "shot-changed",
|
|
157
|
+
...base,
|
|
158
|
+
approvedShot: shot.file,
|
|
159
|
+
capturedShot: capture.file
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
for (const [, shot] of approved) if (!shown.has(`${shot.ref} ${shot.criterion}`) || input.optedOut.includes(shot.ref) || !expected.includes(shot.language)) items.push(item(baseline, {
|
|
163
|
+
type: "shot-removed",
|
|
164
|
+
ref: shot.ref,
|
|
165
|
+
criterion: shot.criterion,
|
|
166
|
+
language: shot.language,
|
|
167
|
+
approvedShot: shot.file
|
|
168
|
+
}));
|
|
169
|
+
return items;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
//#endregion
|
|
173
|
+
export { computeDrift, currentFlows, driftId };
|
|
174
|
+
//# sourceMappingURL=drift.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"drift.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/shots/drift.ts"],"sourcesContent":["/**\n * Drift: the current state of the flows, proving tests and captures against\n * the approved baseline. Ids are `<type>:<feature>/<flow>[:<AC-n>][:<language>|:<case>]`.\n */\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type {\n ApprovedBaseline,\n ApprovedFlow,\n DriftItem,\n DriftType,\n ShotCaptureIndex,\n ShowsLine,\n} from \"../contracts/shots\";\nimport type { ProofLine } from \"../contracts/test-results\";\nimport type { WrittenGrimoire } from \"../contracts/written\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { comparePng } from \"./png\";\n\n/** Everything drift reads. */\nexport type DriftInput = {\n root: string;\n written: WrittenGrimoire;\n proofs: readonly ProofLine[];\n shows: readonly ShowsLine[];\n captures: ShotCaptureIndex | null;\n baseline: ApprovedBaseline;\n /** The languages scenes run in; `[]` for one unnamed language. */\n languages: readonly string[];\n /** Flows opted out of captures. */\n optedOut: readonly string[];\n};\n\n/** The flows of a written grimoire in the shape the baseline stores. */\nexport function currentFlows(written: WrittenGrimoire): ApprovedFlow[] {\n return written.features\n .flatMap((feature) => feature.flows)\n .map((flow) => ({\n ref: flow.ref,\n criteria: flow.criteria.map((criterion) => ({ id: criterion.id, text: criterion.text })),\n cases: [...new Set(flow.cases.map((entry) => entry.question))],\n }))\n .sort((left, right) => left.ref.localeCompare(right.ref));\n}\n\n/** The id of a drift item. */\nexport function driftId(\n type: DriftType,\n ref: string,\n criterion: string | null,\n extra: string | null,\n): string {\n return [type, ref, criterion, extra === \"\" ? null : extra]\n .filter((part) => part !== null)\n .join(\":\");\n}\n\nfunction item(\n baseline: ApprovedBaseline,\n fields: { type: DriftType; ref: string } & Partial<\n Omit<DriftItem, \"id\" | \"rejected\" | \"type\" | \"ref\">\n >,\n): DriftItem {\n const criterion = fields.criterion ?? null;\n const extra = fields.language ?? fields.case ?? null;\n const id = driftId(fields.type, fields.ref, criterion, extra);\n\n return {\n id,\n type: fields.type,\n ref: fields.ref,\n criterion,\n language: fields.language ?? null,\n case: fields.case ?? null,\n before: fields.before ?? null,\n after: fields.after ?? null,\n approvedShot: fields.approvedShot ?? null,\n capturedShot: fields.capturedShot ?? null,\n rejected: baseline.rejected.find((entry) => entry.id === id) ?? null,\n };\n}\n\nasync function readImage(root: string, file: string): Promise<Uint8Array | null> {\n try {\n return await readFile(\n path.join(root, ...GRIMOIRE_PATHS.screenshots.split(\"/\"), ...file.split(\"/\")),\n );\n } catch {\n return null;\n }\n}\n\n/** The differences of the current state from the approved baseline, in a stable order. */\nexport async function computeDrift(input: DriftInput): Promise<DriftItem[]> {\n const { baseline } = input;\n const items: DriftItem[] = [];\n const now = new Map(currentFlows(input.written).map((flow) => [flow.ref, flow]));\n const approved = new Map(baseline.flows.map((flow) => [flow.ref, flow]));\n\n for (const [ref, flow] of now) {\n const before = approved.get(ref);\n\n if (before === undefined) {\n items.push(item(baseline, { type: \"flow-added\", ref }));\n continue;\n }\n\n const beforeCriteria = new Map(\n before.criteria.map((criterion) => [criterion.id, criterion.text]),\n );\n const nowCriteria = new Map(flow.criteria.map((criterion) => [criterion.id, criterion.text]));\n\n for (const [id, text] of nowCriteria) {\n const old = beforeCriteria.get(id);\n\n if (old === undefined) {\n items.push(item(baseline, { type: \"criterion-added\", ref, criterion: id, after: text }));\n } else if (old !== text) {\n items.push(\n item(baseline, {\n type: \"criterion-changed\",\n ref,\n criterion: id,\n before: old,\n after: text,\n }),\n );\n }\n }\n\n for (const [id, text] of beforeCriteria) {\n if (!nowCriteria.has(id)) {\n items.push(item(baseline, { type: \"criterion-removed\", ref, criterion: id, before: text }));\n }\n }\n\n for (const question of flow.cases) {\n if (!before.cases.includes(question)) {\n items.push(item(baseline, { type: \"case-added\", ref, case: question, after: question }));\n }\n }\n\n for (const question of before.cases) {\n if (!flow.cases.includes(question)) {\n items.push(item(baseline, { type: \"case-removed\", ref, case: question, before: question }));\n }\n }\n }\n\n for (const ref of approved.keys()) {\n if (!now.has(ref)) items.push(item(baseline, { type: \"flow-removed\", ref }));\n }\n\n // A proving test is removed when the criterion has no `@proves` line left.\n const proven = new Set(input.proofs.map((proof) => `${proof.ref} ${proof.criterion}`));\n const seenProofs = new Set<string>();\n\n for (const proof of baseline.proofs) {\n const key = `${proof.ref} ${proof.criterion}`;\n\n if (proven.has(key) || seenProofs.has(key)) continue;\n\n seenProofs.add(key);\n // A removed flow or criterion is already reported by its own item.\n if (!now.get(proof.ref)?.criteria.some((criterion) => criterion.id === proof.criterion))\n continue;\n\n items.push(\n item(baseline, {\n type: \"proof-removed\",\n ref: proof.ref,\n criterion: proof.criterion,\n before: proof.testName ?? proof.testFile,\n }),\n );\n }\n\n items.push(...(await shotDrift(input)));\n\n return items.sort(\n (left, right) =>\n left.ref.localeCompare(right.ref) ||\n (left.criterion ?? \"\").localeCompare(right.criterion ?? \"\", \"en\", { numeric: true }) ||\n left.id.localeCompare(right.id),\n );\n}\n\nasync function shotDrift(input: DriftInput): Promise<DriftItem[]> {\n const { baseline } = input;\n const items: DriftItem[] = [];\n const shown = new Set(\n input.shows.filter((line) => line.call !== null).map((line) => `${line.ref} ${line.criterion}`),\n );\n const expected = input.languages.length > 0 ? input.languages : [\"\"];\n const approved = new Map(\n baseline.shots.map((shot) => [`${shot.ref} ${shot.criterion} ${shot.language}`, shot]),\n );\n const captured = new Map(\n (input.captures?.captures ?? [])\n .filter((capture) => capture.outcome === \"pass\" && capture.file !== null)\n .map((capture) => [`${capture.ref} ${capture.criterion} ${capture.language}`, capture]),\n );\n\n for (const [key, capture] of captured) {\n if (!shown.has(`${capture.ref} ${capture.criterion}`) || input.optedOut.includes(capture.ref)) {\n continue;\n }\n\n const shot = approved.get(key);\n const base = { ref: capture.ref, criterion: capture.criterion, language: capture.language };\n\n if (shot === undefined) {\n items.push(item(baseline, { type: \"shot-added\", ...base, capturedShot: capture.file }));\n continue;\n }\n\n if (capture.sha256 === shot.sha256) continue;\n\n const [before, after] = await Promise.all([\n readImage(input.root, shot.file),\n readImage(input.root, capture.file ?? \"\"),\n ]);\n\n // A capture whose file is gone proves nothing; an approved image that is gone cannot be compared.\n if (after === null) continue;\n\n if (before === null || comparePng(before, after).changed) {\n items.push(\n item(baseline, {\n type: \"shot-changed\",\n ...base,\n approvedShot: shot.file,\n capturedShot: capture.file,\n }),\n );\n }\n }\n\n for (const [, shot] of approved) {\n const gone =\n !shown.has(`${shot.ref} ${shot.criterion}`) ||\n input.optedOut.includes(shot.ref) ||\n !expected.includes(shot.language);\n\n if (gone) {\n items.push(\n item(baseline, {\n type: \"shot-removed\",\n ref: shot.ref,\n criterion: shot.criterion,\n language: shot.language,\n approvedShot: shot.file,\n }),\n );\n }\n }\n\n return items;\n}\n"],"mappings":";;;;;;;;;;;AAkCA,SAAgB,aAAa,SAA0C;CACrE,OAAO,QAAQ,SACZ,SAAS,YAAY,QAAQ,KAAK,CAAC,CACnC,KAAK,UAAU;EACd,KAAK,KAAK;EACV,UAAU,KAAK,SAAS,KAAK,eAAe;GAAE,IA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