@warlock.js/grimoire 0.0.0-stage → 5.56.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.
Files changed (211) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +21 -0
  3. package/README.md +55 -2
  4. package/esm/apps/check-apps.mjs +207 -0
  5. package/esm/apps/check-apps.mjs.map +1 -0
  6. package/esm/apps/index.mjs +4 -0
  7. package/esm/apps/match-apps.d.mts +12 -0
  8. package/esm/apps/match-apps.d.mts.map +1 -0
  9. package/esm/apps/match-apps.mjs +30 -0
  10. package/esm/apps/match-apps.mjs.map +1 -0
  11. package/esm/book/build.d.mts +14 -0
  12. package/esm/book/build.d.mts.map +1 -0
  13. package/esm/book/build.mjs +300 -0
  14. package/esm/book/build.mjs.map +1 -0
  15. package/esm/book/index.mjs +5 -0
  16. package/esm/book/io.mjs +162 -0
  17. package/esm/book/io.mjs.map +1 -0
  18. package/esm/book/normalize.mjs +71 -0
  19. package/esm/book/normalize.mjs.map +1 -0
  20. package/esm/book/render.mjs +262 -0
  21. package/esm/book/render.mjs.map +1 -0
  22. package/esm/book/write.d.mts +12 -0
  23. package/esm/book/write.d.mts.map +1 -0
  24. package/esm/book/write.mjs +90 -0
  25. package/esm/book/write.mjs.map +1 -0
  26. package/esm/bookmap/build.d.mts +21 -0
  27. package/esm/bookmap/build.d.mts.map +1 -0
  28. package/esm/bookmap/build.mjs +272 -0
  29. package/esm/bookmap/build.mjs.map +1 -0
  30. package/esm/bookmap/index.mjs +5 -0
  31. package/esm/bookmap/steps.mjs +137 -0
  32. package/esm/bookmap/steps.mjs.map +1 -0
  33. package/esm/bookmap/write.d.mts +19 -0
  34. package/esm/bookmap/write.d.mts.map +1 -0
  35. package/esm/bookmap/write.mjs +118 -0
  36. package/esm/bookmap/write.mjs.map +1 -0
  37. package/esm/check/check-grimoire.d.mts +7 -0
  38. package/esm/check/check-grimoire.d.mts.map +1 -0
  39. package/esm/check/check-grimoire.mjs +98 -0
  40. package/esm/check/check-grimoire.mjs.map +1 -0
  41. package/esm/check/format-check-report.d.mts +20 -0
  42. package/esm/check/format-check-report.d.mts.map +1 -0
  43. package/esm/check/format-check-report.mjs +55 -0
  44. package/esm/check/format-check-report.mjs.map +1 -0
  45. package/esm/check/index.mjs +4 -0
  46. package/esm/check/rules/book-notes.mjs +18 -0
  47. package/esm/check/rules/book-notes.mjs.map +1 -0
  48. package/esm/check/rules/criteria.mjs +48 -0
  49. package/esm/check/rules/criteria.mjs.map +1 -0
  50. package/esm/check/rules/links.mjs +196 -0
  51. package/esm/check/rules/links.mjs.map +1 -0
  52. package/esm/check/rules/lookup.mjs +41 -0
  53. package/esm/check/rules/lookup.mjs.map +1 -0
  54. package/esm/check/rules/source-files.mjs +119 -0
  55. package/esm/check/rules/source-files.mjs.map +1 -0
  56. package/esm/check/rules/versions.mjs +92 -0
  57. package/esm/check/rules/versions.mjs.map +1 -0
  58. package/esm/codes/codes.d.mts +182 -0
  59. package/esm/codes/codes.d.mts.map +1 -0
  60. package/esm/codes/codes.mjs +111 -0
  61. package/esm/codes/codes.mjs.map +1 -0
  62. package/esm/codes/index.d.mts +33 -0
  63. package/esm/codes/index.d.mts.map +1 -0
  64. package/esm/codes/index.mjs +63 -0
  65. package/esm/codes/index.mjs.map +1 -0
  66. package/esm/contracts/adapter.d.mts +209 -0
  67. package/esm/contracts/adapter.d.mts.map +1 -0
  68. package/esm/contracts/book.d.mts +233 -0
  69. package/esm/contracts/book.d.mts.map +1 -0
  70. package/esm/contracts/book.mjs +7 -0
  71. package/esm/contracts/book.mjs.map +1 -0
  72. package/esm/contracts/bookmap.d.mts +175 -0
  73. package/esm/contracts/bookmap.d.mts.map +1 -0
  74. package/esm/contracts/findings.d.mts +79 -0
  75. package/esm/contracts/findings.d.mts.map +1 -0
  76. package/esm/contracts/location.d.mts +22 -0
  77. package/esm/contracts/location.d.mts.map +1 -0
  78. package/esm/contracts/releases.d.mts +53 -0
  79. package/esm/contracts/releases.d.mts.map +1 -0
  80. package/esm/contracts/scry.d.mts +143 -0
  81. package/esm/contracts/scry.d.mts.map +1 -0
  82. package/esm/contracts/snapshot.d.mts +52 -0
  83. package/esm/contracts/snapshot.d.mts.map +1 -0
  84. package/esm/contracts/test-results.d.mts +63 -0
  85. package/esm/contracts/test-results.d.mts.map +1 -0
  86. package/esm/contracts/written.d.mts +363 -0
  87. package/esm/contracts/written.d.mts.map +1 -0
  88. package/esm/contracts/written.mjs +19 -0
  89. package/esm/contracts/written.mjs.map +1 -0
  90. package/esm/devtools/data.mjs +171 -0
  91. package/esm/devtools/data.mjs.map +1 -0
  92. package/esm/devtools/graphs.mjs +142 -0
  93. package/esm/devtools/graphs.mjs.map +1 -0
  94. package/esm/devtools/index.d.mts +42 -0
  95. package/esm/devtools/index.d.mts.map +1 -0
  96. package/esm/devtools/index.mjs +103 -0
  97. package/esm/devtools/index.mjs.map +1 -0
  98. package/esm/devtools/site.d.mts +26 -0
  99. package/esm/devtools/site.d.mts.map +1 -0
  100. package/esm/devtools/site.mjs +190 -0
  101. package/esm/devtools/site.mjs.map +1 -0
  102. package/esm/devtools/snapshot-source.mjs +70 -0
  103. package/esm/devtools/snapshot-source.mjs.map +1 -0
  104. package/esm/front-matter/index.d.mts +33 -0
  105. package/esm/front-matter/index.d.mts.map +1 -0
  106. package/esm/front-matter/index.mjs +130 -0
  107. package/esm/front-matter/index.mjs.map +1 -0
  108. package/esm/graph/index.d.mts +15 -0
  109. package/esm/graph/index.d.mts.map +1 -0
  110. package/esm/graph/index.mjs +42 -0
  111. package/esm/graph/index.mjs.map +1 -0
  112. package/esm/index.d.mts +33 -0
  113. package/esm/index.mjs +33 -0
  114. package/esm/ownership/index.d.mts +8 -0
  115. package/esm/ownership/index.d.mts.map +1 -0
  116. package/esm/ownership/index.mjs +137 -0
  117. package/esm/ownership/index.mjs.map +1 -0
  118. package/esm/paths/index.d.mts +58 -0
  119. package/esm/paths/index.d.mts.map +1 -0
  120. package/esm/paths/index.mjs +137 -0
  121. package/esm/paths/index.mjs.map +1 -0
  122. package/esm/proves/index.mjs +3 -0
  123. package/esm/proves/scan-proofs.d.mts +22 -0
  124. package/esm/proves/scan-proofs.d.mts.map +1 -0
  125. package/esm/proves/scan-proofs.mjs +214 -0
  126. package/esm/proves/scan-proofs.mjs.map +1 -0
  127. package/esm/releases/index.d.mts +29 -0
  128. package/esm/releases/index.d.mts.map +1 -0
  129. package/esm/releases/index.mjs +157 -0
  130. package/esm/releases/index.mjs.map +1 -0
  131. package/esm/scry/format.d.mts +14 -0
  132. package/esm/scry/format.d.mts.map +1 -0
  133. package/esm/scry/format.mjs +193 -0
  134. package/esm/scry/format.mjs.map +1 -0
  135. package/esm/scry/index.mjs +5 -0
  136. package/esm/scry/parse.d.mts +10 -0
  137. package/esm/scry/parse.d.mts.map +1 -0
  138. package/esm/scry/parse.mjs +108 -0
  139. package/esm/scry/parse.mjs.map +1 -0
  140. package/esm/scry/query.d.mts +11 -0
  141. package/esm/scry/query.d.mts.map +1 -0
  142. package/esm/scry/query.mjs +457 -0
  143. package/esm/scry/query.mjs.map +1 -0
  144. package/esm/tasks/index.mjs +116 -0
  145. package/esm/tasks/index.mjs.map +1 -0
  146. package/esm/test-results/criterion-status.d.mts +15 -0
  147. package/esm/test-results/criterion-status.d.mts.map +1 -0
  148. package/esm/test-results/criterion-status.mjs +17 -0
  149. package/esm/test-results/criterion-status.mjs.map +1 -0
  150. package/esm/test-results/index.d.mts +8 -0
  151. package/esm/test-results/index.d.mts.map +1 -0
  152. package/esm/test-results/index.mjs +124 -0
  153. package/esm/test-results/index.mjs.map +1 -0
  154. package/esm/vitest/index.d.mts +15 -0
  155. package/esm/vitest/index.d.mts.map +1 -0
  156. package/esm/vitest/index.mjs +146 -0
  157. package/esm/vitest/index.mjs.map +1 -0
  158. package/esm/warlock/actions.mjs +265 -0
  159. package/esm/warlock/actions.mjs.map +1 -0
  160. package/esm/warlock/adapter.d.mts +28 -0
  161. package/esm/warlock/adapter.d.mts.map +1 -0
  162. package/esm/warlock/adapter.mjs +377 -0
  163. package/esm/warlock/adapter.mjs.map +1 -0
  164. package/esm/warlock/commands.d.mts +15 -0
  165. package/esm/warlock/commands.d.mts.map +1 -0
  166. package/esm/warlock/commands.mjs +199 -0
  167. package/esm/warlock/commands.mjs.map +1 -0
  168. package/esm/warlock/index.d.mts +4 -0
  169. package/esm/warlock/index.mjs +5 -0
  170. package/esm/warlock/mcp-tools.mjs +247 -0
  171. package/esm/warlock/mcp-tools.mjs.map +1 -0
  172. package/esm/warlock/mobile-facts.d.mts +32 -0
  173. package/esm/warlock/mobile-facts.d.mts.map +1 -0
  174. package/esm/warlock/mobile-facts.mjs +185 -0
  175. package/esm/warlock/mobile-facts.mjs.map +1 -0
  176. package/esm/workspace/index.d.mts +11 -0
  177. package/esm/workspace/index.d.mts.map +1 -0
  178. package/esm/workspace/index.mjs +122 -0
  179. package/esm/workspace/index.mjs.map +1 -0
  180. package/esm/written/apps.mjs +227 -0
  181. package/esm/written/apps.mjs.map +1 -0
  182. package/esm/written/features.mjs +400 -0
  183. package/esm/written/features.mjs.map +1 -0
  184. package/esm/written/fields.mjs +173 -0
  185. package/esm/written/fields.mjs.map +1 -0
  186. package/esm/written/index.mjs +3 -0
  187. package/esm/written/lists.mjs +68 -0
  188. package/esm/written/lists.mjs.map +1 -0
  189. package/esm/written/markdown.mjs +173 -0
  190. package/esm/written/markdown.mjs.map +1 -0
  191. package/esm/written/parse-grimoire.d.mts +20 -0
  192. package/esm/written/parse-grimoire.d.mts.map +1 -0
  193. package/esm/written/parse-grimoire.mjs +552 -0
  194. package/esm/written/parse-grimoire.mjs.map +1 -0
  195. package/esm/written/sink.mjs +65 -0
  196. package/esm/written/sink.mjs.map +1 -0
  197. package/esm/written/tasks-releases.mjs +166 -0
  198. package/esm/written/tasks-releases.mjs.map +1 -0
  199. package/llms-full.txt +869 -0
  200. package/llms.txt +15 -0
  201. package/package.json +66 -4
  202. package/skills/backfill-a-grimoire/SKILL.md +128 -0
  203. package/skills/describe-an-app/SKILL.md +162 -0
  204. package/skills/document-a-file/SKILL.md +75 -0
  205. package/skills/index.md +26 -0
  206. package/skills/record-a-change/SKILL.md +139 -0
  207. package/skills/use-the-grimoire/SKILL.md +137 -0
  208. package/skills/write-a-feature/SKILL.md +168 -0
  209. package/ui/grimoire-static.js +136 -0
  210. package/ui/grimoire-view.js +1005 -0
  211. package/ui/grimoire.css +88 -0
@@ -0,0 +1,300 @@
1
+ import { BOOK_SCHEMA_VERSION } from "../contracts/book.mjs";
2
+ import { GrimoireError } from "../codes/index.mjs";
3
+ import { GRIMOIRE_PATHS, isCodeFile, isInsideFolder } from "../paths/index.mjs";
4
+ import { fileGraph, importClosure } from "../graph/index.mjs";
5
+ import { cleanFolder, hashFile, hashIfExists, isMissing, listFiles, mapLimit, readJson, toJson, writeBookFile } from "./io.mjs";
6
+ import { cleanPath, normalizeFiles, normalizeMobile, normalizeNamed, normalizePages, normalizeRoutes, normalizeSites } from "./normalize.mjs";
7
+ import { entryPathsFor } from "./render.mjs";
8
+ import path from "node:path";
9
+ import { rm, stat } from "node:fs/promises";
10
+ import { readFileSync } from "node:fs";
11
+
12
+ //#region ../../packages/grimoire/src/book/build.ts
13
+ /**
14
+ * `buildBook` and `loadBook`: the freshness fingerprint, the facts cache and
15
+ * the route (boot) cache. Entries are written by `writeBook` (write.ts).
16
+ */
17
+ /** Where `writeBook` remembers what it wrote (see write.ts). */
18
+ const WRITE_STATE_PATH = `${GRIMOIRE_PATHS.book}/.cache/written.json`;
19
+ let cachedVersion = null;
20
+ /** The `@warlock.js/grimoire` version, from its package.json. */
21
+ function grimoireVersion() {
22
+ if (cachedVersion !== null) return cachedVersion;
23
+ try {
24
+ const manifest = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
25
+ cachedVersion = typeof manifest.version === "string" ? manifest.version : "0.0.0";
26
+ } catch {
27
+ cachedVersion = "0.0.0";
28
+ }
29
+ return cachedVersion;
30
+ }
31
+ const absolutePath = (root, file) => path.join(root, ...file.split("/"));
32
+ async function readStoredBook(root) {
33
+ const manifest = await readJson(absolutePath(root, GRIMOIRE_PATHS.bookManifest));
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;
36
+ return {
37
+ manifest,
38
+ facts: cache.facts
39
+ };
40
+ }
41
+ /** Stat every code file; hash only those whose size or mtime differ from the previous manifest. */
42
+ async function scanSourceRoots(root, sourceRoots, previous) {
43
+ let files;
44
+ try {
45
+ files = (await listFiles(root, sourceRoots)).filter(isCodeFile);
46
+ } catch (error) {
47
+ throw new GrimoireError("GR8001", `The source roots could not be read: ${error.message}`);
48
+ }
49
+ let statMoved = false;
50
+ const states = await mapLimit(files, 32, async (file) => {
51
+ const absolute = absolutePath(root, file);
52
+ try {
53
+ const info = await stat(absolute);
54
+ const before = previous[file];
55
+ if (before !== void 0 && before.size === info.size && before.mtimeMs === info.mtimeMs) return {
56
+ file,
57
+ hash: before.hash,
58
+ size: info.size,
59
+ mtimeMs: info.mtimeMs
60
+ };
61
+ const hash = await hashFile(absolute, info.size);
62
+ if (before !== void 0 && before.hash === hash) statMoved = true;
63
+ return {
64
+ file,
65
+ hash,
66
+ size: info.size,
67
+ mtimeMs: info.mtimeMs
68
+ };
69
+ } catch (error) {
70
+ if (isMissing(error)) return null;
71
+ throw new GrimoireError("GR8001", `${file} could not be read: ${error.message}`);
72
+ }
73
+ });
74
+ const result = {};
75
+ for (const state of states) if (state !== null) result[state.file] = {
76
+ hash: state.hash,
77
+ size: state.size,
78
+ mtimeMs: state.mtimeMs
79
+ };
80
+ return {
81
+ files: result,
82
+ statMoved
83
+ };
84
+ }
85
+ /** Hashes of the given files: from the scan when inside the source roots, else read (`""` when missing). */
86
+ async function hashFiles(root, files, scan, sourceRoots) {
87
+ const hashes = await mapLimit([...new Set(files)].sort(), 32, async (file) => {
88
+ const scanned = scan[file];
89
+ if (scanned !== void 0) return [file, scanned.hash];
90
+ if (isCodeFile(file) && sourceRoots.some((folder) => folder === "." || isInsideFolder(file, folder))) return [file, ""];
91
+ return [file, await hashIfExists(root, file)];
92
+ });
93
+ return Object.fromEntries(hashes);
94
+ }
95
+ function sameRecord(left, right) {
96
+ const leftKeys = Object.keys(left);
97
+ return leftKeys.length === Object.keys(right).length && leftKeys.every((key) => right[key] === left[key]);
98
+ }
99
+ /** Source files added, changed or removed between two manifests, sorted. */
100
+ function changedFiles(previous, current) {
101
+ const changed = [];
102
+ for (const [file, state] of Object.entries(current)) if (previous[file]?.hash !== state.hash) changed.push(file);
103
+ for (const file of Object.keys(previous)) if (current[file] === void 0) changed.push(file);
104
+ return changed.sort();
105
+ }
106
+ const NAMED_FILE_TYPES = /* @__PURE__ */ new Set([
107
+ "mail",
108
+ "job",
109
+ "event"
110
+ ]);
111
+ /**
112
+ * Files whose change makes the route cache stale: every `routes` file and
113
+ * everything it imports, every `config` file, `warlock.config.ts`,
114
+ * `package.json`, and every mail, job, event and notification file (the
115
+ * named things are cached with the routes).
116
+ */
117
+ function defaultRouteInputs(files) {
118
+ const routesFiles = files.filter((file) => file.type === "routes").map((file) => file.file);
119
+ const inputs = new Set(importClosure(fileGraph(files), routesFiles));
120
+ for (const file of files) if (file.type === "config" || NAMED_FILE_TYPES.has(file.type) || /\.notification\.[^/]+$/.test(file.file)) inputs.add(file.file);
121
+ inputs.add("warlock.config.ts");
122
+ inputs.add("package.json");
123
+ return [...inputs].sort();
124
+ }
125
+ /** The route cache's input files: the adapter's list when it has one, else the default. */
126
+ async function routeInputFiles(root, adapter, files) {
127
+ return adapter.routeInputs ? (await adapter.routeInputs(root, files)).map(cleanPath) : defaultRouteInputs(files);
128
+ }
129
+ const hasBootFacts = (adapter) => typeof adapter.routes === "function" || typeof adapter.named === "function";
130
+ async function collectBootFacts(root, adapter) {
131
+ try {
132
+ return {
133
+ routes: adapter.routes ? normalizeRoutes(await adapter.routes(root)) : null,
134
+ named: adapter.named ? normalizeNamed(await adapter.named(root)) : []
135
+ };
136
+ } catch (error) {
137
+ if (error instanceof GrimoireError) throw error;
138
+ throw new GrimoireError("GR8002", `Route facts could not be read: ${error.message}`);
139
+ }
140
+ }
141
+ /** How the stored route facts relate to the current inputs. */
142
+ function bootState(boot, routes, inputs) {
143
+ if (boot.collectedAt === null || routes === null) return "missing";
144
+ return sameRecord(boot.inputs, inputs) ? "fresh" : "stale";
145
+ }
146
+ async function writeStoredBook(root, manifest, facts) {
147
+ if (facts !== null) {
148
+ const cache = {
149
+ schemaVersion: 1,
150
+ facts
151
+ };
152
+ await writeBookFile(root, GRIMOIRE_PATHS.bookFactsCache, toJson(cache));
153
+ }
154
+ await writeBookFile(root, GRIMOIRE_PATHS.bookManifest, toJson(manifest));
155
+ }
156
+ /**
157
+ * Bring the book's facts up to date and write `manifest.json` and
158
+ * `.cache/facts.json`. Does not write entries (see `writeBook`).
159
+ *
160
+ * @param root Absolute project root.
161
+ */
162
+ async function buildBook(root, adapter, options = {}) {
163
+ const projectRoot = path.resolve(root);
164
+ const mode = options.routes ?? "cached";
165
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
166
+ const write = options.write !== false;
167
+ const sourceRoots = [...new Set((await adapter.sourceRoots(projectRoot)).map(cleanFolder))].sort();
168
+ const stored = await readStoredBook(projectRoot);
169
+ const previousFiles = stored?.manifest.files ?? {};
170
+ const scan = await scanSourceRoots(projectRoot, sourceRoots, previousFiles);
171
+ const version = grimoireVersion();
172
+ if (stored !== null && options.force !== true) {
173
+ const { manifest, facts } = stored;
174
+ if (manifest.grimoireVersion === version && manifest.adapter.name === adapter.name && manifest.adapter.version === adapter.version && manifest.sourceRoots.length === sourceRoots.length && manifest.sourceRoots.every((folder, index) => folder === sourceRoots[index]) && Object.keys(previousFiles).length === Object.keys(scan.files).length && Object.entries(scan.files).every(([file, state]) => previousFiles[file]?.hash === state.hash) && sameRecord(manifest.tests, await hashFiles(projectRoot, Object.keys(manifest.tests), scan.files, sourceRoots))) {
175
+ const inputs = await hashFiles(projectRoot, Object.keys(manifest.boot.inputs), scan.files, sourceRoots);
176
+ let routes = hasBootFacts(adapter) ? bootState(manifest.boot, facts.routes, inputs) : "missing";
177
+ let changedBook = false;
178
+ if (mode === "fresh" && hasBootFacts(adapter) && routes !== "fresh") {
179
+ const current = await hashFiles(projectRoot, await routeInputFiles(projectRoot, adapter, facts.files), scan.files, sourceRoots);
180
+ Object.assign(facts, await collectBootFacts(projectRoot, adapter));
181
+ manifest.boot = {
182
+ collectedAt: now().toISOString(),
183
+ inputs: current
184
+ };
185
+ routes = "fresh";
186
+ changedBook = true;
187
+ }
188
+ if (changedBook || scan.statMoved) {
189
+ for (const [file, state] of Object.entries(scan.files)) manifest.files[file] = {
190
+ ...state,
191
+ entry: manifest.files[file]?.entry ?? null
192
+ };
193
+ if (changedBook) manifest.builtAt = now().toISOString();
194
+ if (write) await writeStoredBook(projectRoot, manifest, changedBook ? facts : null);
195
+ }
196
+ return {
197
+ book: {
198
+ root: projectRoot,
199
+ manifest,
200
+ facts,
201
+ routes
202
+ },
203
+ rebuilt: changedBook,
204
+ changed: []
205
+ };
206
+ }
207
+ }
208
+ let files;
209
+ try {
210
+ files = normalizeFiles(await adapter.files(projectRoot));
211
+ } catch (error) {
212
+ if (error instanceof GrimoireError) throw error;
213
+ throw new GrimoireError("GR8001", `The source files could not be read: ${error.message}`);
214
+ }
215
+ let staticFacts;
216
+ try {
217
+ staticFacts = {
218
+ sites: adapter.sites ? normalizeSites(await adapter.sites(projectRoot)) : [],
219
+ pages: adapter.pages ? normalizePages(await adapter.pages(projectRoot)) : [],
220
+ mobile: adapter.mobile ? normalizeMobile(await adapter.mobile(projectRoot)) : [],
221
+ tests: adapter.tests ? (await adapter.tests(projectRoot)).map(cleanPath) : files.filter((file) => file.type === "spec").map((file) => file.file)
222
+ };
223
+ } catch (error) {
224
+ if (error instanceof GrimoireError) throw error;
225
+ throw new GrimoireError("GR8004", `Pages or screens could not be read: ${error.message}`);
226
+ }
227
+ staticFacts.tests = [...new Set(staticFacts.tests)].sort();
228
+ const inputs = await hashFiles(projectRoot, await routeInputFiles(projectRoot, adapter, files), scan.files, sourceRoots);
229
+ const previousBoot = stored?.manifest.boot ?? {
230
+ collectedAt: null,
231
+ inputs: {}
232
+ };
233
+ let boot = previousBoot;
234
+ let bootFacts = {
235
+ routes: stored?.facts.routes ?? null,
236
+ named: stored?.facts.named ?? []
237
+ };
238
+ let routes = hasBootFacts(adapter) ? bootState(previousBoot, bootFacts.routes, inputs) : "missing";
239
+ if (mode === "fresh" && hasBootFacts(adapter) && (routes !== "fresh" || options.force === true)) {
240
+ bootFacts = await collectBootFacts(projectRoot, adapter);
241
+ boot = {
242
+ collectedAt: now().toISOString(),
243
+ inputs
244
+ };
245
+ routes = "fresh";
246
+ }
247
+ const facts = {
248
+ files,
249
+ ...bootFacts,
250
+ ...staticFacts
251
+ };
252
+ const entries = entryPathsFor(facts);
253
+ const manifest = {
254
+ schemaVersion: 1,
255
+ grimoireVersion: version,
256
+ adapter: {
257
+ name: adapter.name,
258
+ version: adapter.version
259
+ },
260
+ builtAt: now().toISOString(),
261
+ sourceRoots,
262
+ files: Object.fromEntries(Object.entries(scan.files).map(([file, state]) => [file, {
263
+ ...state,
264
+ entry: entries.get(file) ?? null
265
+ }])),
266
+ tests: await hashFiles(projectRoot, facts.tests, scan.files, sourceRoots),
267
+ writtenHash: stored?.manifest.writtenHash ?? "",
268
+ boot
269
+ };
270
+ if (write) {
271
+ if (options.force === true) await rm(absolutePath(projectRoot, WRITE_STATE_PATH), { force: true });
272
+ await writeStoredBook(projectRoot, manifest, facts);
273
+ }
274
+ return {
275
+ book: {
276
+ root: projectRoot,
277
+ manifest,
278
+ facts,
279
+ routes
280
+ },
281
+ rebuilt: true,
282
+ changed: changedFiles(previousFiles, scan.files)
283
+ };
284
+ }
285
+ /** Read the book from disk without calling an adapter; `null` when it was never built. */
286
+ async function loadBook(root) {
287
+ const projectRoot = path.resolve(root);
288
+ const stored = await readStoredBook(projectRoot);
289
+ if (stored === null) return null;
290
+ return {
291
+ root: projectRoot,
292
+ manifest: stored.manifest,
293
+ facts: stored.facts,
294
+ routes: stored.facts.routes === null ? "missing" : "cached"
295
+ };
296
+ }
297
+
298
+ //#endregion
299
+ export { WRITE_STATE_PATH, buildBook, defaultRouteInputs, grimoireVersion, loadBook };
300
+ //# sourceMappingURL=build.mjs.map
@@ -0,0 +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;;AA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;EACjB,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"}
@@ -0,0 +1,5 @@
1
+ import { packagesOf, renderModuleSummary } from "./render.mjs";
2
+ import { buildBook, defaultRouteInputs, loadBook } from "./build.mjs";
3
+ import { writeBook } from "./write.mjs";
4
+
5
+ export { buildBook, loadBook, packagesOf, writeBook };
@@ -0,0 +1,162 @@
1
+ import { GRIMOIRE_PATHS, toPosixPath } from "../paths/index.mjs";
2
+ import path from "node:path";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { mkdir, readFile, readdir, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { createReadStream } from "node:fs";
6
+ import { pipeline } from "node:stream/promises";
7
+
8
+ //#region ../../packages/grimoire/src/book/io.ts
9
+ /**
10
+ * File helpers of the book builder: walking the source roots, hashing with a
11
+ * stat cache, bounded concurrency, and atomic writes that never leave
12
+ * `grimoire/book/`.
13
+ */
14
+ /** How many file operations run at once. */
15
+ const IO_CONCURRENCY = 32;
16
+ /** Files up to this size are read in one go; larger ones are streamed into the hash. */
17
+ const READ_WHOLE_LIMIT = 262144;
18
+ /** Folder names never walked under a source root. */
19
+ function isSkippedName(name) {
20
+ return name === "node_modules" || name.startsWith(".");
21
+ }
22
+ /** Run `task` over `items` with at most `limit` at once; results keep the input order. */
23
+ async function mapLimit(items, limit, task) {
24
+ const results = new Array(items.length);
25
+ let next = 0;
26
+ const worker = async () => {
27
+ while (next < items.length) {
28
+ const index = next++;
29
+ results[index] = await task(items[index], index);
30
+ }
31
+ };
32
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
33
+ return results;
34
+ }
35
+ /** sha256 (hex) of a string. */
36
+ function hashText(text) {
37
+ return createHash("sha256").update(text).digest("hex");
38
+ }
39
+ /** sha256 (hex) of a file's bytes; large files are streamed. */
40
+ async function hashFile(absolute, size) {
41
+ if (size <= READ_WHOLE_LIMIT) return createHash("sha256").update(await readFile(absolute)).digest("hex");
42
+ const hash = createHash("sha256");
43
+ await pipeline(createReadStream(absolute), hash);
44
+ return hash.digest("hex");
45
+ }
46
+ /** sha256 of a project file, or `""` when it does not exist. */
47
+ async function hashIfExists(root, file) {
48
+ const absolute = path.join(root, ...file.split("/"));
49
+ try {
50
+ const info = await stat(absolute);
51
+ return info.isFile() ? await hashFile(absolute, info.size) : "";
52
+ } catch (error) {
53
+ if (isMissing(error)) return "";
54
+ throw error;
55
+ }
56
+ }
57
+ /** Whether an fs error says the path is not there. */
58
+ function isMissing(error) {
59
+ const code = error?.code;
60
+ return code === "ENOENT" || code === "ENOTDIR";
61
+ }
62
+ /** A source root as a clean project-relative POSIX folder (`.` for the project itself). */
63
+ function cleanFolder(folder) {
64
+ const posix = path.posix.normalize(toPosixPath(folder)).replace(/\/+$/, "");
65
+ return posix === "" || posix === "./" ? "." : posix;
66
+ }
67
+ /**
68
+ * Every file under the given project-relative folders, as sorted
69
+ * project-relative POSIX paths. `node_modules`, dot folders and the
70
+ * `grimoire/` folder are skipped; symbolic links are not followed.
71
+ */
72
+ async function listFiles(root, folders) {
73
+ const found = /* @__PURE__ */ new Set();
74
+ let pending = [...new Set(folders.map(cleanFolder))];
75
+ while (pending.length > 0) {
76
+ const nextLevel = [];
77
+ await mapLimit(pending, 32, async (folder) => {
78
+ let entries;
79
+ try {
80
+ entries = await readdir(folder === "." ? root : path.join(root, ...folder.split("/")), { withFileTypes: true });
81
+ } catch (error) {
82
+ if (isMissing(error)) return;
83
+ throw error;
84
+ }
85
+ for (const entry of entries) {
86
+ if (isSkippedName(entry.name)) continue;
87
+ const file = folder === "." ? entry.name : `${folder}/${entry.name}`;
88
+ if (entry.isDirectory()) {
89
+ if (file !== "grimoire") nextLevel.push(file);
90
+ } else if (entry.isFile()) found.add(file);
91
+ }
92
+ });
93
+ pending = nextLevel;
94
+ }
95
+ return [...found].sort();
96
+ }
97
+ /** Read and parse a JSON file; `null` when it is missing or cannot be parsed. */
98
+ async function readJson(absolute) {
99
+ try {
100
+ return JSON.parse(await readFile(absolute, "utf8"));
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+ /** JSON as every generated file is written. */
106
+ function toJson(value) {
107
+ return `${JSON.stringify(value, null, 2)}\n`;
108
+ }
109
+ /** Whether a project-relative path stays inside `grimoire/book/` (no `..` escape). */
110
+ function isInsideBook(bookPath) {
111
+ const normalized = path.posix.normalize(toPosixPath(bookPath));
112
+ return normalized === bookPath && normalized.startsWith(`${GRIMOIRE_PATHS.book}/`);
113
+ }
114
+ /** The absolute path of a book file; throws for a path outside `grimoire/book/`. */
115
+ function bookFile(root, bookPath) {
116
+ if (!isInsideBook(bookPath)) throw new Error(`Grimoire refused to touch ${bookPath}: it is outside ${GRIMOIRE_PATHS.book}/.`);
117
+ return path.join(root, ...bookPath.split("/"));
118
+ }
119
+ /**
120
+ * Write a book file atomically: the content goes to a temporary file next to
121
+ * it, which is then renamed over the target, so a reader sees the old file or
122
+ * the new one, never half of one.
123
+ */
124
+ async function writeBookFile(root, bookPath, content) {
125
+ const target = bookFile(root, bookPath);
126
+ const temporary = `${target}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
127
+ await mkdir(path.dirname(target), { recursive: true });
128
+ try {
129
+ await writeFile(temporary, content);
130
+ await rename(temporary, target);
131
+ } catch (error) {
132
+ await rm(temporary, { force: true });
133
+ throw error;
134
+ }
135
+ }
136
+ /** Remove a book file (missing is fine), then any folders it leaves empty, up to the book root. */
137
+ async function removeBookFile(root, bookPath) {
138
+ const target = bookFile(root, bookPath);
139
+ const bookRoot = path.join(root, ...GRIMOIRE_PATHS.book.split("/"));
140
+ try {
141
+ await unlink(target);
142
+ } catch (error) {
143
+ if (!isMissing(error)) throw error;
144
+ }
145
+ let folder = path.dirname(target);
146
+ while (folder.startsWith(`${bookRoot}${path.sep}`)) {
147
+ try {
148
+ await rmdir(folder);
149
+ } catch {
150
+ return;
151
+ }
152
+ folder = path.dirname(folder);
153
+ }
154
+ }
155
+ /** Every file under `grimoire/book/`, project-relative, or `[]` when there is no book. */
156
+ async function listBookFiles(root) {
157
+ return listFiles(root, [GRIMOIRE_PATHS.book]).then((files) => files.filter((file) => !file.endsWith(".tmp")));
158
+ }
159
+
160
+ //#endregion
161
+ export { bookFile, cleanFolder, hashFile, hashIfExists, hashText, isInsideBook, isMissing, listBookFiles, listFiles, mapLimit, readJson, removeBookFile, toJson, writeBookFile };
162
+ //# sourceMappingURL=io.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"io.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/io.ts"],"sourcesContent":["/**\n * File helpers of the book builder: walking the source roots, hashing with a\n * stat cache, bounded concurrency, and atomic writes that never leave\n * `grimoire/book/`.\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { createReadStream, type Dirent } from \"node:fs\";\nimport {\n mkdir,\n readdir,\n readFile,\n rename,\n rm,\n rmdir,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { GRIMOIRE_PATHS, toPosixPath } from \"../paths\";\n\n/** How many file operations run at once. */\nexport const IO_CONCURRENCY = 32;\n\n/** Files up to this size are read in one go; larger ones are streamed into the hash. */\nconst READ_WHOLE_LIMIT = 256 * 1024;\n\n/** Folder names never walked under a source root. */\nfunction isSkippedName(name: string): boolean {\n return name === \"node_modules\" || name.startsWith(\".\");\n}\n\n/** Run `task` over `items` with at most `limit` at once; results keep the input order. */\nexport async function mapLimit<T, R>(\n items: readonly T[],\n limit: number,\n task: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n\n const worker = async (): Promise<void> => {\n while (next < items.length) {\n const index = next++;\n results[index] = await task(items[index] as T, index);\n }\n };\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n\n return results;\n}\n\n/** sha256 (hex) of a string. */\nexport function hashText(text: string): string {\n return createHash(\"sha256\").update(text).digest(\"hex\");\n}\n\n/** sha256 (hex) of a file's bytes; large files are streamed. */\nexport async function hashFile(absolute: string, size: number): Promise<string> {\n if (size <= READ_WHOLE_LIMIT) {\n return createHash(\"sha256\")\n .update(await readFile(absolute))\n .digest(\"hex\");\n }\n\n const hash = createHash(\"sha256\");\n await pipeline(createReadStream(absolute), hash);\n\n return hash.digest(\"hex\");\n}\n\n/** sha256 of a project file, or `\"\"` when it does not exist. */\nexport async function hashIfExists(root: string, file: string): Promise<string> {\n const absolute = path.join(root, ...file.split(\"/\"));\n\n try {\n const info = await stat(absolute);\n\n return info.isFile() ? await hashFile(absolute, info.size) : \"\";\n } catch (error) {\n if (isMissing(error)) return \"\";\n throw error;\n }\n}\n\n/** Whether an fs error says the path is not there. */\nexport function isMissing(error: unknown): boolean {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n\n return code === \"ENOENT\" || code === \"ENOTDIR\";\n}\n\n/** A source root as a clean project-relative POSIX folder (`.` for the project itself). */\nexport function cleanFolder(folder: string): string {\n const posix = path.posix.normalize(toPosixPath(folder)).replace(/\\/+$/, \"\");\n\n return posix === \"\" || posix === \"./\" ? \".\" : posix;\n}\n\n/**\n * Every file under the given project-relative folders, as sorted\n * project-relative POSIX paths. `node_modules`, dot folders and the\n * `grimoire/` folder are skipped; symbolic links are not followed.\n */\nexport async function listFiles(root: string, folders: readonly string[]): Promise<string[]> {\n const found = new Set<string>();\n let pending = [...new Set(folders.map(cleanFolder))];\n\n while (pending.length > 0) {\n const nextLevel: string[] = [];\n\n await mapLimit(pending, IO_CONCURRENCY, async (folder) => {\n let entries: Dirent[];\n\n try {\n entries = await readdir(folder === \".\" ? root : path.join(root, ...folder.split(\"/\")), {\n withFileTypes: true,\n });\n } catch (error) {\n if (isMissing(error)) return;\n throw error;\n }\n\n for (const entry of entries) {\n if (isSkippedName(entry.name)) continue;\n\n const file = folder === \".\" ? entry.name : `${folder}/${entry.name}`;\n\n if (entry.isDirectory()) {\n if (file !== \"grimoire\") nextLevel.push(file);\n } else if (entry.isFile()) {\n found.add(file);\n }\n }\n });\n\n pending = nextLevel;\n }\n\n return [...found].sort();\n}\n\n/** Read and parse a JSON file; `null` when it is missing or cannot be parsed. */\nexport async function readJson<T>(absolute: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(absolute, \"utf8\")) as T;\n } catch {\n return null;\n }\n}\n\n/** JSON as every generated file is written. */\nexport function toJson(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\n/** Whether a project-relative path stays inside `grimoire/book/` (no `..` escape). */\nexport function isInsideBook(bookPath: string): boolean {\n const normalized = path.posix.normalize(toPosixPath(bookPath));\n\n return normalized === bookPath && normalized.startsWith(`${GRIMOIRE_PATHS.book}/`);\n}\n\n/** The absolute path of a book file; throws for a path outside `grimoire/book/`. */\nexport function bookFile(root: string, bookPath: string): string {\n if (!isInsideBook(bookPath)) {\n throw new Error(\n `Grimoire refused to touch ${bookPath}: it is outside ${GRIMOIRE_PATHS.book}/.`,\n );\n }\n\n return path.join(root, ...bookPath.split(\"/\"));\n}\n\n/**\n * Write a book file atomically: the content goes to a temporary file next to\n * it, which is then renamed over the target, so a reader sees the old file or\n * the new one, never half of one.\n */\nexport async function writeBookFile(\n root: string,\n bookPath: string,\n content: string,\n): Promise<void> {\n const target = bookFile(root, bookPath);\n const temporary = `${target}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`;\n\n await mkdir(path.dirname(target), { recursive: true });\n\n try {\n await writeFile(temporary, content);\n await rename(temporary, target);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n}\n\n/** Remove a book file (missing is fine), then any folders it leaves empty, up to the book root. */\nexport async function removeBookFile(root: string, bookPath: string): Promise<void> {\n const target = bookFile(root, bookPath);\n const bookRoot = path.join(root, ...GRIMOIRE_PATHS.book.split(\"/\"));\n\n try {\n await unlink(target);\n } catch (error) {\n if (!isMissing(error)) throw error;\n }\n\n let folder = path.dirname(target);\n\n while (folder.startsWith(`${bookRoot}${path.sep}`)) {\n try {\n await rmdir(folder);\n } catch {\n // Not empty (or already gone): the folders above it are not empty either.\n return;\n }\n\n folder = path.dirname(folder);\n }\n}\n\n/** Every file under `grimoire/book/`, project-relative, or `[]` when there is no book. */\nexport async function listBookFiles(root: string): Promise<string[]> {\n return listFiles(root, [GRIMOIRE_PATHS.book]).then((files) =>\n // `listFiles` skips dot folders, so `.cache/` never appears here.\n files.filter((file) => !file.endsWith(\".tmp\")),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA,MAAa,iBAAiB;;AAG9B,MAAM,mBAAmB;;AAGzB,SAAS,cAAc,MAAuB;CAC5C,OAAO,SAAS,kBAAkB,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ath } from "../paths/index.mjs";
2
+
3
+ //#region ../../packages/grimoire/src/book/normalize.ts
4
+ /** A project-relative POSIX path. */
5
+ function cleanPath(file) {
6
+ return toPosixPath(file).replace(/^(?:\.\/)+/, "").replace(/\/+$/, "");
7
+ }
8
+ function cleanNullable(file) {
9
+ return file === null ? null : cleanPath(file);
10
+ }
11
+ function normalizeFiles(files) {
12
+ return files.map((file) => ({
13
+ ...file,
14
+ file: cleanPath(file.file),
15
+ module: cleanPath(file.module),
16
+ imports: file.imports.map((entry) => ({
17
+ ...entry,
18
+ file: cleanNullable(entry.file)
19
+ })),
20
+ importedBy: file.importedBy.map(cleanPath)
21
+ }));
22
+ }
23
+ function normalizeRoutes(routes) {
24
+ return routes.map((route) => ({
25
+ ...route,
26
+ method: route.method.toUpperCase(),
27
+ sourceFile: cleanNullable(route.sourceFile),
28
+ handlerFile: cleanNullable(route.handlerFile)
29
+ }));
30
+ }
31
+ function normalizeSites(sites) {
32
+ return sites.map((site) => ({
33
+ ...site,
34
+ root: cleanPath(site.root)
35
+ }));
36
+ }
37
+ function normalizePages(pages) {
38
+ return pages.map((page) => ({
39
+ ...page,
40
+ file: cleanPath(page.file),
41
+ setupFile: cleanNullable(page.setupFile),
42
+ layouts: page.layouts.map(cleanPath),
43
+ loaders: page.loaders.map(cleanPath),
44
+ reachedFrom: page.reachedFrom === null ? null : page.reachedFrom.map((link) => ({
45
+ ...link,
46
+ from: cleanPath(link.from)
47
+ }))
48
+ }));
49
+ }
50
+ function normalizeMobile(apps) {
51
+ return apps.map((app) => ({
52
+ ...app,
53
+ root: cleanPath(app.root),
54
+ routesDir: cleanNullable(app.routesDir),
55
+ screens: app.screens.map((screen) => ({
56
+ ...screen,
57
+ file: cleanPath(screen.file),
58
+ layouts: screen.layouts.map(cleanPath)
59
+ }))
60
+ }));
61
+ }
62
+ function normalizeNamed(named) {
63
+ return named.map((thing) => ({
64
+ ...thing,
65
+ file: cleanNullable(thing.file)
66
+ }));
67
+ }
68
+
69
+ //#endregion
70
+ export { cleanPath, normalizeFiles, normalizeMobile, normalizeNamed, normalizePages, normalizeRoutes, normalizeSites };
71
+ //# sourceMappingURL=normalize.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/normalize.ts"],"sourcesContent":["/**\n * Puts every path an adapter reports into one form (project-relative, `/`,\n * no leading `./`), so facts from a Windows machine and a POSIX machine give\n * the same book.\n */\nimport type {\n BookFacts,\n BookFile,\n BookMobileApp,\n BookNamedThing,\n BookPage,\n BookRoute,\n BookSite,\n} from \"../contracts/adapter\";\nimport { toPosixPath } from \"../paths\";\n\n/** A project-relative POSIX path. */\nexport function cleanPath(file: string): string {\n return toPosixPath(file)\n .replace(/^(?:\\.\\/)+/, \"\")\n .replace(/\\/+$/, \"\");\n}\n\nfunction cleanNullable(file: string | null): string | null {\n return file === null ? null : cleanPath(file);\n}\n\nexport function normalizeFiles(files: readonly BookFile[]): BookFile[] {\n return files.map((file) => ({\n ...file,\n file: cleanPath(file.file),\n module: cleanPath(file.module),\n imports: file.imports.map((entry) => ({ ...entry, file: cleanNullable(entry.file) })),\n importedBy: file.importedBy.map(cleanPath),\n }));\n}\n\nexport function normalizeRoutes(routes: readonly BookRoute[]): BookRoute[] {\n return routes.map((route) => ({\n ...route,\n method: route.method.toUpperCase(),\n sourceFile: cleanNullable(route.sourceFile),\n handlerFile: cleanNullable(route.handlerFile),\n }));\n}\n\nexport function normalizeSites(sites: readonly BookSite[]): BookSite[] {\n return sites.map((site) => ({ ...site, root: cleanPath(site.root) }));\n}\n\nexport function normalizePages(pages: readonly BookPage[]): BookPage[] {\n return pages.map((page) => ({\n ...page,\n file: cleanPath(page.file),\n setupFile: cleanNullable(page.setupFile),\n layouts: page.layouts.map(cleanPath),\n loaders: page.loaders.map(cleanPath),\n reachedFrom:\n page.reachedFrom === null\n ? null\n : page.reachedFrom.map((link) => ({ ...link, from: cleanPath(link.from) })),\n }));\n}\n\nexport function normalizeMobile(apps: readonly BookMobileApp[]): BookMobileApp[] {\n return apps.map((app) => ({\n ...app,\n root: cleanPath(app.root),\n routesDir: cleanNullable(app.routesDir),\n screens: app.screens.map((screen) => ({\n ...screen,\n file: cleanPath(screen.file),\n layouts: screen.layouts.map(cleanPath),\n })),\n }));\n}\n\nexport function normalizeNamed(named: readonly BookNamedThing[]): BookNamedThing[] {\n return named.map((thing) => ({ ...thing, file: cleanNullable(thing.file) }));\n}\n\n/** The facts with every path in one form. */\nexport function normalizeFacts(facts: BookFacts): BookFacts {\n return {\n files: normalizeFiles(facts.files),\n routes: facts.routes === null ? null : normalizeRoutes(facts.routes),\n sites: normalizeSites(facts.sites),\n pages: normalizePages(facts.pages),\n mobile: normalizeMobile(facts.mobile),\n named: normalizeNamed(facts.named),\n tests: [...new Set(facts.tests.map(cleanPath))].sort(),\n };\n}\n"],"mappings":";;;;AAiBA,SAAgB,UAAU,MAAsB;CAC9C,OAAO,YAAY,IAAI,CAAC,CACrB,QAAQ,cAAc,EAAE,CAAC,CACzB,QAAQ,QAAQ,EAAE;AACvB;AAEA,SAAS,cAAc,MAAoC;CACzD,OAAO,SAAS,OAAO,OAAO,UAAU,IAAI;AAC9C;AAEA,SAAgB,eAAe,OAAwC;CACrE,OAAO,MAAM,KAAK,UAAU;EAC1B,GAAG;EACH,MAAM,UAAU,KAAK,IAAI;EACzB,QAAQ,UAAU,KAAK,MAAM;EAC7B,SAAS,KAAK,QAAQ,KAAK,WAAW;GAAE,GAAG;GAAO,MAAM,cAAc,MAAM,IAAI;EAAE,EAAE;EACpF,YAAY,KAAK,WAAW,IAAI,SAAS;CAC3C,EAAE;AACJ;AAEA,SAAgB,gBAAgB,QAA2C;CACzE,OAAO,OAAO,KAAK,WAAW;EAC5B,GAAG;EACH,QAAQ,MAAM,OAAO,YAAY;EACjC,YAAY,cAAc,MAAM,UAAU;EAC1C,aAAa,cAAc,MAAM,WAAW;CAC9C,EAAE;AACJ;AAEA,SAAgB,eAAe,OAAw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