@warlock.js/grimoire 5.57.0 → 5.58.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 +20 -0
- package/esm/book/build.d.mts.map +1 -1
- package/esm/book/build.mjs +2 -1
- package/esm/book/build.mjs.map +1 -1
- package/esm/book/render.mjs +10 -0
- package/esm/book/render.mjs.map +1 -1
- package/esm/bookmap/build.d.mts.map +1 -1
- package/esm/bookmap/build.mjs +2 -2
- package/esm/bookmap/build.mjs.map +1 -1
- package/esm/bookmap/steps.mjs +53 -38
- package/esm/bookmap/steps.mjs.map +1 -1
- package/esm/check/check-grimoire.d.mts.map +1 -1
- package/esm/check/check-grimoire.mjs +4 -1
- package/esm/check/check-grimoire.mjs.map +1 -1
- package/esm/check/rules/criteria.mjs +21 -2
- package/esm/check/rules/criteria.mjs.map +1 -1
- package/esm/check/rules/screenshots.mjs +57 -0
- package/esm/check/rules/screenshots.mjs.map +1 -0
- package/esm/codes/codes.d.mts +12 -0
- package/esm/codes/codes.d.mts.map +1 -1
- package/esm/codes/codes.mjs +6 -0
- package/esm/codes/codes.mjs.map +1 -1
- package/esm/contracts/adapter.d.mts +6 -0
- package/esm/contracts/adapter.d.mts.map +1 -1
- package/esm/contracts/book.d.mts +2 -0
- package/esm/contracts/book.d.mts.map +1 -1
- package/esm/contracts/book.mjs.map +1 -1
- package/esm/contracts/bookmap.d.mts +19 -1
- package/esm/contracts/bookmap.d.mts.map +1 -1
- package/esm/contracts/snapshot.d.mts +11 -0
- package/esm/contracts/snapshot.d.mts.map +1 -1
- package/esm/contracts/test-results.d.mts +34 -0
- package/esm/contracts/test-results.d.mts.map +1 -1
- package/esm/contracts/written.d.mts +44 -0
- package/esm/contracts/written.d.mts.map +1 -1
- package/esm/contracts/written.mjs.map +1 -1
- package/esm/devtools/data.mjs +94 -3
- package/esm/devtools/data.mjs.map +1 -1
- package/esm/devtools/index.d.mts +26 -0
- package/esm/devtools/index.d.mts.map +1 -1
- package/esm/devtools/index.mjs +88 -5
- package/esm/devtools/index.mjs.map +1 -1
- package/esm/devtools/product-map.d.mts +14 -0
- package/esm/devtools/product-map.d.mts.map +1 -0
- package/esm/devtools/product-map.mjs +385 -0
- package/esm/devtools/product-map.mjs.map +1 -0
- package/esm/devtools/site.d.mts.map +1 -1
- package/esm/devtools/site.mjs +85 -13
- package/esm/devtools/site.mjs.map +1 -1
- package/esm/devtools/snapshot-source.mjs +10 -6
- package/esm/devtools/snapshot-source.mjs.map +1 -1
- package/esm/graph/index.d.mts +10 -1
- package/esm/graph/index.d.mts.map +1 -1
- package/esm/graph/index.mjs +3 -2
- package/esm/graph/index.mjs.map +1 -1
- package/esm/index.d.mts +4 -4
- package/esm/paths/index.d.mts +2 -0
- package/esm/paths/index.d.mts.map +1 -1
- package/esm/paths/index.mjs +3 -1
- package/esm/paths/index.mjs.map +1 -1
- package/esm/scry/compact.mjs +169 -0
- package/esm/scry/compact.mjs.map +1 -0
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +7 -1
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +12 -1
- package/esm/scry/query.mjs.map +1 -1
- package/esm/test-results/index.d.mts +7 -2
- package/esm/test-results/index.d.mts.map +1 -1
- package/esm/test-results/index.mjs +79 -12
- package/esm/test-results/index.mjs.map +1 -1
- package/esm/vitest/index.d.mts +6 -0
- package/esm/vitest/index.d.mts.map +1 -1
- package/esm/vitest/index.mjs +22 -6
- package/esm/vitest/index.mjs.map +1 -1
- package/esm/warlock/adapter.d.mts.map +1 -1
- package/esm/warlock/adapter.mjs +6 -2
- package/esm/warlock/adapter.mjs.map +1 -1
- package/esm/warlock/mcp-tools.mjs +48 -12
- package/esm/warlock/mcp-tools.mjs.map +1 -1
- package/esm/workspace/index.d.mts.map +1 -1
- package/esm/workspace/index.mjs +4 -2
- package/esm/workspace/index.mjs.map +1 -1
- package/esm/written/apps.mjs +4 -2
- package/esm/written/apps.mjs.map +1 -1
- package/esm/written/features.mjs +119 -6
- package/esm/written/features.mjs.map +1 -1
- package/esm/written/markdown.mjs +66 -1
- package/esm/written/markdown.mjs.map +1 -1
- package/esm/written/parse-grimoire.d.mts.map +1 -1
- package/esm/written/parse-grimoire.mjs +1 -1
- package/esm/written/parse-grimoire.mjs.map +1 -1
- package/llms-full.txt +76 -3
- package/package.json +3 -3
- package/skills/backfill-a-grimoire/SKILL.md +5 -0
- package/skills/describe-an-app/SKILL.md +12 -0
- package/skills/record-a-change/SKILL.md +8 -0
- package/skills/use-the-grimoire/SKILL.md +14 -1
- package/skills/write-a-feature/SKILL.md +37 -2
- package/ui/grimoire-static.js +4 -0
- package/ui/grimoire-view.js +1016 -178
- package/ui/grimoire.css +427 -2
- package/ui/product-map.css +636 -0
- package/ui/product-map.js +817 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
`@warlock.js/grimoire` is new in 5.55.0 and experimental: its file layout, `GR` codes and API may change in any release until it is marked stable.
|
|
4
4
|
|
|
5
|
+
## 5.58.0 - 2026-11-18
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Flows have a summary: the paragraph under the `# Title`. It shows on the flow page, in `scry --flow` and in the product map. A flow without one gets the warning GR1030.
|
|
10
|
+
- The devtools Grimoire tab has a flow page: summary, status and origin, previous and next flow, a health strip, a "Fix next" box with a ready `@proves` line, the journey as a stepper with file counts, one row per criterion with its tests, and edge cases with "does not apply" collapsed.
|
|
11
|
+
- A "Product map" view in the Grimoire tab for readers who do not read code: feature cards with a plain summary, audience, apps and a health light; feature pages with why, flows as short stories, where each appears in the apps with screenshots, release history and planned work; flow pages with the steps in the user's words and what proves them. Code detail sits behind "For developers". In the production monitor an admin can share it with a read-only link.
|
|
12
|
+
- Written format: feature `audience` and `## Why`, flow `## Story`, screenshots as image lines pointing into `grimoire/screenshots/` (pages, blocks and story steps), and `(AC-n)` at the end of a case line to link it to a criterion. New checks GR1029, GR2013 and GR2014.
|
|
13
|
+
- The panel option `testResultsFile` reads test results from another file; the reporter writes there with `grimoireReporter({ file })`. New warnings GR4009 (proofs but no recorded results) and GR4010 (a proving test the reporter could not match).
|
|
14
|
+
- The static export includes the product map and its screenshots.
|
|
15
|
+
- A new route pages through the files of one flow step.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- Flow steps list the files that run: type-only imports are no longer followed, so a page that imports a type through a barrel no longer lists the server files behind it. Book maps add `entries`, `direct` and `typeOnlyFiles` per step, and book entries add `typeOnlyImports`. Ownership coverage (GR3006) still counts type-only reach.
|
|
20
|
+
- The devtools flow answer and the MCP `grimoire_flow` tool send counts and direct imports per step instead of every reachable file. Flow answers on large apps drop from megabytes to kilobytes.
|
|
21
|
+
- The Check tab groups findings by code with counts and the fix shown once, filters by severity, code, feature and flow, and shows "files no flow reaches" (GR3006) one row per feature. The Overview's top problems rank by severity, then by count.
|
|
22
|
+
- The devtools tab works on phones: cards instead of tables, scrolling sub-tabs, no overflowing tables or wrapped ids, and readable module graph labels. Code spans in criteria and task text render as code.
|
|
23
|
+
- The Test results view tells "no results recorded" apart from "did not run" and picks up new results without a restart.
|
|
24
|
+
|
|
5
25
|
## 5.57.0 - 2026-11-18
|
|
6
26
|
|
|
7
27
|
### Added
|
package/esm/book/build.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"mappings":";;;;;;;;;wBAqSsB,UACpB,cACA,SAAS,aACT,UAAS,mBACR,QAAQ;;wBAyKW,SAAS,eAAe,QAAQ"}
|
package/esm/book/build.mjs
CHANGED
|
@@ -32,7 +32,7 @@ const absolutePath = (root, file) => path.join(root, ...file.split("/"));
|
|
|
32
32
|
async function readStoredBook(root) {
|
|
33
33
|
const manifest = await readJson(absolutePath(root, GRIMOIRE_PATHS.bookManifest));
|
|
34
34
|
const cache = await readJson(absolutePath(root, GRIMOIRE_PATHS.bookFactsCache));
|
|
35
|
-
if (manifest === null || cache === null || manifest.schemaVersion !== 1 || cache.schemaVersion !== 1 || typeof manifest.files !== "object" || typeof cache.facts !== "object") return null;
|
|
35
|
+
if (manifest === null || cache === null || manifest.schemaVersion !== 1 || cache.schemaVersion !== 1 || cache.typeOnlyEdges !== true || typeof manifest.files !== "object" || typeof cache.facts !== "object") return null;
|
|
36
36
|
return {
|
|
37
37
|
manifest,
|
|
38
38
|
facts: cache.facts
|
|
@@ -147,6 +147,7 @@ async function writeStoredBook(root, manifest, facts) {
|
|
|
147
147
|
if (facts !== null) {
|
|
148
148
|
const cache = {
|
|
149
149
|
schemaVersion: 1,
|
|
150
|
+
typeOnlyEdges: true,
|
|
150
151
|
facts
|
|
151
152
|
};
|
|
152
153
|
await writeBookFile(root, GRIMOIRE_PATHS.bookFactsCache, toJson(cache));
|
package/esm/book/build.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"sourcesContent":["/**\n * `buildBook` and `loadBook`: the freshness fingerprint, the facts cache and\n * the route (boot) cache. Entries are written by `writeBook` (write.ts).\n */\nimport { readFileSync } from \"node:fs\";\nimport { rm, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter, BookFacts, BookFile } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookFactsCache,\n type BookManifest,\n type BookManifestFile,\n type BuildBookOptions,\n type BuildBookResult,\n type LoadedBook,\n} from \"../contracts/book\";\nimport type { RouteFreshness } from \"../contracts/findings\";\nimport { GrimoireError } from \"../codes\";\nimport { importClosure, fileGraph } from \"../graph\";\nimport { GRIMOIRE_PATHS, isCodeFile, isInsideFolder } from \"../paths\";\nimport {\n cleanFolder,\n hashFile,\n hashIfExists,\n IO_CONCURRENCY,\n isMissing,\n listFiles,\n mapLimit,\n readJson,\n toJson,\n writeBookFile,\n} from \"./io\";\nimport {\n cleanPath,\n normalizeFiles,\n normalizeMobile,\n normalizeNamed,\n normalizePages,\n normalizeRoutes,\n normalizeSites,\n} from \"./normalize\";\nimport { entryPathsFor } from \"./render\";\n\n/** Where `writeBook` remembers what it wrote (see write.ts). */\nexport const WRITE_STATE_PATH = `${GRIMOIRE_PATHS.book}/.cache/written.json`;\n\nlet cachedVersion: string | null = null;\n\n/** The `@warlock.js/grimoire` version, from its package.json. */\nexport function grimoireVersion(): string {\n if (cachedVersion !== null) return cachedVersion;\n\n try {\n const manifest = JSON.parse(\n readFileSync(new URL(\"../../package.json\", import.meta.url), \"utf8\"),\n ) as {\n version?: unknown;\n };\n cachedVersion = typeof manifest.version === \"string\" ? manifest.version : \"0.0.0\";\n } catch {\n cachedVersion = \"0.0.0\";\n }\n\n return cachedVersion;\n}\n\nconst absolutePath = (root: string, file: string): string => path.join(root, ...file.split(\"/\"));\n\ntype StoredBook = { manifest: BookManifest; facts: BookFacts };\n\nasync function readStoredBook(root: string): Promise<StoredBook | null> {\n const manifest = await readJson<BookManifest>(absolutePath(root, GRIMOIRE_PATHS.bookManifest));\n const cache = await readJson<BookFactsCache>(absolutePath(root, GRIMOIRE_PATHS.bookFactsCache));\n\n if (\n manifest === null ||\n cache === null ||\n manifest.schemaVersion !== BOOK_SCHEMA_VERSION ||\n cache.schemaVersion !== BOOK_SCHEMA_VERSION ||\n typeof manifest.files !== \"object\" ||\n typeof cache.facts !== \"object\"\n ) {\n return null;\n }\n\n return { manifest, facts: cache.facts };\n}\n\n/** The current state of every code file under the source roots (images, fonts and certificates are not part of the book). */\ntype Scan = {\n files: Record<string, Omit<BookManifestFile, \"entry\">>;\n /** A file kept its hash but its size or mtime moved: the manifest needs the new stat. */\n statMoved: boolean;\n};\n\n/** Stat every code file; hash only those whose size or mtime differ from the previous manifest. */\nasync function scanSourceRoots(\n root: string,\n sourceRoots: readonly string[],\n previous: Record<string, BookManifestFile>,\n): Promise<Scan> {\n let files: string[];\n\n try {\n files = (await listFiles(root, sourceRoots)).filter(isCodeFile);\n } catch (error) {\n throw new GrimoireError(\n \"GR8001\",\n `The source roots could not be read: ${(error as Error).message}`,\n );\n }\n\n let statMoved = false;\n const states = await mapLimit(files, IO_CONCURRENCY, async (file) => {\n const absolute = absolutePath(root, file);\n\n try {\n const info = await stat(absolute);\n const before = previous[file];\n\n if (before !== undefined && before.size === info.size && before.mtimeMs === info.mtimeMs) {\n return { file, hash: before.hash, size: info.size, mtimeMs: info.mtimeMs };\n }\n\n const hash = await hashFile(absolute, info.size);\n\n if (before !== undefined && before.hash === hash) statMoved = true;\n\n return { file, hash, size: info.size, mtimeMs: info.mtimeMs };\n } catch (error) {\n // Deleted between the walk and the stat: treat it as gone.\n if (isMissing(error)) return null;\n throw new GrimoireError(\"GR8001\", `${file} could not be read: ${(error as Error).message}`);\n }\n });\n const result: Scan[\"files\"] = {};\n\n for (const state of states) {\n if (state !== null)\n result[state.file] = { hash: state.hash, size: state.size, mtimeMs: state.mtimeMs };\n }\n\n return { files: result, statMoved };\n}\n\n/** Hashes of the given files: from the scan when inside the source roots, else read (`\"\"` when missing). */\nasync function hashFiles(\n root: string,\n files: readonly string[],\n scan: Scan[\"files\"],\n sourceRoots: readonly string[],\n): Promise<Record<string, string>> {\n const hashes = await mapLimit([...new Set(files)].sort(), IO_CONCURRENCY, async (file) => {\n const scanned = scan[file];\n\n if (scanned !== undefined) return [file, scanned.hash] as const;\n // A code file inside a source root that the scan did not find is gone; any other input (a JSON config) is read.\n if (\n isCodeFile(file) &&\n sourceRoots.some((folder) => folder === \".\" || isInsideFolder(file, folder))\n )\n return [file, \"\"] as const;\n\n return [file, await hashIfExists(root, file)] as const;\n });\n\n return Object.fromEntries(hashes);\n}\n\nfunction sameRecord(left: Record<string, string>, right: Record<string, string>): boolean {\n const leftKeys = Object.keys(left);\n\n return (\n leftKeys.length === Object.keys(right).length &&\n leftKeys.every((key) => right[key] === left[key])\n );\n}\n\n/** Source files added, changed or removed between two manifests, sorted. */\nfunction changedFiles(\n previous: Record<string, BookManifestFile>,\n current: Scan[\"files\"],\n): string[] {\n const changed: string[] = [];\n\n for (const [file, state] of Object.entries(current)) {\n if (previous[file]?.hash !== state.hash) changed.push(file);\n }\n\n for (const file of Object.keys(previous)) {\n if (current[file] === undefined) changed.push(file);\n }\n\n return changed.sort();\n}\n\nconst NAMED_FILE_TYPES = new Set([\"mail\", \"job\", \"event\"]);\n\n/**\n * Files whose change makes the route cache stale: every `routes` file and\n * everything it imports, every `config` file, `warlock.config.ts`,\n * `package.json`, and every mail, job, event and notification file (the\n * named things are cached with the routes).\n */\nexport function defaultRouteInputs(files: readonly BookFile[]): string[] {\n const routesFiles = files.filter((file) => file.type === \"routes\").map((file) => file.file);\n const inputs = new Set(importClosure(fileGraph(files), routesFiles));\n\n for (const file of files) {\n if (\n file.type === \"config\" ||\n NAMED_FILE_TYPES.has(file.type) ||\n /\\.notification\\.[^/]+$/.test(file.file)\n ) {\n inputs.add(file.file);\n }\n }\n\n inputs.add(\"warlock.config.ts\");\n inputs.add(\"package.json\");\n\n return [...inputs].sort();\n}\n\n/** The route cache's input files: the adapter's list when it has one, else the default. */\nasync function routeInputFiles(\n root: string,\n adapter: BookAdapter,\n files: readonly BookFile[],\n): Promise<string[]> {\n return adapter.routeInputs\n ? (await adapter.routeInputs(root, files)).map(cleanPath)\n : defaultRouteInputs(files);\n}\n\nconst hasBootFacts = (adapter: BookAdapter): boolean =>\n typeof adapter.routes === \"function\" || typeof adapter.named === \"function\";\n\nasync function collectBootFacts(\n root: string,\n adapter: BookAdapter,\n): Promise<Pick<BookFacts, \"routes\" | \"named\">> {\n try {\n return {\n routes: adapter.routes ? normalizeRoutes(await adapter.routes(root)) : null,\n named: adapter.named ? normalizeNamed(await adapter.named(root)) : [],\n };\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\"GR8002\", `Route facts could not be read: ${(error as Error).message}`);\n }\n}\n\n/** How the stored route facts relate to the current inputs. */\nfunction bootState(\n boot: BookManifest[\"boot\"],\n routes: BookFacts[\"routes\"],\n inputs: Record<string, string>,\n): \"fresh\" | \"stale\" | \"missing\" {\n if (boot.collectedAt === null || routes === null) return \"missing\";\n\n return sameRecord(boot.inputs, inputs) ? \"fresh\" : \"stale\";\n}\n\nasync function writeStoredBook(\n root: string,\n manifest: BookManifest,\n facts: BookFacts | null,\n): Promise<void> {\n if (facts !== null) {\n const cache: BookFactsCache = { schemaVersion: BOOK_SCHEMA_VERSION, facts };\n await writeBookFile(root, GRIMOIRE_PATHS.bookFactsCache, toJson(cache));\n }\n\n // The manifest last: a reader that sees it also sees the facts it describes.\n await writeBookFile(root, GRIMOIRE_PATHS.bookManifest, toJson(manifest));\n}\n\n/**\n * Bring the book's facts up to date and write `manifest.json` and\n * `.cache/facts.json`. Does not write entries (see `writeBook`).\n *\n * @param root Absolute project root.\n */\nexport async function buildBook(\n root: string,\n adapter: BookAdapter,\n options: BuildBookOptions = {},\n): Promise<BuildBookResult> {\n const projectRoot = path.resolve(root);\n const mode = options.routes ?? \"cached\";\n const now = options.now ?? (() => new Date());\n // `write: false` (passed by `openGrimoire({ write: false })`) computes in memory only.\n const write = options.write !== false;\n const sourceRoots = [\n ...new Set((await adapter.sourceRoots(projectRoot)).map(cleanFolder)),\n ].sort();\n const stored = await readStoredBook(projectRoot);\n const previousFiles = stored?.manifest.files ?? {};\n const scan = await scanSourceRoots(projectRoot, sourceRoots, previousFiles);\n const version = grimoireVersion();\n\n // ── The fast path: nothing under the source roots (or the tests) changed. ──\n if (stored !== null && options.force !== true) {\n const { manifest, facts } = stored;\n const sameSetup =\n manifest.grimoireVersion === version &&\n manifest.adapter.name === adapter.name &&\n manifest.adapter.version === adapter.version &&\n manifest.sourceRoots.length === sourceRoots.length &&\n manifest.sourceRoots.every((folder, index) => folder === sourceRoots[index]);\n const sameFiles =\n sameSetup &&\n Object.keys(previousFiles).length === Object.keys(scan.files).length &&\n Object.entries(scan.files).every(([file, state]) => previousFiles[file]?.hash === state.hash);\n const sameTests =\n sameFiles &&\n sameRecord(\n manifest.tests,\n await hashFiles(projectRoot, Object.keys(manifest.tests), scan.files, sourceRoots),\n );\n\n if (sameTests) {\n const inputs = await hashFiles(\n projectRoot,\n Object.keys(manifest.boot.inputs),\n scan.files,\n sourceRoots,\n );\n let routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(manifest.boot, facts.routes, inputs)\n : \"missing\";\n let changedBook = false;\n\n if (mode === \"fresh\" && hasBootFacts(adapter) && routes !== \"fresh\") {\n // The stored input list can be older than the files (a cached rebuild keeps it): work it out again.\n const current = await hashFiles(\n projectRoot,\n await routeInputFiles(projectRoot, adapter, facts.files),\n scan.files,\n sourceRoots,\n );\n Object.assign(facts, await collectBootFacts(projectRoot, adapter));\n manifest.boot = { collectedAt: now().toISOString(), inputs: current };\n routes = \"fresh\";\n changedBook = true;\n }\n\n if (changedBook || scan.statMoved) {\n for (const [file, state] of Object.entries(scan.files)) {\n manifest.files[file] = { ...state, entry: manifest.files[file]?.entry ?? null };\n }\n\n if (changedBook) manifest.builtAt = now().toISOString();\n\n if (write) await writeStoredBook(projectRoot, manifest, changedBook ? facts : null);\n }\n\n return {\n book: { root: projectRoot, manifest, facts, routes },\n rebuilt: changedBook,\n changed: [],\n };\n }\n }\n\n // ── Rebuild the static facts. ──\n let files: BookFile[];\n\n try {\n files = normalizeFiles(await adapter.files(projectRoot));\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\n \"GR8001\",\n `The source files could not be read: ${(error as Error).message}`,\n );\n }\n\n let staticFacts: Omit<BookFacts, \"files\" | \"routes\" | \"named\">;\n\n try {\n staticFacts = {\n sites: adapter.sites ? normalizeSites(await adapter.sites(projectRoot)) : [],\n pages: adapter.pages ? normalizePages(await adapter.pages(projectRoot)) : [],\n mobile: adapter.mobile ? normalizeMobile(await adapter.mobile(projectRoot)) : [],\n tests: adapter.tests\n ? (await adapter.tests(projectRoot)).map(cleanPath)\n : files.filter((file) => file.type === \"spec\").map((file) => file.file),\n };\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\n \"GR8004\",\n `Pages or screens could not be read: ${(error as Error).message}`,\n );\n }\n\n staticFacts.tests = [...new Set(staticFacts.tests)].sort();\n\n const inputs = await hashFiles(\n projectRoot,\n await routeInputFiles(projectRoot, adapter, files),\n scan.files,\n sourceRoots,\n );\n const previousBoot = stored?.manifest.boot ?? { collectedAt: null, inputs: {} };\n let boot = previousBoot;\n let bootFacts: Pick<BookFacts, \"routes\" | \"named\"> = {\n routes: stored?.facts.routes ?? null,\n named: stored?.facts.named ?? [],\n };\n let routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(previousBoot, bootFacts.routes, inputs)\n : \"missing\";\n\n if (mode === \"fresh\" && hasBootFacts(adapter) && (routes !== \"fresh\" || options.force === true)) {\n bootFacts = await collectBootFacts(projectRoot, adapter);\n boot = { collectedAt: now().toISOString(), inputs };\n routes = \"fresh\";\n }\n\n const facts: BookFacts = { files, ...bootFacts, ...staticFacts };\n const entries = entryPathsFor(facts);\n const manifest: BookManifest = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n grimoireVersion: version,\n adapter: { name: adapter.name, version: adapter.version },\n builtAt: now().toISOString(),\n sourceRoots,\n files: Object.fromEntries(\n Object.entries(scan.files).map(([file, state]) => [\n file,\n { ...state, entry: entries.get(file) ?? null },\n ]),\n ),\n tests: await hashFiles(projectRoot, facts.tests, scan.files, sourceRoots),\n writtenHash: stored?.manifest.writtenHash ?? \"\",\n boot,\n };\n\n // A forced build rewrites every entry: forget what `writeBook` wrote.\n if (write) {\n if (options.force === true)\n await rm(absolutePath(projectRoot, WRITE_STATE_PATH), { force: true });\n\n await writeStoredBook(projectRoot, manifest, facts);\n }\n\n return {\n book: { root: projectRoot, manifest, facts, routes },\n rebuilt: true,\n changed: changedFiles(previousFiles, scan.files),\n };\n}\n\n/** Read the book from disk without calling an adapter; `null` when it was never built. */\nexport async function loadBook(root: string): Promise<LoadedBook | null> {\n const projectRoot = path.resolve(root);\n const stored = await readStoredBook(projectRoot);\n\n if (stored === null) return null;\n\n return {\n root: projectRoot,\n manifest: stored.manifest,\n facts: stored.facts,\n // Not checked against the sources here; `buildBook` tells fresh from stale.\n routes: stored.facts.routes === null ? \"missing\" : \"cached\",\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6CA,MAAa,mBAAmB,GAAG,eAAe,KAAK;AAEvD,IAAI,gBAA+B;;AAGnC,SAAgB,kBAA0B;CACxC,IAAI,kBAAkB,MAAM,OAAO;CAEnC,IAAI;EACF,MAAM,WAAW,KAAK,MACpB,aAAa,IAAI,IAAI,sBAAsB,YAAY,GAAG,GAAG,MAAM,CACrE;EAGA,gBAAgB,OAAO,SAAS,YAAY,WAAW,SAAS,UAAU;CAC5E,QAAQ;EACN,gBAAgB;CAClB;CAEA,OAAO;AACT;AAEA,MAAM,gBAAgB,MAAc,SAAyB,KAAK,KAAK,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC;AAI/F,eAAe,eAAe,MAA0C;CACtE,MAAM,WAAW,MAAM,SAAuB,aAAa,MAAM,eAAe,YAAY,CAAC;CAC7F,MAAM,QAAQ,MAAM,SAAyB,aAAa,MAAM,eAAe,cAAc,CAAC;CAE9F,IACE,aAAa,QACb,UAAU,QACV,SAAS,uBACT,MAAM,uBACN,OAAO,SAAS,UAAU,YAC1B,OAAO,MAAM,UAAU,UAEvB,OAAO;CAGT,OAAO;EAAE;EAAU,OAAO,MAAM;CAAM;AACxC;;AAUA,eAAe,gBACb,MACA,aACA,UACe;CACf,IAAI;CAEJ,IAAI;EACF,SAAS,MAAM,UAAU,MAAM,WAAW,EAAC,CAAE,OAAO,UAAU;CAChE,SAAS,OAAO;EACd,MAAM,IA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MAAM;EACN,UAAU,OAAO;EACjB,OAAO,OAAO;EAEd,QAAQ,OAAO,MAAM,WAAW,OAAO,YAAY;CACrD;AACF"}
|
|
1
|
+
{"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"sourcesContent":["/**\n * `buildBook` and `loadBook`: the freshness fingerprint, the facts cache and\n * the route (boot) cache. Entries are written by `writeBook` (write.ts).\n */\nimport { readFileSync } from \"node:fs\";\nimport { rm, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter, BookFacts, BookFile } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookFactsCache,\n type BookManifest,\n type BookManifestFile,\n type BuildBookOptions,\n type BuildBookResult,\n type LoadedBook,\n} from \"../contracts/book\";\nimport type { RouteFreshness } from \"../contracts/findings\";\nimport { GrimoireError } from \"../codes\";\nimport { importClosure, fileGraph } from \"../graph\";\nimport { GRIMOIRE_PATHS, isCodeFile, isInsideFolder } from \"../paths\";\nimport {\n cleanFolder,\n hashFile,\n hashIfExists,\n IO_CONCURRENCY,\n isMissing,\n listFiles,\n mapLimit,\n readJson,\n toJson,\n writeBookFile,\n} from \"./io\";\nimport {\n cleanPath,\n normalizeFiles,\n normalizeMobile,\n normalizeNamed,\n normalizePages,\n normalizeRoutes,\n normalizeSites,\n} from \"./normalize\";\nimport { entryPathsFor } from \"./render\";\n\n/** Where `writeBook` remembers what it wrote (see write.ts). */\nexport const WRITE_STATE_PATH = `${GRIMOIRE_PATHS.book}/.cache/written.json`;\n\nlet cachedVersion: string | null = null;\n\n/** The `@warlock.js/grimoire` version, from its package.json. */\nexport function grimoireVersion(): string {\n if (cachedVersion !== null) return cachedVersion;\n\n try {\n const manifest = JSON.parse(\n readFileSync(new URL(\"../../package.json\", import.meta.url), \"utf8\"),\n ) as {\n version?: unknown;\n };\n cachedVersion = typeof manifest.version === \"string\" ? manifest.version : \"0.0.0\";\n } catch {\n cachedVersion = \"0.0.0\";\n }\n\n return cachedVersion;\n}\n\nconst absolutePath = (root: string, file: string): string => path.join(root, ...file.split(\"/\"));\n\ntype StoredBook = { manifest: BookManifest; facts: BookFacts };\n\n/**\n * `facts.json` as written since type-only import edges were recorded. A cache\n * without the marker comes from an older version: it is not reused, so file\n * facts are scanned once more.\n */\ntype StoredFactsCache = BookFactsCache & { typeOnlyEdges?: boolean };\n\nasync function readStoredBook(root: string): Promise<StoredBook | null> {\n const manifest = await readJson<BookManifest>(absolutePath(root, GRIMOIRE_PATHS.bookManifest));\n const cache = await readJson<StoredFactsCache>(absolutePath(root, GRIMOIRE_PATHS.bookFactsCache));\n\n if (\n manifest === null ||\n cache === null ||\n manifest.schemaVersion !== BOOK_SCHEMA_VERSION ||\n cache.schemaVersion !== BOOK_SCHEMA_VERSION ||\n cache.typeOnlyEdges !== true ||\n typeof manifest.files !== \"object\" ||\n typeof cache.facts !== \"object\"\n ) {\n return null;\n }\n\n return { manifest, facts: cache.facts };\n}\n\n/** The current state of every code file under the source roots (images, fonts and certificates are not part of the book). */\ntype Scan = {\n files: Record<string, Omit<BookManifestFile, \"entry\">>;\n /** A file kept its hash but its size or mtime moved: the manifest needs the new stat. */\n statMoved: boolean;\n};\n\n/** Stat every code file; hash only those whose size or mtime differ from the previous manifest. */\nasync function scanSourceRoots(\n root: string,\n sourceRoots: readonly string[],\n previous: Record<string, BookManifestFile>,\n): Promise<Scan> {\n let files: string[];\n\n try {\n files = (await listFiles(root, sourceRoots)).filter(isCodeFile);\n } catch (error) {\n throw new GrimoireError(\n \"GR8001\",\n `The source roots could not be read: ${(error as Error).message}`,\n );\n }\n\n let statMoved = false;\n const states = await mapLimit(files, IO_CONCURRENCY, async (file) => {\n const absolute = absolutePath(root, file);\n\n try {\n const info = await stat(absolute);\n const before = previous[file];\n\n if (before !== undefined && before.size === info.size && before.mtimeMs === info.mtimeMs) {\n return { file, hash: before.hash, size: info.size, mtimeMs: info.mtimeMs };\n }\n\n const hash = await hashFile(absolute, info.size);\n\n if (before !== undefined && before.hash === hash) statMoved = true;\n\n return { file, hash, size: info.size, mtimeMs: info.mtimeMs };\n } catch (error) {\n // Deleted between the walk and the stat: treat it as gone.\n if (isMissing(error)) return null;\n throw new GrimoireError(\"GR8001\", `${file} could not be read: ${(error as Error).message}`);\n }\n });\n const result: Scan[\"files\"] = {};\n\n for (const state of states) {\n if (state !== null)\n result[state.file] = { hash: state.hash, size: state.size, mtimeMs: state.mtimeMs };\n }\n\n return { files: result, statMoved };\n}\n\n/** Hashes of the given files: from the scan when inside the source roots, else read (`\"\"` when missing). */\nasync function hashFiles(\n root: string,\n files: readonly string[],\n scan: Scan[\"files\"],\n sourceRoots: readonly string[],\n): Promise<Record<string, string>> {\n const hashes = await mapLimit([...new Set(files)].sort(), IO_CONCURRENCY, async (file) => {\n const scanned = scan[file];\n\n if (scanned !== undefined) return [file, scanned.hash] as const;\n // A code file inside a source root that the scan did not find is gone; any other input (a JSON config) is read.\n if (\n isCodeFile(file) &&\n sourceRoots.some((folder) => folder === \".\" || isInsideFolder(file, folder))\n )\n return [file, \"\"] as const;\n\n return [file, await hashIfExists(root, file)] as const;\n });\n\n return Object.fromEntries(hashes);\n}\n\nfunction sameRecord(left: Record<string, string>, right: Record<string, string>): boolean {\n const leftKeys = Object.keys(left);\n\n return (\n leftKeys.length === Object.keys(right).length &&\n leftKeys.every((key) => right[key] === left[key])\n );\n}\n\n/** Source files added, changed or removed between two manifests, sorted. */\nfunction changedFiles(\n previous: Record<string, BookManifestFile>,\n current: Scan[\"files\"],\n): string[] {\n const changed: string[] = [];\n\n for (const [file, state] of Object.entries(current)) {\n if (previous[file]?.hash !== state.hash) changed.push(file);\n }\n\n for (const file of Object.keys(previous)) {\n if (current[file] === undefined) changed.push(file);\n }\n\n return changed.sort();\n}\n\nconst NAMED_FILE_TYPES = new Set([\"mail\", \"job\", \"event\"]);\n\n/**\n * Files whose change makes the route cache stale: every `routes` file and\n * everything it imports, every `config` file, `warlock.config.ts`,\n * `package.json`, and every mail, job, event and notification file (the\n * named things are cached with the routes).\n */\nexport function defaultRouteInputs(files: readonly BookFile[]): string[] {\n const routesFiles = files.filter((file) => file.type === \"routes\").map((file) => file.file);\n const inputs = new Set(importClosure(fileGraph(files), routesFiles));\n\n for (const file of files) {\n if (\n file.type === \"config\" ||\n NAMED_FILE_TYPES.has(file.type) ||\n /\\.notification\\.[^/]+$/.test(file.file)\n ) {\n inputs.add(file.file);\n }\n }\n\n inputs.add(\"warlock.config.ts\");\n inputs.add(\"package.json\");\n\n return [...inputs].sort();\n}\n\n/** The route cache's input files: the adapter's list when it has one, else the default. */\nasync function routeInputFiles(\n root: string,\n adapter: BookAdapter,\n files: readonly BookFile[],\n): Promise<string[]> {\n return adapter.routeInputs\n ? (await adapter.routeInputs(root, files)).map(cleanPath)\n : defaultRouteInputs(files);\n}\n\nconst hasBootFacts = (adapter: BookAdapter): boolean =>\n typeof adapter.routes === \"function\" || typeof adapter.named === \"function\";\n\nasync function collectBootFacts(\n root: string,\n adapter: BookAdapter,\n): Promise<Pick<BookFacts, \"routes\" | \"named\">> {\n try {\n return {\n routes: adapter.routes ? normalizeRoutes(await adapter.routes(root)) : null,\n named: adapter.named ? normalizeNamed(await adapter.named(root)) : [],\n };\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\"GR8002\", `Route facts could not be read: ${(error as Error).message}`);\n }\n}\n\n/** How the stored route facts relate to the current inputs. */\nfunction bootState(\n boot: BookManifest[\"boot\"],\n routes: BookFacts[\"routes\"],\n inputs: Record<string, string>,\n): \"fresh\" | \"stale\" | \"missing\" {\n if (boot.collectedAt === null || routes === null) return \"missing\";\n\n return sameRecord(boot.inputs, inputs) ? \"fresh\" : \"stale\";\n}\n\nasync function writeStoredBook(\n root: string,\n manifest: BookManifest,\n facts: BookFacts | null,\n): Promise<void> {\n if (facts !== null) {\n const cache: StoredFactsCache = { schemaVersion: BOOK_SCHEMA_VERSION, typeOnlyEdges: true, facts };\n await writeBookFile(root, GRIMOIRE_PATHS.bookFactsCache, toJson(cache));\n }\n\n // The manifest last: a reader that sees it also sees the facts it describes.\n await writeBookFile(root, GRIMOIRE_PATHS.bookManifest, toJson(manifest));\n}\n\n/**\n * Bring the book's facts up to date and write `manifest.json` and\n * `.cache/facts.json`. Does not write entries (see `writeBook`).\n *\n * @param root Absolute project root.\n */\nexport async function buildBook(\n root: string,\n adapter: BookAdapter,\n options: BuildBookOptions = {},\n): Promise<BuildBookResult> {\n const projectRoot = path.resolve(root);\n const mode = options.routes ?? \"cached\";\n const now = options.now ?? (() => new Date());\n // `write: false` (passed by `openGrimoire({ write: false })`) computes in memory only.\n const write = options.write !== false;\n const sourceRoots = [\n ...new Set((await adapter.sourceRoots(projectRoot)).map(cleanFolder)),\n ].sort();\n const stored = await readStoredBook(projectRoot);\n const previousFiles = stored?.manifest.files ?? {};\n const scan = await scanSourceRoots(projectRoot, sourceRoots, previousFiles);\n const version = grimoireVersion();\n\n // ── The fast path: nothing under the source roots (or the tests) changed. ──\n if (stored !== null && options.force !== true) {\n const { manifest, facts } = stored;\n const sameSetup =\n manifest.grimoireVersion === version &&\n manifest.adapter.name === adapter.name &&\n manifest.adapter.version === adapter.version &&\n manifest.sourceRoots.length === sourceRoots.length &&\n manifest.sourceRoots.every((folder, index) => folder === sourceRoots[index]);\n const sameFiles =\n sameSetup &&\n Object.keys(previousFiles).length === Object.keys(scan.files).length &&\n Object.entries(scan.files).every(([file, state]) => previousFiles[file]?.hash === state.hash);\n const sameTests =\n sameFiles &&\n sameRecord(\n manifest.tests,\n await hashFiles(projectRoot, Object.keys(manifest.tests), scan.files, sourceRoots),\n );\n\n if (sameTests) {\n const inputs = await hashFiles(\n projectRoot,\n Object.keys(manifest.boot.inputs),\n scan.files,\n sourceRoots,\n );\n let routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(manifest.boot, facts.routes, inputs)\n : \"missing\";\n let changedBook = false;\n\n if (mode === \"fresh\" && hasBootFacts(adapter) && routes !== \"fresh\") {\n // The stored input list can be older than the files (a cached rebuild keeps it): work it out again.\n const current = await hashFiles(\n projectRoot,\n await routeInputFiles(projectRoot, adapter, facts.files),\n scan.files,\n sourceRoots,\n );\n Object.assign(facts, await collectBootFacts(projectRoot, adapter));\n manifest.boot = { collectedAt: now().toISOString(), inputs: current };\n routes = \"fresh\";\n changedBook = true;\n }\n\n if (changedBook || scan.statMoved) {\n for (const [file, state] of Object.entries(scan.files)) {\n manifest.files[file] = { ...state, entry: manifest.files[file]?.entry ?? null };\n }\n\n if (changedBook) manifest.builtAt = now().toISOString();\n\n if (write) await writeStoredBook(projectRoot, manifest, changedBook ? facts : null);\n }\n\n return {\n book: { root: projectRoot, manifest, facts, routes },\n rebuilt: changedBook,\n changed: [],\n };\n }\n }\n\n // ── Rebuild the static facts. ──\n let files: BookFile[];\n\n try {\n files = normalizeFiles(await adapter.files(projectRoot));\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\n \"GR8001\",\n `The source files could not be read: ${(error as Error).message}`,\n );\n }\n\n let staticFacts: Omit<BookFacts, \"files\" | \"routes\" | \"named\">;\n\n try {\n staticFacts = {\n sites: adapter.sites ? normalizeSites(await adapter.sites(projectRoot)) : [],\n pages: adapter.pages ? normalizePages(await adapter.pages(projectRoot)) : [],\n mobile: adapter.mobile ? normalizeMobile(await adapter.mobile(projectRoot)) : [],\n tests: adapter.tests\n ? (await adapter.tests(projectRoot)).map(cleanPath)\n : files.filter((file) => file.type === \"spec\").map((file) => file.file),\n };\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\n \"GR8004\",\n `Pages or screens could not be read: ${(error as Error).message}`,\n );\n }\n\n staticFacts.tests = [...new Set(staticFacts.tests)].sort();\n\n const inputs = await hashFiles(\n projectRoot,\n await routeInputFiles(projectRoot, adapter, files),\n scan.files,\n sourceRoots,\n );\n const previousBoot = stored?.manifest.boot ?? { collectedAt: null, inputs: {} };\n let boot = previousBoot;\n let bootFacts: Pick<BookFacts, \"routes\" | \"named\"> = {\n routes: stored?.facts.routes ?? null,\n named: stored?.facts.named ?? [],\n };\n let routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(previousBoot, bootFacts.routes, inputs)\n : \"missing\";\n\n if (mode === \"fresh\" && hasBootFacts(adapter) && (routes !== \"fresh\" || options.force === true)) {\n bootFacts = await collectBootFacts(projectRoot, adapter);\n boot = { collectedAt: now().toISOString(), inputs };\n routes = \"fresh\";\n }\n\n const facts: BookFacts = { files, ...bootFacts, ...staticFacts };\n const entries = entryPathsFor(facts);\n const manifest: BookManifest = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n grimoireVersion: version,\n adapter: { name: adapter.name, version: adapter.version },\n builtAt: now().toISOString(),\n sourceRoots,\n files: Object.fromEntries(\n Object.entries(scan.files).map(([file, state]) => [\n file,\n { ...state, entry: entries.get(file) ?? null },\n ]),\n ),\n tests: await hashFiles(projectRoot, facts.tests, scan.files, sourceRoots),\n writtenHash: stored?.manifest.writtenHash ?? \"\",\n boot,\n };\n\n // A forced build rewrites every entry: forget what `writeBook` wrote.\n if (write) {\n if (options.force === true)\n await rm(absolutePath(projectRoot, WRITE_STATE_PATH), { force: true });\n\n await writeStoredBook(projectRoot, manifest, facts);\n }\n\n return {\n book: { root: projectRoot, manifest, facts, routes },\n rebuilt: true,\n changed: changedFiles(previousFiles, scan.files),\n };\n}\n\n/** Read the book from disk without calling an adapter; `null` when it was never built. */\nexport async function loadBook(root: string): Promise<LoadedBook | null> {\n const projectRoot = path.resolve(root);\n const stored = await readStoredBook(projectRoot);\n\n if (stored === null) return null;\n\n return {\n root: projectRoot,\n manifest: stored.manifest,\n facts: stored.facts,\n // Not checked against the sources here; `buildBook` tells fresh from stale.\n routes: stored.facts.routes === null ? \"missing\" : \"cached\",\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6CA,MAAa,mBAAmB,GAAG,eAAe,KAAK;AAEvD,IAAI,gBAA+B;;AAGnC,SAAgB,kBAA0B;CACxC,IAAI,kB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jB,SAAS;GAAE,MAAM,QAAQ;GAAM,SAAS,QAAQ;EAAQ;EACxD,SAAS,IAAI,CAAC,CAAC,YAAY;EAC3B;EACA,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAChD,MACA;GAAE,GAAG;GAAO,OAAO,QAAQ,IAAI,IAAI,KAAK;EAAK,CAC/C,CAAC,CACH;EACA,OAAO,MAAM,UAAU,aAAa,MAAM,OAAO,KAAK,OAAO,WAAW;EACxE,aAAa,QAAQ,SAAS,eAAe;EAC7C;CACF;CAGA,IAAI,OAAO;EACT,IAAI,QAAQ,UAAU,MACpB,MAAM,GAAG,aAAa,aAAa,gBAAgB,GAAG,EAAE,OAAO,KAAK,CAAC;EAEvE,MAAM,gBAAgB,aAAa,UAAU,KAAK;CACpD;CAEA,OAAO;EACL,MAAM;GAAE,MAAM;GAAa;GAAU;GAAO;EAAO;EACnD,SAAS;EACT,SAAS,aAAa,eAAe,KAAK,KAAK;CACjD;AACF;;AAGA,eAAsB,SAAS,MAA0C;CACvE,MAAM,cAAc,KAAK,QAAQ,IAAI;CACrC,MAAM,SAAS,MAAM,eAAe,WAAW;CAE/C,IAAI,WAAW,MAAM,OAAO;CAE5B,OAAO;EACL,MAAM;EACN,UAAU,OAAO;EACjB,OAAO,OAAO;EAEd,QAAQ,OAAO,MAAM,WAAW,OAAO,YAAY;CACrD;AACF"}
|
package/esm/book/render.mjs
CHANGED
|
@@ -40,6 +40,15 @@ function routeRef(route) {
|
|
|
40
40
|
name: route.name
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
|
+
/** Project files whose every import edge from the file is type-only: sorted, unique. */
|
|
44
|
+
function typeOnlyImportsOf(file) {
|
|
45
|
+
const edges = /* @__PURE__ */ new Map();
|
|
46
|
+
for (const entry of file.imports) {
|
|
47
|
+
if (entry.file === null) continue;
|
|
48
|
+
edges.set(entry.file, (edges.get(entry.file) ?? true) && entry.typeOnly === true);
|
|
49
|
+
}
|
|
50
|
+
return [...edges].flatMap(([target, typeOnly]) => typeOnly ? [target] : []).sort(byText);
|
|
51
|
+
}
|
|
43
52
|
/** External package names a file imports: sorted, unique, Node builtins left out. */
|
|
44
53
|
function packagesOf(file) {
|
|
45
54
|
const names = /* @__PURE__ */ new Set();
|
|
@@ -123,6 +132,7 @@ function buildEntries(facts, annotations) {
|
|
|
123
132
|
})),
|
|
124
133
|
packages: packagesOf(file),
|
|
125
134
|
imports: [...new Set(file.imports.flatMap((entry) => entry.file === null ? [] : [entry.file]))].sort(byText),
|
|
135
|
+
typeOnlyImports: typeOnlyImportsOf(file),
|
|
126
136
|
importedBy: [...new Set(file.importedBy)].sort(byText),
|
|
127
137
|
routes: fileRoutes,
|
|
128
138
|
pages: (pages.get(file.file) ?? []).sort((left, right) => byText(left.site, right.site) || byText(left.route, right.route) || byText(left.via, right.via)),
|
package/esm/book/render.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/render.ts"],"sourcesContent":["/**\n * Turns facts and annotations into the content of every book file: the\n * per-file entries, the module summaries, `app/routes.json` and the page and\n * screen lists. Pure: no IO, so a spec can build inputs by hand.\n */\nimport { isBuiltin } from \"node:module\";\nimport path from \"node:path\";\nimport type { BookFacts, BookFile, BookRoute } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookAnnotations,\n type BookEntry,\n type BookMobileScreensFile,\n type BookModuleSummary,\n type BookRouteRef,\n type BookRoutesFile,\n type BookSitePagesFile,\n} from \"../contracts/book\";\nimport { packageNameOf } from \"../graph\";\nimport {\n bookEntryPaths,\n GRIMOIRE_PATHS,\n isInsideFolder,\n mobileScreensPath,\n moduleSummaryPath,\n sitePagesPath,\n} from \"../paths\";\nimport { isInsideBook, toJson } from \"./io\";\n\n/** Key of `BookRoutesFile.modules` for routes with no routes file. */\nexport const NO_MODULE = \"(none)\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\n\n/**\n * Book entry path of every code file in the facts. A file whose mirror would\n * leave `grimoire/book/` (a path with `..`) has no entry.\n */\nexport function entryPathsFor(facts: Pick<BookFacts, \"files\" | \"mobile\">): Map<string, string> {\n const mobileRoots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((file) => {\n const mobileRoot = file.mobileApp === null ? undefined : mobileRoots.get(file.mobileApp);\n\n return {\n file: file.file,\n mobileApp:\n file.mobileApp === null || mobileRoot === undefined\n ? null\n : { id: file.mobileApp, root: mobileRoot },\n };\n }),\n );\n\n for (const [file, entry] of paths) {\n if (!isInsideBook(entry)) paths.delete(file);\n }\n\n return paths;\n}\n\nfunction routeRef(route: BookRoute): BookRouteRef {\n return { method: route.method, path: route.path, name: route.name };\n}\n\n/** External package names a file imports: sorted, unique, Node builtins left out. */\nexport function packagesOf(file: BookFile): string[] {\n const names = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file !== null) continue;\n\n const name = packageNameOf(entry.specifier);\n\n if (name !== null && !isBuiltin(name)) names.add(name);\n }\n\n return [...names].sort(byText);\n}\n\n/** Lists indexed by a key, built once so lookups per file stay constant time. */\nfunction groupBy<T>(items: Iterable<readonly [string | null, T]>): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n\n for (const [key, item] of items) {\n if (key === null) continue;\n\n const group = groups.get(key);\n\n if (group) group.push(item);\n else groups.set(key, [item]);\n }\n\n return groups;\n}\n\ntype PageUse = {\n readonly site: string;\n readonly route: string;\n readonly via: \"page\" | \"setup\" | \"layout\";\n};\ntype ScreenUse = {\n readonly app: string;\n readonly route: string;\n readonly via: \"screen\" | \"layout\";\n};\n\nconst NO_ANNOTATION = { feature: null, borrowedBy: [], flows: [] } as const;\n\n/** The entry of every code file, by source file. */\nexport function buildEntries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): Map<string, BookEntry> {\n const routes = facts.routes ?? [];\n const registered = groupBy(routes.map((route) => [route.sourceFile, route] as const));\n const handled = groupBy(routes.map((route) => [route.handlerFile, route] as const));\n const pages = groupBy<PageUse>(\n facts.pages.flatMap((page): (readonly [string | null, PageUse])[] => [\n [page.file, { site: page.site, route: page.route, via: \"page\" as const }] as const,\n [page.setupFile, { site: page.site, route: page.route, via: \"setup\" as const }] as const,\n ...page.layouts.map(\n (layout) =>\n [layout, { site: page.site, route: page.route, via: \"layout\" as const }] as const,\n ),\n ]),\n );\n const screens = groupBy<ScreenUse>(\n facts.mobile.flatMap((app) =>\n app.screens.flatMap((screen): (readonly [string | null, ScreenUse])[] => [\n [screen.file, { app: app.id, route: screen.route, via: \"screen\" as const }] as const,\n ...screen.layouts.map(\n (layout) =>\n [layout, { app: app.id, route: screen.route, via: \"layout\" as const }] as const,\n ),\n ]),\n ),\n );\n const entries = new Map<string, BookEntry>();\n\n for (const file of facts.files) {\n const annotation = annotations.files[file.file] ?? NO_ANNOTATION;\n const fileRoutes: BookEntry[\"routes\"] = [\n ...(registered.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"registers\" as const,\n })),\n ...(handled.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"handles\" as const,\n })),\n ];\n\n entries.set(file.file, {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation.feature,\n borrowedBy: [...new Set(annotation.borrowedBy)].sort(byText),\n flows: [...new Set(annotation.flows)].sort(byText),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n packages: packagesOf(file),\n imports: [\n ...new Set(file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file]))),\n ].sort(byText),\n importedBy: [...new Set(file.importedBy)].sort(byText),\n routes: fileRoutes,\n pages: (pages.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: (screens.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n });\n }\n\n return entries;\n}\n\n/** `app/routes.json`: routes grouped by the module of their routes file, in registration order. */\nexport function buildRoutesFile(facts: BookFacts): BookRoutesFile | null {\n if (facts.routes === null) return null;\n\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const grouped = groupBy(\n facts.routes.map(\n (route) =>\n [\n route.sourceFile === null ? NO_MODULE : (moduleOf.get(route.sourceFile) ?? NO_MODULE),\n { ...routeRef(route), handlerFile: route.handlerFile },\n ] as const,\n ),\n );\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n modules: Object.fromEntries([...grouped].sort(([left], [right]) => byText(left, right))),\n };\n}\n\n/** One `BookModuleSummary` per `module` value of the code files, sorted by module. */\nexport function buildModuleSummaries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): BookModuleSummary[] {\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const byModule = groupBy(facts.files.map((file) => [file.module, file] as const));\n const routesByModule = groupBy(\n (facts.routes ?? []).map((route) => {\n const home = route.sourceFile ?? route.handlerFile;\n\n return [home === null ? null : (moduleOf.get(home) ?? null), routeRef(route)] as const;\n }),\n );\n const summaries: BookModuleSummary[] = [];\n\n for (const [module, files] of [...byModule].sort(([left], [right]) => byText(left, right))) {\n const featureCounts = new Map<string, number>();\n const importers = new Map<string, Set<string>>();\n\n for (const file of files) {\n const feature = annotations.files[file.file]?.feature ?? null;\n\n if (feature !== null) featureCounts.set(feature, (featureCounts.get(feature) ?? 0) + 1);\n\n for (const importer of file.importedBy) {\n const importerModule = moduleOf.get(importer);\n\n if (importerModule === undefined || importerModule === module) continue;\n\n const set = importers.get(importerModule) ?? new Set<string>();\n set.add(importer);\n importers.set(importerModule, set);\n }\n }\n\n summaries.push({\n module,\n features: [...featureCounts]\n .sort(([leftName, left], [rightName, right]) => right - left || byText(leftName, rightName))\n .map(([feature]) => feature),\n files: files\n .map((file) => ({ file: file.file, type: file.type, lines: file.lines, about: file.about }))\n .sort((left, right) => byText(left.file, right.file)),\n routes: routesByModule.get(module) ?? [],\n usedBy: [...importers]\n .map(([importer, set]) => ({ module: importer, files: set.size }))\n .sort((left, right) => right.files - left.files || byText(left.module, right.module)),\n });\n }\n\n return summaries;\n}\n\nconst plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** The Markdown of one module summary (format in `BookModuleSummary`). */\nexport function renderModuleSummary(summary: BookModuleSummary): string {\n const lines = summary.files.reduce((total, file) => total + file.lines, 0);\n const counts = `${plural(summary.files.length, \"file\")}, ${plural(lines, \"line\")}.`;\n const features =\n summary.features.length === 0\n ? \"\"\n : `${summary.features.length === 1 ? \"Feature\" : \"Features\"}: ${summary.features.join(\", \")}. `;\n const out = [`# ${summary.module}`, \"\", `${features}${counts}`];\n\n if (summary.files.length > 0) {\n out.push(\"\", \"## Files\");\n\n for (const file of summary.files) {\n const relative = isInsideFolder(file.file, summary.module)\n ? path.posix.relative(summary.module, file.file)\n : file.file;\n\n out.push(\n `- ${[relative, file.type, ...(file.about === null ? [] : [file.about])].join(\" \")}`,\n );\n }\n }\n\n if (summary.routes.length > 0) {\n out.push(\"\", \"## Routes\");\n\n for (const route of summary.routes) out.push(`- ${route.method} ${route.path}`);\n }\n\n if (summary.usedBy.length > 0) {\n out.push(\"\", \"## Used by\");\n\n for (const user of summary.usedBy) out.push(`- ${user.module} (${plural(user.files, \"file\")})`);\n }\n\n return `${out.join(\"\\n\")}\\n`;\n}\n\n/**\n * The content of every book file Warlock writes from the facts and the\n * annotations, by project-relative path. `manifest.json`, `.cache/` and\n * `test-results.json` are not part of it.\n */\nexport function renderBook(facts: BookFacts, annotations: BookAnnotations): Map<string, string> {\n const contents = new Map<string, string>();\n const entries = buildEntries(facts, annotations);\n\n for (const [file, entryPath] of entryPathsFor(facts)) {\n const entry = entries.get(file);\n\n if (entry !== undefined) contents.set(entryPath, toJson(entry));\n }\n\n for (const summary of buildModuleSummaries(facts, annotations)) {\n const summaryPath = moduleSummaryPath(summary.module);\n\n if (isInsideBook(summaryPath)) contents.set(summaryPath, renderModuleSummary(summary));\n }\n\n const routesFile = buildRoutesFile(facts);\n\n if (routesFile !== null) contents.set(GRIMOIRE_PATHS.bookRoutes, toJson(routesFile));\n\n for (const site of facts.sites) {\n const sitePath = sitePagesPath(site.id);\n const file: BookSitePagesFile = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n site,\n pages: facts.pages.filter((page) => page.site === site.id),\n };\n\n if (isInsideBook(sitePath)) contents.set(sitePath, toJson(file));\n }\n\n for (const app of facts.mobile) {\n const screensPath = mobileScreensPath(app.id);\n const { screens, ...rest } = app;\n const file: BookMobileScreensFile = { schemaVersion: BOOK_SCHEMA_VERSION, app: rest, screens };\n\n if (isInsideBook(screensPath)) contents.set(screensPath, toJson(file));\n }\n\n return contents;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAa,YAAY;AAEzB,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;;;;;AAMhG,SAAgB,cAAc,OAAiE;CAC7F,MAAM,cAAc,IAAI,IAAI,MAAM,OAAO,KAAK,QAAQ,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC;CACzE,MAAM,QAAQ,eACZ,MAAM,MAAM,KAAK,SAAS;EACxB,MAAM,aAAa,KAAK,cAAc,OAAO,SAAY,YAAY,IAAI,KAAK,SAAS;EAEvF,OAAO;GACL,MAAM,KAAK;GACX,WACE,KAAK,cAAc,QAAQ,eAAe,SACtC,OACA;IAAE,IAAI,KAAK;IAAW,MAAM;GAAW;EAC/C;CACF,CAAC,CACH;CAEA,KAAK,MAAM,CAAC,MAAM,UAAU,OAC1B,IAAI,CAAC,aAAa,KAAK,GAAG,MAAM,OAAO,IAAI;CAG7C,OAAO;AACT;AAEA,SAAS,SAAS,OAAgC;CAChD,OAAO;EAAE,QAAQ,M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aAAa,WAAW,GAAG,SAAS,IAAI,aAAa,OAAO,IAAI,CAAC;CACvE;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"render.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/render.ts"],"sourcesContent":["/**\n * Turns facts and annotations into the content of every book file: the\n * per-file entries, the module summaries, `app/routes.json` and the page and\n * screen lists. Pure: no IO, so a spec can build inputs by hand.\n */\nimport { isBuiltin } from \"node:module\";\nimport path from \"node:path\";\nimport type { BookFacts, BookFile, BookRoute } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookAnnotations,\n type BookEntry,\n type BookMobileScreensFile,\n type BookModuleSummary,\n type BookRouteRef,\n type BookRoutesFile,\n type BookSitePagesFile,\n} from \"../contracts/book\";\nimport { packageNameOf } from \"../graph\";\nimport {\n bookEntryPaths,\n GRIMOIRE_PATHS,\n isInsideFolder,\n mobileScreensPath,\n moduleSummaryPath,\n sitePagesPath,\n} from \"../paths\";\nimport { isInsideBook, toJson } from \"./io\";\n\n/** Key of `BookRoutesFile.modules` for routes with no routes file. */\nexport const NO_MODULE = \"(none)\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\n\n/**\n * Book entry path of every code file in the facts. A file whose mirror would\n * leave `grimoire/book/` (a path with `..`) has no entry.\n */\nexport function entryPathsFor(facts: Pick<BookFacts, \"files\" | \"mobile\">): Map<string, string> {\n const mobileRoots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((file) => {\n const mobileRoot = file.mobileApp === null ? undefined : mobileRoots.get(file.mobileApp);\n\n return {\n file: file.file,\n mobileApp:\n file.mobileApp === null || mobileRoot === undefined\n ? null\n : { id: file.mobileApp, root: mobileRoot },\n };\n }),\n );\n\n for (const [file, entry] of paths) {\n if (!isInsideBook(entry)) paths.delete(file);\n }\n\n return paths;\n}\n\nfunction routeRef(route: BookRoute): BookRouteRef {\n return { method: route.method, path: route.path, name: route.name };\n}\n\n/** Project files whose every import edge from the file is type-only: sorted, unique. */\nfunction typeOnlyImportsOf(file: BookFile): string[] {\n const edges = new Map<string, boolean>();\n\n for (const entry of file.imports) {\n if (entry.file === null) continue;\n edges.set(entry.file, (edges.get(entry.file) ?? true) && entry.typeOnly === true);\n }\n\n return [...edges].flatMap(([target, typeOnly]) => (typeOnly ? [target] : [])).sort(byText);\n}\n\n/** External package names a file imports: sorted, unique, Node builtins left out. */\nexport function packagesOf(file: BookFile): string[] {\n const names = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file !== null) continue;\n\n const name = packageNameOf(entry.specifier);\n\n if (name !== null && !isBuiltin(name)) names.add(name);\n }\n\n return [...names].sort(byText);\n}\n\n/** Lists indexed by a key, built once so lookups per file stay constant time. */\nfunction groupBy<T>(items: Iterable<readonly [string | null, T]>): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n\n for (const [key, item] of items) {\n if (key === null) continue;\n\n const group = groups.get(key);\n\n if (group) group.push(item);\n else groups.set(key, [item]);\n }\n\n return groups;\n}\n\ntype PageUse = {\n readonly site: string;\n readonly route: string;\n readonly via: \"page\" | \"setup\" | \"layout\";\n};\ntype ScreenUse = {\n readonly app: string;\n readonly route: string;\n readonly via: \"screen\" | \"layout\";\n};\n\nconst NO_ANNOTATION = { feature: null, borrowedBy: [], flows: [] } as const;\n\n/** The entry of every code file, by source file. */\nexport function buildEntries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): Map<string, BookEntry> {\n const routes = facts.routes ?? [];\n const registered = groupBy(routes.map((route) => [route.sourceFile, route] as const));\n const handled = groupBy(routes.map((route) => [route.handlerFile, route] as const));\n const pages = groupBy<PageUse>(\n facts.pages.flatMap((page): (readonly [string | null, PageUse])[] => [\n [page.file, { site: page.site, route: page.route, via: \"page\" as const }] as const,\n [page.setupFile, { site: page.site, route: page.route, via: \"setup\" as const }] as const,\n ...page.layouts.map(\n (layout) =>\n [layout, { site: page.site, route: page.route, via: \"layout\" as const }] as const,\n ),\n ]),\n );\n const screens = groupBy<ScreenUse>(\n facts.mobile.flatMap((app) =>\n app.screens.flatMap((screen): (readonly [string | null, ScreenUse])[] => [\n [screen.file, { app: app.id, route: screen.route, via: \"screen\" as const }] as const,\n ...screen.layouts.map(\n (layout) =>\n [layout, { app: app.id, route: screen.route, via: \"layout\" as const }] as const,\n ),\n ]),\n ),\n );\n const entries = new Map<string, BookEntry>();\n\n for (const file of facts.files) {\n const annotation = annotations.files[file.file] ?? NO_ANNOTATION;\n const fileRoutes: BookEntry[\"routes\"] = [\n ...(registered.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"registers\" as const,\n })),\n ...(handled.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"handles\" as const,\n })),\n ];\n\n entries.set(file.file, {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation.feature,\n borrowedBy: [...new Set(annotation.borrowedBy)].sort(byText),\n flows: [...new Set(annotation.flows)].sort(byText),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n packages: packagesOf(file),\n imports: [\n ...new Set(file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file]))),\n ].sort(byText),\n typeOnlyImports: typeOnlyImportsOf(file),\n importedBy: [...new Set(file.importedBy)].sort(byText),\n routes: fileRoutes,\n pages: (pages.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: (screens.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n });\n }\n\n return entries;\n}\n\n/** `app/routes.json`: routes grouped by the module of their routes file, in registration order. */\nexport function buildRoutesFile(facts: BookFacts): BookRoutesFile | null {\n if (facts.routes === null) return null;\n\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const grouped = groupBy(\n facts.routes.map(\n (route) =>\n [\n route.sourceFile === null ? NO_MODULE : (moduleOf.get(route.sourceFile) ?? NO_MODULE),\n { ...routeRef(route), handlerFile: route.handlerFile },\n ] as const,\n ),\n );\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n modules: Object.fromEntries([...grouped].sort(([left], [right]) => byText(left, right))),\n };\n}\n\n/** One `BookModuleSummary` per `module` value of the code files, sorted by module. */\nexport function buildModuleSummaries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): BookModuleSummary[] {\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const byModule = groupBy(facts.files.map((file) => [file.module, file] as const));\n const routesByModule = groupBy(\n (facts.routes ?? []).map((route) => {\n const home = route.sourceFile ?? route.handlerFile;\n\n return [home === null ? null : (moduleOf.get(home) ?? null), routeRef(route)] as const;\n }),\n );\n const summaries: BookModuleSummary[] = [];\n\n for (const [module, files] of [...byModule].sort(([left], [right]) => byText(left, right))) {\n const featureCounts = new Map<string, number>();\n const importers = new Map<string, Set<string>>();\n\n for (const file of files) {\n const feature = annotations.files[file.file]?.feature ?? null;\n\n if (feature !== null) featureCounts.set(feature, (featureCounts.get(feature) ?? 0) + 1);\n\n for (const importer of file.importedBy) {\n const importerModule = moduleOf.get(importer);\n\n if (importerModule === undefined || importerModule === module) continue;\n\n const set = importers.get(importerModule) ?? new Set<string>();\n set.add(importer);\n importers.set(importerModule, set);\n }\n }\n\n summaries.push({\n module,\n features: [...featureCounts]\n .sort(([leftName, left], [rightName, right]) => right - left || byText(leftName, rightName))\n .map(([feature]) => feature),\n files: files\n .map((file) => ({ file: file.file, type: file.type, lines: file.lines, about: file.about }))\n .sort((left, right) => byText(left.file, right.file)),\n routes: routesByModule.get(module) ?? [],\n usedBy: [...importers]\n .map(([importer, set]) => ({ module: importer, files: set.size }))\n .sort((left, right) => right.files - left.files || byText(left.module, right.module)),\n });\n }\n\n return summaries;\n}\n\nconst plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** The Markdown of one module summary (format in `BookModuleSummary`). */\nexport function renderModuleSummary(summary: BookModuleSummary): string {\n const lines = summary.files.reduce((total, file) => total + file.lines, 0);\n const counts = `${plural(summary.files.length, \"file\")}, ${plural(lines, \"line\")}.`;\n const features =\n summary.features.length === 0\n ? \"\"\n : `${summary.features.length === 1 ? \"Feature\" : \"Features\"}: ${summary.features.join(\", \")}. `;\n const out = [`# ${summary.module}`, \"\", `${features}${counts}`];\n\n if (summary.files.length > 0) {\n out.push(\"\", \"## Files\");\n\n for (const file of summary.files) {\n const relative = isInsideFolder(file.file, summary.module)\n ? path.posix.relative(summary.module, file.file)\n : file.file;\n\n out.push(\n `- ${[relative, file.type, ...(file.about === null ? [] : [file.about])].join(\" \")}`,\n );\n }\n }\n\n if (summary.routes.length > 0) {\n out.push(\"\", \"## Routes\");\n\n for (const route of summary.routes) out.push(`- ${route.method} ${route.path}`);\n }\n\n if (summary.usedBy.length > 0) {\n out.push(\"\", \"## Used by\");\n\n for (const user of summary.usedBy) out.push(`- ${user.module} (${plural(user.files, \"file\")})`);\n }\n\n return `${out.join(\"\\n\")}\\n`;\n}\n\n/**\n * The content of every book file Warlock writes from the facts and the\n * annotations, by project-relative path. `manifest.json`, `.cache/` and\n * `test-results.json` are not part of it.\n */\nexport function renderBook(facts: BookFacts, annotations: BookAnnotations): Map<string, string> {\n const contents = new Map<string, string>();\n const entries = buildEntries(facts, annotations);\n\n for (const [file, entryPath] of entryPathsFor(facts)) {\n const entry = entries.get(file);\n\n if (entry !== undefined) contents.set(entryPath, toJson(entry));\n }\n\n for (const summary of buildModuleSummaries(facts, annotations)) {\n const summaryPath = moduleSummaryPath(summary.module);\n\n if (isInsideBook(summaryPath)) contents.set(summaryPath, renderModuleSummary(summary));\n }\n\n const routesFile = buildRoutesFile(facts);\n\n if (routesFile !== null) contents.set(GRIMOIRE_PATHS.bookRoutes, toJson(routesFile));\n\n for (const site of facts.sites) {\n const sitePath = sitePagesPath(site.id);\n const file: BookSitePagesFile = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n site,\n pages: facts.pages.filter((page) => page.site === site.id),\n };\n\n if (isInsideBook(sitePath)) contents.set(sitePath, toJson(file));\n }\n\n for (const app of facts.mobile) {\n const screensPath = mobileScreensPath(app.id);\n const { screens, ...rest } = app;\n const file: BookMobileScreensFile = { schemaVersion: BOOK_SCHEMA_VERSION, app: rest, screens };\n\n if (isInsideBook(screensPath)) contents.set(screensPath, toJson(file));\n }\n\n return contents;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAa,YAAY;AAEzB,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;;;;;AAMhG,SAAgB,cAAc,OAAiE;CAC7F,MAAM,cAAc,IAAI,IAAI,MAAM,OAAO,KAAK,QAAQ,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC;CACzE,MAAM,QAAQ,eACZ,MAAM,MAAM,KAAK,SAAS;EACxB,MAAM,aAAa,KAAK,cAAc,OAAO,SAAY,YAAY,IAAI,KAAK,SAAS;EAEvF,OAAO;GACL,MAAM,KAAK;GACX,WACE,KAAK,cAAc,QAAQ,eAAe,SACtC,OACA;IAAE,IAAI,KAAK;IAAW,MAAM;GAAW;EAC/C;CACF,CAAC,CACH;CAEA,KAAK,MAAM,CAAC,MAAM,UAAU,OAC1B,IAAI,CAAC,aAAa,KAAK,GAAG,MAAM,OAAO,IAAI;CAG7C,OAAO;AACT;AAEA,SAAS,SAAS,OAAgC;CAChD,OAAO;EAAE,QAAQ,MAAM;EAAQ,MAAM,MAAM;EAAM,MAAM,MAAM;CAAK;AACpE;;AAGA,SAAS,kBAAkB,MAA0B;CACnD,MAAM,wBAAQ,IAAI,IAAqB;CAEvC,KAAK,MAAM,SAAS,KAAK,SAAS;EAChC,IAAI,MAAM,SAAS,MAAM;EACzB,MAAM,IAAI,MAAM,OAAO,MAAM,IAAI,MAAM,IAAI,KAAK,SA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,MAAM,cAAc,kBAAkB,IAAI,EAAE;EAC5C,MAAM,EAAE,SAAS,GAAG,SAAS;EAC7B,MAAM,OAA8B;GAAE;GAAoC,KAAK;GAAM;EAAQ;EAE7F,IAAI,aAAa,WAAW,GAAG,SAAS,IAAI,aAAa,OAAO,IAAI,CAAC;CACvE;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"mappings":";;;;;;;YA8BY;EACV,SAAS;EACT,OAAO;EACP,WAAW;EACX,MAAM,eAAe;EACrB,QAAQ;EACR,SAAS;;EAET,YAAY;;;
|
|
1
|
+
{"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"mappings":";;;;;;;YA8BY;EACV,SAAS;EACT,OAAO;EACP,WAAW;EACX,MAAM,eAAe;EACrB,QAAQ;EACR,SAAS;;EAET,YAAY;;;wBAiWE,oBAAoB,OAAO,iBAAiB"}
|
package/esm/bookmap/build.mjs
CHANGED
|
@@ -136,7 +136,7 @@ function featureBookmap(feature, flows, input, byPath) {
|
|
|
136
136
|
});
|
|
137
137
|
const sortedPages = {};
|
|
138
138
|
for (const app of Object.keys(pages).sort()) sortedPages[app] = (pages[app] ?? []).sort((left, right) => left.route.localeCompare(right.route) || left.file.localeCompare(right.file));
|
|
139
|
-
const reached = new Set(flows.flatMap((flow) => flow.steps.flatMap((step) => step.files)));
|
|
139
|
+
const reached = new Set(flows.flatMap((flow) => flow.steps.flatMap((step) => [...step.files, ...step.typeOnlyFiles])));
|
|
140
140
|
return {
|
|
141
141
|
schemaVersion: 1,
|
|
142
142
|
feature: feature.id,
|
|
@@ -246,7 +246,7 @@ function buildCollectedFiles(input) {
|
|
|
246
246
|
/** The per-file owner, borrowers and flows the book entries show. Pure. */
|
|
247
247
|
function annotationsFrom(input, collected, manifest) {
|
|
248
248
|
const flowsOf = /* @__PURE__ */ new Map();
|
|
249
|
-
for (const map of Object.values(collected.flows)) for (const step of map.steps) for (const file of step.files) {
|
|
249
|
+
for (const map of Object.values(collected.flows)) for (const step of map.steps) for (const file of [...step.files, ...step.typeOnlyFiles]) {
|
|
250
250
|
const set = flowsOf.get(file) ?? /* @__PURE__ */ new Set();
|
|
251
251
|
set.add(map.ref);
|
|
252
252
|
flowsOf.set(file, set);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"sourcesContent":["/**\n * Builds the book maps and the collected indexes in memory. Pure: reads only\n * its input.\n */\nimport type { BookFacts, BookFile } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookAnnotations, type BookManifest } from \"../contracts/book\";\nimport type {\n CollectedFiles,\n FeatureBookmap,\n FeaturesIndex,\n FlowBookmap,\n FlowBookmapCriterion,\n Ownership,\n TaskSummary,\n TasksIndex,\n} from \"../contracts/bookmap\";\nimport type { AppMatch } from \"../contracts/snapshot\";\nimport type { ProofLine, ProofResult, TestResultsStore } from \"../contracts/test-results\";\nimport type {\n WrittenFeature,\n WrittenFlow,\n WrittenGrimoire,\n WrittenTask,\n} from \"../contracts/written\";\nimport { fileGraph } from \"../graph\";\nimport { toPosixPath } from \"../paths\";\nimport { criterionStatus } from \"../test-results\";\nimport { resolveStep, type StepContext } from \"./steps\";\n\n/** Everything the book maps are computed from. */\nexport type CollectedInput = {\n written: WrittenGrimoire;\n facts: BookFacts;\n ownership: Ownership;\n apps: Record<string, AppMatch>;\n proofs: ProofLine[];\n results: TestResultsStore | null;\n /** Test file → current sha256 (a result with another hash is stale). */\n testHashes: Record<string, string>;\n};\n\n/** The file name of a flow without `.md`: the name of its book map. */\nexport function flowFileId(flow: WrittenFlow): string {\n const name = toPosixPath(flow.file).split(\"/\").pop() ?? flow.id.value;\n\n return name.endsWith(\".md\") ? name.slice(0, -3) : name;\n}\n\n// ── Flow book maps ─────────────────────────────────────────────────────────\n\n/**\n * The result recorded for the test a proof line points at: same file and\n * line, else (the test moved) same name among the results whose line no\n * proof of that file claims.\n */\nfunction resultFor(\n proof: ProofLine,\n line: number,\n results: readonly ProofResult[],\n claimedLines: ReadonlySet<string>,\n): ProofResult | null {\n const file = toPosixPath(proof.at.file);\n const sameProof = (result: ProofResult): boolean =>\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion;\n const inFile = results.filter((result) => toPosixPath(result.testFile) === file);\n const atLine = inFile.filter((result) => result.line === line);\n const byLine = atLine.find(sameProof) ?? atLine[0];\n\n if (byLine) return byLine;\n\n const name = proof.test?.name ?? null;\n\n if (name === null) return null;\n\n const named = inFile.filter(\n (result) =>\n !claimedLines.has(`${file}:${result.line}`) &&\n (result.testName === name || result.testName.endsWith(` > ${name}`)),\n );\n\n return named.find(sameProof) ?? named[0] ?? null;\n}\n\nfunction flowCriteria(flow: WrittenFlow, input: CollectedInput): FlowBookmapCriterion[] {\n const results = input.results?.results ?? [];\n const claimedLines = new Set(\n input.proofs.flatMap((proof) =>\n proof.test === null ? [] : [`${toPosixPath(proof.at.file)}:${proof.test.line}`],\n ),\n );\n\n return flow.criteria.map((criterion) => {\n const tests = input.proofs\n .filter(\n (proof) =>\n proof.ref === flow.ref && proof.criterion === criterion.id && proof.test !== null,\n )\n .map((proof) => {\n const line = proof.test?.line ?? proof.at.line;\n const file = toPosixPath(proof.at.file);\n const result = resultFor(proof, line, results, claimedLines);\n const currentHash = input.testHashes[file];\n const stale =\n result !== null && currentHash !== undefined && result.testFileHash !== currentHash;\n\n return {\n file,\n line,\n name: proof.test?.name ?? null,\n result: result?.outcome ?? (\"not-run\" as const),\n stale,\n };\n })\n .sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);\n\n return {\n id: criterion.id,\n app: criterion.app,\n text: criterion.text,\n tests,\n status: criterionStatus(tests),\n };\n });\n}\n\nfunction shownBy(flow: WrittenFlow, written: WrittenGrimoire): FlowBookmap[\"shownBy\"] {\n const shown: FlowBookmap[\"shownBy\"] = [];\n\n for (const app of written.apps) {\n const appId = app.id.value;\n\n for (const layout of app.layouts) {\n for (const row of layout.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: \"layout\",\n id: layout.id,\n block: row.block,\n file: layout.file,\n });\n }\n }\n }\n\n for (const page of [...app.pages, ...app.screens]) {\n for (const row of page.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: page.type,\n id: page.id,\n block: row.block,\n file: page.file,\n });\n }\n }\n }\n }\n\n return shown;\n}\n\nfunction flowBookmap(\n feature: WrittenFeature,\n flow: WrittenFlow,\n input: CollectedInput,\n context: StepContext,\n): FlowBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n flow: flowFileId(flow),\n ref: flow.ref,\n steps: flow.steps.map((step) => resolveStep(step, feature, context)),\n criteria: flowCriteria(flow, input),\n shownBy: shownBy(flow, input.written),\n };\n}\n\n// ── Feature book maps ──────────────────────────────────────────────────────\n\nfunction featureBookmap(\n feature: WrittenFeature,\n flows: readonly FlowBookmap[],\n input: CollectedInput,\n byPath: ReadonlyMap<string, BookFile>,\n): FeatureBookmap {\n const { ownership, facts } = input;\n const own = ownership.features[feature.id]?.own ?? [];\n const ownSet = new Set(own);\n\n // Own files importing each file, from one pass over the own files' imports (`own` is sorted, so each list is too).\n const importersOf = new Map<string, string[]>();\n\n for (const ownFile of own) {\n for (const entry of byPath.get(ownFile)?.imports ?? []) {\n if (entry.file === null) continue;\n\n const list = importersOf.get(entry.file) ?? [];\n\n if (list.at(-1) !== ownFile) list.push(ownFile);\n importersOf.set(entry.file, list);\n }\n }\n\n const borrowed: FeatureBookmap[\"borrowed\"] = (ownership.features[feature.id]?.borrowed ?? []).map(\n (file) => ({\n file,\n owner: ownership.files[file]?.owner ?? null,\n by: importersOf.get(file) ?? [],\n }),\n );\n\n const routes: FeatureBookmap[\"routes\"] = [];\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n const file =\n route.handlerFile !== null && ownSet.has(route.handlerFile)\n ? route.handlerFile\n : route.sourceFile !== null && ownSet.has(route.sourceFile)\n ? route.sourceFile\n : null;\n\n if (file !== null)\n routes.push({ method: route.method, path: route.path, name: route.name, file });\n }\n\n const pages: FeatureBookmap[\"pages\"] = {};\n const add = (app: string, item: FeatureBookmap[\"pages\"][string][number]): void => {\n (pages[app] ??= []).push(item);\n };\n const appOfSite = new Map<string, string>();\n const appOfMobile = new Map<string, string>();\n\n for (const match of Object.values(input.apps)) {\n if (match.site && !appOfSite.has(match.site.id)) appOfSite.set(match.site.id, match.app);\n if (match.mobile && !appOfMobile.has(match.mobile.id))\n appOfMobile.set(match.mobile.id, match.app);\n }\n\n for (const page of facts.pages) {\n const owned = ownSet.has(page.file) || (page.setupFile !== null && ownSet.has(page.setupFile));\n\n if (owned)\n add(appOfSite.get(page.site) ?? page.site, {\n route: page.route,\n file: page.file,\n type: \"page\",\n });\n }\n\n for (const mobile of facts.mobile) {\n for (const screen of mobile.screens) {\n if (ownSet.has(screen.file)) {\n add(appOfMobile.get(mobile.id) ?? mobile.id, {\n route: screen.route,\n file: screen.file,\n type: \"screen\",\n });\n }\n }\n }\n\n const sortedPages: FeatureBookmap[\"pages\"] = {};\n\n for (const app of Object.keys(pages).sort()) {\n sortedPages[app] = (pages[app] ?? []).sort(\n (left, right) => left.route.localeCompare(right.route) || left.file.localeCompare(right.file),\n );\n }\n\n const reached = new Set(flows.flatMap((flow) => flow.steps.flatMap((step) => step.files)));\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n own,\n borrowed,\n routes,\n pages: sortedPages,\n unreached: own.filter((file) => !reached.has(file)),\n };\n}\n\n// ── Indexes ────────────────────────────────────────────────────────────────\n\nfunction compareVersions(left: string, right: string): number {\n const [leftWhole = 0, leftDecimal = 0] = left.split(\".\").map(Number);\n const [rightWhole = 0, rightDecimal = 0] = right.split(\".\").map(Number);\n\n return leftWhole - rightWhole || leftDecimal - rightDecimal;\n}\n\nfunction featuresIndex(written: WrittenGrimoire): FeaturesIndex {\n const features: FeaturesIndex[\"features\"] = [];\n\n for (const feature of [...written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const readme = feature.readme;\n\n if (readme === null) continue;\n\n const releases = new Map<string, { version: string; release: string; date: string }>();\n\n for (const entry of feature.changelog?.entries ?? []) {\n if (entry.release === null || entry.date === null) continue;\n\n const version = entry.version.value;\n const known = releases.get(version);\n\n if (!known || entry.date > known.date) {\n releases.set(version, { version, release: entry.release, date: entry.date });\n }\n }\n\n features.push({\n id: feature.id,\n title: readme.title.value,\n status: readme.status.value,\n version: readme.version.value,\n updated: readme.updated.value,\n apps: readme.apps.map((app) => app.value),\n origin: readme.origin?.value ?? null,\n flows: feature.flows.map((flow) => ({\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n })),\n releases: [...releases.values()].sort(\n (left, right) =>\n right.date.localeCompare(left.date) || compareVersions(right.version, left.version),\n ),\n });\n }\n\n return { schemaVersion: BOOK_SCHEMA_VERSION, features };\n}\n\nfunction taskNumber(id: string): number {\n const match = /^T-(\\d+)$/.exec(id);\n\n return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;\n}\n\nfunction taskSummary(task: WrittenTask): TaskSummary {\n return {\n id: task.id.value,\n title: task.heading?.value ?? task.id.value,\n type: task.type.value,\n status: task.status.value,\n feature: task.feature?.value ?? null,\n flow: task.flow?.value ?? null,\n apps: task.apps.map((app) => app.value),\n file: task.file,\n shipped: task.shipped\n ? { feature: task.shipped.value.feature, version: task.shipped.value.version }\n : null,\n decisionNeeded: task.decisionNeeded,\n };\n}\n\nfunction tasksIndex(written: WrittenGrimoire): TasksIndex {\n const sorted = [...written.tasks].sort(\n (left, right) =>\n taskNumber(left.id.value) - taskNumber(right.id.value) ||\n left.id.value.localeCompare(right.id.value),\n );\n const open = sorted.filter((task) => task.folder === \"open\").map(taskSummary);\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n open,\n waiting: open.filter(\n (task) => task.status === \"waiting for approval\" || task.decisionNeeded !== null,\n ),\n done: sorted.filter((task) => task.folder === \"done\").map(taskSummary),\n };\n}\n\n// ── Public ─────────────────────────────────────────────────────────────────\n\n/** Every feature and flow book map, `features/index.json` and `tasks/index.json`. Pure. */\nexport function buildCollectedFiles(input: CollectedInput): CollectedFiles {\n const context: StepContext = {\n written: input.written,\n facts: input.facts,\n apps: input.apps,\n graph: fileGraph(input.facts.files),\n };\n const byPath = new Map(input.facts.files.map((file) => [file.file, file]));\n const features: CollectedFiles[\"features\"] = {};\n const flows: CollectedFiles[\"flows\"] = {};\n\n for (const feature of [...input.written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const maps = feature.flows.map((flow) => flowBookmap(feature, flow, input, context));\n\n for (const map of maps) flows[map.ref] = map;\n\n features[feature.id] = featureBookmap(feature, maps, input, byPath);\n }\n\n return {\n features,\n flows,\n featuresIndex: featuresIndex(input.written),\n tasksIndex: tasksIndex(input.written),\n };\n}\n\n/** The per-file owner, borrowers and flows the book entries show. Pure. */\nexport function annotationsFrom(\n input: CollectedInput,\n collected: CollectedFiles,\n manifest: Pick<BookManifest, \"tests\">,\n): BookAnnotations {\n const flowsOf = new Map<string, Set<string>>();\n\n for (const map of Object.values(collected.flows)) {\n for (const step of map.steps) {\n for (const file of step.files) {\n const set = flowsOf.get(file) ?? new Set<string>();\n set.add(map.ref);\n flowsOf.set(file, set);\n }\n }\n }\n\n const files: BookAnnotations[\"files\"] = {};\n\n for (const file of input.facts.files) {\n const ownership = input.ownership.files[file.file];\n\n files[file.file] = {\n feature: ownership?.owner ?? null,\n borrowedBy: [...(ownership?.borrowedBy ?? [])],\n flows: [...(flowsOf.get(file.file) ?? [])].sort(),\n };\n }\n\n return { writtenHash: input.written.hash, tests: { ...manifest.tests }, files };\n}\n"],"mappings":";;;;;;;;;AA0CA,SAAgB,WAAW,MAA2B;CACpD,MAAM,OA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KAAK;EAClD;CACF;CAEA,OAAO;EAAE,aAAa,MAAM,QAAQ;EAAM,OAAO,EAAE,GAAG,SAAS,MAAM;EAAG;CAAM;AAChF"}
|
|
1
|
+
{"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"sourcesContent":["/**\n * Builds the book maps and the collected indexes in memory. Pure: reads only\n * its input.\n */\nimport type { BookFacts, BookFile } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookAnnotations, type BookManifest } from \"../contracts/book\";\nimport type {\n CollectedFiles,\n FeatureBookmap,\n FeaturesIndex,\n FlowBookmap,\n FlowBookmapCriterion,\n Ownership,\n TaskSummary,\n TasksIndex,\n} from \"../contracts/bookmap\";\nimport type { AppMatch } from \"../contracts/snapshot\";\nimport type { ProofLine, ProofResult, TestResultsStore } from \"../contracts/test-results\";\nimport type {\n WrittenFeature,\n WrittenFlow,\n WrittenGrimoire,\n WrittenTask,\n} from \"../contracts/written\";\nimport { fileGraph } from \"../graph\";\nimport { toPosixPath } from \"../paths\";\nimport { criterionStatus } from \"../test-results\";\nimport { resolveStep, type StepContext } from \"./steps\";\n\n/** Everything the book maps are computed from. */\nexport type CollectedInput = {\n written: WrittenGrimoire;\n facts: BookFacts;\n ownership: Ownership;\n apps: Record<string, AppMatch>;\n proofs: ProofLine[];\n results: TestResultsStore | null;\n /** Test file → current sha256 (a result with another hash is stale). */\n testHashes: Record<string, string>;\n};\n\n/** The file name of a flow without `.md`: the name of its book map. */\nexport function flowFileId(flow: WrittenFlow): string {\n const name = toPosixPath(flow.file).split(\"/\").pop() ?? flow.id.value;\n\n return name.endsWith(\".md\") ? name.slice(0, -3) : name;\n}\n\n// ── Flow book maps ─────────────────────────────────────────────────────────\n\n/**\n * The result recorded for the test a proof line points at: same file and\n * line, else (the test moved) same name among the results whose line no\n * proof of that file claims.\n */\nfunction resultFor(\n proof: ProofLine,\n line: number,\n results: readonly ProofResult[],\n claimedLines: ReadonlySet<string>,\n): ProofResult | null {\n const file = toPosixPath(proof.at.file);\n const sameProof = (result: ProofResult): boolean =>\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion;\n const inFile = results.filter((result) => toPosixPath(result.testFile) === file);\n const atLine = inFile.filter((result) => result.line === line);\n const byLine = atLine.find(sameProof) ?? atLine[0];\n\n if (byLine) return byLine;\n\n const name = proof.test?.name ?? null;\n\n if (name === null) return null;\n\n const named = inFile.filter(\n (result) =>\n !claimedLines.has(`${file}:${result.line}`) &&\n (result.testName === name || result.testName.endsWith(` > ${name}`)),\n );\n\n return named.find(sameProof) ?? named[0] ?? null;\n}\n\nfunction flowCriteria(flow: WrittenFlow, input: CollectedInput): FlowBookmapCriterion[] {\n const results = input.results?.results ?? [];\n const claimedLines = new Set(\n input.proofs.flatMap((proof) =>\n proof.test === null ? [] : [`${toPosixPath(proof.at.file)}:${proof.test.line}`],\n ),\n );\n\n return flow.criteria.map((criterion) => {\n const tests = input.proofs\n .filter(\n (proof) =>\n proof.ref === flow.ref && proof.criterion === criterion.id && proof.test !== null,\n )\n .map((proof) => {\n const line = proof.test?.line ?? proof.at.line;\n const file = toPosixPath(proof.at.file);\n const result = resultFor(proof, line, results, claimedLines);\n const currentHash = input.testHashes[file];\n const stale =\n result !== null && currentHash !== undefined && result.testFileHash !== currentHash;\n\n return {\n file,\n line,\n name: proof.test?.name ?? null,\n result: result?.outcome ?? (\"not-run\" as const),\n stale,\n };\n })\n .sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);\n\n return {\n id: criterion.id,\n app: criterion.app,\n text: criterion.text,\n tests,\n status: criterionStatus(tests),\n };\n });\n}\n\nfunction shownBy(flow: WrittenFlow, written: WrittenGrimoire): FlowBookmap[\"shownBy\"] {\n const shown: FlowBookmap[\"shownBy\"] = [];\n\n for (const app of written.apps) {\n const appId = app.id.value;\n\n for (const layout of app.layouts) {\n for (const row of layout.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: \"layout\",\n id: layout.id,\n block: row.block,\n file: layout.file,\n });\n }\n }\n }\n\n for (const page of [...app.pages, ...app.screens]) {\n for (const row of page.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: page.type,\n id: page.id,\n block: row.block,\n file: page.file,\n });\n }\n }\n }\n }\n\n return shown;\n}\n\nfunction flowBookmap(\n feature: WrittenFeature,\n flow: WrittenFlow,\n input: CollectedInput,\n context: StepContext,\n): FlowBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n flow: flowFileId(flow),\n ref: flow.ref,\n steps: flow.steps.map((step) => resolveStep(step, feature, context)),\n criteria: flowCriteria(flow, input),\n shownBy: shownBy(flow, input.written),\n };\n}\n\n// ── Feature book maps ──────────────────────────────────────────────────────\n\nfunction featureBookmap(\n feature: WrittenFeature,\n flows: readonly FlowBookmap[],\n input: CollectedInput,\n byPath: ReadonlyMap<string, BookFile>,\n): FeatureBookmap {\n const { ownership, facts } = input;\n const own = ownership.features[feature.id]?.own ?? [];\n const ownSet = new Set(own);\n\n // Own files importing each file, from one pass over the own files' imports (`own` is sorted, so each list is too).\n const importersOf = new Map<string, string[]>();\n\n for (const ownFile of own) {\n for (const entry of byPath.get(ownFile)?.imports ?? []) {\n if (entry.file === null) continue;\n\n const list = importersOf.get(entry.file) ?? [];\n\n if (list.at(-1) !== ownFile) list.push(ownFile);\n importersOf.set(entry.file, list);\n }\n }\n\n const borrowed: FeatureBookmap[\"borrowed\"] = (ownership.features[feature.id]?.borrowed ?? []).map(\n (file) => ({\n file,\n owner: ownership.files[file]?.owner ?? null,\n by: importersOf.get(file) ?? [],\n }),\n );\n\n const routes: FeatureBookmap[\"routes\"] = [];\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n const file =\n route.handlerFile !== null && ownSet.has(route.handlerFile)\n ? route.handlerFile\n : route.sourceFile !== null && ownSet.has(route.sourceFile)\n ? route.sourceFile\n : null;\n\n if (file !== null)\n routes.push({ method: route.method, path: route.path, name: route.name, file });\n }\n\n const pages: FeatureBookmap[\"pages\"] = {};\n const add = (app: string, item: FeatureBookmap[\"pages\"][string][number]): void => {\n (pages[app] ??= []).push(item);\n };\n const appOfSite = new Map<string, string>();\n const appOfMobile = new Map<string, string>();\n\n for (const match of Object.values(input.apps)) {\n if (match.site && !appOfSite.has(match.site.id)) appOfSite.set(match.site.id, match.app);\n if (match.mobile && !appOfMobile.has(match.mobile.id))\n appOfMobile.set(match.mobile.id, match.app);\n }\n\n for (const page of facts.pages) {\n const owned = ownSet.has(page.file) || (page.setupFile !== null && ownSet.has(page.setupFile));\n\n if (owned)\n add(appOfSite.get(page.site) ?? page.site, {\n route: page.route,\n file: page.file,\n type: \"page\",\n });\n }\n\n for (const mobile of facts.mobile) {\n for (const screen of mobile.screens) {\n if (ownSet.has(screen.file)) {\n add(appOfMobile.get(mobile.id) ?? mobile.id, {\n route: screen.route,\n file: screen.file,\n type: \"screen\",\n });\n }\n }\n }\n\n const sortedPages: FeatureBookmap[\"pages\"] = {};\n\n for (const app of Object.keys(pages).sort()) {\n sortedPages[app] = (pages[app] ?? []).sort(\n (left, right) => left.route.localeCompare(right.route) || left.file.localeCompare(right.file),\n );\n }\n\n // Ownership coverage (GR3006) counts type-only reach too.\n const reached = new Set(\n flows.flatMap((flow) => flow.steps.flatMap((step) => [...step.files, ...step.typeOnlyFiles])),\n );\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n own,\n borrowed,\n routes,\n pages: sortedPages,\n unreached: own.filter((file) => !reached.has(file)),\n };\n}\n\n// ── Indexes ────────────────────────────────────────────────────────────────\n\nfunction compareVersions(left: string, right: string): number {\n const [leftWhole = 0, leftDecimal = 0] = left.split(\".\").map(Number);\n const [rightWhole = 0, rightDecimal = 0] = right.split(\".\").map(Number);\n\n return leftWhole - rightWhole || leftDecimal - rightDecimal;\n}\n\nfunction featuresIndex(written: WrittenGrimoire): FeaturesIndex {\n const features: FeaturesIndex[\"features\"] = [];\n\n for (const feature of [...written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const readme = feature.readme;\n\n if (readme === null) continue;\n\n const releases = new Map<string, { version: string; release: string; date: string }>();\n\n for (const entry of feature.changelog?.entries ?? []) {\n if (entry.release === null || entry.date === null) continue;\n\n const version = entry.version.value;\n const known = releases.get(version);\n\n if (!known || entry.date > known.date) {\n releases.set(version, { version, release: entry.release, date: entry.date });\n }\n }\n\n features.push({\n id: feature.id,\n title: readme.title.value,\n status: readme.status.value,\n version: readme.version.value,\n updated: readme.updated.value,\n apps: readme.apps.map((app) => app.value),\n origin: readme.origin?.value ?? null,\n flows: feature.flows.map((flow) => ({\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n })),\n releases: [...releases.values()].sort(\n (left, right) =>\n right.date.localeCompare(left.date) || compareVersions(right.version, left.version),\n ),\n });\n }\n\n return { schemaVersion: BOOK_SCHEMA_VERSION, features };\n}\n\nfunction taskNumber(id: string): number {\n const match = /^T-(\\d+)$/.exec(id);\n\n return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;\n}\n\nfunction taskSummary(task: WrittenTask): TaskSummary {\n return {\n id: task.id.value,\n title: task.heading?.value ?? task.id.value,\n type: task.type.value,\n status: task.status.value,\n feature: task.feature?.value ?? null,\n flow: task.flow?.value ?? null,\n apps: task.apps.map((app) => app.value),\n file: task.file,\n shipped: task.shipped\n ? { feature: task.shipped.value.feature, version: task.shipped.value.version }\n : null,\n decisionNeeded: task.decisionNeeded,\n };\n}\n\nfunction tasksIndex(written: WrittenGrimoire): TasksIndex {\n const sorted = [...written.tasks].sort(\n (left, right) =>\n taskNumber(left.id.value) - taskNumber(right.id.value) ||\n left.id.value.localeCompare(right.id.value),\n );\n const open = sorted.filter((task) => task.folder === \"open\").map(taskSummary);\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n open,\n waiting: open.filter(\n (task) => task.status === \"waiting for approval\" || task.decisionNeeded !== null,\n ),\n done: sorted.filter((task) => task.folder === \"done\").map(taskSummary),\n };\n}\n\n// ── Public ─────────────────────────────────────────────────────────────────\n\n/** Every feature and flow book map, `features/index.json` and `tasks/index.json`. Pure. */\nexport function buildCollectedFiles(input: CollectedInput): CollectedFiles {\n const context: StepContext = {\n written: input.written,\n facts: input.facts,\n apps: input.apps,\n graph: fileGraph(input.facts.files),\n };\n const byPath = new Map(input.facts.files.map((file) => [file.file, file]));\n const features: CollectedFiles[\"features\"] = {};\n const flows: CollectedFiles[\"flows\"] = {};\n\n for (const feature of [...input.written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const maps = feature.flows.map((flow) => flowBookmap(feature, flow, input, context));\n\n for (const map of maps) flows[map.ref] = map;\n\n features[feature.id] = featureBookmap(feature, maps, input, byPath);\n }\n\n return {\n features,\n flows,\n featuresIndex: featuresIndex(input.written),\n tasksIndex: tasksIndex(input.written),\n };\n}\n\n/** The per-file owner, borrowers and flows the book entries show. Pure. */\nexport function annotationsFrom(\n input: CollectedInput,\n collected: CollectedFiles,\n manifest: Pick<BookManifest, \"tests\">,\n): BookAnnotations {\n const flowsOf = new Map<string, Set<string>>();\n\n for (const map of Object.values(collected.flows)) {\n for (const step of map.steps) {\n for (const file of [...step.files, ...step.typeOnlyFiles]) {\n const set = flowsOf.get(file) ?? new Set<string>();\n set.add(map.ref);\n flowsOf.set(file, set);\n }\n }\n }\n\n const files: BookAnnotations[\"files\"] = {};\n\n for (const file of input.facts.files) {\n const ownership = input.ownership.files[file.file];\n\n files[file.file] = {\n feature: ownership?.owner ?? null,\n borrowedBy: [...(ownership?.borrowedBy ?? [])],\n flows: [...(flowsOf.get(file.file) ?? [])].sort(),\n };\n }\n\n return { writtenHash: input.written.hash, tests: { ...manifest.tests }, files };\n}\n"],"mappings":";;;;;;;;;AA0CA,SAAgB,WAAW,MAA2B;CACpD,MAAM,OAAO,YAAY,KAAK,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,KAAK,GAAG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D;CACF;CAEA,OAAO;EAAE,aAAa,MAAM,QAAQ;EAAM,OAAO,EAAE,GAAG,SAAS,MAAM;EAAG;CAAM;AAChF"}
|
package/esm/bookmap/steps.mjs
CHANGED
|
@@ -29,33 +29,59 @@ function sortedUnique(files) {
|
|
|
29
29
|
const NOTHING = {
|
|
30
30
|
found: false,
|
|
31
31
|
entry: null,
|
|
32
|
-
|
|
32
|
+
entries: [],
|
|
33
|
+
direct: [],
|
|
34
|
+
files: [],
|
|
35
|
+
typeOnlyFiles: []
|
|
33
36
|
};
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
const UNKNOWN = {
|
|
38
|
+
...NOTHING,
|
|
39
|
+
found: null
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Work out a step's files from its entry files. `extra` are files that belong
|
|
43
|
+
* to the step without being imported by an entry (a route's routes file).
|
|
44
|
+
*/
|
|
45
|
+
function reach(graph, entries, extra = []) {
|
|
46
|
+
const entryFiles = sortedUnique(entries);
|
|
47
|
+
const known = new Set(entryFiles);
|
|
48
|
+
const direct = /* @__PURE__ */ new Set();
|
|
49
|
+
for (const entry of entryFiles) for (const edge of graph.get(entry)?.imports ?? []) if (edge.file !== null && !known.has(edge.file)) direct.add(edge.file);
|
|
50
|
+
const files = /* @__PURE__ */ new Set([
|
|
51
|
+
...entryFiles,
|
|
52
|
+
...extra,
|
|
53
|
+
...importClosure(graph, entryFiles, { skipTypeOnly: true })
|
|
54
|
+
]);
|
|
55
|
+
const everything = importClosure(graph, entryFiles);
|
|
56
|
+
return {
|
|
57
|
+
entries: entryFiles,
|
|
58
|
+
direct: sortedUnique(direct),
|
|
59
|
+
files: sortedUnique(files),
|
|
60
|
+
typeOnlyFiles: everything.filter((file) => !files.has(file))
|
|
39
61
|
};
|
|
62
|
+
}
|
|
63
|
+
function routeStep(step, facts, graph) {
|
|
64
|
+
if (facts.routes === null || step.route === null) return UNKNOWN;
|
|
40
65
|
const target = step.route;
|
|
41
66
|
const routes = facts.routes.filter((route) => routeMatches(route, target.method, target.path));
|
|
42
67
|
const first = routes[0];
|
|
43
68
|
if (!first) return NOTHING;
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}
|
|
69
|
+
const handlers = routes.flatMap((route) => route.handlerFile === null ? [] : [route.handlerFile]);
|
|
70
|
+
const sources = routes.flatMap((route) => route.sourceFile === null ? [] : [route.sourceFile]);
|
|
71
|
+
const handlerReach = reach(graph, handlers, sources);
|
|
72
|
+
const entries = sortedUnique([...handlers, ...sources]);
|
|
49
73
|
return {
|
|
50
74
|
found: true,
|
|
51
75
|
entry: first.handlerFile ?? first.sourceFile,
|
|
52
|
-
|
|
76
|
+
...handlerReach,
|
|
77
|
+
entries,
|
|
78
|
+
direct: handlerReach.direct.filter((file) => !entries.includes(file))
|
|
53
79
|
};
|
|
54
80
|
}
|
|
55
81
|
function pageStep(step, feature, facts, apps, graph) {
|
|
56
82
|
const wanted = normalizeRoutePath(step.target);
|
|
57
|
-
const
|
|
58
|
-
const
|
|
83
|
+
const matched = [];
|
|
84
|
+
const starts = [];
|
|
59
85
|
const appIds = step.app === null ? feature.readme?.apps.map((app) => app.value) ?? [] : [step.app];
|
|
60
86
|
for (const appId of appIds) {
|
|
61
87
|
const match = apps[appId];
|
|
@@ -64,51 +90,44 @@ function pageStep(step, feature, facts, apps, graph) {
|
|
|
64
90
|
const siteId = match.site.id;
|
|
65
91
|
for (const page of facts.pages) {
|
|
66
92
|
if (page.site !== siteId || normalizeRoutePath(page.route) !== wanted) continue;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
start.forEach((file) => files.add(file));
|
|
93
|
+
matched.push(page.file);
|
|
94
|
+
starts.push(page.file);
|
|
95
|
+
if (page.setupFile !== null) starts.push(page.setupFile);
|
|
71
96
|
}
|
|
72
97
|
}
|
|
73
98
|
if (match.mobile) for (const screen of match.mobile.screens) {
|
|
74
99
|
if (normalizeRoutePath(screen.route) !== wanted) continue;
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
files.add(screen.file);
|
|
100
|
+
matched.push(screen.file);
|
|
101
|
+
starts.push(screen.file);
|
|
78
102
|
}
|
|
79
103
|
}
|
|
80
|
-
const entry =
|
|
104
|
+
const entry = matched[0];
|
|
81
105
|
if (entry === void 0) return NOTHING;
|
|
82
106
|
return {
|
|
83
107
|
found: true,
|
|
84
108
|
entry,
|
|
85
|
-
|
|
109
|
+
...reach(graph, starts)
|
|
86
110
|
};
|
|
87
111
|
}
|
|
88
112
|
function namedStep(step, facts, graph) {
|
|
89
113
|
const named = facts.named.filter((thing) => thing.type === step.type && thing.name === step.target);
|
|
90
114
|
const first = named[0];
|
|
91
115
|
if (!first) return NOTHING;
|
|
92
|
-
const
|
|
93
|
-
for (const thing of named) {
|
|
94
|
-
if (thing.file === null) continue;
|
|
95
|
-
importClosure(graph, [thing.file]).forEach((file) => files.add(file));
|
|
96
|
-
files.add(thing.file);
|
|
97
|
-
}
|
|
116
|
+
const entries = named.flatMap((thing) => thing.file === null ? [] : [thing.file]);
|
|
98
117
|
return {
|
|
99
118
|
found: true,
|
|
100
119
|
entry: first.file,
|
|
101
|
-
|
|
120
|
+
...reach(graph, entries)
|
|
102
121
|
};
|
|
103
122
|
}
|
|
104
123
|
function affectsStep(step, written) {
|
|
105
124
|
const target = step.affects;
|
|
106
125
|
if (target === null) return NOTHING;
|
|
107
126
|
const feature = written.features.find((candidate) => candidate.id === target.feature);
|
|
127
|
+
const found = feature !== void 0 && (target.flow === null || feature.flows.some((flow) => flow.id.value === target.flow));
|
|
108
128
|
return {
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
files: []
|
|
129
|
+
...NOTHING,
|
|
130
|
+
found
|
|
112
131
|
};
|
|
113
132
|
}
|
|
114
133
|
/** One step of a flow of `feature`, with what it matched in the book. */
|
|
@@ -118,11 +137,7 @@ function resolveStep(step, feature, context) {
|
|
|
118
137
|
else if (step.type === "page") match = pageStep(step, feature, context.facts, context.apps, context.graph);
|
|
119
138
|
else if (NAMED_TYPES.has(step.type)) match = namedStep(step, context.facts, context.graph);
|
|
120
139
|
else if (step.type === "affects") match = affectsStep(step, context.written);
|
|
121
|
-
else match =
|
|
122
|
-
found: null,
|
|
123
|
-
entry: null,
|
|
124
|
-
files: []
|
|
125
|
-
};
|
|
140
|
+
else match = UNKNOWN;
|
|
126
141
|
const target = step.app === null ? step.target : `${step.target} [${step.app}]`;
|
|
127
142
|
return {
|
|
128
143
|
index: step.index,
|