@warlock.js/grimoire 5.58.0 → 5.60.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 +24 -0
- package/esm/apps/check-apps.mjs +11 -5
- package/esm/apps/check-apps.mjs.map +1 -1
- package/esm/book/build.d.mts.map +1 -1
- package/esm/book/build.mjs.map +1 -1
- package/esm/bookmap/build.d.mts.map +1 -1
- package/esm/bookmap/build.mjs +5 -3
- package/esm/bookmap/build.mjs.map +1 -1
- package/esm/bookmap/steps.mjs +34 -3
- package/esm/bookmap/steps.mjs.map +1 -1
- package/esm/contracts/adapter.d.mts +22 -1
- package/esm/contracts/adapter.d.mts.map +1 -1
- package/esm/contracts/scry.d.mts +26 -6
- package/esm/contracts/scry.d.mts.map +1 -1
- package/esm/contracts/snapshot.d.mts +3 -1
- package/esm/contracts/snapshot.d.mts.map +1 -1
- package/esm/devtools/data.mjs +23 -3
- package/esm/devtools/data.mjs.map +1 -1
- package/esm/devtools/feature-map.mjs +149 -0
- package/esm/devtools/feature-map.mjs.map +1 -0
- package/esm/devtools/index.d.mts +2 -2
- package/esm/devtools/index.mjs +30 -9
- package/esm/devtools/index.mjs.map +1 -1
- package/esm/devtools/product-map.d.mts.map +1 -1
- package/esm/devtools/product-map.mjs +82 -7
- package/esm/devtools/product-map.mjs.map +1 -1
- package/esm/devtools/site.d.mts +43 -1
- package/esm/devtools/site.d.mts.map +1 -1
- package/esm/devtools/site.mjs +111 -15
- package/esm/devtools/site.mjs.map +1 -1
- package/esm/devtools/snapshot-source.mjs +15 -2
- package/esm/devtools/snapshot-source.mjs.map +1 -1
- package/esm/index.d.mts +3 -3
- package/esm/ownership/index.d.mts.map +1 -1
- package/esm/ownership/index.mjs +60 -1
- package/esm/ownership/index.mjs.map +1 -1
- package/esm/scry/compact.mjs +2 -1
- package/esm/scry/compact.mjs.map +1 -1
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +12 -1
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +147 -23
- package/esm/scry/query.mjs.map +1 -1
- package/esm/test-results/index.d.mts.map +1 -1
- package/esm/test-results/index.mjs.map +1 -1
- package/esm/warlock/actions.mjs +15 -7
- package/esm/warlock/actions.mjs.map +1 -1
- package/esm/warlock/adapter.d.mts.map +1 -1
- package/esm/warlock/adapter.mjs +36 -2
- package/esm/warlock/adapter.mjs.map +1 -1
- package/esm/warlock/commands.mjs +7 -2
- package/esm/warlock/commands.mjs.map +1 -1
- package/esm/warlock/logo.mjs +12 -0
- package/esm/warlock/logo.mjs.map +1 -0
- package/esm/warlock/mcp-tools.mjs +6 -6
- package/esm/warlock/mcp-tools.mjs.map +1 -1
- package/esm/workspace/cache.mjs +194 -0
- package/esm/workspace/cache.mjs.map +1 -0
- package/esm/workspace/index.d.mts.map +1 -1
- package/esm/workspace/index.mjs +3 -1
- package/esm/workspace/index.mjs.map +1 -1
- package/llms-full.txt +32 -9
- package/package.json +3 -3
- package/skills/record-a-change/SKILL.md +2 -0
- package/skills/use-the-grimoire/SKILL.md +30 -9
- package/ui/grimoire-static.js +57 -6
- package/ui/grimoire-view.js +1289 -310
- package/ui/grimoire.css +583 -2
- package/ui/product-map.css +157 -8
- package/ui/product-map.js +507 -59
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"site.mjs","names":["data.summary","data.features","data.apps","data.tasks","data.releases","data.check","data.graphOfModules","data.checkGroups","feature","data.feature","flowAnswer","data.flowAnswer","page","data.page","file","data.file"],"sources":["../../../../../../../../packages/grimoire/src/devtools/site.ts"],"sourcesContent":["/**\n * The static export: one folder with an `index.html` that holds the view, the\n * loader, the styles and the data as JSON. It opens from disk (`file://`) or\n * any static host and needs no running app.\n */\nimport { copyFile, mkdir, readFile, realpath, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { GRIMOIRE_PATHS, projectPath, toPosixPath } from \"../paths\";\nimport * as data from \"./data\";\nimport { featureGraph, fileGraph, pageGraph } from \"./graphs\";\nimport { productFeature, productFlow, productMap } from \"./product-map\";\nimport { createSnapshotSource } from \"./snapshot-source\";\n\n/** Options of `exportGrimoireSite()`. */\nexport type ExportGrimoireSiteOptions = {\n /** Output folder, project-relative or absolute. Default `grimoire/book/site` (the book writer leaves it alone and git ignores it). */\n outDir?: string;\n /** The adapter to open the book with. Default: the Warlock adapter. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /** An already opened snapshot; skips opening one. */\n snapshot?: GrimoireSnapshot;\n};\n\n/** The most files the export keeps per-file answers for (the most imported first). */\nexport const SITE_FILE_LIMIT = 3000;\n\ntype SearchItem = { type: string; id: string; detail: string | null };\n\nconst uiFolder = fileURLToPath(new URL(\"../../ui/\", import.meta.url));\n\n/** Every answer the static page can give, keyed by the data route it replaces. */\nexport function buildSiteData(snapshot: GrimoireSnapshot) {\n const routes: Record<string, unknown> = {\n summary: data.summary(snapshot),\n features: data.features(snapshot),\n apps: data.apps(snapshot),\n tasks: data.tasks(snapshot),\n releases: data.releases(snapshot),\n // The page is meant to be shared: it does not name where the project sits on this machine.\n check: { ...data.check(snapshot), root: \".\" },\n \"graph/modules\": data.graphOfModules(snapshot),\n };\n // The static page is the signed-in view: developer detail stays, and no monitor reports errors.\n const productOptions = { shared: false, errors: null } as const;\n const productAnswer = attempt(() => productMap(snapshot, productOptions));\n const groups = attempt(() => data.checkGroups(snapshot));\n\n if (productAnswer !== undefined) routes.product = productAnswer;\n\n if (groups !== undefined) routes[\"check/groups\"] = groups;\n\n const search: SearchItem[] = [];\n\n for (const release of snapshot.written.releases) {\n routes[`releases/${release.release.value}`] = release;\n }\n\n for (const feature of snapshot.written.features) {\n const readme = feature.readme;\n\n search.push({ type: \"feature\", id: feature.id, detail: readme?.title.value ?? null });\n const answered = attempt(() => data.feature(snapshot, feature.id));\n\n if (answered !== undefined) routes[`features/${feature.id}`] = answered;\n\n const graph = featureGraph(snapshot, feature.id);\n\n if (graph !== null) routes[`graph/feature/${feature.id}`] = graph;\n\n const product = attempt(() => productFeature(snapshot, feature.id, productOptions));\n\n if (product !== undefined) routes[`product/features/${feature.id}`] = product;\n\n for (const flow of feature.flows) {\n search.push({ type: \"flow\", id: flow.ref, detail: flow.heading?.value ?? null });\n const flowAnswer = attempt(() => data.flowAnswer(snapshot, feature.id, flow.id.value));\n const productFlowAnswer = attempt(() =>\n productFlow(snapshot, feature.id, flow.id.value, productOptions),\n );\n\n if (flowAnswer !== undefined) routes[`flows/${flow.ref}`] = flowAnswer;\n\n if (productFlowAnswer !== undefined) routes[`product/flows/${flow.ref}`] = productFlowAnswer;\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n\n for (const page of [...app.pages, ...app.screens]) {\n const route = page.route?.value ?? page.screen?.value ?? null;\n const answer = attempt(() => data.page(snapshot, appId, page.id));\n const graph = pageGraph(snapshot, appId, page.id);\n\n for (const key of new Set([page.id, ...(route === null ? [] : [route])])) {\n if (answer !== undefined) routes[`apps/${appId}/pages/${key}`] = answer;\n\n if (graph !== null) routes[`graph/page/${appId}/${key}`] = graph;\n }\n\n if (route !== null)\n search.push({\n type: page.type,\n id: `${appId} ${route}`,\n detail: page.heading?.value ?? null,\n });\n\n for (const block of page.blockFiles) {\n search.push({\n type: \"block\",\n id: `${appId}/${page.id}/${block.id}`,\n detail: block.flow?.value ?? null,\n });\n }\n }\n }\n\n for (const found of snapshot.book.facts.routes ?? []) {\n search.push({\n type: \"route\",\n id: `${found.method} ${found.path}`,\n detail: found.description ?? found.handler,\n });\n }\n\n for (const task of snapshot.collected.tasksIndex.open.concat(\n snapshot.collected.tasksIndex.done,\n )) {\n search.push({ type: \"task\", id: task.id, detail: task.title });\n }\n\n const files: Record<string, { result: unknown; graph: unknown }> = {};\n const ranked = [...snapshot.book.facts.files].sort(\n (left, right) =>\n right.importedBy.length - left.importedBy.length || left.file.localeCompare(right.file),\n );\n\n for (const [index, file] of ranked.entries()) {\n search.push({ type: \"file\", id: file.file, detail: file.about });\n\n if (index >= SITE_FILE_LIMIT) continue;\n\n const result = attempt(() => data.file(snapshot, file.file));\n\n if (result !== undefined) files[file.file] = { result, graph: fileGraph(snapshot, file.file) };\n }\n\n return { routes, files, search };\n}\n\n/** JSON for an inline `<script>`: every `<` is escaped, so no `</script` or `<!--` can appear. */\nfunction inlineJson(value: unknown): string {\n return JSON.stringify(value).replaceAll(\"<\", \"\\\\u003c\");\n}\n\n/** Code for an inline `<script>`: `</script` (in any case) and `<!--` (only possible in strings and comments) are broken up. */\nfunction inlineCode(code: string): string {\n return code.replace(/<\\/(script)/gi, \"<\\\\/$1\").replaceAll(\"<!--\", \"<\\\\!--\");\n}\n\n/** The image types the export copies (the same list the devtools panel serves). */\nconst SCREENSHOT_EXTENSIONS = new Set([\".png\", \".jpg\", \".jpeg\", \".webp\", \".gif\"]);\n\n/** Every `WrittenScreenshot.path` in the written files, once each. */\nexport function collectScreenshotPaths(written: unknown): string[] {\n const found = new Set<string>();\n const walk = (value: unknown): void => {\n if (Array.isArray(value)) {\n for (const item of value) walk(item);\n } else if (value !== null && typeof value === \"object\") {\n const record = value as Record<string, unknown>;\n\n if (\n typeof record.path === \"string\" &&\n typeof record.written === \"string\" &&\n typeof record.alt === \"string\"\n )\n found.add(record.path);\n\n for (const item of Object.values(record)) walk(item);\n }\n };\n\n walk(written);\n\n return [...found].sort();\n}\n\n/**\n * Copy the screenshots the written files use into `<out>/screenshots/`. A path that leaves\n * `grimoire/screenshots/`, has another extension or does not exist is skipped.\n *\n * @returns The paths that were copied.\n */\nexport async function copyScreenshots(\n root: string,\n outFolder: string,\n paths: readonly string[],\n): Promise<string[]> {\n const folder = await realpath(path.join(root, GRIMOIRE_PATHS.screenshots)).catch(() => null);\n const copied: string[] = [];\n\n if (folder === null) return copied;\n\n for (const written of paths) {\n const segments = written.split(\"/\");\n\n if (\n written === \"\" ||\n written.includes(\"\\\\\") ||\n written.includes(\"\\0\") ||\n path.isAbsolute(written) ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\") ||\n !SCREENSHOT_EXTENSIONS.has(path.extname(written).toLowerCase())\n )\n continue;\n\n const source = await realpath(path.join(folder, ...segments)).catch(() => null);\n\n if (source === null || !source.startsWith(folder + path.sep)) continue;\n\n if (!(await stat(source)).isFile()) continue;\n\n const target = path.join(outFolder, \"screenshots\", ...segments);\n\n await mkdir(path.dirname(target), { recursive: true });\n await copyFile(source, target);\n copied.push(written);\n }\n\n return copied;\n}\n\n/** The answer, or `undefined` when the item cannot be answered (the export skips it). */\nfunction attempt<Value>(answer: () => Value): Value | undefined {\n try {\n return answer();\n } catch {\n return undefined;\n }\n}\n\n/** Everything before the page's `export default`, so the view can sit in an inline module. */\nexport function inlineView(source: string): string {\n const marker = \"export default renderGrimoire;\";\n\n if (!source.includes(marker))\n throw new Error(\"grimoire-view.js must end with `export default renderGrimoire;`.\");\n\n return source.replace(marker, \"\");\n}\n\n/**\n * The product map module as inline code: its `export` keywords are removed and the Grimoire view\n * finds it as `globalThis.grimoireProductMap`.\n */\nexport function inlineProductMap(source: string): string {\n const marker = \"export default renderProductMap;\";\n\n if (!source.includes(marker))\n throw new Error(\"product-map.js must end with `export default renderProductMap;`.\");\n\n return `${source.replace(marker, \"\").replace(/^export (async )?function /gm, \"$1function \")}\\nglobalThis.grimoireProductMap = { productMapView };\\n`;\n}\n\n/**\n * The page's own styles: it defines every devtools panel token (light, then dark under\n * `prefers-color-scheme`), so `grimoire.css` renders the same here as in the dashboard.\n * The values keep text AA on `--background` and `--card`.\n */\nexport const PAGE_STYLE = `\n:root{color-scheme:light dark;--background:#f7f8fa;--foreground:#161b22;--card:#fff;--card-foreground:#161b22;--popover:#fff;--popover-foreground:#161b22;--primary:#1f2937;--primary-foreground:#fff;--secondary:#eceff3;--secondary-foreground:#1f2937;--muted:#eceff3;--muted-foreground:#4b5565;--accent:#e4e9f2;--accent-foreground:#161b22;--destructive:#b42318;--border:#d5dae3;--input:#c3cad6;--ring:#2f5fd0;--radius:10px;--brand:#2757c4;--brand-foreground:#fff;--success:#13693b;--warning:#8a5300;--info:#0b66a3;--chart-1:#2757c4;--chart-2:#13693b;--chart-3:#8a5300;--chart-4:#6d3ac7;--chart-5:#b4306b;font-family:system-ui,-apple-system,\"Segoe UI\",sans-serif}\n@media (prefers-color-scheme:dark){:root{--background:#14171c;--foreground:#eceff4;--card:#1c2027;--card-foreground:#eceff4;--popover:#1c2027;--popover-foreground:#eceff4;--primary:#eceff4;--primary-foreground:#14171c;--secondary:#272c35;--secondary-foreground:#eceff4;--muted:#272c35;--muted-foreground:#a9b2c1;--accent:#2d3440;--accent-foreground:#eceff4;--destructive:#ff8f86;--border:#343b47;--input:#3f4756;--ring:#8fb0ff;--radius:10px;--brand:#86adff;--brand-foreground:#0d1320;--success:#5fd391;--warning:#f3b25a;--info:#6cc0f5;--chart-1:#86adff;--chart-2:#5fd391;--chart-3:#f3b25a;--chart-4:#b79cff;--chart-5:#ff8fbd}}\n*{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font-size:14px;line-height:1.5}\nmain{max-width:1180px;margin:0 auto;padding:16px}\n.empty{padding:12px;color:var(--muted-foreground)}.error{padding:12px;color:var(--destructive)}\n`;\n\n/** The `index.html` text. */\nexport function renderSiteHtml(\n siteData: unknown,\n sources: { view: string; loader: string; css: string; productMap?: string; productCss?: string },\n): string {\n const json = inlineJson(siteData);\n const script = inlineCode(\n `${sources.productMap === undefined ? \"\" : inlineProductMap(sources.productMap)}${inlineView(sources.view)}\\n${sources.loader}\\ngrimoireStaticMount(JSON.parse(document.getElementById(\"grimoire-data\").textContent), document.getElementById(\"grimoire-root\"), renderGrimoire);\\n`,\n );\n\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Grimoire</title>\n<style>${PAGE_STYLE}${sources.css}${sources.productCss ?? \"\"}</style>\n</head>\n<body>\n<main id=\"grimoire-root\"><p class=\"empty\">Opening the book…</p></main>\n<script type=\"application/json\" id=\"grimoire-data\">${json}</script>\n<script type=\"module\">${script}</script>\n</body>\n</html>\n`;\n}\n\n/**\n * Write the tab as a static folder for people without the app running.\n *\n * The folder holds `index.html` only: the view, the loader, the styles and\n * the data (as JSON) are inside it, so it opens straight from disk. Open the\n * page and use `#grimoire/...` links; the answers that need the running app\n * (impact of a file) say so in place.\n *\n * @param root Absolute project root.\n * @returns The output folder, project-relative.\n */\nexport async function exportGrimoireSite(\n root: string,\n options: ExportGrimoireSiteOptions = {},\n): Promise<string> {\n // Project-relative from here on; an absolute folder is kept where it is.\n const outDir = projectPath(\n root,\n toPosixPath(options.outDir ?? GRIMOIRE_PATHS.staticSite),\n ).replace(/\\/+$/, \"\");\n const snapshot =\n options.snapshot ??\n (await createSnapshotSource(\n root,\n options.adapter === undefined ? {} : { adapter: options.adapter },\n ).get());\n const [view, loader, css, productMapSource, productCss] = await Promise.all(\n [\n \"grimoire-view.js\",\n \"grimoire-static.js\",\n \"grimoire.css\",\n \"product-map.js\",\n \"product-map.css\",\n ].map((name) => readFile(path.join(uiFolder, name), \"utf8\")),\n );\n const html = renderSiteHtml(buildSiteData(snapshot), {\n view: view ?? \"\",\n loader: loader ?? \"\",\n css: css ?? \"\",\n productMap: productMapSource ?? \"\",\n productCss: productCss ?? \"\",\n });\n const absolute = path.resolve(root, outDir);\n\n await mkdir(absolute, { recursive: true });\n await writeFile(path.join(absolute, \"index.html\"), html);\n await copyScreenshots(root, absolute, collectScreenshotPaths(snapshot.written));\n\n return outDir;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2BA,MAAa,kBAAkB;AAI/B,MAAM,WAAW,cAAc,IAAI,IAAI,aAAa,YAAY,GAAG,CAAC;;AAGpE,SAAgB,cAAc,UAA4B;CACxD,MAAM,SAAkC;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,GAAG;EACnD,MAAM,QAAQ;EACd,QAAQ,UAAU;EAClB,KAAK,OAAO;EACZ,YAAY,oBAAoB;EAChC,YAAY,cAAc;CAC5B,CAAC;CACD,MAAM,WAAW,KAAK,QAAQ,MAAM,MAAM;CAE1C,MAAM,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;CACzC,MAAM,UAAU,KAAK,KAAK,UAAU,YAAY,GAAG,IAAI;CACvD,MAAM,gBAAgB,MAAM,UAAU,uBAAuB,SAAS,OAAO,CAAC;CAE9E,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"site.mjs","names":["data.summary","data.features","data.apps","data.tasks","data.releases","data.check","data.graphOfModules","data.checkGroups","feature","data.feature","flowAnswer","data.flowAnswer","page","data.page","file","data.file"],"sources":["../../../../../../../../packages/grimoire/src/devtools/site.ts"],"sourcesContent":["/**\n * The static export: one folder with an `index.html` that holds the view, the\n * loader, the styles and the data as JSON. It opens from disk (`file://`) or\n * any static host and needs no running app.\n */\nimport { createHash } from \"node:crypto\";\nimport { copyFile, mkdir, open, readFile, realpath, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFlow } from \"../contracts/written\";\nimport { GRIMOIRE_PATHS, projectPath, toPosixPath } from \"../paths\";\nimport { stampOf } from \"../workspace/cache\";\nimport * as data from \"./data\";\nimport { featureGraph, fileGraph, pageGraph } from \"./graphs\";\nimport { productFeature, productFlow, productMap } from \"./product-map\";\nimport { createSnapshotSource } from \"./snapshot-source\";\n\n/** Options of `exportGrimoireSite()`. */\nexport type ExportGrimoireSiteOptions = {\n /** Output folder, project-relative or absolute. Default `grimoire/book/site` (the book writer leaves it alone and git ignores it). */\n outDir?: string;\n /** The adapter to open the book with. Default: the Warlock adapter. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /** An already opened snapshot; skips opening one. */\n snapshot?: GrimoireSnapshot;\n /**\n * Export the business view only: the share-safe Product map (no file paths, test\n * names or export names, no per-file answers, no check or search of code). The\n * page opens on the Product map.\n */\n product?: boolean;\n /** Write the page even when the folder already holds one built from the same book. Default `false`. */\n force?: boolean;\n};\n\n/** What `exportGrimoireSite()` did. */\nexport type GrimoireSiteExport = {\n /** The output folder, project-relative. */\n outDir: string;\n /** `true` when the folder already held a page built from the same book and nothing was written. */\n upToDate: boolean;\n};\n\n/** The most files the export keeps per-file answers for (the most imported first). */\nexport const SITE_FILE_LIMIT = 3000;\n\n/** One entry of the exported search list. `text` is written content (a flow's summary, story, cases and criteria) the search also reads. */\ntype SearchItem = { type: string; id: string; detail: string | null; text?: string };\n\n/** The written text of a flow the exported search reads, with criteria ids so `AC-5` is findable. */\nfunction flowSearchText(flow: WrittenFlow): string {\n return [\n flow.summary ?? \"\",\n ...flow.story.map((step) => step.text),\n ...flow.cases.map((item) => `${item.question} ${item.answer} ${item.criteria.join(\" \")}`),\n ...flow.criteria.map((item) => `${item.id} ${item.text}`),\n ]\n .filter((part) => part !== \"\")\n .join(\" | \");\n}\n\nconst uiFolder = fileURLToPath(new URL(\"../../ui/\", import.meta.url));\n\n/** Every answer the static page can give, keyed by the data route it replaces. */\nexport function buildSiteData(snapshot: GrimoireSnapshot) {\n const routes: Record<string, unknown> = {\n summary: data.summary(snapshot),\n features: data.features(snapshot),\n apps: data.apps(snapshot),\n tasks: data.tasks(snapshot),\n releases: data.releases(snapshot),\n // The page is meant to be shared: it does not name where the project sits on this machine.\n check: { ...data.check(snapshot), root: \".\" },\n \"graph/modules\": data.graphOfModules(snapshot),\n };\n // The static page is the signed-in view: developer detail stays, and no monitor reports errors.\n const productOptions = { shared: false, errors: null } as const;\n const productAnswer = attempt(() => productMap(snapshot, productOptions));\n const groups = attempt(() => data.checkGroups(snapshot));\n\n if (productAnswer !== undefined) routes.product = productAnswer;\n\n if (groups !== undefined) routes[\"check/groups\"] = groups;\n\n const search: SearchItem[] = [];\n\n for (const release of snapshot.written.releases) {\n routes[`releases/${release.release.value}`] = release;\n }\n\n for (const feature of snapshot.written.features) {\n const readme = feature.readme;\n\n search.push({\n type: \"feature\",\n id: feature.id,\n detail: readme?.title.value ?? null,\n text: [readme?.summary ?? \"\", readme?.why ?? \"\"].filter((part) => part !== \"\").join(\" | \"),\n });\n const answered = attempt(() => data.feature(snapshot, feature.id));\n\n if (answered !== undefined) routes[`features/${feature.id}`] = answered;\n\n const graph = featureGraph(snapshot, feature.id);\n\n if (graph !== null) routes[`graph/feature/${feature.id}`] = graph;\n\n const product = attempt(() => productFeature(snapshot, feature.id, productOptions));\n\n if (product !== undefined) routes[`product/features/${feature.id}`] = product;\n\n for (const flow of feature.flows) {\n search.push({\n type: \"flow\",\n id: flow.ref,\n detail: flow.heading?.value ?? null,\n text: flowSearchText(flow),\n });\n const flowAnswer = attempt(() => data.flowAnswer(snapshot, feature.id, flow.id.value));\n const productFlowAnswer = attempt(() =>\n productFlow(snapshot, feature.id, flow.id.value, productOptions),\n );\n\n if (flowAnswer !== undefined) routes[`flows/${flow.ref}`] = flowAnswer;\n\n if (productFlowAnswer !== undefined) routes[`product/flows/${flow.ref}`] = productFlowAnswer;\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n\n for (const page of [...app.pages, ...app.screens]) {\n const route = page.route?.value ?? page.screen?.value ?? null;\n const answer = attempt(() => data.page(snapshot, appId, page.id));\n const graph = pageGraph(snapshot, appId, page.id);\n\n for (const key of new Set([page.id, ...(route === null ? [] : [route])])) {\n if (answer !== undefined) routes[`apps/${appId}/pages/${key}`] = answer;\n\n if (graph !== null) routes[`graph/page/${appId}/${key}`] = graph;\n }\n\n if (route !== null)\n search.push({\n type: page.type,\n id: `${appId} ${route}`,\n detail: page.heading?.value ?? null,\n });\n\n for (const block of page.blockFiles) {\n search.push({\n type: \"block\",\n id: `${appId}/${page.id}/${block.id}`,\n detail: block.flow?.value ?? null,\n });\n }\n }\n }\n\n for (const found of snapshot.book.facts.routes ?? []) {\n search.push({\n type: \"route\",\n id: `${found.method} ${found.path}`,\n detail: found.description ?? found.handler,\n });\n }\n\n for (const task of snapshot.collected.tasksIndex.open.concat(\n snapshot.collected.tasksIndex.done,\n )) {\n search.push({ type: \"task\", id: task.id, detail: task.title });\n }\n\n const files: Record<string, { result: unknown; graph: unknown }> = {};\n const ranked = [...snapshot.book.facts.files].sort(\n (left, right) =>\n right.importedBy.length - left.importedBy.length || left.file.localeCompare(right.file),\n );\n\n for (const [index, file] of ranked.entries()) {\n search.push({ type: \"file\", id: file.file, detail: file.about });\n\n if (index >= SITE_FILE_LIMIT) continue;\n\n const result = attempt(() => data.file(snapshot, file.file));\n\n if (result !== undefined) files[file.file] = { result, graph: fileGraph(snapshot, file.file) };\n }\n\n return { routes, files, search };\n}\n\n/**\n * The business-only data of the static export: the share-safe Product map, its feature\n * and flow pages, and nothing else. No file paths, test names, export names, check\n * findings or per-file answers; the search list is empty.\n */\nexport function buildProductSiteData(snapshot: GrimoireSnapshot) {\n const options = { shared: true, errors: null } as const;\n const routes: Record<string, unknown> = {};\n const map = attempt(() => productMap(snapshot, options));\n\n if (map !== undefined) routes.product = map;\n\n for (const feature of snapshot.written.features) {\n const answer = attempt(() => productFeature(snapshot, feature.id, options));\n\n if (answer !== undefined) routes[`product/features/${feature.id}`] = answer;\n\n for (const flow of feature.flows) {\n const flowAnswer = attempt(() => productFlow(snapshot, feature.id, flow.id.value, options));\n\n if (flowAnswer !== undefined) routes[`product/flows/${flow.ref}`] = flowAnswer;\n }\n }\n\n return { routes, files: {}, search: [] as SearchItem[] };\n}\n\n/** JSON for an inline `<script>`: every `<` is escaped, so no `</script` or `<!--` can appear. */\nfunction inlineJson(value: unknown): string {\n return JSON.stringify(value).replaceAll(\"<\", \"\\\\u003c\");\n}\n\n/** Code for an inline `<script>`: `</script` (in any case) and `<!--` (only possible in strings and comments) are broken up. */\nfunction inlineCode(code: string): string {\n return code.replace(/<\\/(script)/gi, \"<\\\\/$1\").replaceAll(\"<!--\", \"<\\\\!--\");\n}\n\n/** The image types the export copies (the same list the devtools panel serves). */\nconst SCREENSHOT_EXTENSIONS = new Set([\".png\", \".jpg\", \".jpeg\", \".webp\", \".gif\"]);\n\n/** Every `WrittenScreenshot.path` in the written files, once each. */\nexport function collectScreenshotPaths(written: unknown): string[] {\n const found = new Set<string>();\n const walk = (value: unknown): void => {\n if (Array.isArray(value)) {\n for (const item of value) walk(item);\n } else if (value !== null && typeof value === \"object\") {\n const record = value as Record<string, unknown>;\n\n if (\n typeof record.path === \"string\" &&\n typeof record.written === \"string\" &&\n typeof record.alt === \"string\"\n )\n found.add(record.path);\n\n for (const item of Object.values(record)) walk(item);\n }\n };\n\n walk(written);\n\n return [...found].sort();\n}\n\n/**\n * Copy the screenshots the written files use into `<out>/screenshots/`. A path that leaves\n * `grimoire/screenshots/`, has another extension or does not exist is skipped.\n *\n * @returns The paths that were copied.\n */\nexport async function copyScreenshots(\n root: string,\n outFolder: string,\n paths: readonly string[],\n): Promise<string[]> {\n const folder = await realpath(path.join(root, GRIMOIRE_PATHS.screenshots)).catch(() => null);\n const copied: string[] = [];\n\n if (folder === null) return copied;\n\n for (const written of paths) {\n const segments = written.split(\"/\");\n\n if (\n written === \"\" ||\n written.includes(\"\\\\\") ||\n written.includes(\"\\0\") ||\n path.isAbsolute(written) ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\") ||\n !SCREENSHOT_EXTENSIONS.has(path.extname(written).toLowerCase())\n )\n continue;\n\n const source = await realpath(path.join(folder, ...segments)).catch(() => null);\n\n if (source === null || !source.startsWith(folder + path.sep)) continue;\n\n if (!(await stat(source)).isFile()) continue;\n\n const target = path.join(outFolder, \"screenshots\", ...segments);\n\n await mkdir(path.dirname(target), { recursive: true });\n await copyFile(source, target);\n copied.push(written);\n }\n\n return copied;\n}\n\n/** The answer, or `undefined` when the item cannot be answered (the export skips it). */\nfunction attempt<Value>(answer: () => Value): Value | undefined {\n try {\n return answer();\n } catch {\n return undefined;\n }\n}\n\n/** Everything before the page's `export default`, so the view can sit in an inline module. */\nexport function inlineView(source: string): string {\n const marker = \"export default renderGrimoire;\";\n\n if (!source.includes(marker))\n throw new Error(\"grimoire-view.js must end with `export default renderGrimoire;`.\");\n\n return source.replace(marker, \"\");\n}\n\n/**\n * The product map module as inline code: its `export` keywords are removed and the Grimoire view\n * finds it as `globalThis.grimoireProductMap`.\n */\nexport function inlineProductMap(source: string): string {\n const marker = \"export default renderProductMap;\";\n\n if (!source.includes(marker))\n throw new Error(\"product-map.js must end with `export default renderProductMap;`.\");\n\n return `${source.replace(marker, \"\").replace(/^export (async )?function /gm, \"$1function \")}\\nglobalThis.grimoireProductMap = { productMapView };\\n`;\n}\n\n/**\n * The page's own styles: it defines every devtools panel token (light, then dark under\n * `prefers-color-scheme`), so `grimoire.css` renders the same here as in the dashboard.\n * The values keep text AA on `--background` and `--card`.\n */\nexport const PAGE_STYLE = `\n:root{color-scheme:light dark;--background:#faf8f2;--foreground:#1a1814;--card:#fff;--card-foreground:#1a1814;--popover:#fff;--popover-foreground:#1a1814;--primary:#1a1814;--primary-foreground:#faf8f2;--secondary:#f0ece0;--secondary-foreground:#1a1814;--muted:#f0ece0;--muted-foreground:#5c574b;--accent:#f3ecd6;--accent-foreground:#1a1814;--destructive:#b42318;--border:#e0d9c6;--input:#d2cab3;--ring:#8a5a00;--radius:10px;--brand:#8a5a00;--brand-foreground:#fff;--success:#13693b;--warning:#8a5300;--info:#0b66a3;--chart-1:#8a5a00;--chart-2:#13693b;--chart-3:#0b66a3;--chart-4:#6d3ac7;--chart-5:#b4306b;font-family:system-ui,-apple-system,\"Segoe UI\",sans-serif}\n@media (prefers-color-scheme:dark){:root{--background:#0b0b0c;--foreground:#f2f2ee;--card:#141416;--card-foreground:#f2f2ee;--popover:#141416;--popover-foreground:#f2f2ee;--primary:#ffc61a;--primary-foreground:#1a1300;--secondary:#1f1f22;--secondary-foreground:#f2f2ee;--muted:#1f1f22;--muted-foreground:#a9a9b0;--accent:#26262a;--accent-foreground:#f2f2ee;--destructive:#ff8f86;--border:#2a2a2e;--input:#34343a;--ring:#ffc61a;--radius:10px;--brand:#ffc61a;--brand-foreground:#1a1300;--success:#5fd391;--warning:#f3a24a;--info:#6cc0f5;--chart-1:#ffc61a;--chart-2:#5fd391;--chart-3:#6cc0f5;--chart-4:#b79cff;--chart-5:#ff8fbd}}\n*{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font-size:14px;line-height:1.5}\nmain{max-width:1180px;margin:0 auto;padding:16px}\n.empty{padding:12px;color:var(--muted-foreground)}.error{padding:12px;color:var(--destructive)}\n`;\n\n/** The `index.html` text. */\nexport function renderSiteHtml(\n siteData: unknown,\n sources: {\n view: string;\n loader: string;\n css: string;\n productMap?: string;\n productCss?: string;\n /** Mount the share-safe Product map alone (the business export): `view` and `css` are not inlined. */\n product?: boolean;\n /** A freshness stamp written into the page, so the next export can tell it is current. */\n stamp?: string;\n },\n): string {\n const json = inlineJson(siteData);\n\n if (sources.product === true && sources.productMap === undefined) {\n throw new Error(\"A product export needs product-map.js.\");\n }\n\n const mounted = sources.product === true ? \"renderProductMap\" : \"renderGrimoire\";\n const script = inlineCode(\n `${sources.productMap === undefined ? \"\" : inlineProductMap(sources.productMap)}${sources.product === true ? \"\" : inlineView(sources.view)}\\n${sources.loader}\\ngrimoireStaticMount(JSON.parse(document.getElementById(\"grimoire-data\").textContent), document.getElementById(\"grimoire-root\"), ${mounted});\\n`,\n );\n const styles = sources.product === true ? \"\" : sources.css;\n const stamp =\n sources.stamp === undefined ? \"\" : `<meta name=\"grimoire-stamp\" content=\"${sources.stamp}\">\\n`;\n\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n${stamp}<title>${sources.product === true ? \"Product map\" : \"Grimoire\"}</title>\n<style>${PAGE_STYLE}${styles}${sources.productCss ?? \"\"}</style>\n</head>\n<body>\n<main id=\"grimoire-root\"><p class=\"empty\">Opening the book…</p></main>\n<script type=\"application/json\" id=\"grimoire-data\">${json}</script>\n<script type=\"module\">${script}</script>\n</body>\n</html>\n`;\n}\n\n/** The stamp is written near the top of the page; this much of the file is enough to find it. */\nconst STAMP_HEAD_BYTES = 2048;\n\n/** The stamp of the page that is already in `index.html`, or `null` (no page, or one without a stamp). */\nasync function writtenStamp(file: string): Promise<string | null> {\n let handle;\n\n try {\n handle = await open(file, \"r\");\n\n const { buffer, bytesRead } = await handle.read(\n Buffer.alloc(STAMP_HEAD_BYTES),\n 0,\n STAMP_HEAD_BYTES,\n 0,\n );\n\n return (\n /<meta name=\"grimoire-stamp\" content=\"([0-9a-f]+)\">/.exec(\n buffer.toString(\"utf8\", 0, bytesRead),\n )?.[1] ?? null\n );\n } catch {\n return null;\n } finally {\n await handle?.close();\n }\n}\n\n/** Modified times of the files the page is built from, so a new framework version rebuilds the page. */\nasync function uiStamp(): Promise<string> {\n const names = [\n \"grimoire-view.js\",\n \"grimoire-static.js\",\n \"grimoire.css\",\n \"product-map.js\",\n \"product-map.css\",\n ];\n const times = await Promise.all(\n names.map(async (name) => {\n try {\n return (await stat(path.join(uiFolder, name))).mtimeMs;\n } catch {\n return 0;\n }\n }),\n );\n\n return times.join(\",\");\n}\n\n/**\n * Write the tab as a static folder for people without the app running.\n *\n * The folder holds `index.html` only: the view, the loader, the styles and\n * the data (as JSON) are inside it, so it opens straight from disk. Open the\n * page and use `#grimoire/...` links; the answers that need the running app\n * (impact of a file) say so in place.\n *\n * With `product: true` the page is the business export: the share-safe\n * Product map only, no file paths, test names or per-file answers.\n *\n * The page carries a freshness stamp (the files of the book, the written\n * folders and the test results). When the folder already holds a page with\n * the same stamp and the same mode, nothing is rebuilt or written (`force`\n * writes it anyway).\n *\n * @param root Absolute project root.\n */\nexport async function exportGrimoireSiteDetailed(\n root: string,\n options: ExportGrimoireSiteOptions = {},\n): Promise<GrimoireSiteExport> {\n // Project-relative from here on; an absolute folder is kept where it is.\n const outDir = projectPath(\n root,\n toPosixPath(options.outDir ?? GRIMOIRE_PATHS.staticSite),\n ).replace(/\\/+$/, \"\");\n const snapshot =\n options.snapshot ??\n (await createSnapshotSource(\n root,\n options.adapter === undefined ? {} : { adapter: options.adapter },\n ).get());\n const absolute = path.resolve(root, outDir);\n const product = options.product === true;\n const stamp = createHash(\"sha1\")\n .update(`${product ? \"product\" : \"full\"}|${await stampOf(root, snapshot)}|${await uiStamp()}`)\n .digest(\"hex\");\n\n if (options.force !== true && (await writtenStamp(path.join(absolute, \"index.html\"))) === stamp) {\n return { outDir, upToDate: true };\n }\n\n const [view, loader, css, productMapSource, productCss] = await Promise.all(\n [\n \"grimoire-view.js\",\n \"grimoire-static.js\",\n \"grimoire.css\",\n \"product-map.js\",\n \"product-map.css\",\n ].map((name) => readFile(path.join(uiFolder, name), \"utf8\")),\n );\n const html = renderSiteHtml(product ? buildProductSiteData(snapshot) : buildSiteData(snapshot), {\n view: view ?? \"\",\n loader: loader ?? \"\",\n css: css ?? \"\",\n productMap: productMapSource ?? \"\",\n productCss: productCss ?? \"\",\n product,\n stamp,\n });\n\n await mkdir(absolute, { recursive: true });\n await writeFile(path.join(absolute, \"index.html\"), html);\n await copyScreenshots(root, absolute, collectScreenshotPaths(snapshot.written));\n\n return { outDir, upToDate: false };\n}\n\n/** `exportGrimoireSiteDetailed()` that returns only the output folder, project-relative. */\nexport async function exportGrimoireSite(\n root: string,\n options: ExportGrimoireSiteOptions = {},\n): Promise<string> {\n return (await exportGrimoireSiteDetailed(root, options)).outDir;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8CA,MAAa,kBAAkB;;AAM/B,SAAS,eAAe,MAA2B;CACjD,OAAO;EACL,KAAK,WAAW;EAChB,GAAG,KAAK,MAAM,KAAK,SAAS,KAAK,IAAI;EACrC,GAAG,KAAK,MAAM,KAAK,SAAS,GAAG,KAAK,SAAS,GAAG,KAAK,OAAO,GAAG,KAAK,SAAS,KAAK,GAAG,GAA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M,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;CACzC,MAAM,UAAU,KAAK,KAAK,UAAU,YAAY,GAAG,IAAI;CACvD,MAAM,gBAAgB,MAAM,UAAU,uBAAuB,SAAS,OAAO,CAAC;CAE9E,OAAO;EAAE;EAAQ,UAAU;CAAM;AACnC;;AAGA,eAAsB,mBACpB,MACA,UAAqC,CAAC,GACrB;CACjB,QAAQ,MAAM,2BAA2B,MAAM,OAAO,EAAC,CAAE;AAC3D"}
|
|
@@ -62,17 +62,30 @@ async function loadAdapter(option) {
|
|
|
62
62
|
function createSnapshotSource(root, options = {}) {
|
|
63
63
|
let cached = null;
|
|
64
64
|
let opening = null;
|
|
65
|
+
let collected = options.collectRoutes !== true || options.mode === "production";
|
|
65
66
|
const resultsFile = resolveResultsFile(root, options.testResultsFile);
|
|
66
67
|
const keepUntilChanged = options.mode === "production" && options.ttlMs === void 0;
|
|
67
68
|
const reuseFor = (took) => options.ttlMs ?? Math.max(2e3, took * 5);
|
|
68
69
|
async function open() {
|
|
69
70
|
const started = Date.now();
|
|
70
71
|
const adapter = await loadAdapter(options.adapter);
|
|
71
|
-
const
|
|
72
|
-
routes: "cached",
|
|
72
|
+
const openOptions = {
|
|
73
73
|
write: options.write ?? false,
|
|
74
74
|
...options.testResultsFile === void 0 ? {} : { testResultsFile: options.testResultsFile }
|
|
75
|
+
};
|
|
76
|
+
let snapshot = await openGrimoire(root, adapter, {
|
|
77
|
+
routes: "cached",
|
|
78
|
+
...openOptions
|
|
75
79
|
});
|
|
80
|
+
if (!collected && snapshot.routes === "missing") {
|
|
81
|
+
collected = true;
|
|
82
|
+
try {
|
|
83
|
+
snapshot = await openGrimoire(root, adapter, {
|
|
84
|
+
routes: "fresh",
|
|
85
|
+
...openOptions
|
|
86
|
+
});
|
|
87
|
+
} catch {}
|
|
88
|
+
}
|
|
76
89
|
const at = Date.now();
|
|
77
90
|
cached = {
|
|
78
91
|
snapshot,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-source.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/devtools/snapshot-source.ts"],"sourcesContent":["/**\n * Where the panel's routes get the snapshot: opened once with\n * `routes: \"cached\"` (a devtools request never boots the app) and kept in\n * memory. Concurrent requests share one open. A change stamp (the book\n * manifest plus the agent-written folders and indexes, a few `stat` calls and\n * no directory walk) tells when the book changed.\n *\n * - Production (`mode: \"production\"`): a snapshot is reused until the stamp\n * changes, with no time limit, unless `ttlMs` is set. A request that finds\n * the stamp changed waits for the new open. `warm()` opens the book ahead\n * of the first request.\n * - Development: the snapshot is reused for a short window (2 s, or five times\n * the last open when that is longer, so a slow open on a large app is not\n * repeated on every view; written files change while an agent works). A\n * request that finds the stamp changed waits for the new open. After the\n * window, with the stamp unchanged (a file edited in place), the cached\n * snapshot is served at once and one background open refreshes it (stale\n * while revalidate).\n *\n * An open that fails keeps serving the old snapshot; its error surfaces on a\n * request only when there is no snapshot at all. The panel passes\n * `write: true` in development, so the generated book stays current and the\n * next open is incremental; with `write: false` a stored book behind the\n * sources is rebuilt in memory on every open.\n */\nimport { stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { resolveResultsFile } from \"../test-results\";\nimport { openGrimoire } from \"../workspace\";\n\n/** Options of the panel's snapshot source. */\nexport type SnapshotSourceOptions = {\n /** The adapter, or a function that loads it. Default: the Warlock adapter, imported on first use. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /**\n * How long a snapshot is reused when the book did not change (ms).\n * Default in development: 2000, or five times as long as the last open took\n * when that is longer. Default in production: no limit (reused until the\n * book changes).\n */\n ttlMs?: number;\n /** Where the source runs. `\"production\"` keeps a snapshot until the book changes. Default: `\"development\"`. */\n mode?: \"development\" | \"production\";\n /** Let `openGrimoire` write the generated book and collected files (never agent-written files). Default `false`; the devtools panel passes `true`. */\n write?: boolean;\n /**\n * Where the test results are read from (project-relative or absolute).\n * Default `grimoire/book/test-results.json`. The file's modified time is part\n * of the change stamp, so results written after the snapshot opened show up\n * without a restart.\n */\n testResultsFile?: string;\n};\n\n/** A cached, shared snapshot of one project. */\nexport type SnapshotSource = {\n get(): Promise<GrimoireSnapshot>;\n /** Forget the cached snapshot; the next `get()` opens again. */\n invalidate(): void;\n /** Start opening the book now, so the first `get()` is fast. Failures are ignored here and surface on `get()`. */\n warm(): void;\n /** Resolves when no open is running (specs and shutdown). Never rejects. */\n idle(): Promise<void>;\n};\n\n/** Files and folders whose modified time moves when the book or an agent-written file is added, removed or regenerated. */\nconst STAMPED = [\n GRIMOIRE_PATHS.bookManifest,\n GRIMOIRE_PATHS.featuresIndex,\n GRIMOIRE_PATHS.tasksIndex,\n GRIMOIRE_PATHS.features,\n GRIMOIRE_PATHS.apps,\n GRIMOIRE_PATHS.openTasks,\n GRIMOIRE_PATHS.doneTasks,\n GRIMOIRE_PATHS.releases,\n];\n\nasync function changeStamp(root: string, resultsFile: string): Promise<string> {\n const files = [...STAMPED.map((entry) => path.join(root, ...entry.split(\"/\"))), resultsFile];\n const times = await Promise.all(\n files.map(async (file) => {\n try {\n return (await stat(file)).mtimeMs;\n } catch {\n return 0;\n }\n }),\n );\n\n return times.join(\",\");\n}\n\nasync function loadAdapter(option: SnapshotSourceOptions[\"adapter\"]): Promise<BookAdapter> {\n if (option === undefined) {\n const { createWarlockAdapter } = await import(\"../warlock\");\n\n return createWarlockAdapter();\n }\n\n return typeof option === \"function\" ? option() : option;\n}\n\n/** Create the source for the project at `root`. */\nexport function createSnapshotSource(\n root: string,\n options: SnapshotSourceOptions = {},\n): SnapshotSource {\n let cached: { snapshot: GrimoireSnapshot; at: number; stamp: string; took: number } | null = null;\n let opening: Promise<GrimoireSnapshot> | null = null;\n\n const resultsFile = resolveResultsFile(root, options.testResultsFile);\n\n const keepUntilChanged = options.mode === \"production\" && options.ttlMs === undefined;\n const reuseFor = (took: number): number => options.ttlMs ?? Math.max(2000, took * 5);\n\n async function open(): Promise<GrimoireSnapshot> {\n const started = Date.now();\n const adapter = await loadAdapter(options.adapter);\n const snapshot = await openGrimoire(root, adapter, {\n routes: \"cached\",\n write: options.write ?? false,\n ...(options.testResultsFile === undefined ? {} : { testResultsFile: options.testResultsFile }),\n });\n\n const at = Date.now();\n\n cached = { snapshot, at, stamp: await changeStamp(root, resultsFile), took: at - started };\n\n return snapshot;\n }\n\n /** The open in flight, or a new one; concurrent callers share it. */\n function ensureOpening(): Promise<GrimoireSnapshot> {\n opening ??= open().finally(() => {\n opening = null;\n });\n\n return opening;\n }\n\n return {\n async get() {\n if (cached === null) return ensureOpening();\n\n const known = cached;\n const changed = (await changeStamp(root, resultsFile)) !== known.stamp;\n\n if (changed || options.mode === \"production\") {\n if (!changed && (keepUntilChanged || Date.now() - known.at < reuseFor(known.took))) {\n return known.snapshot;\n }\n\n // A failed open keeps the old snapshot; the next request tries again.\n return ensureOpening().catch(() => known.snapshot);\n }\n\n if (Date.now() - known.at < reuseFor(known.took)) return known.snapshot;\n\n // Development, nothing known to have changed: serve the old snapshot now and refresh behind it.\n ensureOpening().catch(() => {});\n\n return known.snapshot;\n },\n invalidate() {\n cached = null;\n },\n warm() {\n if (cached === null) ensureOpening().catch(() => {});\n },\n async idle() {\n await opening?.catch(() => {});\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,UAAU;CACd,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;AACjB;AAEA,eAAe,YAAY,MAAc,aAAsC;CAC7E,MAAM,QAAQ,CAAC,GAAG,QAAQ,KAAK,UAAU,KAAK,KAAK,MAAM,GAAG,MAAM,MAAM,GAAG,CAAC,CAAC,GAAG,WAAW;CAW3F,QAAO,MAVa,QAAQ,IAC1B,MAAM,IAAI,OAAO,SAAS;EACxB,IAAI;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AAY,oBAAoB,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,MAAM,IAAI,IAC9E,OAAO,MAAM;IAIf,OAAO,cAAc,CAAC,CAAC,YAAY,MAAM,QAAQ;GACnD;GAEA,IAAI,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,MAAM,IAAI,GAAG,OAAO,MAAM;GAG/D,cAAc,CAAC,CAAC,YAAY,CAAC,CAAC;GAE9B,OAAO,MAAM;EACf;EACA,aAAa;GACX,SAAS;EACX;EACA,OAAO;GACL,IAAI,WAAW,MAAM,cAAc,CAAC,CAAC,YAAY,CAAC,CAAC;EACrD;EACA,MAAM,OAAO;GACX,MAAM,SAAS,YAAY,CAAC,CAAC;EAC/B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"snapshot-source.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/devtools/snapshot-source.ts"],"sourcesContent":["/**\n * Where the panel's routes get the snapshot: opened once with\n * `routes: \"cached\"` (a devtools request never boots the app) and kept in\n * memory. Concurrent requests share one open. A change stamp (the book\n * manifest plus the agent-written folders and indexes, a few `stat` calls and\n * no directory walk) tells when the book changed.\n *\n * - Production (`mode: \"production\"`): a snapshot is reused until the stamp\n * changes, with no time limit, unless `ttlMs` is set. A request that finds\n * the stamp changed waits for the new open. `warm()` opens the book ahead\n * of the first request.\n * - Development: the snapshot is reused for a short window (2 s, or five times\n * the last open when that is longer, so a slow open on a large app is not\n * repeated on every view; written files change while an agent works). A\n * request that finds the stamp changed waits for the new open. After the\n * window, with the stamp unchanged (a file edited in place), the cached\n * snapshot is served at once and one background open refreshes it (stale\n * while revalidate).\n *\n * An open that fails keeps serving the old snapshot; its error surfaces on a\n * request only when there is no snapshot at all. The panel passes\n * `write: true` in development, so the generated book stays current and the\n * next open is incremental; with `write: false` a stored book behind the\n * sources is rebuilt in memory on every open.\n */\nimport { stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { resolveResultsFile } from \"../test-results\";\nimport { openGrimoire } from \"../workspace\";\n\n/** Options of the panel's snapshot source. */\nexport type SnapshotSourceOptions = {\n /** The adapter, or a function that loads it. Default: the Warlock adapter, imported on first use. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /**\n * How long a snapshot is reused when the book did not change (ms).\n * Default in development: 2000, or five times as long as the last open took\n * when that is longer. Default in production: no limit (reused until the\n * book changes).\n */\n ttlMs?: number;\n /** Where the source runs. `\"production\"` keeps a snapshot until the book changes. Default: `\"development\"`. */\n mode?: \"development\" | \"production\";\n /** Let `openGrimoire` write the generated book and collected files (never agent-written files). Default `false`; the devtools panel passes `true`. */\n write?: boolean;\n /**\n * Where the test results are read from (project-relative or absolute).\n * Default `grimoire/book/test-results.json`. The file's modified time is part\n * of the change stamp, so results written after the snapshot opened show up\n * without a restart.\n */\n testResultsFile?: string;\n /**\n * Read the route facts once when the first open finds none (`routes: \"missing\"`), so the development tab is\n * never \"missing\" without a manual `warlock grimoire build`. The adapter's booted inspect runs at most once per\n * process; a boot that fails keeps the cached answer. Default `false`. Never set it in a process that serves the app: the boot\n * pass boots every connector and re-imports the route and event modules, which registers them twice. The devtools panel\n * does not set it; use it from a separate tool process.\n */\n collectRoutes?: boolean;\n};\n\n/** A cached, shared snapshot of one project. */\nexport type SnapshotSource = {\n get(): Promise<GrimoireSnapshot>;\n /** Forget the cached snapshot; the next `get()` opens again. */\n invalidate(): void;\n /** Start opening the book now, so the first `get()` is fast. Failures are ignored here and surface on `get()`. */\n warm(): void;\n /** Resolves when no open is running (specs and shutdown). Never rejects. */\n idle(): Promise<void>;\n};\n\n/** Files and folders whose modified time moves when the book or an agent-written file is added, removed or regenerated. */\nconst STAMPED = [\n GRIMOIRE_PATHS.bookManifest,\n GRIMOIRE_PATHS.featuresIndex,\n GRIMOIRE_PATHS.tasksIndex,\n GRIMOIRE_PATHS.features,\n GRIMOIRE_PATHS.apps,\n GRIMOIRE_PATHS.openTasks,\n GRIMOIRE_PATHS.doneTasks,\n GRIMOIRE_PATHS.releases,\n];\n\nasync function changeStamp(root: string, resultsFile: string): Promise<string> {\n const files = [...STAMPED.map((entry) => path.join(root, ...entry.split(\"/\"))), resultsFile];\n const times = await Promise.all(\n files.map(async (file) => {\n try {\n return (await stat(file)).mtimeMs;\n } catch {\n return 0;\n }\n }),\n );\n\n return times.join(\",\");\n}\n\nasync function loadAdapter(option: SnapshotSourceOptions[\"adapter\"]): Promise<BookAdapter> {\n if (option === undefined) {\n const { createWarlockAdapter } = await import(\"../warlock\");\n\n return createWarlockAdapter();\n }\n\n return typeof option === \"function\" ? option() : option;\n}\n\n/** Create the source for the project at `root`. */\nexport function createSnapshotSource(\n root: string,\n options: SnapshotSourceOptions = {},\n): SnapshotSource {\n let cached: { snapshot: GrimoireSnapshot; at: number; stamp: string; took: number } | null = null;\n let opening: Promise<GrimoireSnapshot> | null = null;\n\n let collected = options.collectRoutes !== true || options.mode === \"production\";\n const resultsFile = resolveResultsFile(root, options.testResultsFile);\n\n const keepUntilChanged = options.mode === \"production\" && options.ttlMs === undefined;\n const reuseFor = (took: number): number => options.ttlMs ?? Math.max(2000, took * 5);\n\n async function open(): Promise<GrimoireSnapshot> {\n const started = Date.now();\n const adapter = await loadAdapter(options.adapter);\n const openOptions = {\n write: options.write ?? false,\n ...(options.testResultsFile === undefined\n ? {}\n : { testResultsFile: options.testResultsFile }),\n };\n let snapshot = await openGrimoire(root, adapter, { routes: \"cached\", ...openOptions });\n\n if (!collected && snapshot.routes === \"missing\") {\n // Once per source: the route, event and job facts come from one boot pass, then live in the book.\n collected = true;\n\n try {\n snapshot = await openGrimoire(root, adapter, { routes: \"fresh\", ...openOptions });\n } catch {\n // The app did not boot (GR8002): keep the cached answer; the tab says the facts are missing.\n }\n }\n\n const at = Date.now();\n\n cached = { snapshot, at, stamp: await changeStamp(root, resultsFile), took: at - started };\n\n return snapshot;\n }\n\n /** The open in flight, or a new one; concurrent callers share it. */\n function ensureOpening(): Promise<GrimoireSnapshot> {\n opening ??= open().finally(() => {\n opening = null;\n });\n\n return opening;\n }\n\n return {\n async get() {\n if (cached === null) return ensureOpening();\n\n const known = cached;\n const changed = (await changeStamp(root, resultsFile)) !== known.stamp;\n\n if (changed || options.mode === \"production\") {\n if (!changed && (keepUntilChanged || Date.now() - known.at < reuseFor(known.took))) {\n return known.snapshot;\n }\n\n // A failed open keeps the old snapshot; the next request tries again.\n return ensureOpening().catch(() => known.snapshot);\n }\n\n if (Date.now() - known.at < reuseFor(known.took)) return known.snapshot;\n\n // Development, nothing known to have changed: serve the old snapshot now and refresh behind it.\n ensureOpening().catch(() => {});\n\n return known.snapshot;\n },\n invalidate() {\n cached = null;\n },\n warm() {\n if (cached === null) ensureOpening().catch(() => {});\n },\n async idle() {\n await opening?.catch(() => {});\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,MAAM,UAAU;CACd,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;AACjB;AAEA,eAAe,YAAY,MAAc,aAAsC;CAC7E,MAAM,QAAQ,CAAC,GAAG,QAAQ,KAAK,UAAU,KAAK,KAAK,MAAM,GAAG,MAAM,MAAM,GAAG,CAAC,CAAC,GAAG,WAAW;CAW3F,QAAO,MAVa,QAAQ,IAC1B,MAAM,IAAI,OAAO,SAAS;EACxB,IAAI;GACF,QAAQ,MAAM,KAAK,IAAI,EAAC,CAAE;EAC5B,QAAQ;GACN,OAAO;EACT;CACF,CAAC,CACH,EAEY,CAAC,KAAK,GAAG;AACvB;AAEA,eAAe,YAAY,QAAgE;CACzF,IAAI,WAAW,QAAW;EACxB,MAAM,EAAE,yBAAyB,MAAM,OAAO;EAE9C,OAAO,qBAAqB;CAC9B;CAEA,OAAO,OAAO,WAAW,aAAa,OAAO,IAAI;AACnD;;AAGA,SAAg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K,SAAS,MAAM,IAAI,IAC9E,OAAO,MAAM;IAIf,OAAO,cAAc,CAAC,CAAC,YAAY,MAAM,QAAQ;GACnD;GAEA,IAAI,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,MAAM,IAAI,GAAG,OAAO,MAAM;GAG/D,cAAc,CAAC,CAAC,YAAY,CAAC,CAAC;GAE9B,OAAO,MAAM;EACf;EACA,aAAa;GACX,SAAS;EACX;EACA,OAAO;GACL,IAAI,WAAW,MAAM,cAAc,CAAC,CAAC,YAAY,CAAC,CAAC;EACrD;EACA,MAAM,OAAO;GACX,MAAM,SAAS,YAAY,CAAC,CAAC;EAC/B;CACF;AACF"}
|
package/esm/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BookAdapter, BookExport, BookFacts, BookFile, BookFileType, BookImport, BookMobileApp, BookNamedThing, BookNamedType, BookPage, BookPageLink, BookRoute, BookScreen, BookSite } from "./contracts/adapter.mjs";
|
|
1
|
+
import { BookAdapter, BookExport, BookFacts, BookFile, BookFileType, BookHost, BookImport, BookMobileApp, BookNamedThing, BookNamedType, BookPage, BookPageLink, BookRoute, BookScreen, BookSite } from "./contracts/adapter.mjs";
|
|
2
2
|
import { Located, SourceLocation } from "./contracts/location.mjs";
|
|
3
3
|
import { GrimoireCheckReport, GrimoireCodeArea, GrimoireCodeDefinition, GrimoireFinding, GrimoireFindingInput, GrimoireSeverity, RouteFreshness } from "./contracts/findings.mjs";
|
|
4
4
|
import { BOOK_SCHEMA_VERSION, BookAnnotations, BookEntry, BookFactsCache, BookManifest, BookManifestFile, BookMobileScreensFile, BookModuleSummary, BookRouteRef, BookRoutesFile, BookSitePagesFile, BuildBookOptions, BuildBookResult, LoadedBook, WriteBookResult } from "./contracts/book.mjs";
|
|
@@ -6,7 +6,7 @@ import { CASE_QUESTIONS, COLLECTED_END_MARKER, COLLECTED_START_MARKER, CaseQuest
|
|
|
6
6
|
import { CriterionStatus, ProofLine, ProofResult, TestOutcome, TestResultsInfo, TestResultsStore, UnmatchedProof } from "./contracts/test-results.mjs";
|
|
7
7
|
import { CollectedFiles, FeatureBookmap, FeaturesIndex, FileOwnership, FlowBookmap, FlowBookmapCriterion, FlowBookmapStep, Ownership, TaskSummary, TasksIndex } from "./contracts/bookmap.mjs";
|
|
8
8
|
import { AppMatch, GrimoireRule, GrimoireSnapshot, OpenGrimoireOptions } from "./contracts/snapshot.mjs";
|
|
9
|
-
import { ScryFeatureResult, ScryFileResult, ScryFlowResult, ScryHit, ScryHitType, ScryImpactResult, ScryNotes, ScryPageRef, ScryQuery, ScryResult, ScryRouteResult, ScrySearchResult } from "./contracts/scry.mjs";
|
|
9
|
+
import { ScryFeatureFlow, ScryFeatureResult, ScryFileResult, ScryFlowResult, ScryHit, ScryHitType, ScryImpactResult, ScryNotes, ScryPageRef, ScryQuery, ScryResult, ScryRouteResult, ScrySearchResult } from "./contracts/scry.mjs";
|
|
10
10
|
import { CollectedListText, ReleaseCollection, ReleaseEntry, WriteReleaseResult } from "./contracts/releases.mjs";
|
|
11
11
|
import { GRIMOIRE_CODES, GRIMOIRE_CODE_LIST, GrimoireCode } from "./codes/codes.mjs";
|
|
12
12
|
import { GRIMOIRE_CODES_DOCS_URL, GrimoireError, createFinding, explainGrimoireCode, grimoireCodeDocsUrl, isGrimoireCode } from "./codes/index.mjs";
|
|
@@ -30,4 +30,4 @@ import { readTestResults } from "./test-results/index.mjs";
|
|
|
30
30
|
import { formatScryResult } from "./scry/format.mjs";
|
|
31
31
|
import { parseScryQuery } from "./scry/parse.mjs";
|
|
32
32
|
import { scry } from "./scry/query.mjs";
|
|
33
|
-
export { AppMatch, BOOK_SCHEMA_VERSION, BookAdapter, BookAnnotations, BookEntry, BookExport, BookFacts, BookFactsCache, BookFile, BookFileType, BookImport, BookManifest, BookManifestFile, BookMobileApp, BookMobileScreensFile, BookModuleSummary, BookNamedThing, BookNamedType, BookPage, BookPageLink, type BookPathInput, BookRoute, BookRouteRef, BookRoutesFile, BookScreen, BookSite, BookSitePagesFile, BuildBookOptions, BuildBookResult, CASE_QUESTIONS, COLLECTED_END_MARKER, COLLECTED_START_MARKER, CaseQuestion, ChangeWord, CollectedFiles, type CollectedInput, CollectedListText, CriterionId, CriterionStatus, type CriterionTestResult, FeatureBookmap, FeatureVersion, FeaturesIndex, type FileGraph, FileOwnership, FlowBookmap, FlowBookmapCriterion, FlowBookmapStep, FlowRef, type FrontMatterField, type FrontMatterResult, type FrontMatterValue, GRIMOIRE_CODES, GRIMOIRE_CODES_DOCS_URL, GRIMOIRE_CODE_LIST, GRIMOIRE_DIR, GRIMOIRE_IGNORE_RULES, GRIMOIRE_PATHS, GrimoireCheckReport, type GrimoireCode, GrimoireCodeArea, GrimoireCodeDefinition, GrimoireError, GrimoireFinding, GrimoireFindingInput, GrimoireRule, GrimoireSeverity, GrimoireSnapshot, LoadedBook, Located, OpenGrimoireOptions, Ownership, type ParseGrimoireResult, ProofLine, ProofResult, ReleaseCollection, ReleaseEntry, RouteFreshness, type ScanProofsResult, ScryFeatureResult, ScryFileResult, ScryFlowResult, ScryHit, ScryHitType, ScryImpactResult, ScryNotes, ScryPageRef, ScryQuery, ScryResult, ScryRouteResult, ScrySearchResult, SourceLocation, StepType, TaskStatus, TaskSummary, TaskType, TasksIndex, TestOutcome, TestResultsInfo, TestResultsStore, UnmatchedProof, WriteBookResult, WriteReleaseResult, WrittenApp, WrittenBlockFile, WrittenBlockRow, WrittenCase, WrittenChangelog, WrittenChangelogEntry, WrittenChangelogSection, WrittenChangesWith, WrittenCriterion, WrittenEntryPoint, WrittenFeature, WrittenFeatureReadme, WrittenFlow, WrittenGrimoire, WrittenLayout, WrittenListLine, WrittenOrigin, WrittenPage, WrittenRelease, WrittenReleaseListed, WrittenScreenshot, WrittenStatus, WrittenStep, WrittenStoryStep, WrittenTask, WrittenVersionBrief, WrittenWho, bookEntryPath, bookEntryPaths, buildBook, buildCollectedFiles, checkGrimoire, collectRelease, createFinding, criterionStatus, explainGrimoireCode, fileGraph, formatCheckReport, formatScryResult, grimoireCodeDocsUrl, importClosure, importerClosure, isGrimoireCode, loadBook, matchApps, openGrimoire, parseGrimoire, parseScryQuery, readFrontMatter, readTestResults, renderCollectedList, resolveOwnership, scanProofs, scanProofsInText, scry, toPosixPath, writeBook, writeCollectedFiles, writeRelease };
|
|
33
|
+
export { AppMatch, BOOK_SCHEMA_VERSION, BookAdapter, BookAnnotations, BookEntry, BookExport, BookFacts, BookFactsCache, BookFile, BookFileType, BookHost, BookImport, BookManifest, BookManifestFile, BookMobileApp, BookMobileScreensFile, BookModuleSummary, BookNamedThing, BookNamedType, BookPage, BookPageLink, type BookPathInput, BookRoute, BookRouteRef, BookRoutesFile, BookScreen, BookSite, BookSitePagesFile, BuildBookOptions, BuildBookResult, CASE_QUESTIONS, COLLECTED_END_MARKER, COLLECTED_START_MARKER, CaseQuestion, ChangeWord, CollectedFiles, type CollectedInput, CollectedListText, CriterionId, CriterionStatus, type CriterionTestResult, FeatureBookmap, FeatureVersion, FeaturesIndex, type FileGraph, FileOwnership, FlowBookmap, FlowBookmapCriterion, FlowBookmapStep, FlowRef, type FrontMatterField, type FrontMatterResult, type FrontMatterValue, GRIMOIRE_CODES, GRIMOIRE_CODES_DOCS_URL, GRIMOIRE_CODE_LIST, GRIMOIRE_DIR, GRIMOIRE_IGNORE_RULES, GRIMOIRE_PATHS, GrimoireCheckReport, type GrimoireCode, GrimoireCodeArea, GrimoireCodeDefinition, GrimoireError, GrimoireFinding, GrimoireFindingInput, GrimoireRule, GrimoireSeverity, GrimoireSnapshot, LoadedBook, Located, OpenGrimoireOptions, Ownership, type ParseGrimoireResult, ProofLine, ProofResult, ReleaseCollection, ReleaseEntry, RouteFreshness, type ScanProofsResult, ScryFeatureFlow, ScryFeatureResult, ScryFileResult, ScryFlowResult, ScryHit, ScryHitType, ScryImpactResult, ScryNotes, ScryPageRef, ScryQuery, ScryResult, ScryRouteResult, ScrySearchResult, SourceLocation, StepType, TaskStatus, TaskSummary, TaskType, TasksIndex, TestOutcome, TestResultsInfo, TestResultsStore, UnmatchedProof, WriteBookResult, WriteReleaseResult, WrittenApp, WrittenBlockFile, WrittenBlockRow, WrittenCase, WrittenChangelog, WrittenChangelogEntry, WrittenChangelogSection, WrittenChangesWith, WrittenCriterion, WrittenEntryPoint, WrittenFeature, WrittenFeatureReadme, WrittenFlow, WrittenGrimoire, WrittenLayout, WrittenListLine, WrittenOrigin, WrittenPage, WrittenRelease, WrittenReleaseListed, WrittenScreenshot, WrittenStatus, WrittenStep, WrittenStoryStep, WrittenTask, WrittenVersionBrief, WrittenWho, bookEntryPath, bookEntryPaths, buildBook, buildCollectedFiles, checkGrimoire, collectRelease, createFinding, criterionStatus, explainGrimoireCode, fileGraph, formatCheckReport, formatScryResult, grimoireCodeDocsUrl, importClosure, importerClosure, isGrimoireCode, loadBook, matchApps, openGrimoire, parseGrimoire, parseScryQuery, readFrontMatter, readTestResults, renderCollectedList, resolveOwnership, scanProofs, scanProofsInText, scry, toPosixPath, writeBook, writeCollectedFiles, writeRelease };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/ownership/index.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/ownership/index.ts"],"mappings":";;;;;wBA+MgB,iBAAiB,SAAS,iBAAiB,OAAO,YAAY"}
|
package/esm/ownership/index.mjs
CHANGED
|
@@ -17,6 +17,65 @@ function taggedFeatures(file) {
|
|
|
17
17
|
function countsForFeature(file) {
|
|
18
18
|
return file.type !== "spec";
|
|
19
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* File roles no flow step can reach, yet which are real, used code: they run
|
|
22
|
+
* by being present (a migration, a seed, a command, the boot file, a layout or
|
|
23
|
+
* root component). The check does not ask a flow to reach them (`GR3006`).
|
|
24
|
+
*/
|
|
25
|
+
const UNREACHED_ROLES = /* @__PURE__ */ new Set([
|
|
26
|
+
"migration",
|
|
27
|
+
"seed",
|
|
28
|
+
"command",
|
|
29
|
+
"main",
|
|
30
|
+
"layout",
|
|
31
|
+
"root"
|
|
32
|
+
]);
|
|
33
|
+
/** Whether a file's role exempts it from needing a flow to reach it. */
|
|
34
|
+
function isExemptFromReach(file) {
|
|
35
|
+
return UNREACHED_ROLES.has(file.type);
|
|
36
|
+
}
|
|
37
|
+
const HELPER_FOLDERS = /* @__PURE__ */ new Set([
|
|
38
|
+
"tests",
|
|
39
|
+
"__tests__",
|
|
40
|
+
"fixtures",
|
|
41
|
+
"support",
|
|
42
|
+
"test-utils"
|
|
43
|
+
]);
|
|
44
|
+
/** Whether a path is where test helpers live: a tests/fixtures/support folder or a `*.test-utils.*` file. */
|
|
45
|
+
function isTestHelperPath(file) {
|
|
46
|
+
const parts = file.split("/");
|
|
47
|
+
const name = parts[parts.length - 1] ?? "";
|
|
48
|
+
return parts.slice(0, -1).some((part) => HELPER_FOLDERS.has(part)) || /^(?:test-utils|.+\.test-utils)\.[a-z]+$/.test(name);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Files only specs import, directly or through other such files, and that sit in a helper location
|
|
52
|
+
* (`tests/`, `__tests__/`, `fixtures/`, `support/`, `test-utils`): test helpers.
|
|
53
|
+
* Specs are not own files, so a helper they alone use counts as reached. A source file only its
|
|
54
|
+
* spec imports is not a helper: it is dead code and stays reported.
|
|
55
|
+
*/
|
|
56
|
+
function specOnlyFiles(files) {
|
|
57
|
+
const importers = /* @__PURE__ */ new Map();
|
|
58
|
+
for (const file of files) for (const entry of file.imports) {
|
|
59
|
+
if (entry.file === null || entry.file === file.file) continue;
|
|
60
|
+
const list = importers.get(entry.file) ?? /* @__PURE__ */ new Set();
|
|
61
|
+
list.add(file.file);
|
|
62
|
+
importers.set(entry.file, list);
|
|
63
|
+
}
|
|
64
|
+
const specs = new Set(files.filter((file) => file.type === "spec").map((file) => file.file));
|
|
65
|
+
const result = /* @__PURE__ */ new Set();
|
|
66
|
+
let changed = true;
|
|
67
|
+
while (changed) {
|
|
68
|
+
changed = false;
|
|
69
|
+
for (const [file, list] of importers) {
|
|
70
|
+
if (specs.has(file) || result.has(file) || !isTestHelperPath(file)) continue;
|
|
71
|
+
if ([...list].every((importer) => specs.has(importer) || result.has(importer))) {
|
|
72
|
+
result.add(file);
|
|
73
|
+
changed = true;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
20
79
|
function decide(file, features, folders) {
|
|
21
80
|
const result = {
|
|
22
81
|
file: file.file,
|
|
@@ -133,5 +192,5 @@ function resolveOwnership(written, facts) {
|
|
|
133
192
|
}
|
|
134
193
|
|
|
135
194
|
//#endregion
|
|
136
|
-
export { countsForFeature, resolveOwnership };
|
|
195
|
+
export { UNREACHED_ROLES, countsForFeature, isExemptFromReach, isTestHelperPath, resolveOwnership, specOnlyFiles };
|
|
137
196
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/ownership/index.ts"],"sourcesContent":["/**\n * Who owns each source file (owned by T-128). Rules in `FileOwnership`.\n *\n * - A `@feature <id>` header tag that names a feature wins. A tag that names\n * no feature is left out here (the check reports it as `GR3004`), so the\n * folder rule decides.\n * - Otherwise a `folders` entry that names the file itself (an entry with a\n * code-file extension) owns it: a file entry is more specific than any\n * folder entry, so it wins over the folder of another feature.\n * - Otherwise the feature whose `folders` entry is the deepest folder holding\n * the file owns it.\n * - Two features claiming the file the same way (two different tags, the\n * same file listed by two features, or the same deepest folder listed by\n * two features) is a conflict: the file gets no owner and `conflicts`\n * lists the claims (`GR3003`).\n * - A feature borrows a file it does not own when one of its own files\n * imports it directly. Spec files are never own or borrowed files and do\n * not make a feature borrow anything.\n */\nimport type { BookFacts, BookFile } from \"../contracts/adapter\";\nimport type { FileOwnership, Ownership } from \"../contracts/bookmap\";\nimport type { WrittenGrimoire } from \"../contracts/written\";\nimport { isCodeFile, isInsideFolder, toPosixPath } from \"../paths\";\n\ntype Claim = { feature: string; via: \"tag\" | \"folder\"; folder: string | null };\n\n/** Whether a `folders` entry names one code file instead of a folder. */\nfunction isFileEntry(entry: string): boolean {\n return isCodeFile(entry);\n}\n\nfunction normalizeFolder(folder: string): string {\n return toPosixPath(folder.trim()).replace(/^\\.\\//, \"\").replace(/\\/+$/, \"\");\n}\n\n/** Feature ids named by a file's `@feature` tags, trimmed, unique, in tag order. */\nfunction taggedFeatures(file: BookFile): string[] {\n const values = (file.tags.feature ?? [])\n .map((value) => value.trim().split(/\\s+/)[0] ?? \"\")\n .filter((value) => value.length > 0);\n\n return [...new Set(values)];\n}\n\n/** Whether a file counts as an own, borrowed or unreached file of a feature. */\nexport function countsForFeature(file: Pick<BookFile, \"type\">): boolean {\n return file.type !== \"spec\";\n}\n\nfunction decide(\n file: BookFile,\n features: Set<string>,\n folders: Map<string, string[]>,\n): FileOwnership {\n const result: FileOwnership = {\n file: file.file,\n owner: null,\n via: null,\n folder: null,\n conflicts: [],\n borrowedBy: [],\n };\n const tags = taggedFeatures(file).filter((feature) => features.has(feature));\n\n if (tags.length === 1) {\n result.owner = tags[0] ?? null;\n result.via = \"tag\";\n\n return result;\n }\n\n if (tags.length > 1) {\n result.conflicts = tags.sort().map((feature) => ({ feature, via: \"tag\" }));\n\n return result;\n }\n\n const fileOwners = [...folders]\n .filter(([, list]) => list.includes(file.file))\n .map(([feature]) => feature)\n .sort();\n\n if (fileOwners.length === 1) {\n result.owner = fileOwners[0] ?? null;\n result.via = \"file\";\n\n return result;\n }\n\n if (fileOwners.length > 1) {\n result.conflicts = fileOwners.map((feature) => ({ feature, via: \"file\" }));\n\n return result;\n }\n\n let deepest: Claim[] = [];\n let depth = -1;\n\n for (const [feature, list] of folders) {\n for (const folder of list) {\n if (isFileEntry(folder)) continue;\n\n if (!isInsideFolder(file.file, folder)) continue;\n\n const folderDepth = folder.split(\"/\").length;\n\n if (folderDepth > depth) {\n depth = folderDepth;\n deepest = [{ feature, via: \"folder\", folder }];\n } else if (folderDepth === depth && !deepest.some((claim) => claim.feature === feature)) {\n deepest.push({ feature, via: \"folder\", folder });\n }\n }\n }\n\n if (deepest.length === 1) {\n const claim = deepest[0];\n\n if (claim) {\n result.owner = claim.feature;\n result.via = \"folder\";\n result.folder = claim.folder;\n }\n } else if (deepest.length > 1) {\n result.conflicts = deepest\n .map((claim) => ({ feature: claim.feature, via: claim.via }))\n .sort((left, right) => left.feature.localeCompare(right.feature));\n }\n\n return result;\n}\n\n/** Owner, conflicts and borrowers of every code file in `facts`. Pure. */\nexport function resolveOwnership(written: WrittenGrimoire, facts: BookFacts): Ownership {\n const featureIds = new Set(written.features.map((feature) => feature.id));\n const folders = new Map<string, string[]>();\n\n for (const feature of written.features) {\n const list = (feature.readme?.folders ?? [])\n .map((folder) => normalizeFolder(folder.value))\n .filter((folder) => folder.length > 0);\n\n folders.set(feature.id, [...new Set(list)]);\n }\n\n const files: Record<string, FileOwnership> = {};\n\n for (const file of facts.files) {\n files[file.file] = decide(file, featureIds, folders);\n }\n\n const features: Ownership[\"features\"] = {};\n\n for (const id of [...featureIds].sort()) {\n features[id] = { own: [], borrowed: [] };\n }\n\n const byPath = new Map(facts.files.map((file) => [file.file, file]));\n const borrowers = new Map<string, Set<string>>();\n\n for (const file of facts.files) {\n const owner = files[file.file]?.owner ?? null;\n\n if (owner === null || !countsForFeature(file)) continue;\n\n features[owner]?.own.push(file.file);\n\n for (const entry of file.imports) {\n if (entry.file === null || entry.file === file.file) continue;\n\n const imported = files[entry.file];\n\n if (!imported || imported.owner === owner) continue;\n\n const importedFile = byPath.get(entry.file);\n\n if (importedFile && !countsForFeature(importedFile)) continue;\n\n const set = borrowers.get(entry.file) ?? new Set<string>();\n set.add(owner);\n borrowers.set(entry.file, set);\n }\n }\n\n for (const [file, set] of borrowers) {\n const ownership = files[file];\n const sorted = [...set].sort();\n\n if (ownership) ownership.borrowedBy = sorted;\n\n for (const feature of sorted) features[feature]?.borrowed.push(file);\n }\n\n for (const entry of Object.values(features)) {\n entry.own.sort();\n entry.borrowed.sort();\n }\n\n return { files, features };\n}\n"],"mappings":";;;;AA2BA,SAAS,YAAY,OAAwB;CAC3C,OAAO,WAAW,KAAK;AACzB;AAEA,SAAS,gBAAgB,QAAwB;CAC/C,OAAO,YAAY,OAAO,KAAK,CAAC,CAAC,CAAC,QAAQ,SAAS,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;AAC3E;;AAGA,SAAS,eAAe,MAA0B;CAChD,MAAM,UAAU,KAAK,KAAK,WAAW,CAAC,EAAC,CACpC,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,EAAE,CAAC,CAClD,QAAQ,UAAU,MAAM,SAAS,CAAC;CAErC,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;;AAGA,SAAgB,iBAAiB,MAAuC;CACtE,OAAO,KAAK,SAAS;AACvB;AAEA,SAAS,OACP,MACA,UACA,SACe;CACf,MAAM,SAAwB;EAC5B,MAAM,KAAK;EACX,OAAO;EACP,KAAK;EACL,QAAQ;EACR,WAAW,CAAC;EACZ,YAAY,CAAC;CACf;CACA,MAAM,OAAO,eAAe,IAAI,CAAC,CAAC,QAAQ,YAAY,SAAS,IAAI,OAAO,CAAC;CAE3E,IAAI,KAAK,WAAW,GAAG;EACrB,OAAO,QAAQ,KAAK,MAAM;EAC1B,OAAO,MAAM;EAEb,OAAO;CACT;CAEA,IAAI,KAAK,SAAS,GAAG;EACnB,OAAO,YAAY,KAAK,KAAK,CAAC,CAAC,KAAK,aAAa;GAAE;GAAS,KAAK;EAAM,EAAE;EAEzE,OAAO;CACT;CAEA,MAAM,aAAa,CAAC,GAAG,OAAO,CAAC,CAC5B,QAAQ,GAAG,UAAU,KAAK,SAAS,KAAK,IAAI,CAAC,CAAC,CAC9C,KAAK,CAAC,aAAa,OAAO,CAAC,CAC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YAAY,MAAM;EACxB,MAAM,SAAS,CAAC,GAAG,GAAG,CAAC,CAAC,KAAK;EAE7B,IAAI,WAAW,UAAU,aAAa;EAEtC,KAAK,MAAM,WAAW,QAAQ,SAAS,QAAQ,EAAE,SAAS,KAAK,IAAI;CACrE;CAEA,KAAK,MAAM,SAAS,OAAO,OAAO,QAAQ,GAAG;EAC3C,MAAM,IAAI,KAAK;EACf,MAAM,SAAS,KAAK;CACtB;CAEA,OAAO;EAAE;EAAO;CAAS;AAC3B"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/ownership/index.ts"],"sourcesContent":["/**\n * Who owns each source file (owned by T-128). Rules in `FileOwnership`.\n *\n * - A `@feature <id>` header tag that names a feature wins. A tag that names\n * no feature is left out here (the check reports it as `GR3004`), so the\n * folder rule decides.\n * - Otherwise a `folders` entry that names the file itself (an entry with a\n * code-file extension) owns it: a file entry is more specific than any\n * folder entry, so it wins over the folder of another feature.\n * - Otherwise the feature whose `folders` entry is the deepest folder holding\n * the file owns it.\n * - Two features claiming the file the same way (two different tags, the\n * same file listed by two features, or the same deepest folder listed by\n * two features) is a conflict: the file gets no owner and `conflicts`\n * lists the claims (`GR3003`).\n * - A feature borrows a file it does not own when one of its own files\n * imports it directly. Spec files are never own or borrowed files and do\n * not make a feature borrow anything.\n */\nimport type { BookFacts, BookFile } from \"../contracts/adapter\";\nimport type { FileOwnership, Ownership } from \"../contracts/bookmap\";\nimport type { WrittenGrimoire } from \"../contracts/written\";\nimport { isCodeFile, isInsideFolder, toPosixPath } from \"../paths\";\n\ntype Claim = { feature: string; via: \"tag\" | \"folder\"; folder: string | null };\n\n/** Whether a `folders` entry names one code file instead of a folder. */\nfunction isFileEntry(entry: string): boolean {\n return isCodeFile(entry);\n}\n\nfunction normalizeFolder(folder: string): string {\n return toPosixPath(folder.trim()).replace(/^\\.\\//, \"\").replace(/\\/+$/, \"\");\n}\n\n/** Feature ids named by a file's `@feature` tags, trimmed, unique, in tag order. */\nfunction taggedFeatures(file: BookFile): string[] {\n const values = (file.tags.feature ?? [])\n .map((value) => value.trim().split(/\\s+/)[0] ?? \"\")\n .filter((value) => value.length > 0);\n\n return [...new Set(values)];\n}\n\n/** Whether a file counts as an own, borrowed or unreached file of a feature. */\nexport function countsForFeature(file: Pick<BookFile, \"type\">): boolean {\n return file.type !== \"spec\";\n}\n\n/**\n * File roles no flow step can reach, yet which are real, used code: they run\n * by being present (a migration, a seed, a command, the boot file, a layout or\n * root component). The check does not ask a flow to reach them (`GR3006`).\n */\nexport const UNREACHED_ROLES: ReadonlySet<string> = new Set([\n \"migration\",\n \"seed\",\n \"command\",\n \"main\",\n \"layout\",\n \"root\",\n]);\n\n/** Whether a file's role exempts it from needing a flow to reach it. */\nexport function isExemptFromReach(file: Pick<BookFile, \"type\">): boolean {\n return UNREACHED_ROLES.has(file.type);\n}\n\nconst HELPER_FOLDERS = new Set([\"tests\", \"__tests__\", \"fixtures\", \"support\", \"test-utils\"]);\n\n/** Whether a path is where test helpers live: a tests/fixtures/support folder or a `*.test-utils.*` file. */\nexport function isTestHelperPath(file: string): boolean {\n const parts = file.split(\"/\");\n const name = parts[parts.length - 1] ?? \"\";\n\n return (\n parts.slice(0, -1).some((part) => HELPER_FOLDERS.has(part)) ||\n /^(?:test-utils|.+\\.test-utils)\\.[a-z]+$/.test(name)\n );\n}\n\n/**\n * Files only specs import, directly or through other such files, and that sit in a helper location\n * (`tests/`, `__tests__/`, `fixtures/`, `support/`, `test-utils`): test helpers.\n * Specs are not own files, so a helper they alone use counts as reached. A source file only its\n * spec imports is not a helper: it is dead code and stays reported.\n */\nexport function specOnlyFiles(\n files: readonly Pick<BookFile, \"file\" | \"type\" | \"imports\">[],\n): Set<string> {\n const importers = new Map<string, Set<string>>();\n\n for (const file of files) {\n for (const entry of file.imports) {\n if (entry.file === null || entry.file === file.file) continue;\n\n const list = importers.get(entry.file) ?? new Set<string>();\n\n list.add(file.file);\n importers.set(entry.file, list);\n }\n }\n\n const specs = new Set(files.filter((file) => file.type === \"spec\").map((file) => file.file));\n const result = new Set<string>();\n let changed = true;\n\n while (changed) {\n changed = false;\n\n for (const [file, list] of importers) {\n if (specs.has(file) || result.has(file) || !isTestHelperPath(file)) continue;\n\n if ([...list].every((importer) => specs.has(importer) || result.has(importer))) {\n result.add(file);\n changed = true;\n }\n }\n }\n\n return result;\n}\n\nfunction decide(\n file: BookFile,\n features: Set<string>,\n folders: Map<string, string[]>,\n): FileOwnership {\n const result: FileOwnership = {\n file: file.file,\n owner: null,\n via: null,\n folder: null,\n conflicts: [],\n borrowedBy: [],\n };\n const tags = taggedFeatures(file).filter((feature) => features.has(feature));\n\n if (tags.length === 1) {\n result.owner = tags[0] ?? null;\n result.via = \"tag\";\n\n return result;\n }\n\n if (tags.length > 1) {\n result.conflicts = tags.sort().map((feature) => ({ feature, via: \"tag\" }));\n\n return result;\n }\n\n const fileOwners = [...folders]\n .filter(([, list]) => list.includes(file.file))\n .map(([feature]) => feature)\n .sort();\n\n if (fileOwners.length === 1) {\n result.owner = fileOwners[0] ?? null;\n result.via = \"file\";\n\n return result;\n }\n\n if (fileOwners.length > 1) {\n result.conflicts = fileOwners.map((feature) => ({ feature, via: \"file\" }));\n\n return result;\n }\n\n let deepest: Claim[] = [];\n let depth = -1;\n\n for (const [feature, list] of folders) {\n for (const folder of list) {\n if (isFileEntry(folder)) continue;\n\n if (!isInsideFolder(file.file, folder)) continue;\n\n const folderDepth = folder.split(\"/\").length;\n\n if (folderDepth > depth) {\n depth = folderDepth;\n deepest = [{ feature, via: \"folder\", folder }];\n } else if (folderDepth === depth && !deepest.some((claim) => claim.feature === feature)) {\n deepest.push({ feature, via: \"folder\", folder });\n }\n }\n }\n\n if (deepest.length === 1) {\n const claim = deepest[0];\n\n if (claim) {\n result.owner = claim.feature;\n result.via = \"folder\";\n result.folder = claim.folder;\n }\n } else if (deepest.length > 1) {\n result.conflicts = deepest\n .map((claim) => ({ feature: claim.feature, via: claim.via }))\n .sort((left, right) => left.feature.localeCompare(right.feature));\n }\n\n return result;\n}\n\n/** Owner, conflicts and borrowers of every code file in `facts`. Pure. */\nexport function resolveOwnership(written: WrittenGrimoire, facts: BookFacts): Ownership {\n const featureIds = new Set(written.features.map((feature) => feature.id));\n const folders = new Map<string, string[]>();\n\n for (const feature of written.features) {\n const list = (feature.readme?.folders ?? [])\n .map((folder) => normalizeFolder(folder.value))\n .filter((folder) => folder.length > 0);\n\n folders.set(feature.id, [...new Set(list)]);\n }\n\n const files: Record<string, FileOwnership> = {};\n\n for (const file of facts.files) {\n files[file.file] = decide(file, featureIds, folders);\n }\n\n const features: Ownership[\"features\"] = {};\n\n for (const id of [...featureIds].sort()) {\n features[id] = { own: [], borrowed: [] };\n }\n\n const byPath = new Map(facts.files.map((file) => [file.file, file]));\n const borrowers = new Map<string, Set<string>>();\n\n for (const file of facts.files) {\n const owner = files[file.file]?.owner ?? null;\n\n if (owner === null || !countsForFeature(file)) continue;\n\n features[owner]?.own.push(file.file);\n\n for (const entry of file.imports) {\n if (entry.file === null || entry.file === file.file) continue;\n\n const imported = files[entry.file];\n\n if (!imported || imported.owner === owner) continue;\n\n const importedFile = byPath.get(entry.file);\n\n if (importedFile && !countsForFeature(importedFile)) continue;\n\n const set = borrowers.get(entry.file) ?? new Set<string>();\n set.add(owner);\n borrowers.set(entry.file, set);\n }\n }\n\n for (const [file, set] of borrowers) {\n const ownership = files[file];\n const sorted = [...set].sort();\n\n if (ownership) ownership.borrowedBy = sorted;\n\n for (const feature of sorted) features[feature]?.borrowed.push(file);\n }\n\n for (const entry of Object.values(features)) {\n entry.own.sort();\n entry.borrowed.sort();\n }\n\n return { files, features };\n}\n"],"mappings":";;;;AA2BA,SAAS,YAAY,OAAwB;CAC3C,OAAO,WAAW,KAAK;AACzB;AAEA,SAAS,gBAAgB,QAAwB;CAC/C,OAAO,YAAY,OAAO,KAAK,CAAC,CAAC,CAAC,QAAQ,SAAS,EAAE,CAAC,CAAC,QAAQ,QAAQ,E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;CACtB;CAEA,OAAO;EAAE;EAAO;CAAS;AAC3B"}
|
package/esm/scry/compact.mjs
CHANGED
|
@@ -73,7 +73,8 @@ function flowHealth(result) {
|
|
|
73
73
|
},
|
|
74
74
|
steps: {
|
|
75
75
|
total: checked.length,
|
|
76
|
-
resolved: checked.filter((step) => step.found === true).length
|
|
76
|
+
resolved: checked.filter((step) => step.found === true).length,
|
|
77
|
+
unchecked: result.bookmap.steps.length - checked.length
|
|
77
78
|
},
|
|
78
79
|
findings: {
|
|
79
80
|
errors,
|
package/esm/scry/compact.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compact.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/compact.ts"],"sourcesContent":["/**\n * The compact flow answer: a flow's steps as counts and the first direct\n * imports instead of every reachable file, plus what a flow page header needs\n * (feature, neighbours, health, test results). The devtools route\n * `GET /flows/:feature/:flow` and the MCP tool `grimoire_flow` both send it;\n * `scry()` itself keeps the full answer.\n */\nimport type { FlowBookmap, FlowBookmapStep } from \"../contracts/bookmap\";\nimport type { ScryFlowResult } from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { CriterionStatus } from \"../contracts/test-results\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport {\n FLOW_STEP_DIRECT_LIMIT,\n STEP_FILES_PAGE_LIMIT,\n type GrimoireFlowAnswer,\n type GrimoireFlowHealth,\n type GrimoireFlowNeighbour,\n type GrimoireFlowStep,\n type GrimoireStepFilesAnswer,\n type StepFileCounts,\n type StepFileSet,\n} from \"../devtools/answers\";\nimport { testResultsInfo } from \"../test-results\";\n\n/** The file sets a step can list, in the order a view shows them. */\nexport const STEP_FILE_SETS: readonly StepFileSet[] = [\"direct\", \"feature\", \"reachable\", \"type-only\"];\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\n\n/** The files of a step the flow's feature owns. */\nfunction featureFiles(snapshot: GrimoireSnapshot, feature: string, step: FlowBookmapStep): string[] {\n return step.files.filter((file) => snapshot.ownership.files[file]?.owner === feature);\n}\n\n/** How many files a step reaches, by set. */\nexport function stepCounts(\n snapshot: GrimoireSnapshot,\n feature: string,\n step: FlowBookmapStep,\n): StepFileCounts {\n return {\n direct: step.direct.length,\n feature: featureFiles(snapshot, feature, step).length,\n reachable: step.files.length,\n typeOnly: step.typeOnlyFiles.length,\n };\n}\n\n/** The flows of a feature in the README's Flows order, else in file order. */\nexport function flowOrder(feature: WrittenFeature): WrittenFlow[] {\n const byId = new Map(feature.flows.map((flow) => [flow.id.value, flow]));\n const listed = (feature.readme?.flows ?? []).flatMap((line) => {\n const flow = byId.get(line.name);\n\n return flow === undefined ? [] : [flow];\n });\n\n if (listed.length === 0) return feature.flows;\n\n // A flow the README does not list follows the listed ones, in file order.\n const seen = new Set(listed);\n\n return [...listed, ...feature.flows.filter((flow) => !seen.has(flow))];\n}\n\nfunction neighbour(flow: WrittenFlow | undefined): GrimoireFlowNeighbour | null {\n return flow === undefined ? null : { id: flow.id.value, heading: flow.heading?.value ?? null };\n}\n\n/** The flow before and after `flowId` in its feature. */\nexport function neighboursOf(\n feature: WrittenFeature,\n flowId: string,\n): { previous: GrimoireFlowNeighbour | null; next: GrimoireFlowNeighbour | null } {\n const order = flowOrder(feature);\n const position = order.findIndex((flow) => flow.id.value === flowId);\n\n if (position < 0) return { previous: null, next: null };\n\n return { previous: neighbour(order[position - 1]), next: neighbour(order[position + 1]) };\n}\n\n/** The health strip numbers of a flow (criteria, steps, findings). */\nexport function flowHealth(result: ScryFlowResult): GrimoireFlowHealth {\n const byStatus: Record<CriterionStatus, number> = {\n pass: 0,\n fail: 0,\n stale: 0,\n \"not-run\": 0,\n \"no-test\": 0,\n };\n\n for (const criterion of result.bookmap.criteria) byStatus[criterion.status] += 1;\n\n const checked = result.bookmap.steps.filter((step) => step.found !== null);\n const unexpected = result.findings.filter((finding) => !finding.expected);\n const errors = unexpected.filter((finding) => finding.severity === \"error\").length;\n\n return {\n criteria: { total: result.bookmap.criteria.length, proven: byStatus.pass, byStatus },\n steps: { total: checked.length, resolved: checked.filter((step) => step.found === true).length },\n findings: {\n errors,\n warnings: unexpected.length - errors,\n expected: result.findings.length - unexpected.length,\n },\n };\n}\n\n/** One step with counts and the first direct imports; the file lists are left out. */\nexport function compactStep(\n snapshot: GrimoireSnapshot,\n feature: WrittenFeature,\n step: FlowBookmapStep,\n written: WrittenFlow | undefined,\n): GrimoireFlowStep {\n const { files: _files, typeOnlyFiles: _typeOnly, direct, ...rest } = step;\n const target = written?.steps.find((item) => item.index === step.index)?.affects ?? null;\n let linked: GrimoireFlowStep[\"linked\"] = null;\n\n if (target !== null && target.flow !== null) {\n const owner =\n target.feature === feature.id\n ? feature\n : snapshot.written.features.find((item) => item.id === target.feature);\n const other = owner?.flows.find((item) => item.id.value === target.flow);\n\n if (other !== undefined) {\n linked = { ref: other.ref, heading: other.heading?.value ?? null, summary: other.summary };\n }\n }\n\n return {\n ...rest,\n counts: stepCounts(snapshot, feature.id, step),\n direct: direct.slice(0, FLOW_STEP_DIRECT_LIMIT),\n linked,\n };\n}\n\n/** The scry flow answer made compact, with the flow page header data. */\nexport function compactFlow(snapshot: GrimoireSnapshot, result: ScryFlowResult): GrimoireFlowAnswer {\n const feature = snapshot.written.features.find((item) => item.id === result.flow.feature);\n\n if (feature === undefined) {\n throw new Error(`Feature ${result.flow.feature} is not written.`);\n }\n\n const readme = feature.readme;\n const { previous, next } = neighboursOf(feature, result.flow.id.value);\n\n return {\n ...result,\n bookmap: {\n ...result.bookmap,\n steps: result.bookmap.steps.map((step) => compactStep(snapshot, feature, step, result.flow)),\n },\n feature: {\n id: feature.id,\n title: readme?.title.value ?? feature.id,\n status: readme?.status.value ?? result.flow.status.value,\n apps: (readme?.apps ?? []).map((app) => app.value),\n },\n previous,\n next,\n health: flowHealth(result),\n results: testResultsInfo(snapshot),\n };\n}\n\n/** The files of one set of a step, sorted by module and then path. */\nexport function stepFileSet(\n snapshot: GrimoireSnapshot,\n feature: string,\n step: FlowBookmapStep,\n set: StepFileSet,\n): string[] {\n const files =\n set === \"direct\"\n ? step.direct\n : set === \"feature\"\n ? featureFiles(snapshot, feature, step)\n : set === \"reachable\"\n ? step.files\n : step.typeOnlyFiles;\n const modules = new Map(snapshot.book.facts.files.map((item) => [item.file, item.module]));\n const moduleOf = (file: string): string => modules.get(file) ?? \"\";\n\n return [...files].sort((left, right) => byText(moduleOf(left), moduleOf(right)) || byText(left, right));\n}\n\n/**\n * One page of a step's files with the module counts of the whole set.\n * `limit` is capped at {@link STEP_FILES_PAGE_LIMIT}.\n */\nexport function stepFilePage(\n snapshot: GrimoireSnapshot,\n bookmap: FlowBookmap,\n step: FlowBookmapStep,\n set: StepFileSet,\n offset: number,\n limit: number,\n): GrimoireStepFilesAnswer {\n const sorted = stepFileSet(snapshot, bookmap.feature, step, set);\n const modules = new Map(snapshot.book.facts.files.map((item) => [item.file, item.module]));\n const moduleOf = (file: string): string => modules.get(file) ?? \"\";\n const size = Math.min(Math.max(1, Math.floor(limit)), STEP_FILES_PAGE_LIMIT);\n const start = Math.max(0, Math.floor(offset));\n const counts = new Map<string, number>();\n\n for (const file of sorted) counts.set(moduleOf(file), (counts.get(moduleOf(file)) ?? 0) + 1);\n\n return {\n ref: bookmap.ref,\n index: step.index,\n set,\n total: sorted.length,\n offset: start,\n limit: size,\n files: sorted.slice(start, start + size).map((file) => ({\n file,\n module: moduleOf(file),\n owner: snapshot.ownership.files[file]?.owner ?? null,\n })),\n modules: [...counts]\n .map(([module, count]) => ({ module, count }))\n .sort((left, right) => right.count - left.count || byText(left.module, right.module)),\n };\n}\n"],"mappings":";;;;AA0BA,MAAa,iBAAyC;CAAC;CAAU;CAAW;CAAa;AAAW;AAEpG,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;;AAGhG,SAAS,aAAa,UAA4B,SAAiB,MAAiC;CAClG,OAAO,KAAK,MAA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U,IAAI,IAAI,SAAS,KAAK,MAAM,MAAM,KAAK,SAAS,CAAC,KAAK,MAAM,KAAK,MAAM,CAAC,CAAC;CACzF,MAAM,YAAY,SAAyB,QAAQ,IAAI,IAAI,KAAK;CAChE,MAAM,OAAO,KAAK,IAAI,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC,MAAwB;CAC3E,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,MAAM,CAAC;CAC5C,MAAM,yBAAS,IAAI,IAAoB;CAEvC,KAAK,MAAM,QAAQ,QAAQ,OAAO,IAAI,SAAS,IAAI,IAAI,OAAO,IAAI,SAAS,IAAI,CAAC,KAAK,KAAK,CAAC;CAE3F,OAAO;EACL,KAAK,QAAQ;EACb,OAAO,KAAK;EACZ;EACA,OAAO,OAAO;EACd,QAAQ;EACR,OAAO;EACP,OAAO,OAAO,MAAM,OAAO,QAAQ,IAAI,CAAC,CAAC,KAAK,UAAU;GACtD;GACA,QAAQ,SAAS,IAAI;GACrB,OAAO,SAAS,UAAU,MAAM,KAAK,EAAE,SAAS;EAClD,EAAE;EACF,SAAS,CAAC,GAAG,MAAM,CAAC,CACjB,KAAK,CAAC,QAAQ,YAAY;GAAE;GAAQ;EAAM,EAAE,CAAC,CAC7C,MAAM,MAAM,UAAU,MAAM,QAAQ,KAAK,SAAS,OAAO,KAAK,QAAQ,MAAM,MAAM,CAAC;CACxF;AACF"}
|
|
1
|
+
{"version":3,"file":"compact.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/compact.ts"],"sourcesContent":["/**\n * The compact flow answer: a flow's steps as counts and the first direct\n * imports instead of every reachable file, plus what a flow page header needs\n * (feature, neighbours, health, test results). The devtools route\n * `GET /flows/:feature/:flow` and the MCP tool `grimoire_flow` both send it;\n * `scry()` itself keeps the full answer.\n */\nimport type { FlowBookmap, FlowBookmapStep } from \"../contracts/bookmap\";\nimport type { ScryFlowResult } from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { CriterionStatus } from \"../contracts/test-results\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport {\n FLOW_STEP_DIRECT_LIMIT,\n STEP_FILES_PAGE_LIMIT,\n type GrimoireFlowAnswer,\n type GrimoireFlowHealth,\n type GrimoireFlowNeighbour,\n type GrimoireFlowStep,\n type GrimoireStepFilesAnswer,\n type StepFileCounts,\n type StepFileSet,\n} from \"../devtools/answers\";\nimport { testResultsInfo } from \"../test-results\";\n\n/** The file sets a step can list, in the order a view shows them. */\nexport const STEP_FILE_SETS: readonly StepFileSet[] = [\n \"direct\",\n \"feature\",\n \"reachable\",\n \"type-only\",\n];\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\n\n/** The files of a step the flow's feature owns. */\nfunction featureFiles(\n snapshot: GrimoireSnapshot,\n feature: string,\n step: FlowBookmapStep,\n): string[] {\n return step.files.filter((file) => snapshot.ownership.files[file]?.owner === feature);\n}\n\n/** How many files a step reaches, by set. */\nexport function stepCounts(\n snapshot: GrimoireSnapshot,\n feature: string,\n step: FlowBookmapStep,\n): StepFileCounts {\n return {\n direct: step.direct.length,\n feature: featureFiles(snapshot, feature, step).length,\n reachable: step.files.length,\n typeOnly: step.typeOnlyFiles.length,\n };\n}\n\n/** The flows of a feature in the README's Flows order, else in file order. */\nexport function flowOrder(feature: WrittenFeature): WrittenFlow[] {\n const byId = new Map(feature.flows.map((flow) => [flow.id.value, flow]));\n const listed = (feature.readme?.flows ?? []).flatMap((line) => {\n const flow = byId.get(line.name);\n\n return flow === undefined ? [] : [flow];\n });\n\n if (listed.length === 0) return feature.flows;\n\n // A flow the README does not list follows the listed ones, in file order.\n const seen = new Set(listed);\n\n return [...listed, ...feature.flows.filter((flow) => !seen.has(flow))];\n}\n\nfunction neighbour(flow: WrittenFlow | undefined): GrimoireFlowNeighbour | null {\n return flow === undefined ? null : { id: flow.id.value, heading: flow.heading?.value ?? null };\n}\n\n/** The flow before and after `flowId` in its feature. */\nexport function neighboursOf(\n feature: WrittenFeature,\n flowId: string,\n): { previous: GrimoireFlowNeighbour | null; next: GrimoireFlowNeighbour | null } {\n const order = flowOrder(feature);\n const position = order.findIndex((flow) => flow.id.value === flowId);\n\n if (position < 0) return { previous: null, next: null };\n\n return { previous: neighbour(order[position - 1]), next: neighbour(order[position + 1]) };\n}\n\n/** The health strip numbers of a flow (criteria, steps, findings). */\nexport function flowHealth(result: ScryFlowResult): GrimoireFlowHealth {\n const byStatus: Record<CriterionStatus, number> = {\n pass: 0,\n fail: 0,\n stale: 0,\n \"not-run\": 0,\n \"no-test\": 0,\n };\n\n for (const criterion of result.bookmap.criteria) byStatus[criterion.status] += 1;\n\n const checked = result.bookmap.steps.filter((step) => step.found !== null);\n const unexpected = result.findings.filter((finding) => !finding.expected);\n const errors = unexpected.filter((finding) => finding.severity === \"error\").length;\n\n return {\n criteria: { total: result.bookmap.criteria.length, proven: byStatus.pass, byStatus },\n steps: {\n total: checked.length,\n resolved: checked.filter((step) => step.found === true).length,\n unchecked: result.bookmap.steps.length - checked.length,\n },\n findings: {\n errors,\n warnings: unexpected.length - errors,\n expected: result.findings.length - unexpected.length,\n },\n };\n}\n\n/** One step with counts and the first direct imports; the file lists are left out. */\nexport function compactStep(\n snapshot: GrimoireSnapshot,\n feature: WrittenFeature,\n step: FlowBookmapStep,\n written: WrittenFlow | undefined,\n): GrimoireFlowStep {\n const { files: _files, typeOnlyFiles: _typeOnly, direct, ...rest } = step;\n const target = written?.steps.find((item) => item.index === step.index)?.affects ?? null;\n let linked: GrimoireFlowStep[\"linked\"] = null;\n\n if (target !== null && target.flow !== null) {\n const owner =\n target.feature === feature.id\n ? feature\n : snapshot.written.features.find((item) => item.id === target.feature);\n const other = owner?.flows.find((item) => item.id.value === target.flow);\n\n if (other !== undefined) {\n linked = { ref: other.ref, heading: other.heading?.value ?? null, summary: other.summary };\n }\n }\n\n return {\n ...rest,\n counts: stepCounts(snapshot, feature.id, step),\n direct: direct.slice(0, FLOW_STEP_DIRECT_LIMIT),\n linked,\n };\n}\n\n/** The scry flow answer made compact, with the flow page header data. */\nexport function compactFlow(\n snapshot: GrimoireSnapshot,\n result: ScryFlowResult,\n): GrimoireFlowAnswer {\n const feature = snapshot.written.features.find((item) => item.id === result.flow.feature);\n\n if (feature === undefined) {\n throw new Error(`Feature ${result.flow.feature} is not written.`);\n }\n\n const readme = feature.readme;\n const { previous, next } = neighboursOf(feature, result.flow.id.value);\n\n return {\n ...result,\n bookmap: {\n ...result.bookmap,\n steps: result.bookmap.steps.map((step) => compactStep(snapshot, feature, step, result.flow)),\n },\n feature: {\n id: feature.id,\n title: readme?.title.value ?? feature.id,\n status: readme?.status.value ?? result.flow.status.value,\n apps: (readme?.apps ?? []).map((app) => app.value),\n },\n previous,\n next,\n health: flowHealth(result),\n results: testResultsInfo(snapshot),\n };\n}\n\n/** The files of one set of a step, sorted by module and then path. */\nexport function stepFileSet(\n snapshot: GrimoireSnapshot,\n feature: string,\n step: FlowBookmapStep,\n set: StepFileSet,\n): string[] {\n const files =\n set === \"direct\"\n ? step.direct\n : set === \"feature\"\n ? featureFiles(snapshot, feature, step)\n : set === \"reachable\"\n ? step.files\n : step.typeOnlyFiles;\n const modules = new Map(snapshot.book.facts.files.map((item) => [item.file, item.module]));\n const moduleOf = (file: string): string => modules.get(file) ?? \"\";\n\n return [...files].sort(\n (left, right) => byText(moduleOf(left), moduleOf(right)) || byText(left, right),\n );\n}\n\n/**\n * One page of a step's files with the module counts of the whole set.\n * `limit` is capped at {@link STEP_FILES_PAGE_LIMIT}.\n */\nexport function stepFilePage(\n snapshot: GrimoireSnapshot,\n bookmap: FlowBookmap,\n step: FlowBookmapStep,\n set: StepFileSet,\n offset: number,\n limit: number,\n): GrimoireStepFilesAnswer {\n const sorted = stepFileSet(snapshot, bookmap.feature, step, set);\n const modules = new Map(snapshot.book.facts.files.map((item) => [item.file, item.module]));\n const moduleOf = (file: string): string => modules.get(file) ?? \"\";\n const size = Math.min(Math.max(1, Math.floor(limit)), STEP_FILES_PAGE_LIMIT);\n const start = Math.max(0, Math.floor(offset));\n const counts = new Map<string, number>();\n\n for (const file of sorted) counts.set(moduleOf(file), (counts.get(moduleOf(file)) ?? 0) + 1);\n\n return {\n ref: bookmap.ref,\n index: step.index,\n set,\n total: sorted.length,\n offset: start,\n limit: size,\n files: sorted.slice(start, start + size).map((file) => ({\n file,\n module: moduleOf(file),\n owner: snapshot.ownership.files[file]?.owner ?? null,\n })),\n modules: [...counts]\n .map(([module, count]) => ({ module, count }))\n .sort((left, right) => right.count - left.count || byText(left.module, right.module)),\n };\n}\n"],"mappings":";;;;AA0BA,MAAa,iBAAyC;CACpD;CACA;CACA;CACA;AACF;AAEA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;;AAGhG,SAAS,aACP,UACA,SACA,MACU;CACV,OAAO,KAAK,MAAM,QAAQ,SAAS,SAAS,UAAU,MAAM,KAAK,EAAE,UAAU,OAAO;AACtF;;AAGA,SAAgB,WACd,UACA,SACA,MACgB;CAChB,OAAO;EACL,QAAQ,KAAK,OAAO;EACpB,SAAS,aAAa,UAAU,SAAS,IAAI,CAAC,CAAC;EAC/C,WAAW,KAAK,MAAM;EACtB,UAAU,KAAK,cAAc;CAC/B;AACF;;AAGA,SAAgB,UAAU,SAAwC;CAChE,MAAM,OAAO,IAAI,IAAI,QAAQ,MAAM,KAAK,SAAS,CAAC,KAAK,GAAG,OAAO,IAAI,CAAC,CAAC;CACvE,MAAM,UAAU,QAAQ,QAAQ,SAAS,CAAC,EAAC,CAAE,SAAS,SAAS;EAC7D,MAAM,OAAO,KAAK,IAAI,KAAK,IAAI;EAE/B,OAAO,SAAS,SAAY,CAAC,IAAI,CAAC,IAAI;CACxC,CAAC;CAED,IAAI,OAAO,WAAW,GAAG,OAAO,QAAQ;CAGxC,MAAM,OAAO,IAAI,IAAI,MAAM;CAE3B,OAAO,CAAC,GAAG,QAAQ,GAAG,QAAQ,MAA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AAU,MAAM,KAAK,EAAE,SAAS;EAClD,EAAE;EACF,SAAS,CAAC,GAAG,MAAM,CAAC,CACjB,KAAK,CAAC,QAAQ,YAAY;GAAE;GAAQ;EAAM,EAAE,CAAC,CAC7C,MAAM,MAAM,UAAU,MAAM,QAAQ,KAAK,SAAS,OAAO,KAAK,QAAQ,MAAM,MAAM,CAAC;CACxF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/format.ts"],"mappings":";;;YAmCY;;EAEV;;;;;;
|
|
1
|
+
{"version":3,"file":"format.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/format.ts"],"mappings":";;;YAmCY;;EAEV;;;;;;wBA8Wc,iBAAiB,QAAQ,YAAY,UAAS"}
|
package/esm/scry/format.mjs
CHANGED
|
@@ -174,10 +174,21 @@ function formatFlow(result) {
|
|
|
174
174
|
...notes(result)
|
|
175
175
|
];
|
|
176
176
|
}
|
|
177
|
+
/** One line telling what the limit cut, per type, or nothing when every match is listed. */
|
|
178
|
+
function truncatedLine(result) {
|
|
179
|
+
const total = Object.values(result.counts).reduce((sum, count) => sum + (count ?? 0), 0);
|
|
180
|
+
if (total <= result.hits.length) return [];
|
|
181
|
+
const parts = Object.entries(result.counts).map(([type, count]) => `${count} ${type}`);
|
|
182
|
+
return [`showing ${result.hits.length} of ${total} (${parts.join(", ")}); raise --limit for more`];
|
|
183
|
+
}
|
|
177
184
|
function formatSearch(result) {
|
|
178
185
|
if (result.hits.length === 0) return [`no match for ${JSON.stringify(result.text)}`, ...notes(result)];
|
|
179
186
|
const idWidth = Math.min(32, Math.max(0, ...result.hits.map((hit) => hit.id.length)));
|
|
180
|
-
return [
|
|
187
|
+
return [
|
|
188
|
+
...result.hits.map((hit) => (hit.detail === null ? `${hit.type.padEnd(9)}${hit.id}` : `${hit.type.padEnd(9)}${hit.id.padEnd(idWidth)} ${hit.detail}`).trimEnd() + (hit.matched === void 0 ? "" : ` [${hit.matched}]`)),
|
|
189
|
+
...truncatedLine(result),
|
|
190
|
+
...notes(result)
|
|
191
|
+
];
|
|
181
192
|
}
|
|
182
193
|
/**
|
|
183
194
|
* The compact text of a result (formats in the commands guide). Long lists in an
|
package/esm/scry/format.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/format.ts"],"sourcesContent":["/**\n * The compact text of a scry answer: a title line, then `label value` lines\n * with the labels in one column. Empty sections are left out.\n */\nimport type { FlowBookmapCriterion, FlowBookmapStep } from \"../contracts/bookmap\";\nimport type { CriterionStatus } from \"../contracts/test-results\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryImpactResult,\n ScryResult,\n ScryRouteResult,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { WrittenChangelogEntry } from \"../contracts/written\";\n\nconst LABEL = 10;\n\n/** `label` padded to the column, then the first value; more values go on indented lines. */\nfunction section(label: string, values: readonly string[], width = LABEL): string[] {\n if (values.length === 0) return [];\n\n const pad = \" \".repeat(Math.max(width, label.length + 1));\n\n return values.map((value, index) =>\n index === 0 ? `${label.padEnd(pad.length)}${value}` : `${pad}${value}`,\n );\n}\n\n/** Longest list a text section prints before it says how many more there are. */\nconst SECTION_CAP = 20;\n\n/** What the text formatters may be told. */\nexport type FormatScryOptions = {\n /** Print every line of every section, not the first 20. */\n all?: boolean;\n};\n\n/** A section whose heading carries the count (`routes (3)`) and whose list stops at the cap. */\nfunction countedSection(\n label: string,\n values: readonly string[],\n options: FormatScryOptions,\n width: number,\n): string[] {\n const shown = options.all === true ? values : values.slice(0, SECTION_CAP);\n const lines = section(`${label} (${values.length})`, shown, width);\n\n if (shown.length < values.length) {\n lines.push(\n `${\" \".repeat(Math.max(width, label.length + 1))}… and ${values.length - shown.length} more (--all lists every one)`,\n );\n }\n\n return lines;\n}\n\nconst plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** Cut text at a word so it fits `max` characters, ending with ` …`. */\nfunction shorten(text: string, max: number): string {\n if (text.length <= max) return text;\n\n const words = text.split(\" \");\n let kept = \"\";\n\n for (const word of words) {\n const next = kept === \"\" ? word : `${kept} ${word}`;\n\n if (next.length + 2 > max) break;\n\n kept = next;\n }\n\n return `${kept === \"\" ? text.slice(0, max - 2) : kept} …`;\n}\n\nfunction notes(result: ScryResult): string[] {\n return section(\"note\", result.notes);\n}\n\nfunction countsLine(findings: readonly GrimoireFinding[]): string {\n const errors = findings.filter(\n (finding) => !finding.expected && finding.severity === \"error\",\n ).length;\n const warnings = findings.filter(\n (finding) => !finding.expected && finding.severity === \"warning\",\n ).length;\n const expected = findings.filter((finding) => finding.expected).length;\n\n return `${plural(errors, \"error\")}, ${plural(warnings, \"warning\")}, ${expected} expected`;\n}\n\nfunction releaseOf(entry: WrittenChangelogEntry): string {\n return entry.release === null ? \"unreleased\" : `${entry.release}, ${entry.date ?? \"no date\"}`;\n}\n\nfunction formatFile(result: ScryFileResult): string[] {\n const entry = result.entry;\n const feature =\n entry.feature === null && entry.borrowedBy.length === 0\n ? []\n : [\n `${entry.feature ?? \"none\"}${entry.borrowedBy.length > 0 ? ` (borrowed by: ${entry.borrowedBy.join(\", \")})` : \"\"}`,\n ];\n const exportWidth = Math.max(0, ...entry.exports.map((item) => item.name.length));\n\n return [\n `${entry.file} ${entry.type} ${plural(entry.lines, \"line\")}`,\n ...section(\"about\", entry.about === null ? [] : [entry.about]),\n ...section(\"feature\", feature),\n ...section(\"flows\", entry.flows),\n ...section(\n \"exports\",\n entry.exports.map((item) =>\n item.about === null ? item.name : `${item.name.padEnd(exportWidth)} ${item.about}`,\n ),\n ),\n ...section(\"packages\", entry.packages.length > 0 ? [entry.packages.join(\" \")] : []),\n ...section(\"imports\", entry.imports),\n ...section(\"used by\", entry.importedBy),\n ...section(\n \"routes\",\n entry.routes.map(\n (route) =>\n `${route.method} ${route.path}${route.via === \"handles\" ? \" (handles)\" : \" (registers)\"}`,\n ),\n ),\n ...section(\n \"pages\",\n entry.pages.map((page) => `${page.site} ${page.route} (${page.via})`),\n ),\n ...section(\n \"screens\",\n entry.screens.map((screen) => `${screen.app} ${screen.route} (${screen.via})`),\n ),\n ...section(\"entry\", result.bookEntry === null ? [] : [result.bookEntry]),\n ...notes(result),\n ];\n}\n\nfunction formatImpact(result: ScryImpactResult, options: FormatScryOptions): string[] {\n const width = 14;\n\n return [\n `impact of ${result.file}`,\n `${\"importers\".padEnd(width)}${result.importers.direct.length} direct, ${result.importers.all.length} in all`,\n ...countedSection(\n \"routes\",\n result.routes.map((route) => `${route.method} ${route.path}`),\n options,\n width,\n ),\n ...countedSection(\n \"pages\",\n result.pages.map((page) => `${page.app} ${page.route}`),\n options,\n width,\n ),\n ...countedSection(\"flows\", result.flows, options, width),\n ...countedSection(\n \"features\",\n result.features.map((feature) => `${feature.id} (${feature.via})`),\n options,\n width,\n ),\n ...countedSection(\"tests\", result.tests, options, width),\n ...notes(result),\n ];\n}\n\nfunction formatRoute(result: ScryRouteResult): string[] {\n const route = result.route;\n const width = 12;\n const auth = route.auth.required\n ? `required (${route.auth.userTypes.length > 0 ? route.auth.userTypes.join(\", \") : \"any user\"})`\n : \"none\";\n\n return [\n `${route.method} ${route.path}${route.name === null ? \"\" : ` ${route.name}`}`,\n ...section(\n \"handler\",\n [`${route.handler}${route.handlerFile === null ? \"\" : ` ${route.handlerFile}`}`],\n width,\n ),\n ...section(\"registered\", route.sourceFile === null ? [] : [route.sourceFile], width),\n ...section(\n \"middleware\",\n route.middleware.length > 0 ? [route.middleware.join(\" \")] : [],\n width,\n ),\n ...section(\"auth\", [auth], width),\n ...section(\"description\", route.description === null ? [] : [route.description], width),\n ...section(\n \"page\",\n result.page === null ? [] : [`${result.page.site} ${result.page.route} ${result.page.file}`],\n width,\n ),\n ...section(\"files\", result.files, width),\n ...section(\n \"steps\",\n result.steps.map((step) => `${step.flow} step ${step.index}`),\n width,\n ),\n ...notes(result),\n ];\n}\n\nfunction changeLine(entry: WrittenChangelogEntry): string {\n const text = `${entry.flow === null ? \"\" : `${entry.flow}: `}${entry.text}`;\n\n return `${entry.version.value} ${entry.word} ${shorten(text, 60)} (${releaseOf(entry)})`;\n}\n\nfunction formatFeature(result: ScryFeatureResult): string[] {\n const readme = result.readme;\n const bookmap = result.bookmap;\n const idWidth = Math.max(0, ...result.flows.map((flow) => flow.id.length));\n const statusWidth = Math.max(0, ...result.flows.map((flow) => flow.status.length));\n const pages = Object.entries(bookmap.pages)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n .flatMap(([app, list]) => list.map((page) => `${app} ${page.route}`));\n const apps = readme.apps.map((app) => app.value);\n\n return [\n [\n readme.id.value,\n readme.title.value,\n `${readme.status.value} ${readme.version.value}`,\n `updated ${readme.updated.value}`,\n ...(apps.length > 0 ? [`apps ${apps.join(\", \")}`] : []),\n ].join(\" \"),\n ...section(\n \"flows\",\n result.flows.map(\n (flow) =>\n `${flow.id.padEnd(idWidth)} ${flow.status.padEnd(statusWidth)} since ${flow.since}`,\n ),\n ),\n ...section(\"own\", [\n `${plural(bookmap.own.length, \"file\")} (unreached: ${bookmap.unreached.length === 0 ? \"none\" : bookmap.unreached.length})`,\n ]),\n ...section(\"unreached\", bookmap.unreached),\n ...section(\n \"borrows\",\n bookmap.borrowed.map((item) => item.file),\n ),\n ...section(\n \"routes\",\n bookmap.routes.length > 0\n ? [bookmap.routes.map((route) => `${route.method} ${route.path}`).join(\" \")]\n : [],\n ),\n ...section(\"pages\", pages.length > 0 ? [pages.join(\" \")] : []),\n ...section(\"changes\", result.changes.map(changeLine)),\n ...section(\n \"tasks\",\n result.tasks.map((task) => `${task.id} ${task.status} ${task.title}`),\n ),\n ...section(\"check\", [countsLine(result.findings)]),\n ...notes(result),\n ];\n}\n\nconst STATUS_TEXT: Record<CriterionStatus, string> = {\n pass: \"pass\",\n fail: \"fail\",\n stale: \"stale\",\n \"not-run\": \"not run\",\n \"no-test\": \"no test\",\n};\n\n/** ` (+12 reachable, 3 type-only)`: what a step reaches beyond its entry file; empty when nothing. */\nfunction reachNote(step: FlowBookmapStep): string {\n const parts = [\n ...(step.files.length > 1 ? [`+${step.files.length - 1} reachable`] : []),\n ...(step.typeOnlyFiles.length > 0 ? [`${step.typeOnlyFiles.length} type-only`] : []),\n ];\n\n return parts.length === 0 ? \"\" : ` (${parts.join(\", \")})`;\n}\n\nfunction stepLines(steps: readonly FlowBookmapStep[]): string[] {\n const typeWidth = Math.max(0, ...steps.map((step) => step.type.length));\n const targetWidth = Math.max(0, ...steps.map((step) => step.target.length));\n\n return steps.map((step) => {\n const where =\n step.found === false\n ? \"not found\"\n : step.entry === null\n ? step.found === null && step.type === \"route\"\n ? \"no route facts\"\n : \"—\"\n : `${step.entry}${reachNote(step)}`;\n\n return `${step.index}. ${step.type.padEnd(typeWidth)} ${step.target.padEnd(targetWidth)} ${where}`;\n });\n}\n\nfunction criterionLines(criteria: readonly FlowBookmapCriterion[]): string[] {\n const labels = criteria.map(\n (criterion) => `${criterion.id}${criterion.app === null ? \"\" : ` [${criterion.app}]`}`,\n );\n const labelWidth = Math.max(0, ...labels.map((label) => label.length));\n const texts = criteria.map((criterion) => shorten(criterion.text, 36));\n const textWidth = Math.max(0, ...texts.map((text) => text.length));\n\n return criteria.map((criterion, index) => {\n const test = criterion.tests[0];\n const where =\n test === undefined\n ? \"\"\n : `${test.file}:${test.line}${criterion.tests.length > 1 ? ` (+${criterion.tests.length - 1})` : \"\"}`;\n const line = `${(labels[index] ?? \"\").padEnd(labelWidth)} ${STATUS_TEXT[criterion.status].padEnd(7)} ${\n where === \"\" ? (texts[index] ?? \"\") : `${(texts[index] ?? \"\").padEnd(textWidth)} ${where}`\n }`;\n\n return line.trimEnd();\n });\n}\n\nfunction formatFlow(result: ScryFlowResult): string[] {\n const flow = result.flow;\n const shown = result.bookmap.shownBy.map((item) => `${item.app} ${item.id}: ${item.block}`);\n\n return [\n [\n flow.ref,\n ...(flow.heading === null ? [] : [flow.heading.value]),\n `${flow.status.value} since ${flow.since.value}`,\n `who ${flow.who.value}`,\n ].join(\" \"),\n ...(flow.summary === null ? [] : [flow.summary]),\n ...stepLines(result.bookmap.steps),\n ...section(\n \"differs\",\n flow.differs.map((line) => `${line.name}: ${line.text}`),\n ),\n ...section(\n \"not handled\",\n flow.notHandled.map((line) => `${line.name}: ${line.text}`),\n 12,\n ),\n ...section(\n \"unknown\",\n flow.unknowns.map((item) => item.text.replace(/^Unknown:\\s*/, \"\")),\n ),\n ...criterionLines(result.bookmap.criteria),\n ...section(\"shown on\", shown.length > 0 ? [shown.join(\" \")] : []),\n ...section(\n \"history\",\n result.history.length > 0\n ? [\n result.history\n .map((entry) => `${entry.version.value} ${entry.word} (${releaseOf(entry)})`)\n .join(\" \"),\n ]\n : [],\n ),\n ...section(\"check\", [countsLine(result.findings)]),\n ...notes(result),\n ];\n}\n\nfunction formatSearch(result: ScrySearchResult): string[] {\n if (result.hits.length === 0)\n return [`no match for ${JSON.stringify(result.text)}`, ...notes(result)];\n\n const idWidth = Math.min(32, Math.max(0, ...result.hits.map((hit) => hit.id.length)));\n\n return [\n ...result.hits.map((hit) =>\n (hit.detail === null\n ? `${hit.type.padEnd(9)}${hit.id}`\n : `${hit.type.padEnd(9)}${hit.id.padEnd(idWidth)} ${hit.detail}`\n ).trimEnd(),\n ),\n ...notes(result),\n ];\n}\n\n/**\n * The compact text of a result (formats in the commands guide). Long lists in an\n * impact answer stop after 20 lines with a count; `options.all` prints them all.\n */\nexport function formatScryResult(result: ScryResult, options: FormatScryOptions = {}): string[] {\n switch (result.type) {\n case \"file\":\n return formatFile(result);\n case \"impact\":\n return formatImpact(result, options);\n case \"route\":\n return formatRoute(result);\n case \"feature\":\n return formatFeature(result);\n case \"flow\":\n return formatFlow(result);\n case \"search\":\n return formatSearch(result);\n }\n}\n"],"mappings":";AAkBA,M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AC1B,KAAK,UACH,OAAO,aAAa,QAAQ,OAAO;EACrC,KAAK,SACH,OAAO,YAAY,MAAM;EAC3B,KAAK,WACH,OAAO,cAAc,MAAM;EAC7B,KAAK,QACH,OAAO,WAAW,MAAM;EAC1B,KAAK,UACH,OAAO,aAAa,MAAM;CAC9B;AACF"}
|
|
1
|
+
{"version":3,"file":"format.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/format.ts"],"sourcesContent":["/**\n * The compact text of a scry answer: a title line, then `label value` lines\n * with the labels in one column. Empty sections are left out.\n */\nimport type { FlowBookmapCriterion, FlowBookmapStep } from \"../contracts/bookmap\";\nimport type { CriterionStatus } from \"../contracts/test-results\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryImpactResult,\n ScryResult,\n ScryRouteResult,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { WrittenChangelogEntry } from \"../contracts/written\";\n\nconst LABEL = 10;\n\n/** `label` padded to the column, then the first value; more values go on indented lines. */\nfunction section(label: string, values: readonly string[], width = LABEL): string[] {\n if (values.length === 0) return [];\n\n const pad = \" \".repeat(Math.max(width, label.length + 1));\n\n return values.map((value, index) =>\n index === 0 ? `${label.padEnd(pad.length)}${value}` : `${pad}${value}`,\n );\n}\n\n/** Longest list a text section prints before it says how many more there are. */\nconst SECTION_CAP = 20;\n\n/** What the text formatters may be told. */\nexport type FormatScryOptions = {\n /** Print every line of every section, not the first 20. */\n all?: boolean;\n};\n\n/** A section whose heading carries the count (`routes (3)`) and whose list stops at the cap. */\nfunction countedSection(\n label: string,\n values: readonly string[],\n options: FormatScryOptions,\n width: number,\n): string[] {\n const shown = options.all === true ? values : values.slice(0, SECTION_CAP);\n const lines = section(`${label} (${values.length})`, shown, width);\n\n if (shown.length < values.length) {\n lines.push(\n `${\" \".repeat(Math.max(width, label.length + 1))}… and ${values.length - shown.length} more (--all lists every one)`,\n );\n }\n\n return lines;\n}\n\nconst plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** Cut text at a word so it fits `max` characters, ending with ` …`. */\nfunction shorten(text: string, max: number): string {\n if (text.length <= max) return text;\n\n const words = text.split(\" \");\n let kept = \"\";\n\n for (const word of words) {\n const next = kept === \"\" ? word : `${kept} ${word}`;\n\n if (next.length + 2 > max) break;\n\n kept = next;\n }\n\n return `${kept === \"\" ? text.slice(0, max - 2) : kept} …`;\n}\n\nfunction notes(result: ScryResult): string[] {\n return section(\"note\", result.notes);\n}\n\nfunction countsLine(findings: readonly GrimoireFinding[]): string {\n const errors = findings.filter(\n (finding) => !finding.expected && finding.severity === \"error\",\n ).length;\n const warnings = findings.filter(\n (finding) => !finding.expected && finding.severity === \"warning\",\n ).length;\n const expected = findings.filter((finding) => finding.expected).length;\n\n return `${plural(errors, \"error\")}, ${plural(warnings, \"warning\")}, ${expected} expected`;\n}\n\nfunction releaseOf(entry: WrittenChangelogEntry): string {\n return entry.release === null ? \"unreleased\" : `${entry.release}, ${entry.date ?? \"no date\"}`;\n}\n\nfunction formatFile(result: ScryFileResult): string[] {\n const entry = result.entry;\n const feature =\n entry.feature === null && entry.borrowedBy.length === 0\n ? []\n : [\n `${entry.feature ?? \"none\"}${entry.borrowedBy.length > 0 ? ` (borrowed by: ${entry.borrowedBy.join(\", \")})` : \"\"}`,\n ];\n const exportWidth = Math.max(0, ...entry.exports.map((item) => item.name.length));\n\n return [\n `${entry.file} ${entry.type} ${plural(entry.lines, \"line\")}`,\n ...section(\"about\", entry.about === null ? [] : [entry.about]),\n ...section(\"feature\", feature),\n ...section(\"flows\", entry.flows),\n ...section(\n \"exports\",\n entry.exports.map((item) =>\n item.about === null ? item.name : `${item.name.padEnd(exportWidth)} ${item.about}`,\n ),\n ),\n ...section(\"packages\", entry.packages.length > 0 ? [entry.packages.join(\" \")] : []),\n ...section(\"imports\", entry.imports),\n ...section(\"used by\", entry.importedBy),\n ...section(\n \"routes\",\n entry.routes.map(\n (route) =>\n `${route.method} ${route.path}${route.via === \"handles\" ? \" (handles)\" : \" (registers)\"}`,\n ),\n ),\n ...section(\n \"pages\",\n entry.pages.map((page) => `${page.site} ${page.route} (${page.via})`),\n ),\n ...section(\n \"screens\",\n entry.screens.map((screen) => `${screen.app} ${screen.route} (${screen.via})`),\n ),\n ...section(\"entry\", result.bookEntry === null ? [] : [result.bookEntry]),\n ...notes(result),\n ];\n}\n\nfunction formatImpact(result: ScryImpactResult, options: FormatScryOptions): string[] {\n const width = 14;\n\n return [\n `impact of ${result.file}`,\n `${\"importers\".padEnd(width)}${result.importers.direct.length} direct, ${result.importers.all.length} in all`,\n ...countedSection(\n \"routes\",\n result.routes.map((route) => `${route.method} ${route.path}`),\n options,\n width,\n ),\n ...countedSection(\n \"pages\",\n result.pages.map((page) => `${page.app} ${page.route}`),\n options,\n width,\n ),\n ...countedSection(\"flows\", result.flows, options, width),\n ...countedSection(\n \"features\",\n result.features.map((feature) => `${feature.id} (${feature.via})`),\n options,\n width,\n ),\n ...countedSection(\"tests\", result.tests, options, width),\n ...notes(result),\n ];\n}\n\nfunction formatRoute(result: ScryRouteResult): string[] {\n const route = result.route;\n const width = 12;\n const auth = route.auth.required\n ? `required (${route.auth.userTypes.length > 0 ? route.auth.userTypes.join(\", \") : \"any user\"})`\n : \"none\";\n\n return [\n `${route.method} ${route.path}${route.name === null ? \"\" : ` ${route.name}`}`,\n ...section(\n \"handler\",\n [`${route.handler}${route.handlerFile === null ? \"\" : ` ${route.handlerFile}`}`],\n width,\n ),\n ...section(\"registered\", route.sourceFile === null ? [] : [route.sourceFile], width),\n ...section(\n \"middleware\",\n route.middleware.length > 0 ? [route.middleware.join(\" \")] : [],\n width,\n ),\n ...section(\"auth\", [auth], width),\n ...section(\"description\", route.description === null ? [] : [route.description], width),\n ...section(\n \"page\",\n result.page === null ? [] : [`${result.page.site} ${result.page.route} ${result.page.file}`],\n width,\n ),\n ...section(\"files\", result.files, width),\n ...section(\n \"steps\",\n result.steps.map((step) => `${step.flow} step ${step.index}`),\n width,\n ),\n ...notes(result),\n ];\n}\n\nfunction changeLine(entry: WrittenChangelogEntry): string {\n const text = `${entry.flow === null ? \"\" : `${entry.flow}: `}${entry.text}`;\n\n return `${entry.version.value} ${entry.word} ${shorten(text, 60)} (${releaseOf(entry)})`;\n}\n\nfunction formatFeature(result: ScryFeatureResult): string[] {\n const readme = result.readme;\n const bookmap = result.bookmap;\n const idWidth = Math.max(0, ...result.flows.map((flow) => flow.id.length));\n const statusWidth = Math.max(0, ...result.flows.map((flow) => flow.status.length));\n const pages = Object.entries(bookmap.pages)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n .flatMap(([app, list]) => list.map((page) => `${app} ${page.route}`));\n const apps = readme.apps.map((app) => app.value);\n\n return [\n [\n readme.id.value,\n readme.title.value,\n `${readme.status.value} ${readme.version.value}`,\n `updated ${readme.updated.value}`,\n ...(apps.length > 0 ? [`apps ${apps.join(\", \")}`] : []),\n ].join(\" \"),\n ...section(\n \"flows\",\n result.flows.map(\n (flow) =>\n `${flow.id.padEnd(idWidth)} ${flow.status.padEnd(statusWidth)} since ${flow.since}`,\n ),\n ),\n ...section(\"own\", [\n `${plural(bookmap.own.length, \"file\")} (unreached: ${bookmap.unreached.length === 0 ? \"none\" : bookmap.unreached.length})`,\n ]),\n ...section(\"unreached\", bookmap.unreached),\n ...section(\n \"borrows\",\n bookmap.borrowed.map((item) => item.file),\n ),\n ...section(\n \"routes\",\n bookmap.routes.length > 0\n ? [bookmap.routes.map((route) => `${route.method} ${route.path}`).join(\" \")]\n : [],\n ),\n ...section(\"pages\", pages.length > 0 ? [pages.join(\" \")] : []),\n ...section(\"changes\", result.changes.map(changeLine)),\n ...section(\n \"tasks\",\n result.tasks.map((task) => `${task.id} ${task.status} ${task.title}`),\n ),\n ...section(\"check\", [countsLine(result.findings)]),\n ...notes(result),\n ];\n}\n\nconst STATUS_TEXT: Record<CriterionStatus, string> = {\n pass: \"pass\",\n fail: \"fail\",\n stale: \"stale\",\n \"not-run\": \"not run\",\n \"no-test\": \"no test\",\n};\n\n/** ` (+12 reachable, 3 type-only)`: what a step reaches beyond its entry file; empty when nothing. */\nfunction reachNote(step: FlowBookmapStep): string {\n const parts = [\n ...(step.files.length > 1 ? [`+${step.files.length - 1} reachable`] : []),\n ...(step.typeOnlyFiles.length > 0 ? [`${step.typeOnlyFiles.length} type-only`] : []),\n ];\n\n return parts.length === 0 ? \"\" : ` (${parts.join(\", \")})`;\n}\n\nfunction stepLines(steps: readonly FlowBookmapStep[]): string[] {\n const typeWidth = Math.max(0, ...steps.map((step) => step.type.length));\n const targetWidth = Math.max(0, ...steps.map((step) => step.target.length));\n\n return steps.map((step) => {\n const where =\n step.found === false\n ? \"not found\"\n : step.entry === null\n ? step.found === null && step.type === \"route\"\n ? \"no route facts\"\n : \"—\"\n : `${step.entry}${reachNote(step)}`;\n\n return `${step.index}. ${step.type.padEnd(typeWidth)} ${step.target.padEnd(targetWidth)} ${where}`;\n });\n}\n\nfunction criterionLines(criteria: readonly FlowBookmapCriterion[]): string[] {\n const labels = criteria.map(\n (criterion) => `${criterion.id}${criterion.app === null ? \"\" : ` [${criterion.app}]`}`,\n );\n const labelWidth = Math.max(0, ...labels.map((label) => label.length));\n const texts = criteria.map((criterion) => shorten(criterion.text, 36));\n const textWidth = Math.max(0, ...texts.map((text) => text.length));\n\n return criteria.map((criterion, index) => {\n const test = criterion.tests[0];\n const where =\n test === undefined\n ? \"\"\n : `${test.file}:${test.line}${criterion.tests.length > 1 ? ` (+${criterion.tests.length - 1})` : \"\"}`;\n const line = `${(labels[index] ?? \"\").padEnd(labelWidth)} ${STATUS_TEXT[criterion.status].padEnd(7)} ${\n where === \"\" ? (texts[index] ?? \"\") : `${(texts[index] ?? \"\").padEnd(textWidth)} ${where}`\n }`;\n\n return line.trimEnd();\n });\n}\n\nfunction formatFlow(result: ScryFlowResult): string[] {\n const flow = result.flow;\n const shown = result.bookmap.shownBy.map((item) => `${item.app} ${item.id}: ${item.block}`);\n\n return [\n [\n flow.ref,\n ...(flow.heading === null ? [] : [flow.heading.value]),\n `${flow.status.value} since ${flow.since.value}`,\n `who ${flow.who.value}`,\n ].join(\" \"),\n ...(flow.summary === null ? [] : [flow.summary]),\n ...stepLines(result.bookmap.steps),\n ...section(\n \"differs\",\n flow.differs.map((line) => `${line.name}: ${line.text}`),\n ),\n ...section(\n \"not handled\",\n flow.notHandled.map((line) => `${line.name}: ${line.text}`),\n 12,\n ),\n ...section(\n \"unknown\",\n flow.unknowns.map((item) => item.text.replace(/^Unknown:\\s*/, \"\")),\n ),\n ...criterionLines(result.bookmap.criteria),\n ...section(\"shown on\", shown.length > 0 ? [shown.join(\" \")] : []),\n ...section(\n \"history\",\n result.history.length > 0\n ? [\n result.history\n .map((entry) => `${entry.version.value} ${entry.word} (${releaseOf(entry)})`)\n .join(\" \"),\n ]\n : [],\n ),\n ...section(\"check\", [countsLine(result.findings)]),\n ...notes(result),\n ];\n}\n\n/** One line telling what the limit cut, per type, or nothing when every match is listed. */\nfunction truncatedLine(result: ScrySearchResult): string[] {\n const total = Object.values(result.counts).reduce((sum, count) => sum + (count ?? 0), 0);\n\n if (total <= result.hits.length) return [];\n\n const parts = Object.entries(result.counts).map(([type, count]) => `${count} ${type}`);\n\n return [\n `showing ${result.hits.length} of ${total} (${parts.join(\", \")}); raise --limit for more`,\n ];\n}\n\nfunction formatSearch(result: ScrySearchResult): string[] {\n if (result.hits.length === 0)\n return [`no match for ${JSON.stringify(result.text)}`, ...notes(result)];\n\n const idWidth = Math.min(32, Math.max(0, ...result.hits.map((hit) => hit.id.length)));\n\n return [\n ...result.hits.map(\n (hit) =>\n (hit.detail === null\n ? `${hit.type.padEnd(9)}${hit.id}`\n : `${hit.type.padEnd(9)}${hit.id.padEnd(idWidth)} ${hit.detail}`\n ).trimEnd() + (hit.matched === undefined ? \"\" : ` [${hit.matched}]`),\n ),\n ...truncatedLine(result),\n ...notes(result),\n ];\n}\n\n/**\n * The compact text of a result (formats in the commands guide). Long lists in an\n * impact answer stop after 20 lines with a count; `options.all` prints them all.\n */\nexport function formatScryResult(result: ScryResult, options: FormatScryOptions = {}): string[] {\n switch (result.type) {\n case \"file\":\n return formatFile(result);\n case \"impact\":\n return formatImpact(result, options);\n case \"route\":\n return formatRoute(result);\n case \"feature\":\n return formatFeature(result);\n case \"flow\":\n return formatFlow(result);\n case \"search\":\n return formatSearch(result);\n }\n}\n"],"mappings":";AAkBA,MAAM,QAAQ;;AAGd,SAAS,QAAQ,OAAe,QAA2B,QAAQ,OAAiB;CAClF,IAAI,OAAO,WAAW,GAAG,OAAO,CAAC;CAEjC,MAAM,MAAM,IAAI,OAAO,KAAK,IAAI,OAAO,MAAM,SAAS,CAAC,CAAC;CAExD,OAAO,OAAO,KAAK,OAAO,UACxB,UAAU,IAAI,GAAG,MAAM,OAAO,IAAI,MAAM,IAAI,UAAU,GAAG,MAAM,OACjE;AACF;;AAGA,MAAM,cAAc;;AASpB,SAAS,eACP,OACA,QACA,SACA,OACU;CACV,MAAM,QAAQ,QAAQ,QAAQ,OAAO,SAAS,OAAO,MAAM,GAAG,WAAW;CACzE,MAAM,QAAQ,QAAQ,GAAG,MAAM,IAAI,OAAO,OAAO,IAAI,OAAO,KAAK;CAEjE,IAAI,MAAM,SAAS,OAAO,QACxB,MAAM,KACJ,GAAG,IAAI,OAAO,KAAK,IAAI,OAAO,MAAM,SAAS,CAAC,CAAC,EAAE,QAAQ,OAAO,SAAS,MAAM,OAAO,8BACxF;CAGF,OAAO;AACT;AAEA,MAAM,UAAU,OAAe,SAAyB,GAAG,MAAM,GAAG,OAAO,UAAU,IAAI,KAAK;;AAG9F,SAAS,QAAQ,MAAc,KAAqB;CAClD,IAAI,KAAK,UAAU,KAAK,OAAO;CAE/B,MAAM,QAAQ,KAAK,MAAM,GAAG;CAC5B,IAAI,OAAO;CAEX,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,OAAO,SAAS,KAAK,OAAO,GAAG,KAAK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